我试图嘲笑 django.core.urlresolvers.resolve 函数,但它似乎并不起作用。我已经使用自定义函数进行了测试,它就像魅力一样,但是mock会完全忽略 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'>"}
我的目标是让 resolve 函数返回我可以获取应用名称的内容。
为什么mock.patch无法覆盖解析函数?
答案 0 :(得分:1)
首先,您正在错误的位置修补它。您应该在正在使用的文件中对其进行修补,而不是在运行修补程序之前导入目标代码的位置进行修补。
其次,如果模拟工作,它会在NoneType object has no attribute app_name
的行上引发错误。
@patch(<path_to_middleware.py>, side_effect=lambda: type('mock', (object,), {'app_name': 1})):
def test_something(self):
self.assertEqual(self.middleware.process_request(self.request), None)