首页 > 解决方案 > 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

我想要:

  1. 每次调用 get_id 给我一个不同的 id
  2. 由于 id 已更改,因此应为 get_id“产生”的每个 id 运行 2 个测试。(基本上为每个 id 重复整个测试套件/会话)

我怎样才能做到这一点?

我不知道 id 列表以便在每次测试之前执行 pytest.mark.parameterize() 因为 id 的变化并且不是恒定的。

标签: pythonpython-3.xpytest

解决方案


您可以使用@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)

推荐阅读