如何使用在后台运行的fixture在python中捕获stdout和stderr
我想为一组测试编写一个自定义记录器,而不对测试进行任何重大更改。我想使用像fixture这样的东西,我可以将它传递给测试方法,在测试的整个过程中,fixture在后台运行,捕获stdout和stderr并将其更改为自定义消息。如何做到这一点如何使用在后台运行的fixture在python中捕获stdout和stderr,python,logging,fixture,Python,Logging,Fixture,我想为一组测试编写一个自定义记录器,而不对测试进行任何重大更改。我想使用像fixture这样的东西,我可以将它传递给测试方法,在测试的整个过程中,fixture在后台运行,捕获stdout和stderr并将其更改为自定义消息。如何做到这一点 def test_1(): blah blah print('Some msg') blah assert something, assert_msg Output: Some msg (if assert fails, th
def test_1():
blah
blah
print('Some msg')
blah
assert something, assert_msg
Output:
Some msg (if assert fails, then assertion error too)
我想要的是
@fixture
def logger():
capture stdout, stderr
custom_msg = cust_msg(stdout, stderr)
print(custom_msg)
def test_1(logger):
blah
blah
print('Some msg')
blah
assert something, assert_msg
Output:
Custom msg (if assert fails, then custom assertion error too)
如果不重新定义
sys.stdout
或print
,则无法从模块内捕获标准输出。重新定义打印更容易,因为它已经是一项功能了。要捕获失败的assert
s,只需捕获AssertionError
s即可
import functools
import sys
def fixture(f):
old_print = print
@functools.wraps(f)
def wrapped(*args, **kwargs):
global print
def print(*value, sep=' ', end='\n', file=sys.stdout, flush=False):
msg = sep.join(map(str, value)) + end
# Manipulate msg here
file.write(manipulated)
if flush:
file.flush()
try:
return f(*args, **kwargs)
except AssertionError as e:
# Custom message on failed assertion
msg = e.args[0] if len(e.args) == 1 else None
old_print(manipulated)
finally:
print = old_print
return wrapped
但是,assert
s并没有提供多少有用的信息。我会使用一个实际的测试库,比如
另一种方法是将其作为子流程运行