python config_error ai_generated true

ValueError: Incorrect number of ids: 3 instead of 2

ID: python/pytest-mark-parametrize-ids-mismatch

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —
7.x active — — —
8.x active — — —

Root Cause

In @pytest.mark.parametrize, the `ids` list length must match the number of parameter sets (not the number of arguments). Supplying too many or too few ids raises ValueError.

generic

中文

在 @pytest.mark.parametrize 中,`ids` 列表长度必须与参数集的数量匹配(而不是参数个数)。提供过多或过少的 id 会引发 ValueError。

Workarounds

  1. 98% success
    @pytest.mark.parametrize(
        'a,b',
        [(1, 2), (3, 4)],
        ids=['small', 'large'],  # 2 ids for 2 tuples
    )
    def test_add(a, b):
        ...
  2. 90% success
    def idfn(val):
        return f'v={val}'
    
    @pytest.mark.parametrize('x', [1, 2, 3], ids=idfn)
    def test_x(x):
        ...

Dead Ends

Common approaches that don't work:

  1. 85% fail

    pytest expects an iterable of id strings (or a callable); a single string is treated as an iterable of characters, producing confusing ids and possibly a length mismatch.

  2. 30% fail

    Works but loses readable test names; not a real fix if the user needs custom ids for reporting.