我一直在使用Python的unittest.mock
库,但是现在我正在努力解决可能无法正确使用的用例。
考虑包含以下代码段的文件mymodule/code.py
:
def sum():
pass
def mul():
pass
def div():
pass
def get_functions():
return [sum, mul, div]
def foo():
functions = get_functions()
for func in functions:
func()
我想测试foo
函数,修补sum
函数,然后保留mul
和div
。这是我最初尝试过的:
class TestFoo(unittest.TestCase):
@mock.patch('mymodule.code.foo.sum')
def test_foo(foo_sum_mock):
foo()
foo_sum_mock.assert_called_once()
但是,上面说明的修补方法不起作用。我相信sum
功能在加载mymodule.code.py
时已正确修补,但由于def sum()
阻止而重新定义。
通过阅读官方文档,我还尝试使用start
库的stop
和unittest.mock
函数,如下所示:
def test_foo():
patcher = mock.patch('module.code.sum')
mocked_sum_fun = patcher.start()
foo()
mocked_sum_fun.assert_called_once()
mock_sum_fun.stop()
这种方法也行不通。我希望在sum
文件加载后避免modules/code.py
函数覆盖。
是否可以修补sum
等本地功能?或者将sum
函数移动到另一个文件是唯一的修补选项?
非常感谢提前!
答案 0 :(得分:0)
通常来说,您希望将测试代码与生产代码分开:
code.py
def sum():
pass
def mul():
pass
def div():
pass
def get_functions():
return [sum, mul, div]
def foo():
functions = get_functions()
for func in functions:
func()
code_test.py
import unittest
import mock_test as mock
import code
class TestFoo(unittest.TestCase):
@mock.patch('code.sum')
def test_foo(self, sum_mock):
def new_sum_mock(*args, **kwargs):
# mock code here
pass
sum_mock.side_effect = new_sum_mock
code.foo()
sum_mock.assert_called_once()
但是可以,您可以将它们全部放入一个文件中
code_test.py:
import unittest
import mock_test as mock
import code
def sum():
pass
def mul():
pass
def div():
pass
def get_functions():
return [sum, mul, div]
def foo():
functions = get_functions()
for func in functions:
func()
class TestFoo(unittest.TestCase):
@mock.patch('code_test.sum')
def test_foo(self, sum_mock):
def new_sum_mock(*args, **kwargs):
# mock code here
pass
sum_mock.side_effect = new_sum_mock
code.foo()
sum_mock.assert_called_once()
答案 1 :(得分:0)
您可以使用mock.patch
并将该模块称为__main__
来模拟相同模块的功能
code.py
from unittest.mock import patch
def sum():
print("called method sum")
pass
def call_sum():
sum()
def return_mock():
print("I'm a mocked method")
return True
with mock.patch('__main__.sum', return_value=return_mock()) as mock_test:
call_sum()
mock_test.assert_called_once() # assure that mocked method was called, not original.
您还可以使用lib(my_project.code.sum
)的路径代替__main__.sum
。