python - 使用通用测试函数中的 pytest fixture

标签 python pytest

我有一些基于 unittest 的代码 currently looks like this :

class TestMain(TestCase):
    def run_prog(self, args):
        with TemporaryFile() as stdout:
            old_stdout = sys.stdout
            try:
                main.main()
                stdout.seek(0)
                stdout_data = stdout.read()
            finally:
                sys.stdout = old_stdout
        return stdout_data

    def test_one(self):
        out = self.run_prog(...)

    def test_two(self):
        out = self.run_prog(...)

    def test_three(self):
        out = self.run_prog(...)

run_prog 调用被测试的“主”程序并手动捕获其标准输出。

我正在将此项目转换为 pytest,但这最后一部分突破了我对 pytest 装置理解的极限。

我了解 pytest 完全支持 capturing stdout/stderr我想利用这一点。

问题是,他们的示例在测试功能级别上工作:

def test_myoutput(capfd):
    do_something
    captured = capsys.readouterr()
    assert captured.out == "hello\n"
    assert captured.err == "world\n"

就我而言,run_prog 使用了 42 次,因此我尝试使用从 run_prog 开始的固定装置——理想情况下,调用函数不需要打扰 capsys/capfd

有没有办法从我的 run_prog 助手中“调用”固定装置?或者我是否需要将 capfd 添加到所有 42 个测试中并将其传递给 run_prog

最佳答案

您可以定义一个自动使用装置,将 CaptureFixture 对象(由 capsys 装置返回)存储为实例属性:

class TestMain(TestCase):

    @pytest.fixture(autouse=True)
    def inject_capsys(self, capsys):
        self._capsys = capsys

    def run_prog(self, args):
        main.main()
        return self._capsys.out

    def test_out(self):
        assert self.run_prog('spam') == 'eggs'

TestMain.inject_capsys 固定装置将针对每个测试重新运行,以保证测试隔离(test_one 的输出不会在 test_two 中泄漏)等)。

关于python - 使用通用测试函数中的 pytest fixture ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63441978/

相关文章:

python - 在不通过 SSH 进入我的容器的情况下运行测试

python - 使用 pytest.raises 检查自定义异常属性

python - 从scrapy中的POST请求下载文件

python - 如何假设 pandas 数据帧的值为 "default column"?

python - 如果未运行最小数量的测试,如何使 pytest 返回失败?

python - 如何自定义pytest名称

python - Py.Test : Report using --cov, 排除了报告中的一些 'def' 并且没有显示任何失败

python - Django级联删除反向外键

python - 将 pandas 数据框转换为 Orange 数据表

python - 将具有内部条件的循环从 python 转换为 golang