Skip to content

gh-94478: Propagate unsafe=True in patch, patch.object, and create_autospec - #162997

Open
gastondana627 wants to merge 1 commit into
python:mainfrom
gastondana627:gh-94478-propagate-unsafe
Open

gastondana627 wants to merge 1 commit into
python:mainfrom
gastondana627:gh-94478-propagate-unsafe

Conversation

@gastondana627

Copy link
Copy Markdown

Problem

Since fdb9efce6a (bpo-41877), unsafe=False was extracted as an explicit keyword-only parameter in _patch.__init__, patch, patch.object, and create_autospec. Because unsafe was no longer in kwargs, passing unsafe=True disabled typo checking in _check_spec_arg_typos but was never propagated to the created mocks (leaving _mock_unsafe = False) or copied by _patch.copy().

Solution

  • Store self.unsafe = unsafe on _patch and pass unsafe=self.unsafe in _patch.copy() so class decoration preserves unsafe.
  • In _patch.__enter__, forward unsafe=self.unsafe when instantiating NonCallableMock subclasses (so new=... and non-Mock new_callable=... such as dict are unaffected) and when calling create_autospec(...).
  • In create_autospec, pass unsafe=unsafe directly to Klass(...) (after descriptor handling) and to the recursive mock.return_value = create_autospec(..., instance=True, unsafe=unsafe) call.

Supersedes stale PR #94479 (adds _patch.copy() handling, avoids mutating self.kwargs when new=... or non-Mock new_callable is used, preserves unsafe across descriptor specs and create_autospec class return_value, and includes a NEWS entry).

Tests

  • Extended test_misspelled_arguments and added test_patch_and_autospec_propagate_unsafe in Lib/test/test_unittest/testmock/testmock.py.
  • Verified with ./python.exe -m test test_unittest and ./python.exe -W error -m unittest discover -s Lib/test/test_unittest/testmock.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant