python type_error ai_generated true

索引错误:在带有 indirect=True 的参数化测试中列表索引超出范围

IndexError: list index out of range in parametrized test with indirect=True

ID: python/pytest-parametrize-index-error

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-06-01首次发现

版本兼容性

版本状态引入弃用备注
7.0.0 active
8.0.0 active

根因分析

当使用pytest.mark.parametrize并设置indirect=True时,提供的fixture值数量与测试参数数量不匹配,导致访问参数列表时出现索引错误。

English

When using pytest.mark.parametrize with indirect=True, the number of fixture values provided does not match the number of test arguments, causing an index error when accessing the parameter list.

generic

解决方案

  1. 95% 成功率 Ensure the number of values in the parametrize list matches the number of fixture arguments
    If you have two fixtures (fixture1, fixture2) with indirect=True, provide a list of tuples: 
    @pytest.mark.parametrize('fixture1,fixture2', [(val1, val2), (val3, val4)], indirect=True)
    def test_example(fixture1, fixture2):
        ...
    Each tuple must have exactly two elements.
  2. 85% 成功率 Use indirect for only specific fixtures by specifying them explicitly
    @pytest.mark.parametrize('fixture1', [val1, val2], indirect=['fixture1'])
    def test_example(fixture1, other_arg):
        ...
    This avoids index errors for mixed indirect and direct parameters.

无效尝试

常见但无效的做法:

  1. Removing indirect=True from the parametrize decorator 60% 失败

    This changes how fixtures are injected, potentially breaking the test logic that depends on indirect fixture configuration.

  2. Adding extra dummy values to the parameter list without adjusting fixture definitions 50% 失败

    This may cause fixture resolution failures or incorrect test behavior if the extra values are not handled.