Skip to content

Commit ea73246

Browse files
authored
Merge pull request #4740 from asottile/bugfix_4739
Fix `parametrize(... ids=<function>)` when the function returns non-strings
2 parents a1fcd6e + 4c7ddb8 commit ea73246

File tree

3 files changed

+20
-6
lines changed

3 files changed

+20
-6
lines changed

changelog/4739.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix ``parametrize(... ids=<function>)`` when the function returns non-strings.

src/_pytest/python.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1144,20 +1144,18 @@ def _find_parametrized_scope(argnames, arg2fixturedefs, indirect):
11441144

11451145
def _idval(val, argname, idx, idfn, item, config):
11461146
if idfn:
1147-
s = None
11481147
try:
1149-
s = idfn(val)
1148+
generated_id = idfn(val)
1149+
if generated_id is not None:
1150+
val = generated_id
11501151
except Exception as e:
11511152
# See issue https://github.com/pytest-dev/pytest/issues/2169
11521153
msg = "{}: error raised while trying to determine id of parameter '{}' at position {}\n"
11531154
msg = msg.format(item.nodeid, argname, idx)
11541155
# we only append the exception type and message because on Python 2 reraise does nothing
11551156
msg += " {}: {}\n".format(type(e).__name__, e)
11561157
six.raise_from(ValueError(msg), e)
1157-
if s:
1158-
return ascii_escaped(s)
1159-
1160-
if config:
1158+
elif config:
11611159
hook_id = config.hook.pytest_make_parametrize_id(
11621160
config=config, val=val, argname=argname
11631161
)

testing/python/metafunc.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,21 @@ def test_foo(arg):
418418
]
419419
)
420420

421+
def test_parametrize_ids_returns_non_string(self, testdir):
422+
testdir.makepyfile(
423+
"""\
424+
import pytest
425+
426+
def ids(d):
427+
return d
428+
429+
@pytest.mark.parametrize("arg", ({1: 2}, {3, 4}), ids=ids)
430+
def test(arg):
431+
assert arg
432+
"""
433+
)
434+
assert testdir.runpytest().ret == 0
435+
421436
def test_idmaker_with_ids(self):
422437
from _pytest.python import idmaker
423438

0 commit comments

Comments
 (0)