Pythonのpytestで-qオプションを試してみた
はじめに
この記事では、「pytestのqオプション(pytest -q
)を行うとどうなるのか」について書いています。
私はこれまでpytestを使ったことはほぼなく、pytestの勉強も兼ねて記事を書きました。
自分に向けた備忘録の意味もありますが、「pytest使いたいけどよく知らない」な人の一助になれば嬉しいです。
要点だけ
pytest -q
すると、結果の出力文がコンパクトになる。- ただし、失敗したテストについては
pytest
と同じレベルの説明を出力する
前提(環境)
以下の環境、フォルダ構成で実験をしていきます。
sample ├ test_add.py └ test_sub.py
test_add.pyの中身は以下のようになっています。
def test_add1(): assert 3 == 1 + 2 def test_add2(): assert 4 == 1 + 3
また、test_sub.pyの中身は以下のようになっています。
def test_sub1(): assert 1 == 2 - 1 def test_sub2(): assert 2 == 3 - 1
pytest
をしてみる
上で示したsampleフォルダに対してpytest
を実行すると、以下のような結果になります。
================================================= test session starts ================================================= platform win32 -- Python 3.9.4, pytest-7.1.3, pluggy-1.0.0 rootdir: C:\Users\xxxx\sample plugins: anyio-3.6.1 collected 4 items test_add.py .. [ 50%] test_sub.py .. [100%] ================================================== 4 passed in 0.04s ==================================================
pytest -q
をしてみる
上で示したsampleフォルダに対してpytest
を実行すると、以下のような結果になります。
.... [100%] 4 passed in 0.02s
出力される文章が非常にコンパクトになりました。
失敗するテストが含まれた時はどうなるのか
上の例は全てのテストが成功しましたが、失敗するテストが含まれていた場合はどう出力が変わるのでしょうか。
試しに、test_add.py
のtest_add1
関数を以下のように必ず失敗するように変えてみます
def test_add1(): assert 3 == 1 + 1
では、pytest
実行時とpytest -q
実行時の出力の違いを見てみましょう。
まずはpytest
実行時です。
================================================= test session starts ================================================= platform win32 -- Python 3.9.4, pytest-7.1.3, pluggy-1.0.0 rootdir: C:\Users\xxxx\sample plugins: anyio-3.6.1 collected 4 items test_add.py F. [ 50%] test_sub.py .. [100%] ====================================================== FAILURES ======================================================= ______________________________________________________ test_add1 ______________________________________________________ def test_add1(): > assert 3 == 1 + 1 E assert 3 == (1 + 1) test_add.py:2: AssertionError =============================================== short test summary info =============================================== FAILED test_add.py::test_add1 - assert 3 == (1 + 1) ============================================= 1 failed, 3 passed in 0.20s =============================================
続いてpytest -q
実行時です。
F... [100%] ====================================================== FAILURES ======================================================= ______________________________________________________ test_add1 ______________________________________________________ def test_add1(): > assert 3 == 1 + 1 E assert 3 == (1 + 1) test_add.py:2: AssertionError =============================================== short test summary info =============================================== FAILED test_add.py::test_add1 - assert 3 == (1 + 1) 1 failed, 3 passed in 0.16s
失敗した場合は、pytest -q
でも何がどう失敗したのか丁寧に表示してくれるんですね!
おわりに
「pytestのqオプション(pytest -q
)を行うとどうなるのか」について解説しました。
さいごに、記事を書く上で参考にしたサイトのリンクを以下に掲載します。合わせて読んでいただくと良いかと思います。