samedi 23 janvier 2016

Patch persisting across multiple Django unit tests?

I'm at a bit of a loss as to why two of my tests are conflicting. The patch in one test seems to be persisting to the other test. If I comment the patching test out, or just run the other test by itself there is no problem. My tests are:

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

With the Home view being a TemplateView. The error I end up with is:

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

Because I'm not doing anything special with the patch decorator, my guess is that it has something to do with how Django is setting things up. In particular, I found that patching myapp.urls.Home does not work. Instead I need to patch myapp.views.Home, despite the fact that the line under test is in urls.py as url(r'^$', Home.as_view(), name='home'),. Any thoughts as to why this patch is persisting and how I can fix it? Thank you much!

Aucun commentaire:

Enregistrer un commentaire