diff options
| author | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2019-12-08 22:59:23 -0800 |
|---|---|---|
| committer | Chris Withers <chris@withers.org> | 2019-12-09 06:59:23 +0000 |
| commit | 41973c99fdfdc78315e819661e279bdcc2f058b1 (patch) | |
| tree | 3207800340e78a77411ff53a141b5c85f62476c4 | |
| parent | 9baa870c27b54c26f9dd292c26936b70bdb64a06 (diff) | |
| download | cpython-git-41973c99fdfdc78315e819661e279bdcc2f058b1.tar.gz | |
bpo-38669: patch.object now raises a helpful error (GH17511)
This means a clearer message is now shown when patch.object is called with two string arguments, rather than a class and a string argument.
(cherry picked from commit cd90a52983db34896a6335a572d55bdda274778f)
Co-authored-by: Elena Oat <oat.elena@gmail.com>
| -rw-r--r-- | Lib/unittest/mock.py | 4 | ||||
| -rw-r--r-- | Lib/unittest/test/testmock/testpatch.py | 4 | ||||
| -rw-r--r-- | Misc/NEWS.d/next/Tests/2019-11-04-02-54-16.bpo-38669.pazXZ8.rst | 1 |
3 files changed, 9 insertions, 0 deletions
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index 2b9e7f14a7..213e596629 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -1492,6 +1492,10 @@ def _patch_object( When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` for choosing which methods to wrap. """ + if type(target) is str: + raise TypeError( + f"{target!r} must be the actual object to be patched, not a str" + ) getter = lambda: target return _patch( getter, attribute, new, spec, create, diff --git a/Lib/unittest/test/testmock/testpatch.py b/Lib/unittest/test/testmock/testpatch.py index 6358154b3e..7453c4902a 100644 --- a/Lib/unittest/test/testmock/testpatch.py +++ b/Lib/unittest/test/testmock/testpatch.py @@ -112,6 +112,10 @@ class PatchTest(unittest.TestCase): self.assertEqual(Something.attribute, sentinel.Original, "patch not restored") + def test_patchobject_with_string_as_target(self): + msg = "'Something' must be the actual object to be patched, not a str" + with self.assertRaisesRegex(TypeError, msg): + patch.object('Something', 'do_something') def test_patchobject_with_none(self): class Something(object): diff --git a/Misc/NEWS.d/next/Tests/2019-11-04-02-54-16.bpo-38669.pazXZ8.rst b/Misc/NEWS.d/next/Tests/2019-11-04-02-54-16.bpo-38669.pazXZ8.rst new file mode 100644 index 0000000000..5060ecf2dc --- /dev/null +++ b/Misc/NEWS.d/next/Tests/2019-11-04-02-54-16.bpo-38669.pazXZ8.rst @@ -0,0 +1 @@ +Raise :exc:`TypeError` when passing target as a string with :meth:`unittest.mock.patch.object`.
\ No newline at end of file |
