我正在尝试使用模拟和 @patch 装饰器为 Python 应用程序构建测试。
给定以下目录结构:
|-- mypackage
| |-- mymodule
| | |-- __init__.py
| | \-- somefile.py
| \-- myothermodule
| |-- tests
| | |-- __init__.py
| | \-- test_func_to_test.py
| \-- __init__.py
\-- __init__.py
文件的内容是:
#mypackage/mymodule/somefile.py
def some_function():
return 'A'
#mypackage/myothermodule/__init__.py
from mypackage.mymodule.somefile import some_function
def func_to_test():
return some_function()
#mypackage/myothermodule/tests/test_func_to_test.py
from unittest import TestCase
from mock import patch
class TestFunc_to_test(TestCase):
def test_func_to_test(self):
from mypackage.myothermodule import func_to_test
self.assertEqual('A', func_to_test())
@patch('mypackage.mymodule.somefile.some_function')
def test_func_to_test_mocked(self, some_mock_function):
from mypackage.myothermodule import func_to_test
some_mock_function.return_value = 'B'
self.assertEqual('B', func_to_test())
我遇到的问题是,虽然第一个测试通过(test_func_to_test),但第二个测试(test_func_to_test_mocked)没有通过(由于 AssertionError)。
我已经能够使用相同的方法从“内置”模块(例如 requests.get)模拟函数,但是当我尝试从我的一个模块修补函数时,我似乎无法让 @patch 工作。模块...
任何帮助,将不胜感激 :)
mypackage.myothermodule
已经导入了,所以名称some_function
已绑定在该模块内。您需要在调用该名称的模块中模拟该名称的使用:
@patch('mypackage.myothermodule.some_function')
您也可以重新加载mypackage.myothermodule
:
import mypackage.myothermodule
reload(mypackage.myothermodule)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)