Open1
pytest - monkeypatchの使い方

カレントディレクトリを差し替える場合
production_code.py
def create_file(word):
# テスト対象のコード
with open("sample.txt", "w") as f:
f.write(f"{word}")
test_production_code.py
import production_code
def test_create_file(monkeypatch, tmp_path):
# 差し替え先はtmp_path(/tmp/pytest-of-{os_username}/pytest-current)
monkeypatch.chdir(tmp_path)
# pytest-current配下でsample.txtが作成される
create_file("test-word")
# テストコード
with open(tmp_path / "sample.txt", "r") as f:
expected = "test-word"
assert expected == f.read()
関数を差し替える方法
production_code.py
# テスト時に実行が難しい関数(差し替えたい関数)
def get_name():
return "Yamada"
# テスト対象のコード
def greeting():
name = get_name()
return f"Hello, {name}!"
test_production_code.py
import production_code
def test_greeting(monkeypatch):
# ダミー関数を用意
def dummy_get_name():
return "Dummy"
# 関数の差し替え
monkeypatch.setattr(production_code, "get_name", dummy_get_name)
# テストコード
expected = "Hello, Dummy!"
assert expected == production_code.greeting()