Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将测试状态传递给it';s拆卸,最好通过夹具_Python_Unit Testing_Pytest - Fatal编程技术网

Python 如何将测试状态传递给it';s拆卸,最好通过夹具

Python 如何将测试状态传递给it';s拆卸,最好通过夹具,python,unit-testing,pytest,Python,Unit Testing,Pytest,我有一个BaseTest类,它已经分解了,我想在内部分解一个表示测试是否失败的变量 我试着看了很多旧的帖子,但我无法实现它们,因为它们是钩子或钩子和固定装置的混合体,在我这方面有些东西不起作用 这样做的最佳实践是什么 我最后试过的是- @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item): outcome = yield rep = outcome.get_res

我有一个BaseTest类,它已经分解了,我想在内部分解一个表示测试是否失败的变量

我试着看了很多旧的帖子,但我无法实现它们,因为它们是钩子或钩子和固定装置的混合体,在我这方面有些东西不起作用

这样做的最佳实践是什么

我最后试过的是-

@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 
但请求根本没有属性,它是一种方法。 也试过-

@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\u status这样做吗

重要的是,无论是否失败,拆卸都要有bool参数,并且不要在拆卸之外做任何事情


谢谢

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

传递给
pytest\u runtest\u makereport
参数上似乎有一个私有的
\u testcase
属性,该属性包含测试用例的实例。我们可以在其上设置一个属性,然后可以在
teardown\u方法中访问该属性

# 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
这里有一个小小的示例测试用例

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 =========================

谢谢正是我想要的