Skip to content

Bug in _pytest.compat.getfuncargnames() corrupts fixture handling for test methods w/ positional-only self parameter #13376

@purplezimmermann

Description

@purplezimmermann
  • a detailed description of the bug or problem you are having
  • Doesn't depend on specific packages [ ] output of pip list from the virtual environment you are using
  • Isn't related to specific Pytest versions [ ] pytest and operating system versions
  • minimal example if possible

Basic example

Passing:

import pytest

@pytest.fixture
def value_fixture():
    return 'value'

class TestClass:

    def test_value(self, value_fixture):
        assert value_fixture == 'value'

Failing:

import pytest


@pytest.fixture
def value_fixture():
    return 'value'


class TestClass:

    def test_value(self, /, value_fixture):
        assert value_fixture == 'value'
  • Result:
pyfuncitem = <Function test_value>

    @hookimpl(trylast=True)
    def pytest_pyfunc_call(pyfuncitem: Function) -> object | None:
        testfunction = pyfuncitem.obj
        if is_async_function(testfunction):
            async_fail(pyfuncitem.nodeid)
        funcargs = pyfuncitem.funcargs
        testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}
>       result = testfunction(**testargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^
E       TypeError: TestClass.test_value() missing 1 required positional argument: 'value_fixture'

Reason

_pytest.compat.getfuncargnames() collects keyword-callable parameters as fixture-receiving arguments:

arg_names = tuple(
p.name
for p in parameters.values()
if (
p.kind is Parameter.POSITIONAL_OR_KEYWORD
or p.kind is Parameter.KEYWORD_ONLY
)
and p.default is Parameter.empty
)

Then it removes the first one – supposedly 'self' – if given function is a non-static method:

if (
# Not using `getattr` because we don't want to resolve the staticmethod.
# Not using `cls.__dict__` because we want to check the entire MRO.
cls
and not isinstance(
inspect.getattr_static(cls, name, default=None), staticmethod
)
):
arg_names = arg_names[1:]

Yet, if 'self' is defined as positional only, it wasn't contained in arg_names before removal ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions