如何创建可返回参数组合的pytest.fixture适配算法测试场景?
Absolutely! You don't need to create separate fixtures for each prefix like A, B, etc. Instead, you can build a single (or small set of) fixtures that generate all the required parameter combinations, saving you from repetitive code and making your test suite easier to maintain.
Here are two straightforward approaches to achieve this:
Approach 1: Reuse Your Existing year Fixture with a Prefix Fixture
Since you already have a year fixture covering 2018-2024, pair it with a new prefix fixture to generate all combinations of prefixes and years:
import pytest # Your existing year fixture @pytest.fixture(params=range(2018, 2025)) def year(request): return request.param # Fixture for all prefixes you want to test (including empty string if needed) @pytest.fixture(params=['A', 'B', 'C', '']) def prefix(request): return request.param # Combined fixture that returns the formatted string (or tuple, if preferred) @pytest.fixture def year_string(prefix, year): # Handle empty prefix case gracefully return f"{prefix}_{year}" if prefix else str(year)
In your tests, use year_string to automatically iterate over every possible combination:
def test_algorithm_single_input(year_string): # Test your algorithm with individual input strings result = your_algorithm([year_string]) assert result == expected_result_for_this_input
If you want to test pre-defined full lists (like your examples: ['A_2018', 'B_2019', 'C_2018'], [], ['A_2018']), create a dedicated fixture for those:
@pytest.fixture(params=[ ['A_2018', 'B_2019', 'C_2018'], [], ['A_2018'] ]) def input_list(request): return request.param def test_algorithm_with_lists(input_list): result = your_algorithm(input_list) assert result == expected_result_for_this_list
Approach 2: Generate All Combinations in One Fixture Using itertools.product
If you prefer condensing the logic into one place, use itertools.product to generate every permutation of prefixes and years directly:
import pytest from itertools import product @pytest.fixture(params=product(['A', 'B', 'C', ''], range(2018, 2025))) def year_prefix_combination(request): prefix, year = request.param # Return formatted string or raw tuple based on your needs return f"{prefix}_{year}" if prefix else str(year)
This fixture produces the same combinations as Approach 1 but keeps all the logic in a single fixture.
Both approaches eliminate repetitive per-prefix fixtures and make it trivial to adjust prefixes or year ranges later.
内容的提问来源于stack exchange,提问作者thebjorn

