Skip to content

Spying on a cached method through its class drops self #657

Open

Description

@HocVoNgThai

Spying on an instance method decorated with functools.lru_cache or functools.cache through its class breaks calls through an instance: the spy does not bind self, so a previously valid call raises TypeError. Spying on the instance directly works.

from functools import lru_cache


def test_cached_method(mocker):
    class Worker:
        @lru_cache(maxsize=128)
        def calculate(self, value):
            return value * 2

    worker = Worker()
    assert worker.calculate(3) == 6
    spy = mocker.spy(Worker, "calculate")
    assert worker.calculate(3) == 6
    spy.assert_called_once_with(worker, 3)

The second call raises TypeError: ...calculate() missing 1 required positional argument: 'value'. Expected: it returns 6, preserves caching, and records the instance and argument like a spy on an ordinary instance method.

Reproduced on Linux with Python 3.12.16 and pytest-mock main 163f3221165929d64ac6549f693ea34edeb2b95d, using both unittest.mock and the standalone mock backend.

Activity

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