Code Snippet for Django Unit Test for AJAX Responses

View

def api_get_destinations(request):
    if request.is_ajax():
        searchText = request.GET.get('searchText', '')
        maxResults = request.GET.get('maxResults', '10')
        n = int(maxResults)
        cities = ParentRegionList.city\
                .filter(region_name_long__icontains=searchText, subclass=None)\
                .values_list('pk', 'region_name_long')[:n]

        results = []
        for city in cities:
            city_dict = {'id': city[0],
                    'label': city[1],
                    'value': city[1]}
            results.append(city_dict)
        if not results:
            results.append({
                'id': -1,
                'label': 'No Results Found',
                'value': 'No Results Found'
                })
        data = simplejson.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

Test

class TestAPIResponses(TestCase):
    def setUp(self):
        self.parent_region_list = ParentRegionListFactory()

    def test_get_destinations(self):
        kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
        url = reverse('api_get_destinations')

        get_data = {'searchText': 'Singap',}

        response = self.client.get(url, get_data, **kwargs)
        json_string = response.content
        data = json.loads(json_string)
        self.assertEqual(data[0]['id'], self.parent_region_list.pk)
        self.assertEqual(data[0]['value'],
                self.parent_region_list.region_name_long)
        self.assertEqual(data[0]['label'],
                self.parent_region_list.region_name_long)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s