diff --git a/_pytest/python.py b/_pytest/python.py index 650171a9e9c..57ebcfbb32e 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -933,7 +933,7 @@ def _idval(val, argname, idx, idfn, config=None): return ascii_escaped(val.pattern) elif enum is not None and isinstance(val, enum.Enum): return str(val) - elif isclass(val) and hasattr(val, '__name__'): + elif (isclass(val) or isfunction(val)) and hasattr(val, '__name__'): return val.__name__ return str(argname) + str(idx) diff --git a/changelog/2976.trivial b/changelog/2976.trivial new file mode 100644 index 00000000000..5f767dd2740 --- /dev/null +++ b/changelog/2976.trivial @@ -0,0 +1 @@ +Change parametrized automatic test id generation to use the ``__name__`` attribute of functions instead of the fallback argument name plus counter. diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index 2ffb7bb5da2..0ed9f56bfee 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -235,6 +235,25 @@ def test_bytes_idval(self): for val, expected in values: assert _idval(val, 'a', 6, None) == expected + def test_class_or_function_idval(self): + """unittest for the expected behavior to obtain ids for parametrized + values that are classes or functions: their __name__. + """ + from _pytest.python import _idval + + class TestClass: + pass + + def test_function(): + pass + + values = [ + (TestClass, "TestClass"), + (test_function, "test_function"), + ] + for val, expected in values: + assert _idval(val, 'a', 6, None) == expected + @pytest.mark.issue250 def test_idmaker_autoname(self): from _pytest.python import idmaker