@@ -63,40 +63,38 @@ testing, you do not want your test to depend on the running user. ``monkeypatch`
6363can be used to patch functions dependent on the user to always return a
6464specific value.
6565
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.
6868This removes any dependency on the running user for testing purposes.
6969:py:meth: `monkeypatch.setattr ` must be called before the function which will use
7070the 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.
7272
7373.. code-block :: python
7474
7575 # 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
7877
7978
8079 def getssh ():
8180 """ Simple function to return expanded homedir ssh path."""
82- return os.path.expanduser( " ~/ .ssh" )
81+ return Path.home() / " .ssh"
8382
8483
8584 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" )
9089
91- # Application of the monkeypatch to replace os.path.expanduser
90+ # Application of the monkeypatch to replace Path.home
9291 # with the behavior of mockreturn defined above.
93- monkeypatch.setattr(os.path , " expanduser " , mockreturn)
92+ monkeypatch.setattr(Path , " home " , mockreturn)
9493
95- # Calling getssh() will use mockreturn in place of os.path.expanduser
94+ # Calling getssh() will use mockreturn in place of Path.home
9695 # for this test with the monkeypatch.
9796 x = getssh()
98- assert x == " /abc/.ssh"
99-
97+ assert x == Path(" /abc/.ssh" )
10098
10199 Monkeypatching returned objects: building mock classes
102100------------------------------------------------------
0 commit comments