py.test teardown 查看测试是否失败并打印子进程输出 [英] py.test teardown see if the test failed and print subprocess output

查看:51
本文介绍了py.test teardown 查看测试是否失败并打印子进程输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to print subprocess output in py.test teardown if the test is failed - or send it to any other human readable output. Is it possible to check if the test has failed in teardown? Any other ways to get the output of subprocess commands only during test failures?

我的代码:

"""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)

推荐答案

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

You can decorate the test with a function that catches exceptions in the test. If there is an exception, log the process output:

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

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

This code leaves out some details from your example, but I think it should contain all you need to handle your case.

这篇关于py.test teardown 查看测试是否失败并打印子进程输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆