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で関数を置換してテストする

Posted at

pytest-mockでなくても簡単な置き換えはpytestmonkeypatchで可能

animal.py
def get_animal():
    return "cat"

def get_my_pet():
    return get_animal()
tests/test_animal.py
from animal import get_my_pet

def test_get_animal():
    assert "cat" == get_my_pet() # 通常はcatが返る

def test_get_animal_fake(monkeypatch):
    # 置き換える関数を作成
    def get_animal_fake():
        return "dog"

    # 関数を置き換える
    monkeypatch.setattr("animal.get_animal", get_animal_fake)
    assert "dog" == get_my_pet() # 置き換えた関数の返値
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?