python - Pytest:根据 config.ini 中指定的次数运行所有测试
问题描述
这是我编写测试的方式:
**config.ini**
idlist: 1
Class MyConfig:
def __init__(self):
self.id = config.idlist
....
**conftest.py**
@pytest.fixture(scope='module')
def obj()
myobj = new MyConfig()
yield myobj
@pytest.fixture(scope='module')
def get_id(obj)
yield obj.id
**test_mytests.py**
def test_a_sample_test(get_id):
assert get_id == 1
def test_a_sample_even test(get_id):
assert get_id % 2 == 0
现在,我想将 idlist(来自 config.ini)更改为如下数字列表 idlist = [1, 2, 3, 4, ....]
我希望能够test_
根据 idlist 中的 id 数量自动触发运行以运行所有以开头的测试。如下图
new config.ini
idlist: id1, id2, id3, id4, ... idN
def get_id(obj):
for anId in obj.id
yield anId **<--- notice that the id's change.**
最后测试..
**test_mytests.py**
def test_a_sample_test(get_id):
assert get_id == 1
def test_a_sample_even test(get_id):
assert get_id % 2 == 0
我想要:
- 每次调用 get_id 给我一个不同的 id
- 由于 id 已更改,因此应为 get_id“产生”的每个 id 运行 2 个测试。(基本上为每个 id 重复整个测试套件/会话)
我怎样才能做到这一点?
我不知道 id 列表以便在每次测试之前执行 pytest.mark.parameterize() 因为 id 的变化并且不是恒定的。
解决方案
您可以使用@pytest.mark.parametrize
参数化测试功能:
内置
pytest.mark.parametrize
装饰器可以对测试函数的参数进行参数化。这是一个测试函数的典型示例,它实现了检查某个输入是否导致预期输出
# take the following example and adjust to your needs
import pytest
@pytest.mark.parametrize("_id,expected", [
(1, False),
(2, True),
(3, False),
])
def test_a_sample_even(_id, expected):
assert expected == is_even(_id)
推荐阅读
- tensorflow - 在张量流中,我是否必须设置一些特殊的东西来在训练时忽略零填充值?还是自动的?
- java - Android Studio Map setOnMarkerClickListener 无法处理片段
- flutter - FlutterFire Firestore 2.0.0 的流式集合迁移问题
- javascript - 如何在 Angular 中集成 WinBox JS?
- r - 当变量存储为因子与数值时,使用 hetcor 的四弦相关性不同
- javascript - 如何在 Javascript 中显示 HTML 文本
- laravel - Laravel 7 通过 AWS SES 发送电子邮件
- r - 导出 Hmisc::describe 输出到 excel/csv
- r - 使用包时“for”循环在 R 中不起作用
- apache-spark - 如何获取不为空的列名