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

时间:2015-12-11 03:54:33

标签: python pytest

如果测试失败,我想在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)

3 个答案:

答案 0 :(得分:3)

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

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

此代码会从您的示例中省略一些细节,但我认为它应该包含您处理案例所需的全部内容。

答案 1 :(得分:1)

您可以使用capsyscapfd灯具实际捕获在执行期间创建的stdout / stderr :( https://pytest.org/latest/capture.html

答案 2 :(得分:1)

pytest-instafail 插件可能很有用

运行测试时,您可以使用 - instafail 选项。在执行其他测试时继续显示失败测试的失败

参见:https://pypi.python.org/pypi/pytest-instafail