@@ -63,40 +63,38 @@ testing, you do not want your test to depend on the running user. ``monkeypatch`
63
63
can be used to patch functions dependent on the user to always return a
64
64
specific value.
65
65
66
- In this example, :py:meth: `monkeypatch.setattr ` is used to patch ``os.path.expanduser ``
67
- so that the known testing string ``"/abc" `` is always used when the test is run.
66
+ In this example, :py:meth: `monkeypatch.setattr ` is used to patch ``Path.home ``
67
+ so that the known testing path ``Path( "/abc") `` is always used when the test is run.
68
68
This removes any dependency on the running user for testing purposes.
69
69
:py:meth: `monkeypatch.setattr ` must be called before the function which will use
70
70
the patched function is called.
71
- After the test function finishes the ``os.path.expanduser `` modification will be undone.
71
+ After the test function finishes the ``Path.home `` modification will be undone.
72
72
73
73
.. code-block :: python
74
74
75
75
# contents of test_module.py with source code and the test
76
- # os.path is imported for reference in monkeypatch.setattr()
77
- import os.path
76
+ from pathlib import Path
78
77
79
78
80
79
def getssh ():
81
80
""" Simple function to return expanded homedir ssh path."""
82
- return os.path.expanduser( " ~/ .ssh" )
81
+ return Path.home() / " .ssh"
83
82
84
83
85
84
def test_getssh (monkeypatch ):
86
- # mocked return function to replace os.path.expanduser
87
- # given a path, always return '/abc'
88
- def mockreturn (path ):
89
- return " /abc"
85
+ # mocked return function to replace Path.home
86
+ # always return '/abc'
87
+ def mockreturn ():
88
+ return Path( " /abc" )
90
89
91
- # Application of the monkeypatch to replace os.path.expanduser
90
+ # Application of the monkeypatch to replace Path.home
92
91
# with the behavior of mockreturn defined above.
93
- monkeypatch.setattr(os.path , " expanduser " , mockreturn)
92
+ monkeypatch.setattr(Path , " home " , mockreturn)
94
93
95
- # Calling getssh() will use mockreturn in place of os.path.expanduser
94
+ # Calling getssh() will use mockreturn in place of Path.home
96
95
# for this test with the monkeypatch.
97
96
x = getssh()
98
- assert x == " /abc/.ssh"
99
-
97
+ assert x == Path(" /abc/.ssh" )
100
98
101
99
Monkeypatching returned objects: building mock classes
102
100
------------------------------------------------------
0 commit comments