Skip to content

Commit 3345ac9

Browse files
authored
Merge pull request #1861 from nicoddemus/ids-invalid-type-msg
Improve error message when passing non-string ids to pytest.mark.parametrize
2 parents ea0feba + 972a5fb commit 3345ac9

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

CHANGELOG.rst

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,17 @@
33

44
*
55

6-
*
6+
* Improve error message when passing non-string ids to ``pytest.mark.parametrize`` (`#1857`_).
7+
Thanks `@okken`_ for the report and `@nicoddemus`_ for the PR.
78

89
*
910

1011
*
1112

1213

14+
.. _#1857: https://github.com/pytest-dev/pytest/issues/1857
15+
16+
1317
3.0.1
1418
=====
1519

_pytest/python.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -778,6 +778,7 @@ def parametrize(self, argnames, argvalues, indirect=False, ids=None,
778778
"""
779779
from _pytest.fixtures import scopes
780780
from _pytest.mark import extract_argvalue
781+
from py.io import saferepr
781782

782783
unwrapped_argvalues = []
783784
newkeywords = []
@@ -831,9 +832,14 @@ def parametrize(self, argnames, argvalues, indirect=False, ids=None,
831832
if callable(ids):
832833
idfn = ids
833834
ids = None
834-
if ids and len(ids) != len(argvalues):
835-
raise ValueError('%d tests specified with %d ids' %(
836-
len(argvalues), len(ids)))
835+
if ids:
836+
if len(ids) != len(argvalues):
837+
raise ValueError('%d tests specified with %d ids' %(
838+
len(argvalues), len(ids)))
839+
for id_value in ids:
840+
if id_value is not None and not isinstance(id_value, str):
841+
msg = 'ids must be list of strings, found: %s (type: %s)'
842+
raise ValueError(msg % (saferepr(id_value), type(id_value).__name__))
837843
ids = idmaker(argnames, argvalues, idfn, ids, self.config)
838844
newcalls = []
839845
for callspec in self._calls or [CallSpec2(self)]:

testing/python/metafunc.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -916,6 +916,18 @@ def test_temp(temp):
916916
result = testdir.runpytest()
917917
result.stdout.fnmatch_lines(['* 1 skipped *'])
918918

919+
def test_parametrized_ids_invalid_type(self, testdir):
920+
"""Tests parametrized with ids as non-strings (#1857)."""
921+
testdir.makepyfile('''
922+
import pytest
923+
924+
@pytest.mark.parametrize("x, expected", [(10, 20), (40, 80)], ids=(None, 2))
925+
def test_ids_numbers(x,expected):
926+
assert x * 2 == expected
927+
''')
928+
result = testdir.runpytest()
929+
result.stdout.fnmatch_lines(['*ids must be list of strings, found: 2 (type: int)*'])
930+
919931
def test_parametrize_with_identical_ids_get_unique_names(self, testdir):
920932
testdir.makepyfile("""
921933
import pytest

0 commit comments

Comments
 (0)