Skip to main content
 首页 » 编程设计

python之如何在 pytest 中使用具有不同数据结构的不同 fixture 进行一次测试

2025年05月04日10虾米姐

我有一个测试,目前使用的是冒烟测试装置,它覆盖了完整测试装置的一个子集。对于测试的一部分,我想使用冒烟测试 fixture 进行测试,但是如果我想进行大型测试,我想使用采用不同数据结构的完整测试 fixture (在下面的例子,small 使用元组,big 使用列表)。目前,我使用如下所示的一个 fixture 进行测试,但我无法弄清楚如何在具有不同数据结构的 fixture 之间进行互换。

import pytest 
 
@pytest.fixture(params=[ 
    (1, 1), 
    (2, 2) 
]) 
def small_fixture_of_numbers(request): 
    # returns a list of pairs of numbers for smoke testing 
    return request.param 
 
@pytest.fixture(params=[ 
    1, 2, 3, 4 
]) 
def big_fixture_of_numbers(request): 
    # returns the full list of numbers for full-scale testing 
    return request.param 
 
def test_addition(small_fixture_of_numbers): 
    (x, y) = small_fixture_of_numbers 
    total = x + y 
    assert total > 2 

请您参考如下方法:

以不同方式运行相同的测试是不明智的。如果不同的运行由不同的数据结构支持,则更不用说。

测试用例的整体理念是,它为代码每次都在相同条件下运行提供了一个稳定的环境。测试和 fixture 应该是固定的伙伴,因此代码行为的变化是唯一的因素。

换句话说,你似乎需要两个不同的测试。您应该选择运行什么测试,而不是如何运行它。