修补程序在多个Django单元测试中持续存在?

时间:2016-01-24 01:14:57

标签: python django unit-testing python-3.x mocking

为什么我的两个测试存在冲突,我有点失落。一次测试中的补丁似乎持续到另一次测试。如果我评论补丁测试,或者只是自己运行其他测试就没有问题。我的测试是:

class TestUrlRouting(TestCase):
    @patch('myapp.views.Home')
    def test_home_url_routes_to_home_view(self, mock_home_view):
        url = reverse('home')
        match = resolve(url)

        assert match.func == mock_home_view.as_view()


class TestHomeView(TestCase):
    def test_front_page_renders_home_template(self):
        response = self.client.get('/')
        self.assertTemplateUsed(response, 'home.html')

Home视图为TemplateView。我最终得到的错误是:

Traceback (most recent call last):
  File "/path/to/code/source/myapp/tests/test_views.py", line 11, in test_front_page_renders_home_template
    response = self.client.get('/')
  File "/path/to/code/virtualenv/lib/python3.5/site-packages/django/test/client.py", line 503, in get
    **extra)
  File "/path/to/code/virtualenv/lib/python3.5/site-packages/django/test/client.py", line 304, in get
    return self.generic('GET', path, secure=secure, **r)
  File "/path/to/code/virtualenv/lib/python3.5/site-packages/django/test/client.py", line 380, in generic
    return self.request(**r)
  File "/path/to/code/virtualenv/lib/python3.5/site-packages/django/test/client.py", line 467, in request
    six.reraise(*exc_info)
  File "/path/to/code/virtualenv/lib/python3.5/site-packages/django/utils/six.py", line 686, in reraise
    raise value
  File "/path/to/code/virtualenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 242, in get_response
    response = self.apply_response_fixes(request, response)
  File "/path/to/code/virtualenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 305, in apply_response_fixes
    response = func(request, response)
  File "/path/to/code/virtualenv/lib/python3.5/site-packages/django/http/utils.py", line 17, in conditional_content_removal
    if 100 <= response.status_code < 200 or response.status_code in (204, 304):
TypeError: unorderable types: int() <= MagicMock()

因为我没有对补丁装饰器做任何特别的事情,我的猜测是它与Django如何设置有关。特别是,我发现修补myapp.urls.Home不起作用。相反,我需要修补myapp.views.Home,尽管被测线在urls.pyurl(r'^$', Home.as_view(), name='home'),。有什么想法为什么这个补丁持续存在以及我如何解决它?非常感谢!

更新 即使在模仿myapp.views.Home.as_view而不仅仅是myapp.views.Home时问题仍然存在(再一次,注意views是正确模拟的选项,而不是urls由于某种原因)。

1 个答案:

答案 0 :(得分:0)

.as_view()的调用仅在导入时进行一次(Django第一次需要访问&#34; urls.py&#34;),这就是为什么&#39}&# 34;持续&#34;

IMO你的第一个测试用例只是测试Django框架,而不是你自己代码中的任何东西,除了主视图的网址名称为&#34; home&#34;。挑剔是不值得的。您可以轻松地覆盖reverse('home')在另一个不需要模拟Django全局变量的测试用例中将您带到正确的视图。