python
type_error
ai_generated
true
TypeError: 不支持 '<' 在 'int' 和 'str' 实例之间进行比较
TypeError: '<' not supported between instances of 'int' and 'str'
ID: python/pytest-parametrize-id-special-chars
80%修复率
85%置信度
0证据数
2024-08-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
向 `@pytest.mark.parametrize` 的 `ids=` 传入混合类型(如 ids=[1, 'two'])会使 pytest 在显示时排序它们,比较 int 与 str 时失败。
English
Passing mixed types as `ids=` to `@pytest.mark.parametrize` (e.g. ids=[1, 'two']) causes pytest to sort them for display, which fails when comparing int and str.
解决方案
-
95% 成功率
Cast all ids to strings: @pytest.mark.parametrize('n', [1, 2, 3], ids=lambda n: f'case-{n}') -
90% 成功率
Provide a callable for ids that returns unique strings: ids=lambda v: str(v).replace(' ', '_')
无效尝试
常见但无效的做法:
-
30% 失败
Works, but loses readability; long parameter values produce unreadable test IDs.
-
90% 失败
Sorting mixed types raises the same TypeError before pytest even sees it.