1
我試圖模擬django.core.urlresolvers.resolve函數,但它似乎並不工作。我用自定義函數進行了測試,它的工作原理類似於魅力,但模擬忽略了完全解決了。Django單元測試:不能模擬django.core.urlresolvers.resolve
代碼:
test_something.py:
class SomethingTestCase(TestCase)
def setUp(self):
self.middleware = SomeMiddleware()
self.request = Mock()
self.request.session = {}
@patch('django.core.urlresolvers.resolve', side_effect=lambda: None)
def test_something(self):
self.assertEqual(self.middleware.process_request(self.request), None)
middleware.py
class SomeMiddleware(object):
def process_request(self, request):
app = resolve(request.path).app_name
print('App name: {}'.format(app))
這將導致以下錯誤:
======================================================================
ERROR: test_process_request_unauthenticated (something.tests.unit.test_middleware.SomethingTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/user/virtualenv/something/local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "/home/user/projects/something/working/something/tests/unit/test_middleware.py", line 23, in test_process_request_unauthenticated
self.assertEqual(self.middleware.process_request(self.request), None)
File "/home/user/projects/something/working/something/middleware.py", line 14, in process_request
app = resolve(request.path).app_name
File "/home/user/virtualenv/something/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 534, in resolve
return get_resolver(urlconf).resolve(path)
File "/home/user/virtualenv/something/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 405, in resolve
raise Resolver404({'path': path})
Resolver404: {u'path': u"<Mock name='mock.path' id='140678271233168'>"}
我的目標是使解決函數返回的東西,我可以得到應用程序名稱。
爲什麼mock.patch無法覆蓋解析函數?
哦,這是完全合理的。謝謝! – user2937998