12
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pytestの基本的な使い方

Last updated at Posted at 2017-12-16

pytestのインストール

$ pip install pytest

まずは上記のコマンドでインストールします。

作成したテストの実行方法

特定のファイルのみ指定してテストする場合

$ pytest test_sample001.py

上記のコマンドでテストを実行します。
オプション等...
-s テスト内で実行されたprint()をコンソールに表示

同一ディレクトリ配下のテストファイルを全て実行する場合

.
├── test_sample001
├── test_sample002
└── test_sample003

このようなディレクトリ構成の中で pytest . を実行すれば頭に test_ で始まるファイルを全て実行してくれます。

モジュール内の関数をモックにする場合

test_sample001.py
import sys

current_module = sys.modules[__name__]

def bar():
    return 'bar'

def test_bar(monkeypatch):
    monkeypatch.setattr(current_module, 'bar', lambda: 'patched')
    assert bar() == 'patched'

今回は同一モジュール内の関数をモックに置き換えるのでcurrent_moduleに現在実行中のモジュールを与えておく。
monkeypatchをテスト関数の引数として読み込む。
このテストでは関数barを'patched'を返す関数に置き換えている。

クラス内のメソッドをモックにする場合

test_sample002.py
import sys

current_module = sys.modules[__name__]

class Piyo:
    def piyo_func(self):
        return('piyo')

def hoge():
    piyo = Piyo()
    return piyo.piyo_func()

def test_hoge(monkeypatch):
    monkeypatch.setattr(current_module.Piyo, 'piyo_func', lambda *args: 'patched')
    assert hoge() == 'patched'

この例ではPiyoクラスのpiyo_func()をモックに置き換えて'patched'を返却するようにしています。

クラス自体をモックに置き換える場合

test_sample003.py
import sys

current_module = sys.modules[__name__]

class Foo:
    pass

def bbb():
    foo = Foo()
    return foo.foo_func()

def test_bbb(monkeypatch):
    class DummyFoo:
        def foo_func(self):
            return 'patched'

    monkeypatch.setattr(current_module, 'Foo', DummyFoo)
    assert bbb() == 'patched'

FooをモックのDummyFooに置き換えて、foo_funk()を実行しています。

monkeypatch.setattrメソッドの説明

monkeypatch.setattr(a, b, c)

a:モックにしたい[関数, クラス]を含む[モジュール, クラス]
b:モックにしたい[関数名, クラス名]
c:モックの[関数, クラス]

12
14
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
12
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?