0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

monkeypatchでdatetime.now()を固定化してテストする

Posted at

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()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?