Matan Wiesner
Matan Wiesner

Reputation: 186

Mock pathlib.Path.exists

My Python function creates pathlib.Path objects. I want to mock this, so when the code will call pathlib.Path("/tmp/a").exists() it will get True, and when the code will call pathlib.Path("/tmp/b").exists() it will get False.

I tried this:

import pathlib
from unittest.mock import patch

def my_side_effect(*args, **kwargs):
    print (f" args = {args} , kwargs={kwargs}")
    return True

with patch.object(pathlib.Path, 'exists') as mock_exists:
    mock_exists.side_effect = my_side_effect
    print(pathlib.Path("a").exists())

Output:

 args = () , kwargs={}
True

As you can see, my side effect is not getting any args/kwargs based on the path.

Upvotes: 2

Views: 2214

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16855

Your example works as expected, because pathlib.Path.exists doesn't take any arguments. The path you are interested in is saved in the Path object.
Instead of using side_effect, you can just patch pathlib.Path.exists with your own function that does what you need:

import pathlib
from unittest import TestCase
from unittest.mock import patch

def my_exists(self):
    # self is the Path instance, str(Path) returns the path string
    return str(self) == "a"

class MyTest(TestCase):
    def test_exists(self):
        with patch.object(pathlib.Path, 'exists', my_exists):
            self.assertTrue(pathlib.Path("a").exists())
            self.assertFalse(pathlib.Path("b").exists())

Upvotes: 3

Related Questions