python - Pytest 在测试用例以外的类中获取测试信息
问题描述
我正在使用 pytest 编写一个测试框架。有没有办法在测试用例以外的类中获取测试用例对象。例如实用程序类。
我想为实用程序类中的测试打印测试用例名称和一些标记。这些信息在某些上下文管理器中可用吗?
解决方案
如果您不在测试夹具或钩子函数内,则无法直接访问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
变量被另一个测试覆盖而不起作用(尽管这取决于实现 - 如果在测试运行期间复制变量,它可能会起作用)。在这种情况下,您可以直接在夹具或钩子函数中进行日志记录(这通常可能是一个更好的主意,具体取决于您的用例)。
有关可用测试节点属性的更多信息,您可以查看请求节点的文档。
推荐阅读
- react-native - 如何在通过电缆连接到笔记本电脑的 android 设备中运行 ignite 应用程序?
- javascript - 正则表达式 - 在给定数量的 3 个字母序列之后,如何匹配特定的 3 个字母序列?
- gradle - gradle buildscript“name”变量解析不起作用
- node.js - 在aws pinpoint(NodeJS)中,当用户触发客户事件时如何触发电子邮件
- ruby-on-rails - Rails 应用程序的每个请求的入口点是什么?
- python-3.x - 发送带有cookie的post请求时遇到问题----urllib.error.HTTPError: HTTP Error 503: Service Unavailable
- c++ - 编译cpp代码时出错:collect2:错误:ld返回1退出状态
- r - R如何将结果以一种方式绘制
- julia - 鉴于 Zygote 不支持突变,Recur 如何摆脱它?
- testing - 赛普拉斯导入规范文件