hwj*_*wjp 5 python unit-testing pytest
我正在测试一个写入日志文件的函数(具体是它写入日志文件并不重要,它可能正在做任何事情,它只是引起这个问题的原因)
像这样的东西:
def do_stuff():
with open('/tmp/mylogs.txt', 'a') as f:
f.write(str(time.time()))
f.write(' stuff done! \n')
return 42
Run Code Online (Sandbox Code Playgroud)
我可以测试它有点像这样:
def test_doing_stuff(watch_logs):
assert do_stuff() == 42
assert do_stuff() == 43
Run Code Online (Sandbox Code Playgroud)
出于调试目的,当测试失败时,我希望能够打印出新的日志记录 - 我可以使夹具有点像这样:
@pytest.fixture()
def watch_logs(request):
with open('/tmp/mylogs.txt') as f:
log_before = f.read()
def get_new_logs():
with open('/tmp/mylogs.txt') as f:
log_after = f.read()
return log_after.replace(log_before, '')
return get_new_logs
Run Code Online (Sandbox Code Playgroud)
太棒了 - 现在我可以在测试中的任何一点检查日志内容:
def test_doing_stuff(watch_logs):
assert do_stuff() == 42
print(watch_logs())
assert do_stuff() == 43
print(watch_logs())
Run Code Online (Sandbox Code Playgroud)
嗯 - 啊,但第二次打印不起作用,它是在测试失败后.
如果我的测试夹具总是在测试结束时打印出日志怎么办?然后pytest的stdout捕获会在它失败时显示给我,但不会在它通过时显示给我!
@pytest.fixture()
def watch_logs(request):
with open('/tmp/mylogs.txt') as f:
log_before = f.read()
def get_new_logs():
with open('/tmp/mylogs.txt') as f:
log_after = f.read()
return log_after.replace(log_before, '')
def print_new_logs():
print('~' * 20 + ' logs ' + '~' * 20)
print(get_new_logs())
print('~' * 50)
request.addfinalizer(print_new_logs)
return get_new_logs
Run Code Online (Sandbox Code Playgroud)
哦,但这不起作用,因为在测试终结器期间没有发生pytests的日志捕获.
所以问题是:如何制作可以打印东西的测试终结器?
这是一个超级最小的要点,没有(不相关的)写入日志文件的东西:https: //gist.github.com/hjwp/5154ec40a476a5c01ba6
感谢霍尔格本人的帮助(感谢@hpk42!),我得到了一些有用的东西。只是有点神奇/hacky。
解决方案是使用名为 的 py.test 钩子pytest_pyfunc_call
以及名为 的装饰器hookwrapper
。它们为我提供了一种在测试运行之前和之后挂钩某些代码的方法,但也不会受到标准输出劫持的影响。
我们在conftest.py中定义一个新函数:
# conftest.py
@pytest.mark.hookwrapper
def pytest_pyfunc_call(pyfuncitem):
yield
print('this happens after the test runs')
if 'watch_logs' in pyfuncitem.funcargs:
print(pyfuncitem.funcargs['watch_logs']())
Run Code Online (Sandbox Code Playgroud)
现在,如果 pytest 发现任何使用该watch_logs
装置的测试,它将在测试运行后打印其输出。
完整示例: https: //gist.github.com/hjwp/4294f0acbef5345a7d46
归档时间: |
|
查看次数: |
769 次 |
最近记录: |