目次

前のトピックへ

属性をもつテスト関数のマーク

次のトピックへ

unittest.TestCase の対応

非推奨の警告やその他の警告のアサート

関数の引数 recwarn

Python のワーニングシステムからの警告を受け取るコードをアサートするために recwarn という関数の引数が使えます。簡単な自己完結型のテストを紹介します:

# test_recwarn.py の内容
def test_hello(recwarn):
    from warnings import warn
    warn("hello", DeprecationWarning)
    w = recwarn.pop(DeprecationWarning)
    assert issubclass(w.category, DeprecationWarning)
    assert 'hello' in str(w.message)
    assert w.filename
    assert w.lineno

関数の引数 recwarn は次のメソッドを提供します:

  • pop(category=None): カテゴリに一致する最後の警告を返す
  • clear(): 警告の一覧をクリアする

非推奨の警告を発生させる関数の確認

非推奨の警告を発生させる特定の関数呼び出しを確認するためのグローバルなヘルパー関数も呼び出せます:

import pytest

def test_global():
    pytest.deprecated_call(myfunction, 17)