2017-10-06 173 views
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無法覆蓋解析函數?

回答

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) 
+0

哦,這是完全合理的。謝謝! – user2937998