[Python-checkins] gh-100739: Respect mock spec when checking for unsafe prefixes (GH-100740)

miss-islington webhook-mailer at python.org
Wed Jan 4 18:11:51 EST 2023


https://github.com/python/cpython/commit/f49cc3c805dbc1bc54edeba3c248b875b3e6f3d3
commit: f49cc3c805dbc1bc54edeba3c248b875b3e6f3d3
branch: 3.10
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: miss-islington <31488909+miss-islington at users.noreply.github.com>
date: 2023-01-04T15:11:46-08:00
summary:

gh-100739: Respect mock spec when checking for unsafe prefixes (GH-100740)

(cherry picked from commit 7f1eefc6f4843f0fca60308f557a71af11d18a53)

Co-authored-by: Christian Klein <167265+cklein at users.noreply.github.com>
Co-authored-by: Nikita Sobolev <mail at sobolevn.me>

files:
A Misc/NEWS.d/next/Library/2023-01-04-09-53-38.gh-issue-100740.-j5UjI.rst
M Lib/unittest/mock.py
M Lib/unittest/test/testmock/testmock.py

diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index 7832092d4b98..7453dfa187e2 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -643,7 +643,7 @@ def __getattr__(self, name):
                 raise AttributeError("Mock object has no attribute %r" % name)
         elif _is_magic(name):
             raise AttributeError(name)
-        if not self._mock_unsafe:
+        if not self._mock_unsafe and (not self._mock_methods or name not in self._mock_methods):
             if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')):
                 raise AttributeError(
                     f"{name!r} is not a valid assertion. Use a spec "
diff --git a/Lib/unittest/test/testmock/testmock.py b/Lib/unittest/test/testmock/testmock.py
index fdba543b5351..535f9083b76c 100644
--- a/Lib/unittest/test/testmock/testmock.py
+++ b/Lib/unittest/test/testmock/testmock.py
@@ -1644,6 +1644,22 @@ def test_mock_unsafe(self):
         m.aseert_foo_call()
         m.assrt_foo_call()
 
+    # gh-100739
+    def test_mock_safe_with_spec(self):
+        class Foo(object):
+            def assert_bar(self):
+                pass
+
+            def assertSome(self):
+                pass
+
+        m = Mock(spec=Foo)
+        m.assert_bar()
+        m.assertSome()
+
+        m.assert_bar.assert_called_once()
+        m.assertSome.assert_called_once()
+
     #Issue21262
     def test_assert_not_called(self):
         m = Mock()
diff --git a/Misc/NEWS.d/next/Library/2023-01-04-09-53-38.gh-issue-100740.-j5UjI.rst b/Misc/NEWS.d/next/Library/2023-01-04-09-53-38.gh-issue-100740.-j5UjI.rst
new file mode 100644
index 000000000000..4753e7b40825
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2023-01-04-09-53-38.gh-issue-100740.-j5UjI.rst
@@ -0,0 +1 @@
+Fix ``unittest.mock.Mock`` not respecting the spec for attribute names prefixed with ``assert``.



More information about the Python-checkins mailing list