]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-35022: unittest.mock.MagicMock now also supports __fspath__ (GH-9960)
authorMax Bélanger <aeromax@gmail.com>
Thu, 25 Oct 2018 21:48:58 +0000 (14:48 -0700)
committerVictor Stinner <vstinner@redhat.com>
Thu, 25 Oct 2018 21:48:58 +0000 (23:48 +0200)
The MagicMock class supports many magic methods, but not __fspath__. To ease
testing with modules such as os.path, this function is now supported by default.

Doc/library/unittest.mock.rst
Lib/unittest/mock.py
Lib/unittest/test/testmock/testmagicmethods.py
Misc/NEWS.d/next/Library/2018-10-18-17-57-28.bpo-35022.KeEF4T.rst [new file with mode: 0644]

index 136804cfc2c88d9a199045ef5d1c0d0347af4607..0ae29546586a0af81efd6009981f17141f51ed85 100644 (file)
@@ -1699,6 +1699,10 @@ The full list of supported magic methods is:
 * Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
 * Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
   ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
+* File system path representation: ``__fspath__``
+
+.. versionchanged:: 3.8
+   Added support for :func:`os.PathLike.__fspath__`.
 
 
 The following methods exist but are *not* supported as they are either in use
index 6b7f293bc5e08c046612e6039759817d5b306ad1..1a6c1a606c5a257211e460033d8e0cb38a50f37b 100644 (file)
@@ -1713,6 +1713,7 @@ magic_methods = (
     "complex int float index "
     "round trunc floor ceil "
     "bool next "
+    "fspath "
 )
 
 numerics = (
@@ -1760,6 +1761,7 @@ _calculate_return_value = {
     '__hash__': lambda self: object.__hash__(self),
     '__str__': lambda self: object.__str__(self),
     '__sizeof__': lambda self: object.__sizeof__(self),
+    '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
 }
 
 _return_values = {
index 5ab95978f60db218ccef74d7b59eb4cbca0e655b..69dfe60f7eaed2b41eb167e66a3ea1fee994f7af 100644 (file)
@@ -1,5 +1,6 @@
 import math
 import unittest
+import os
 import sys
 from unittest.mock import Mock, MagicMock, _magics
 
@@ -293,6 +294,15 @@ class TestMockingMagicMethods(unittest.TestCase):
         # how to test __sizeof__ ?
 
 
+    def test_magic_methods_fspath(self):
+        mock = MagicMock()
+        expected_path = mock.__fspath__()
+        mock.reset_mock()
+
+        self.assertEqual(os.fspath(mock), expected_path)
+        mock.__fspath__.assert_called_once()
+
+
     def test_magic_methods_and_spec(self):
         class Iterable(object):
             def __iter__(self):
diff --git a/Misc/NEWS.d/next/Library/2018-10-18-17-57-28.bpo-35022.KeEF4T.rst b/Misc/NEWS.d/next/Library/2018-10-18-17-57-28.bpo-35022.KeEF4T.rst
new file mode 100644 (file)
index 0000000..426be70
--- /dev/null
@@ -0,0 +1,2 @@
+:class:`unittest.mock.MagicMock` now supports the ``__fspath__`` method
+(from :class:`os.PathLike`).