animal.py
from datetime import datetime
from pathlib import Path
def make_date_file(target_dir: str):
"""現在時刻でファイルを作成する関数"""
now = datetime.now()
file_name = now.strftime("%Y%m%d%H%M%S.txt")
Path(f"{target_dir}/{file_name}").touch()
test_animal.py
from animal import make_date_file
from datetime import datetime
def test_make_date_file(tmp_path, monkeypatch):
# 同じ固定時刻を返す
class FixedDateTime(datetime):
@classmethod
def now(cls, tz=None):
return cls(2025, 10, 10, 10, 10, 10, tzinfo=tz)
# 適用
monkeypatch.setattr("animal.datetime", FixedDateTime)
# 実行
make_date_file(str(tmp_path))
# 指定時刻のファイルで作成されている
assert (tmp_path / "20251010101010.txt").exists()