LoginSignup
3
5

More than 3 years have passed since last update.

pytestの超基本の使い方

Posted at

pytestの使い方ノート

pytestを触ってみたので、そのノート。

pytestとは

Pythonのテストフレームワーク
pytest: helps you write better programs ? pytest documentation

pytestをインストールする

普通にpipからインストールすればOK

pytestのインストール
pip install pytest

pytest用のテストを書く

基本的な書き方は下記。

  • Pythonのプログラムとして書く
  • テストとして実行する部分を下記のいずれかで書く
    • 先頭がtest_で始まる関数にする
    • 先頭がTestで始まるクラスのtest_で始まるメソッドにする
  • 結果がOKかNGかは、assert 条件式の結果がTrueかFalseかで判定される
    • returnじゃないよ、assertだよ

テストする側とされる側のサンプル

テストする側(pytestから実行するプログラム)

test_program.py
from my_funcs import add, sub


def test_add():
    assert add(1, 2) == 3


def test_sub():
    assert sub(3, 1) == 2


class TestCase:
    def test_true(self):
        assert True

    def test_add_zero(self):
        assert add(1, 0) == 1

テストされる側

my_funcs.py
def add(a, b):
    return a + b

def sub(a, b):
    return a - b

pytestを実行する

普通にpytestを実行すると、カレントディレクトリの中で
ファイル名がtest_で始まるファイルか、_testで終わるファイルを自動で実行する。

pytestを実行する
pytest

テストプログラムを指定する場合

pytest テストする側のプログラム名で指定したテストのみが実行される。

ファイルを指定してpytestを実行する
pytest test_program.py

実行結果の見方

テストにパスした例

  • 最初にヘッダーがあって、その後に結果がファイル名 ..の書式で続く
  • この.の一つ一つがテスト関数での結果=OKに対応する
  • 末尾にパスした個数が表示されて終了
実行結果
==================================== test session starts ====================================
platform linux -- Python 3.6.3, pytest-5.3.0, py-1.8.0, pluggy-0.13.1
rootdir: /mnt/c/Users/nab391/pytest
collected 2 items

test_example1-1.py ..                                                                 [100%]

===================================== 2 passed in 0.02s =====================================

テストでこけた例

  • 最初にヘッダーがあって、その後に結果がファイル名 ..の書式で続くのは同じ
  • パスしなかったテストはFが表示される
  • その後、FAILURESにパスしなかった箇所が表示される
  • 末尾にOKとNGの個数とが表示されて終了
テストNG
==================================== test session starts ====================================
platform linux -- Python 3.6.3, pytest-5.3.0, py-1.8.0, pluggy-0.13.1
rootdir: /mnt/c/Users/nab391/pytest
collected 3 items

test_example1-1.py ..F                                                                [100%]

========================================= FAILURES ==========================================
________________________________________ test_false _________________________________________

    def test_false():
>       assert False
E       assert False

test_example1-1.py:14: AssertionError
================================ 1 failed, 2 passed in 0.08s ================================

実行オプション

  • -s:標準出力を出力する(デフォルト:しない)
  • -v:結果の詳細を出力する(デフォルト:しない)
詳細出力の例
test_example1-1.py::test_add PASSED                                                   [ 50%]
test_example1-1.py::test_sub PASSED                                                   [100%]
### 実行結果の見方
3
5
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
3
5