Skip to content

Commit 6c83d9f

Browse files
maxbelangervstinner
authored andcommitted
bpo-35022: unittest.mock.MagicMock now also supports __fspath__ (GH-9960)
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.
1 parent 1770d1c commit 6c83d9f

File tree

4 files changed

+18
-0
lines changed

4 files changed

+18
-0
lines changed

Doc/library/unittest.mock.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1699,6 +1699,10 @@ The full list of supported magic methods is:
16991699
* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
17001700
* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
17011701
``__getnewargs__``, ``__getstate__`` and ``__setstate__``
1702+
* File system path representation: ``__fspath__``
1703+
1704+
.. versionchanged:: 3.8
1705+
Added support for :func:`os.PathLike.__fspath__`.
17021706

17031707

17041708
The following methods exist but are *not* supported as they are either in use

Lib/unittest/mock.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1713,6 +1713,7 @@ def _patch_stopall():
17131713
"complex int float index "
17141714
"round trunc floor ceil "
17151715
"bool next "
1716+
"fspath "
17161717
)
17171718

17181719
numerics = (
@@ -1760,6 +1761,7 @@ def method(self, *args, **kw):
17601761
'__hash__': lambda self: object.__hash__(self),
17611762
'__str__': lambda self: object.__str__(self),
17621763
'__sizeof__': lambda self: object.__sizeof__(self),
1764+
'__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
17631765
}
17641766

17651767
_return_values = {

Lib/unittest/test/testmock/testmagicmethods.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import math
22
import unittest
3+
import os
34
import sys
45
from unittest.mock import Mock, MagicMock, _magics
56

@@ -293,6 +294,15 @@ def test_magicmock_defaults(self):
293294
# how to test __sizeof__ ?
294295

295296

297+
def test_magic_methods_fspath(self):
298+
mock = MagicMock()
299+
expected_path = mock.__fspath__()
300+
mock.reset_mock()
301+
302+
self.assertEqual(os.fspath(mock), expected_path)
303+
mock.__fspath__.assert_called_once()
304+
305+
296306
def test_magic_methods_and_spec(self):
297307
class Iterable(object):
298308
def __iter__(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:class:`unittest.mock.MagicMock` now supports the ``__fspath__`` method
2+
(from :class:`os.PathLike`).

0 commit comments

Comments
 (0)