Skip to content

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

Closed

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 ...

Activity

  1. added 12 commits that reference this issue on Apr 15, 2025
    1d10dfb
    edaf3ef
    c3423a8
    9edb5a6
    9383685
    4bd2b0a
    a9f881d
    4989399
    c666e83
    a9e5dc7
    f0df140
    da6a467
  2. added 2 commits that reference this issue on Apr 19, 2025
    c9c9dc0
    7c34357
  3. added a commit that references this issue on Apr 20, 2025
    61c204a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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