2016-11-09 128 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测试来获取错误 –