テック
pytest向けのpluginを書く

以前紹介したpython pluginの作り方に続いて、今回はpytestのpluginの作り方を紹介したいと思います。
そもそもpytestって何
pytest is a mature full-featured Python testing tool that helps you write better programs. << 公式サイトの引用ですが、pytestはpythonのtestのための便利ツールという扱い。 ツールという言葉が正しいか難しいところですが、単にtest runnerとは言えないくらいたくさんの機能を有しています。詳細は公式サイトを参照ください。 https://docs.pytest.org/en/latest/index.html
作るもの
今回はpytestの特徴の一つである、hookの機能を利用して、setup/call/teardownでdebugメッセージを表示する、簡単なpytest pluginを作ってみようと思います。
環境
- macOS 10.12.4
- Python 3.5.3
- pytest 3.1.2
構成
https://github.com/sirouma/hello_pytest
hello_pytest/ ├ hello_pytest/ │ ├ init.py │ └ plugin.py ├ test/ │ ├ init.py │ └ test_sample.py └ setup.py << pluginの実態となるコードはplugin.pyで、今回は動作確認用としてtestコードも用意しています。
コード
一部のコードについて解説します。 まずは、setup.pyですが、前回紹介したpython pluginのsetup.pyからの主な変更点として、entry_pointsがあります。 pytestはentry_points pytest11からpytestの各種pluginを探しに行きます。なので、自身でpluginを定義する場合は、ここに自身のpytest pluginの情報を追加する必要があります。
<script src="http://gist-it.appspot.com/http://github.com/sirouma/hello_pytest/blob/master/setup.py"></script>続いてpluginの実態となる部分のコードになります。 今回は3つのhook関数pytest_runtest_setup, pytest_runtest_call, pytest_runtest_teardownを定義することで、それぞれのタイミングでdebugログをコンソールに出力します。 各種hookの仕様は以下を参考にしてみてください。 https://docs.pytest.org/en/latest/writing_plugins.html#writing-hook-functions https://docs.pytest.org/en/latest/_modules/_pytest/hookspec.html
<script src="http://gist-it.appspot.com/http://github.com/sirouma/hello_pytest/blob/master/hello_pytest/plugin.py"></script>動かしてみる
まずはインストール。setup.pyのあるディレクトリで、pip3 installを実行。
sirouma$ pip3 install ./ Processing /Users/sirouma/Workspace/hello_pytest Installing collected packages: siro-uma.hello-pytest Running setup.py install for siro-uma.hello-pytest ... done Successfully installed siro-uma.hello-pytest-0.1.0 << 実際にpytestを使ってtestを走らせてみる。 -sオプションをつけて、stdout/stderr/stdin capturingを無効にしましょう。
sirouma$ py.test test/test_sample.py -s ================== test session starts ================== platform darwin -- Python 3.5.3, pytest-3.1.2, py-1.4.34, pluggy-0.4.0 rootdir: /Users/sirouma/Workspace/hello_pytest, inifile: plugins: siro-uma.hello-pytest-0.1.0 collected 1 items
test/test_sample.py pytest_runtest_setup pytest_runtest_call .pytest_runtest_teardown
================== 1 passed in 0.02 seconds ================== << 少し見づらいですが、pytest_runtest_setup, pytest_runtest_call, pytest_runtest_teardownがコンソールログに出力されているのがわかります。
まとめ
上記の通り、自作のpytest pluginができました。 その他にもたくさんのhookや、今回は特に触れていませんが、fixtureという便利な仕組みもあるので、ぜひ便利なpytest pluginを作ってみてください。


