我的代码如下所示:
with patch("package.module.func") as f1, \
patch("package.module.func2") as f2, \
patch("package.module.func3") as f3, \
patch("package.module.func4") as f4:
# Do something with the patched functions
我想避免在我的代码中一遍又一遍地重复此上下文。我总是希望在不同的地方有相同的行为。
一种方法是使用装饰器并装饰我的测试类:
@patch("package.module.func")
class TestSomething:
# do stuff
据我所知,TestSomething
的每个测试现在都使用补丁。
但是如果我在多个类中再次使用这些补丁,我就必须重写装饰器。 有没有办法只编写这些补丁一次并在不同的测试模块中重用它们?
This没有回答我的问题,因为问题是关于每个函数有不同的返回值,这是我不需要的。
最佳答案
喝完一杯好咖啡后找到了解决方案:
模拟示例取自此YT: How to use Python's unittest.mock.patch
class BaseMock(TestCase):
def setUp(self) -> None:
self.patcher = mock.patch('src.examplemodule.print_content_cwd', return_value=b"[\"base mocked\"]")
self.patcher.start()
def tearDown(self) -> None:
self.patcher.stop()
# Use the mocking, without defining it again
class TestDerived1(BaseMock):
def test_d(self):
ls = examplemodule.print_content_cwd()
print(f"TestDerived1: ls returned {ls}\n")
# Use the mocking, without defining it again
class TestDerived2(BaseMock):
def test_d(self):
ls = examplemodule.print_content_cwd()
print(f"TestDerived2: ls returned {ls}\n")
我们要在src/examplemodule.py
中模拟的代码:
from subprocess import check_output
def print_content_cwd():
return check_output(['ls']).split()
关于python - 如何重用复杂的补丁语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71647984/