LoginSignup
6
2

More than 1 year has passed since last update.

pytest の PytestUnknownMarkWarning 出力を抑制する

Last updated at Posted at 2021-10-26

結論

以下の方針が良さそう。

  • marker の数が少なければ marker を登録する
  • marker が多ければ filterwarnings を設定する

テスト環境

$ python --version
Python 3.8.5
$ pytest --version
pytest 6.2.5
$ echo $OSTYPE
darwin20.0

PytestUnknownMarkWarning

pytest では marker を付けることができる。例えば以下のようなテストファイルがあったとして

test_example.py
import pytest

@pytest.mark.testmarker1
def test_example1():
    assert True

@pytest.mark.testmarker2
def test_example2():
    assert True

例えば次のように -m オプションで marker を指定すればその marker が付いたテストだけが実行される。この場合は test_example2。(-m でもう少し複雑な条件も指定できるがここでは割愛。)

$ pytest -m testmarker2

しかし @pytest.mark.<marker> でデコレーションしただけでは以下のような warning が出力されてしまう。何も対策しないと鬱陶しいし、確認すべき warning や error が見づらくなるので出力を抑制したい。

=========================================== warnings summary ===========================================
test_example.py:3
  /Users/guest/test_example.py:3: PytestUnknownMarkWarning: Unknown pytest.mark.testmarker1 - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/mark.html
    @pytest.mark.testmarker1

test_example.py:7
  /Users/guest/test_example.py:7: PytestUnknownMarkWarning: Unknown pytest.mark.testmarker2 - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/mark.html
    @pytest.mark.testmarker2

-- Docs: https://docs.pytest.org/en/stable/warnings.html
==================================== 2 passed, 2 warnings in 0.01s =====================================

対策

1. markers を設定する

warning メッセージに表示されている通り pytest のドキュメントページ を見るとこの方法が書かれている。pytest.ini もしくは pyproject.toml に自分が利用する marker の設定を記載するというもの。記述例は以下。

pytest.ini
[pytest]
markers =
    testmarker1
    testmarker2
pyproject.toml
[tool.pytest.ini_options]
markers = [
    "testmarker1",
    "testmarker2",
]

2. filterwarnings を設定する

ドキュメントに記載されている通り、基本的には 1. がよいはずである。が、marker の数が多くなってくると面倒だし、test のメンテナンス(追加・削除)に応じて ini や toml を都度更新しないといけないのも何だかうれしくない。

検索して stackoverflow とか見てもイマイチで、ピンポイントで PytestUnknownMarkWarning だけ抑止するような方法が出てこない。ふと pytest 自体のソースコードを確認していると、pytest の pyproject.toml に以下のような設定が記載されていた(抜粋)。

pyproject.toml
[tool.pytest.ini_options]
filterwarnings = [
    "ignore::_pytest.warning_types.PytestUnknownMarkWarning",
]

コメントで # ignore use of unregistered marks, because we use many to test the implementation とまで書いてくれているので目的にも合致していそう。これを設定するとピンポイントで PytestUnknownMarkWarning が無視される。

pytest.ini であれば以下のように設定すればよい。

pytest.ini
[pytest]
filterwarnings =
    ignore::_pytest.warning_types.PytestUnknownMarkWarning
6
2
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
6
2