5
4

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 1 year has passed since last update.

【Python3】pytestで例外を検出する方法

Posted at

メモ書きです

環境

  • python3.8.10
  • pytest6.2.5

実装例

# pytestモジュールをimport
import pytest


def target(int):
    
    
    if int > 100:
        # 100より大きい数値の場合例外を送出
        raise ValueError("不正な値です")
    return int * 2

def test_target():
    
    test_int = 101
    # ValueErrorを検知
    with pytest.raises(ValueError) as e:
        target(test_int)
        
    # エラーメッセージを検証
    assert str(e.value) == "不正な値です"

with.pytest.raises(例外クラス) で例外を検知します。
注意点は以下の2点です。

  • pytest.raises()の引数にExceptionを指定すると、関係のない例外がキャッチされるので本来検証したい観点が検証できない
  • assert文はwith句と同じインデントレベルにする

あたりです。

5
4
1

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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?