Mocking pathlib.Path I/O methods in a maintainable way which tests functionality not implementation
Mocking system calls, especially those with side effects (mkdir()), is difficult and error prone.

I would rather use a temporary directory for test purposes. This approach has the added advantage of really testing your FS manipluation code.

import datetime
import os
import pathlib

from contextlib import contextmanager
from tempfile import TemporaryDirectory


@contextmanager
def temporary_test_dir():
    oldpwd = os.getcwd()
    with TemporaryDirectory("test-path") as td:
        try:
            os.chdir(td)
            yield
        finally:
            os.chdir(oldpwd)


def get(base, timestamp, channel):
    base = pathlib.Path(base)
    path = base / "tofu" / timestamp.strftime("%Y%m%d") / f"{channel:&gt;02d}" / "quinoa.txt"
    if path.exists():
        print(path, "exists")
    else:
        path.parent.mkdir(exist_ok=True, parents=True)
    return path


@temporary_test_dir()
def test_get():
    # All relative FS operations will be made in a temporary directory
    result = get("quorn", datetime.datetime.now(), 42)
    assert result.parent.exists()



I'm not sure what is the point of the tested function, but it doesn't matter for this example's sake.

If you really need to mock the filesystem part, I would suggest using an existing library such as pyfakefs, although I have never had such a need.