python - Pytest:为未参数化的测试提供 id
问题描述
我想id
与我运行的任何 pytest 关联,无论它是否参数化。有没有办法为未参数化的测试提供 id,使得 nodeid 看起来像my_test[my_id]
ie 与参数化测试一致的东西?
解决方案
除此之外没有内置机制parametrize
- 也就是说,您可以通过修改函数的模块范围名称来构建一个〜模拟它的东西:
def test_thing(): pass
# need to use `globals()` since `[` isn't a valid identifier
globals()['test_thing[my_id]'] = test_thing
# delete the old test so it isn't run
del test_thing
$ pytest -v t3.py
...
collected 1 item
t3.py::test_thing[my_id] PASSED [100%]
============================== 1 passed in 0.00s ===============================
或者也许一个神奇的装饰器更适合你的风格:
import sys
def name_test(testid):
def decorator(func):
setattr(sys.modules[func.__module__], testid, func)
return None # need to avoid double-discovery
return decorator
@name_test('test_thing[my_id]')
def test_thing():
pass
$ pytest -v t2.py
...
collected 1 item
t2.py::test_thing[my_id] PASSED [100%]
============================== 1 passed in 0.00s ===============================
但是,使用参数化有一个相当简单且不那么棘手的方法:
import pytest
@pytest.mark.parametrize('_', (pytest.param(0, id='my_id'),))
def test_thing(_): pass
这会生成一个带有自定义 id 的单个参数化案例,_
之所以选择它是因为未使用该值
免责声明:我是 pytest 核心开发人员
推荐阅读
- c# - 在列表中强制输入值(搜索时键入)?
- python - 如何使用滑动窗口调整 PyTorch 张量的大小?
- python - 在数据框列 Python 中查找和删除子字符串
- r - 从 XML 文件中提取数据 - R
- github - 如何将 GitHub 存储库连接到 Google Data Studio?
- ios - 我的节目没有推到下一个屏幕,只是出现了一个奇怪的空白空间弹出窗口。我不明白这是怎么回事
- java - 如何在 dsl 查询/java 高级别的客户端查询中包含 kql
- c# - 如何在 Unity 3D 中缩放父游戏对象而不缩放子游戏对象?
- excel - 基于数据透视表在图表中自动添加行
- sql - 在 PostgreSQL 中查找具有多个用户和重叠时间范围的时间戳中的差距