os.makedirs
をモックするのはどうでしょうか。より詳しい使い方は「python モック 例外」といったキーワードでググってください。
main.py
import os
def my_makedirs(path: str):
os.makedirs(path, exist_ok=True)
test_main.py
from main import my_makedirs
from unittest.mock import patch
def test_my_makedirs():
path = "/tmp/dir"
# *path* が何だろうが、os.makedirsはFileExistsError例外を送出する
with patch("os.makedirs", side_effect=FileExistsError()):
my_makedirs(path)
def test_my_makedirs_with_expected_dir():
expect_path = "/tmp/expect/dir"
# *path* が *expect_path* と一致した場合のみ、FileExistsError例外を送出する
def raise_with_expect_path(path: str, *args, **kargs):
if path == expect_path:
raise FileExistsError()
else:
raise Exception(f"os.makedirs was called with unexpected arguments")
# *path_to_be_made* の内容を変えて結果を確認してください
path_to_be_made = "/tmp/expect/dir"
with patch("os.makedirs", side_effect=raise_with_expect_path):
my_makedirs(path_to_be_made)
$ pytest test_main.py
Like!