python - 如何重用复杂的补丁语句?

标签 python python-unittest

我的代码如下所示:

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/

相关文章:

python - OpenCV:HoughCircles 返回无效的圆参数

python - 如何在不丢失数据框的情况下在 Pandas 中编辑姓氏、名字的顺序

python - 如何在 Python 中测试命令行应用程序?

python - 如何在 Flask 中对 HTTP 摘要身份验证进行单元测试?

python - 如何将 Tornado 日志存储到文件中?

python - lxml 中的 iterdescendants() 和 iterchildren() 有什么区别?

python - Flask session 在 Heroku 上使用 Gunicorn 的 Flask 应用程序中的请求之间不持久

python - 在 PyUnit 中运行任何测试之前,在开始时只运行一次方法

python - 如何遍历 Python unittest runner 的所有成功测试结果?

python - 如何模拟 xml 数据交换以在 python 中编写单元测试