]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-100739: Respect mock spec when checking for unsafe prefixes (#100740)
authorChristian Klein <167265+cklein@users.noreply.github.com>
Wed, 4 Jan 2023 22:31:29 +0000 (23:31 +0100)
committerGitHub <noreply@github.com>
Wed, 4 Jan 2023 22:31:29 +0000 (22:31 +0000)
Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
Lib/test/test_unittest/testmock/testmock.py
Lib/unittest/mock.py
Misc/NEWS.d/next/Library/2023-01-04-09-53-38.gh-issue-100740.-j5UjI.rst [new file with mode: 0644]

index 8a92490137f9a721f76f8a8cda4ec5a2c7cb32cc..b224f87fa3e4a1ab31127b5e3ae60d00ff386e32 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()
index 994947cad518f9908a403b2794621048f30fb951..47928e56485035478b82a37dbc3923c69628d16e 100644 (file)
@@ -652,7 +652,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 "
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``.