gpt4 book ai didi

python - py.test teardown 查看测试是否失败并打印子进程输出

转载 作者:行者123 更新时间:2023-11-28 21:49:02 25 4
gpt4 key购买 nike

如果测试失败,我想在 py.test 拆解中打印子进程输出 - 或者将它发送到任何其他人类可读的输出。是否可以检查测试是否在拆解中失败?还有其他方法可以仅在测试失败期间获取子流程命令的输出吗?

我的代码:

"""Test different scaffold operations."""
import subprocess

import pytest
from tempfile import mkdtemp


@pytest.fixture(scope='module')
def app_scaffold(request) -> str:
"""py.test fixture to create app scaffold."""

folder = mkdtemp(prefix="websauna_test_")

cmdline = ["..."]

worker = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

worker.wait(timeout=5.0)

if worker.returncode is not None:
raise AssertionError("scaffold command did not properly exit: {}".format(" ".join(cmdline)))

def teardown():
worker.terminate()
# XXX: Hard to capture this only on failure for now
print(worker.stdout.read().decode("utf-8"))
print(worker.stderr.read().decode("utf-8"))

request.addfinalizer(teardown)

最佳答案

您可以使用捕获测试中的异常的函数来修饰测试。如果有异常,记录流程输出:

import functools
import subprocess

import pytest


def catch_exception(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
worker = kwargs['app_scaffold']
try:
return func(*args, **kwargs)
except Exception as e:
print('stdout:', worker.stdout.read().decode("utf-8"))
print('stderr:', worker.stderr.read().decode("utf-8"))
raise
return wrapper


@pytest.fixture(scope='module')
def app_scaffold(request) -> subprocess.Popen:
"""py.test fixture to create app scaffold."""
cmdline = ["echo", "something"]

worker = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
worker.wait(timeout=5.0)

return worker


@catch_exception
def test_foo(app_scaffold):
assert False

此代码从您的示例中遗漏了一些细节,但我认为它应该包含处理您的案例所需的所有内容。

关于python - py.test teardown 查看测试是否失败并打印子进程输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34215850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com