LoginSignup
11
7

More than 3 years have passed since last update.

pytestでデバッグする際の個人的頻出オプション

Posted at

はじめに

個人的に頻繁に使うオプションの紹介です。
こちらで紹介しているのは最低限ですので気になった方はご自身で調べてみてください。

オプション 結果
-k 特定のテストケースを実行する
-s printを出力する
--pdb テスト失敗時にデバッグモードにする

環境

$ pytest -V
pytest 6.0.1

オプション

特定のテストケースを実行する

test.py
def test_success():
    assert(1+2) == 3

def test_success2():
    assert(2+3) == 5

def test_failed():
    assert(1+2) == 4

テストを実行します。今回は成功ケースのみを対象にします。

pytest -k test_success

3件のテストケース中、2件が実行されました。
部分一致になるのでこのメソッド名だとtest_success1件だけを実行できない点に注意が必要です。

collected 3 items / 1 deselected / 2 selected 
tests\test_app.py ..
[100%] 
=================== 2 passed, 1 deselected in 3.02s===================

printの中身を出力する

テストがpassするとテストケースの中に記述したprint文はコンソール上に出ないので、意図的に出したい時に利用します。

test.py
def test_success():
    sample = 1+2
    print("変数sampleの中身:",sample)
    assert(sample) == 3
pytest -s

成功ケースですがprintの中身がコンソール上に出力されました。

collected 1 item

tests\test_app.py 変数sampleの中身: 3

tests\test_app.py . 
[100%] 
=================== 1 passed in 0.25s===================

テスト失敗時にデバッグモードになるようにする

pytest --pdb
tests\test_app.py:183: AssertionError
>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>PDB post_mortem (IO-capturing turned off)>>>>>>>>>>>

(Pdb) print(sample)
3
(Pdb) 

終了時はqを入力してエンター
pdbはpythonの対話型デバッガーです。
https://docs.python.org/ja/3/library/pdb.html

11
7
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
11
7