LoginSignup
1
0

More than 1 year has passed since last update.

pytestを使ってみる

Last updated at Posted at 2021-10-10

前提

  • pythonインストール済み

pytestのインストール

pip install pytest

テストファイルの作成

  • testで始まる関数名を作成する
  • testで始まる名前の関数自動的にテスト対象となる
  • テストしたい関数内に assert で評価式を記述する
sample.py
def add_number(x):
    return x + 1

def test_sum():
    result: int = add_number(4)
    assert result >= 5

pytestの実行

pytest sample.py

 成功した場合

sample.png

失敗した場合

sample 2.png

pythonのカバレッチを調べる

単体テストには処理ルートや分岐条件が網羅されているかという観点のテスト(ガバレッジテスト)をしたい場合は以下のコマンドでpytestのプラグインをインストールする。

pip install pytest-cov

pytest-cov 実行オプション

-s: print文を出力
-v: 冗長なログ出力
--cov=CODE_DIRECTORY: ディレクトリ内をテストコードを指定する場合
--cov: C0カバレッジの表示
--cov --cov-branch: C1カバレッジの表示
--cov-report=html : HTML形式のカバレッジレポートを出力

実行コマンド例

pytest -s -v --cov sample.py

カバレッジのhtml出力

pytest -s -v --cov=../src --cov-report=html

pytestでテストをスキップする

テストが必要ないコードの場合(テストコード内で呼び出すサブルーチンなど)

@pytest.mark.skip(reason="このテストは無条件でスキップします。")
def test_sample():
    hoge = "hoge"
    return hoge

@pytest.mark.skipif(True, reason="[スキップする理由]")
def test_function_1():
    moge = 1
    return moge

失敗すると期待されるテストにマークを付ける

@pytest.mark.xfail()
def test_unique_id_is_a_duck():
    uid = tasks.unique_id()
    assert uid == 'a duck'
1
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
1
0