]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-100739: Respect mock spec when checking for unsafe prefixes (GH-100740)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Wed, 4 Jan 2023 23:08:37 +0000 (15:08 -0800)
committerGitHub <noreply@github.com>
Wed, 4 Jan 2023 23:08:37 +0000 (15:08 -0800)
(cherry picked from commit 7f1eefc6f4843f0fca60308f557a71af11d18a53)

Co-authored-by: Christian Klein <167265+cklein@users.noreply.github.com>
Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
Lib/unittest/mock.py
Lib/unittest/test/testmock/testmock.py
Misc/NEWS.d/next/Library/2023-01-04-09-53-38.gh-issue-100740.-j5UjI.rst [new file with mode: 0644]

index 6a1c932081e0f5ccd74c81d2dbda98d512afb7a2..fa0bd9131a21e7c88ad64c740e356a08abd5ad53 100644 (file)
@@ -647,7 +647,7 @@ class NonCallableMock(Base):
                 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 "
index c99098dc4ea86a50b418c6eb9462e1ffc01d13b2..eaae22e854e9493e2d2d37fca4f14c12c74068cd 100644 (file)
@@ -1652,6 +1652,22 @@ class MockTest(unittest.TestCase):
         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 (file)
index 0000000..4753e7b
--- /dev/null
@@ -0,0 +1 @@
+Fix ``unittest.mock.Mock`` not respecting the spec for attribute names prefixed with ``assert``.