首页 > 解决方案 > Pytest 在测试用例以外的类中获取测试信息

问题描述

我正在使用 pytest 编写一个测试框架。有没有办法在测试用例以外的类中获取测试用例对象。例如实用程序类。

我想为实用程序类中的测试打印测试用例名称和一些标记。这些信息在某些上下文管理器中可用吗?

标签: pythonpytestcontextmanager

解决方案


如果您不在测试夹具或钩子函数内,则无法直接访问pytest测试属性,因为没有固定的测试用例类,如unittest. 您最好的选择可能是在夹具中获取此信息并将其全局存储以供从实用程序函数访问:

testinfo={} 

@pytest.fixture(autouse=True)
def test_info(request):
    global testinfo
    testinfo['name'] = request.node.name
    testinfo['markers'] = [m.name for m in request.node.iter_markers()]
    ...
    yield  # the information is stored at test start... 
    testinfo = {}  # ... and removed on test teardown 

def utility_func():
    if testinfo:
        print(f"Name: {testinfo['name']} Markers: {testinfo['markers']}")
   ... 

或者,如果您使用测试类,则相同:

class TestSomething:
    def setup_method(self):
        self.testinfo = {}

    @pytest.fixture(autouse=True)
    def info(self, request):
        self.testinfo['name'] = request.node.name
        self.testinfo['markers'] = [m.name for m in
                                    request.node.iter_markers()]
        yield  # the information is stored at test start...
        self.testinfo = {}  # ... and removed on test teardown

    def utility_func(self):
        if self.testinfo:
            print(f"Name: {self.testinfo['name']} Markers:"
                  f" {self.testinfo['markers']}")

    @pytest.mark.test_marker
    def test_something(self):
        self.utility_func()
        assert True

这将显示输出:

Name: test_something Markers: ['test_marker']

如果您在测试执行期间调用实用程序函数,这将起作用 - 否则将不会设置任何值。

但是请注意,这只有在您同步执行测试时才能可靠地工作。如果使用pytest-xdist或类似的工具进行异步测试执行,这可能由于testinfo变量被另一个测试覆盖而不起作用(尽管这取决于实现 - 如果在测试运行期间复制变量,它可能会起作用)。在这种情况下,您可以直接在夹具或钩子函数中进行日志记录(这通常可能是一个更好的主意,具体取决于您的用例)。

有关可用测试节点属性的更多信息,您可以查看请求节点的文档。


推荐阅读