[Python] Mocking pathlib.path object for Python unittest

Discussão em 'Python' iniciado por Stack, Fevereiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I wanted to mock the class Path from pathlib. Let's assume that I have a function called functionX() where the Path object is being created. This throws an exeception. How I can make this work? My test looks like the following:

    @patch('pathlib.Path')
    def test_start(self, patch_path):
    patch_path.is_file.return_value = True
    patch_path.exists.return_value = True
    x = functionX()
    self.assertTrue(x)


    def functionX():
    p=Path("/some/non/existing/path/to/a/file.hpp")
    if p.exists() and p.is_file():
    return True


    The output is the following:

    AttributeError: type object 'Path' has no attribute '_flavour'


    Can anyone help me?

    Using pathlib3x instead of pathlib resolves the issue of the exception. But now I have encountered that the functions is_file() and exists() are not executed like mentioned in the return_value.

    Continue reading...

Compartilhe esta Página