特定于主机的请求打破了不相关的测试用例

时间:2018-06-13 21:40:21

标签: django django-1.11 django-hosts

我有以下测试:

from django.test import TestCase
from django.core.urlresolvers import reverse

class TestA(TestCase):
    def test_a(self):
        reverse('view1')

class TestB(TestCase):
    def test_b(self):
        self.client.get('/view2/', HTTP_HOST='second.test.net')

class TestC(TestCase):
    def test_c(self):
        reverse('view1')

TestATestB成功运行,但TestC打破了

..E
======================================================================
ERROR: test_c (dhtest.tests.test_view2.TestC)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/phihag/dhtest/dhtest/tests/test_view2.py", line 14, in test_c
    reverse('view1')
  File "/home/phihag/.local/share/virtualenvs/dhtest---IwXRQ3/lib/python3.6/site-packages/django/urls/base.py", line 91, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "/home/phihag/.local/share/virtualenvs/dhtest---IwXRQ3/lib/python3.6/site-packages/django/urls/resolvers.py", line 497, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'view1' not found. 'view1' is not a valid view function or pattern name.

----------------------------------------------------------------------
Ran 3 tests in 0.006s

FAILED (errors=1)

但当我评论TestB时,TestC有效!如何解决这个问题?

我正在使用具有以下配置的django-hosts:

from django.conf import settings
from django_hosts import patterns, host

host_patterns = patterns(
    '',
    host(
        r'second\.test\.net',
        'dhtest.secondurls',
        name='second'
    ),
    host(
        r'(\w+)',
        'dhtest.urls',
        name='default'
    ),
)

和相当简单的URL文件:

# dhtest/urls.py
from django.conf.urls import url
from django.http import HttpResponse

urlpatterns = [
    url(r'^view1/', lambda _: HttpResponse('This is view1'), name='view1'),
]
# dhtest/secondurls.py
from django.conf.urls import url
from django.http import HttpResponse

urlpatterns = [
    url(r'^view2/', lambda _: HttpResponse('view2 on another host')),
]

供参考,here is the full project

1 个答案:

答案 0 :(得分:0)

这是Django-hosts中的一个错误。 In its response middleware,django-hosts使用线程范围的urlconf来破坏请求。

在制作中,这不是问题,因为Django resets the urlconf to the default for every requestthe request-specific one

但是在测试期间,在TestB之后没有更多请求到来,reverse(和许多其他与URL相关的函数)正在使用urlconf为不同的主机。

要解决此问题,请在对特定主机发出任何请求后恢复urlconf,如下所示:

class TestB(TestCase):
    def test_b(self):
        self.client.get('/view2/', HTTP_HOST='second.test.net')

    def tearDown(self):
        from django.urls.base import set_urlconf
        set_urlconf(None)