2012-10-23 53 views
0

您好我有一個觀點,像這樣:Django的測試JSON轉儲視圖

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', '[email protected]', '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

的URL可能不正確。反向使用(即reverse('ajax_populate'))。不要硬編碼的網址。 http://django.steerway.com/tip/bNk8P/do-not-hard-code-urls-use-name-in-url-patterns-then-use-reverse-in-your-views-url-tag- in-your-template-to-resolve-urls/ – dannyroa

+1

對於我來說,你的URL在你的url conf的根目錄下有'ajax_populate /',並且你在測試中要求'/ colors/ajax_populate /'。你是否從其他地方加入了這個urls.py?如果是這樣,你需要在url行的開頭刪除'^'。 –

+0

+1 http://django.steerway.com/!雖然問題歸結爲不正確的'setUp()',那麼url絕對不應該被硬編碼,所以謝謝你。 –

回答

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', 
      '[email protected]', 
      '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)