2016-11-09 182 views
1
|-- my_module 
| |-- __init__.py 
| |-- function.py 
`-- test.py 
在function.py

補丁功能

import other_function 

def function(): 
    doStuff() 
    other_function() 
    return 
在__init__.py

from .function import function 

在我test.py

from django.test import TestCase 
from mock import patch 
from my_module import function 

class Test(TestCase): 

    @patch('my_module.function.other_function') 
    def function_test(self, mock_other_function): 
     function() 

當我運行這個時,我得到了一個 Attri buteError:

<@task: my_module.function.function of project:0x7fed6b4fc198> does not have the attribute 'other_function'

這意味着我試圖修補功能「功能」,而不是模塊「功能」。我不知道如何讓它理解我想修補模塊。

我也想避免重命名我的模塊或功能。

任何想法?

[編輯] 你可以在https://github.com/vthorey/example_mock 運行找到一個例子

python manage.py test 
+0

你有解決這個問題嗎? –

+0

@HaykDavtyan沒有。如果您想提高知名度,您可以提出問題;) –

回答

0

你可以使可用的模塊以不同的名稱在__init__.py

from . import function as function_module 
from .function import function 

然後,你可以做以下在test.py

from django.test import TestCase 
from mock import patch 
from dir import function 

class Test(TestCase): 

    @patch('dir.function_module.other_function') 
    def function_test(self, mock_other_function): 
     function() 

我不認爲這是一個特別優雅的解決方案 - 對於一個隨便的讀者來說代碼不是很清楚。

請注意,dir是一個內置的,所以你應該避免在示例代碼中使用它!

+0

感謝您的反饋,我正在使用一個字符串。我編輯了這個問題! –

+0

你能提供一個實際運行並遇到錯誤的例子嗎?我使用'requests'包作爲'other_function',我的代碼運行正常 –

+0

https://github.com/vthorey/example_mock你可以運行python manage.py測試來獲取錯誤 –