python type_error ai_generated true

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

ID: python/pytest-parametrize-index-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-06-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.0.0 active
8.0.0 active

Root Cause

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

中文

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

Workarounds

  1. 95% success 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% success 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.

Dead Ends

Common approaches that don't work:

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

    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% fail

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