Django测试json转储视图

时间:2012-10-23 21:14:40

标签: django unit-testing testing django-testing

嗨我有这样的观点:

def AjaxPopulate(request):
    colour = request.GET.get('colour_id')
    if colour is None:
        return HttpResponseBadRequest()

    qs = Thing.objects.select_related()
    things = get_list_or_404(qs, colour=colour)
    data = []
    for x in things:
        data.append({
            'id': x.id,
            'name': unicode(x),
        })
    return HttpResponse(simplejson.dumps(data), mimetype='application/json'

挂钩到这个网址:

url(r'^ajax_populate/$', 'colours.views.AjaxPopulate', name='ajax_populate'),

在我的测试中我有:

def setUp(self):
    self.client = Client()
    user = User.objects.create_superuser('foo', 'myemail@test.com', 'bar')
    colour1 = Colour.objects.create(colour='Green')
    thing1 = Thing.objects.create(name='Leaf', colour=colour1, description='foo')

def test_ajax_populate(self):
    response = self.client.get('/colours/ajax_populate/', {'colour_id': 1}) 
    self.assertEqual(response.status_code, 200)

但是,我收到AssertionError: 404 != 200错误。

我做错了什么?

任何帮助非常感谢。

1 个答案:

答案 0 :(得分:0)

有效的最终代码。

tests.py

class ViewTests(TestCase):
    """
    Run before each test in class
    """
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_superuser(
            'foo',
            'myemail@test.com',
            'pass'
        )
        self.colour = Colour.objects.create(colour='Green')
        self.thing = Thing.objects.create(
            name='Leaf',
            colour=self.colour,
            description='leafy'
        )
        self.logged_in = self.client.login(
            username='foo',
            password='pass'
        )

    """
    Test ajax call
    """
    def test_ajax_populate(self):
        response = self.client.get(tests.py
            reverse('ajax_populate'),
            {'colour_id': self.colour.pk})
        self.assertEqual(response.status_code, 200)