如何以交互方式探索测试失败的原因?

时间:2010-02-23 22:01:28

标签: python django django-testing

我的测试失败了:

======================================================================  
    FAIL: test_register_should_create_UserProfile (APP.forum.tests.test_views.UserTestCAse)  
    ----------------------------------------------------------------------  
    Traceback (most recent call last):  
      File "/Users/Bryan/work/app/../app/forum/tests/test_views.py", line 25, in test_register_should_create_UserProfile  
        self.assertEqual(response.status_code, 200)  
    AssertionError: 404 != 200

以下是测试:

class UserTestCAse(TestCase):  
  def test_register_should_create_UserProfile(self):  
    from django.test.client import Client  
    c = Client()  
    # I'm skipping account/signin/ because that requires me to visit Google.  
    response = c.post('account/signin/complete/', {'username': 'john', "email":'john@beatles.com', u'bnewaccount': 'Signup'}) 
    # request.POST from pdb() session with breakpoint in register()
    # <QueryDict: {u'username': [u'john'], u'email': [u'john@beatles.com'], u'bnewaccount': [u'Signup']}>

    #How do I inspect what is breaking in the test case?  
    #How do I run the test client in the shell?  
    self.assertEqual(response.status_code, 200)  

    user = User.objects.get(username ='john')  
    self.assertTrue(user.get_profile())  

无论如何,我能看出为什么这个回复没有返回200?

我尝试在shell中使用TestClient(),但这不起作用:

In [1]: from django.test.client import Client  

In [2]: c = Client()  

In [3]: response = c.post('account/signin/complete/', {'username': 'john', "email":'john@beatles.com', u'bnewaccount': 'Signup'})  
---------------------------------------------------------------------------  

KeyError: 'tried'  

2 个答案:

答案 0 :(得分:3)

这看起来不对。

user = User.objects.get('username'=='john')  

如果要查询,则必须以教程

中显示的样式编写查询

http://docs.djangoproject.com/en/1.1/topics/db/queries/#topics-db-queries

user = User.objects.get( username = 'john' ) 

例如。

要进行调试,您可以在命令行运行。这就是我们的工作。 Django教程显示了所有示例,就好像它们是在命令行中以交互方式键入的一样。

>>> from myapp.models import Client
>>> Client.objects.get( name = 'value' )

您通常不会尝试从命令行运行单元测试。由于单元测试框架为您做的所有事情,这很难做到。

您通常只需逐个浏览应用程序视图函数语句,以确保您的视图函数真正起作用。

答案 1 :(得分:2)

如果您收到意外的404,Django错误页面会显示错误(假设DEBUG为True)。在这种情况下,您可以print response.content显示该追溯,并将其剪切并粘贴到浏览器中。

此外,不要忘记您可以使用交互式调试器pdb进入运行测试,就像任何其他形式的运行代码一样,因此您可以动态检查响应。或者甚至将断点放在帖子之前,这样你就可以逐步浏览视图。

然而,第二眼看,我怀疑你的网址不匹配,因为你错过了一个初始\