Skip to content

gh-76273: Fix autospec mocking of instance and class methods#146526

Draft
stephenfin wants to merge 1 commit intopython:mainfrom
stephenfin:bpo-32092
Draft

gh-76273: Fix autospec mocking of instance and class methods#146526
stephenfin wants to merge 1 commit intopython:mainfrom
stephenfin:bpo-32092

Conversation

@stephenfin
Copy link
Copy Markdown

@stephenfin stephenfin commented Mar 27, 2026

Currently, when patching instance / class methods with autospec, their self / cls arguments are not consumed, causing call asserts to fail (they expect an instance / class reference as the first argument).
Example:

from unittest import mock

class Something(object):
    def foo(self, a, b, c, d):
        pass

with mock.patch.object(Something, 'foo', autospec=True):
    s = Something()
    s.foo()

Fix this by skipping the first argument when presented with a method.

Based on #4476 with the changes to the Mock signature stripped out and left for a separate, follow-up PR.

Currently, when patching instance / class methods with autospec, their
self / cls arguments are not consumed, causing call asserts to fail
(they expect an instance / class reference as the first argument).
Example:

  from unittest import mock

  class Something(object):
      def foo(self, a, b, c, d):
          pass

  with mock.patch.object(Something, 'foo', autospec=True):
      s = Something()
      s.foo()

Fix this by skipping the first argument when presented with a method.

Based on python#4476

Signed-off-by: Stephen Finucane <stephen@that.guru>
Co-authored-by: Claudiu Belu <cbelu@cloudbasesolutions.com>
@johnslavik
Copy link
Copy Markdown
Member

Hi! Nice to see some work on this. Btw, we generally avoid force pushes.

@stephenfin
Copy link
Copy Markdown
Author

Btw, we generally avoid force pushes.

Understood. I've got a small bit more work to do this on to resolve the test_hmac_constructor_uses_builtin failure (we need to handle calling patch.object(cls, name, autospec=True, wraps=wraps) where wraps is unbound). If I push a patch will it be squashed on merge? I can't see anything in the contributor docs in relation to this.

@johnslavik
Copy link
Copy Markdown
Member

johnslavik commented Mar 27, 2026

If I push a patch will it be squashed on merge?

Yes, all PRs are squashed on merge.

I can't see anything in the contributor docs in relation to this.

I see! It's in https://devguide.python.org/getting-started/pull-request-lifecycle/#don-t-force-push. Maybe we can make it more visible elsewhere, what do you think? Let me know what you had read before you created the PR, maybe we can add it there :-) Thanks for saying that you didn't see that note.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants