【发布时间】:2016-07-22 16:40:06
【问题描述】:
生产文件 (production_file.py) 是:
class MyError(Exception):
pass
class MyClass:
def __init__(self):
self.value = None
def set_value(self, value):
self.value = value
def foo(self):
raise RuntimeError("error!")
class Caller:
def bar(self, smth):
obj = MyClass()
obj.set_value(smth)
try:
obj.foo()
except MyError:
pass
obj.set_value("str2")
obj.foo()
测试文件(test.py):
import unittest
from unittest.mock import patch
from unittest.mock import call
from production_file import MyClass, Caller
class MyTest(unittest.TestCase):
def test_caller(self):
with patch('production_file.MyClass', autospec=MyClass) as MyClassMock:
my_class_mock_obj = MyClassMock.return_value
my_class_mock_obj.foo.side_effect = [MyError("msg"), "text"]
caller = Caller()
caller.bar("str1")
calls = [call("str1"), call("str2")]
my_class_mock_obj.set_value.assert_has_calls(calls)
if __name__ == '__main__':
unittest.main()
以上方法有效。但是如果我将生产类(MyError、MyClass、Caller)移动到测试文件中,并将补丁更新为:
with patch('test.MyClass', autospec=MyClass) as MyClassMock:
然后不再模拟实例方法“foo”。
有人知道这是为什么吗?
我在一些更复杂的代码中也遇到过类似的问题,其中生产代码在 my_package/src/production_file.py 中,而测试在 my_package/tests/test_file.py 中。 Python 不会产生路径错误,路径是正确的,但 mock 仍然不起作用。
【问题讨论】:
标签: python-3.x mocking patch