如何交互式地探查测试失败的原因?

0 投票
2 回答
515 浏览
提问于 2025-04-15 19:39

我有一个测试没有通过,错误信息是:

======================================================================  
    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?

我尝试在命令行里使用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 个回答

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' )

等等。

一般来说,你不会直接在命令行里运行单元测试。这样做比较麻烦,因为单元测试框架会为你处理很多事情。

通常你会逐行检查应用的视图函数,确保你的视图函数能够正常工作。

2

如果你遇到了意外的404错误,Django会显示错误页面(前提是DEBUG设置为True)。在这种情况下,你可以用print response.content来显示错误的详细信息,然后把这些信息复制粘贴到浏览器里。

另外,别忘了你可以用交互式调试器pdb来中断正在运行的测试,就像处理其他代码一样,这样你就可以动态查看响应的内容。或者,你也可以在发送请求之前设置一个断点,这样你就可以逐步查看视图的执行过程。

不过再仔细看一下,我怀疑你的网址没有匹配成功,因为你可能漏掉了一个开头的\

撰写回答