Pytest在testcase以外的类中获取测试信息。

问题描述 投票:0回答:1

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

我想在实用类中打印testcase名称和一些测试的标记。这些信息在一些contextmanager中可以得到吗?

python pytest contextmanager
1个回答
0
投票

你不能直接访问 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 变量被另一个测试覆盖(尽管这取决于实现--如果变量在测试运行期间被复制,它可能会工作)。在这种情况下,您可以直接在夹具或钩子函数中进行日志记录(根据您的用例,这可能是一个更好的主意)。

关于可用的测试节点属性的更多信息,你可以查看文档中的 请求节点.

© www.soinside.com 2019 - 2024. All rights reserved.