我有一些基于 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/