繁体   English   中英

如何通过夹具将测试状态传递给它的拆卸

[英]How to pass test status to it's teardown, through a fixture preferably

我有一个 BaseTest class 它有 tear_down 并且我想在 tear_down 里面有一个代表测试是否失败的变量。

我尝试查看很多较旧的帖子,但我无法实现它们,因为它们是钩子或钩子和固定装置的混合物,而我的结果却不起作用。

这样做的最佳做法是什么?

我试过的最后一件事是——

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item):
    outcome = yield
    rep = outcome.get_result()

    # set a report attribute for each phase of a call, which can
    # be "setup", "call", "teardown"

    setattr(item, "rep_" + rep.when, rep)

然后将请求夹具传递给拆卸和内部使用

has_failed = request.node.rep_call.failed 

但是 request 根本没有属性,它是一个方法。 也试过了——

@pytest.fixture
def has_failed(request):
    yield

    return True if request.node.rep_call.failed else False

并像这样通过它。

def teardown_method(self, has_failed):

再说一次,没有属性。

难道没有一个简单的夹具可以像 request.test_status 或类似的东西吗?

重要的是,无论是否失败,拆解都将具有该 bool 参数,并且不会在拆解之外执行任何操作。

谢谢!

似乎没有任何超级简单的夹具提供测试报告作为夹具。 我明白你的意思:大多数记录测试报告的例子都是针对非单元测试用例(包括官方文档)的 但是,我们可以调整这些示例以使用 unittest TestCases。

传递给pytest_runtest_makereportitem arg 上似乎有一个私有_testcase属性,其中包含 TestCase 的实例。 我们可以在其上设置一个属性,然后可以在teardown_method中访问该属性。

# conftest.py

import pytest

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()

    if report.when == 'call' and hasattr(item, '_testcase'):
        item._testcase.did_pass = report.passed

这是一个极小的例子TestCase

import unittest

class DescribeIt(unittest.TestCase):
    def setup_method(self, method):
        self.did_pass = None

    def teardown_method(self, method):
        print('\nself.did_pass =', self.did_pass)

    def test_it_works(self):
        assert True

    def test_it_doesnt_work(self):
        assert False

当我们运行它时,我们发现它打印出正确的测试失败/成功 bool

$ py.test --no-header --no-summary -qs

============================= test session starts =============================
collected 2 items                                                             

tests/tests.py::DescribeIt::test_it_doesnt_work FAILED
self.did_pass = False

tests/tests.py::DescribeIt::test_it_works PASSED
self.did_pass = True


========================= 1 failed, 1 passed in 0.02s =========================

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM