[英]Pytest getting test Information in classes other than testcase
I am writing a test framework using pytest.我正在使用 pytest 编写一个测试框架。 Is there a way to get testcase object in classes other than testcase.有没有办法在测试用例以外的类中获取测试用例 object。 For example utility classes.例如实用程序类。
I want to print the testcase name and some markers for the test in utility classes.我想为实用程序类中的测试打印测试用例名称和一些标记。 Are these information available in some contextmanager?这些信息在某些上下文管理器中可用吗?
You cannot directly access pytest
test properties if you are not inside a test fixture or a hook function, as there is no fixed test case class as in unittest
.如果您不在测试夹具或挂钩 function 内,则无法直接访问pytest
测试属性,因为在unittest
中没有固定的测试用例 class。 Your best bet is probably to get this information in a fixture and store it globally for access from a utility function:您最好的选择可能是在夹具中获取此信息并将其存储在全局范围内,以便从实用程序 function 访问:
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']}")
...
Or, the same if you use a test class:或者,如果您使用测试 class,则相同:
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
This will show the output:这将显示 output:
Name: test_something Markers: ['test_marker']
This will work if you call the utility function during test execution - otherwise no value will be set.如果您在测试执行期间调用实用程序 function 这将起作用 - 否则将不会设置任何值。
Note however that this will only work reliably if you execute the test synchronously.但是请注意,这只有在您同步执行测试时才能可靠地工作。 If using pytest-xdist
or similar tools for asynchronous test execution, this may not work due to the testinfo
variable being overwitten by another test (though that depends on the implementation - it may work, if the variables are copied during a test run).如果使用pytest-xdist
或类似工具进行异步测试执行,这可能无法正常工作,因为testinfo
变量被另一个测试覆盖(尽管这取决于实现 - 如果在测试运行期间复制变量,它可能会起作用)。 In that case you can to do the logging directly in the fixture or hook function (which may generally be a better idea, depending on your use case).在这种情况下,您可以直接在夹具或挂钩 function 中进行日志记录(这通常可能是一个更好的主意,具体取决于您的用例)。
For more information about available test node properties you can check the documentation of a request node .有关可用测试节点属性的更多信息,您可以查看请求节点的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.