我有一些基于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
调用测试中的“main”程序并手动捕获其标准输出
我正在将这个项目转换为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
开始的fixture——理想情况下,调用函数不需要为capsys
/capfd
而烦恼
有没有办法从我的run_prog
助手中“调用”该装置?或者我需要将capfd
添加到所有42个测试中,并将其传递给run_prog
您可以定义自动使用装置,该装置将
CaptureFixture
对象(由capsys
装置返回)存储为实例属性:每个测试都将重新运行
TestMain.inject_capsys
夹具,以保证测试隔离(来自test_one
的输出不会泄漏到test_two
等中)这里是对hoefling's answer的一个小小的变化,它对
capsys
fixture的范围提供了更多的控制它使用^{} 在函数调用时检索fixture:
相关问题 更多 >
编程相关推荐