LoginSignup
1
0

More than 1 year has passed since last update.

メモ:Pytonのテストフレームワークpytestの基本

Posted at

Pythonは軽く触ってはいたが、本番プロダクトでの利用は殆どなかったのでテストフレームワークを使っていなかった。
pytestというテストフレームワークがPythonには存在しているので見ておく。

基本的にはdefで定義されるメソッドに対して、引数を与えて正しい結果が返ってくるか、
を実行して確認するための単体テストツール。

準備

pip install pytest
でインストール可能

mainフォルダとtestsフォルダにわけてソースコードを管理して、
testsフォルダ内のtest_xxx.pyのtest_xxxメソッドを順次実行していくので、各フォルダに配置する。

なお、アドオンだと

  • pytest-covでcoverage(テスト網羅率)を取れる。
  • toxを使うと仮想のテスト環境を設定出来るので、バージョン依存を知りたい時等には使える。
  • pytest-mockでモック

テスト記述方法

基本的にはtest_メソッドを用意すればいいのだが、

インスタンスをテストメソッド内で作成してテストしても良い。

def test_action(self,x):
    o = cls()
    assert o.action(2) == 1

エラーがraiseされるのが正しい処理の場合はpytest.raisesを利用する。

def test_action(self): 
    with pytest.raises(ValueError):
        o = cls()
        o.action('2')

何かをテスト前に実行したい場合はfixtureを利用。こことか参照

@pytest.fixture
def init_xxx(self):
    xxx

実行

pytest
コマンドで流せばテストが実行されて
8 passed in 0.06s
のように表示される。

ImportError: cannot import name ...
のようにエラーが出る場合はinit.py(空ファイル)をmainやtestsに配置すればOK

その他

時間がかかる処理を特定するには
--durations=10
のようにオプション指定すると上位10個の遅い処理が出てくる。

あと、少し前の情報だと、VSCodeの設定は
linting.flake8.enabled、mypy.enabled,enabled false
が良いらしい。

なお、AWSのCodeBuildで自動テストを実行する場合は以下を参考にする
https://docs.aws.amazon.com/ja_jp/codebuild/latest/userguide/test-report-pytest.html
https://dev.classmethod.jp/articles/codebuild-test-reporting-ga/

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