はじめに
前回では、簡単な関数のカバレッジをpytest-covで確認しました。flaskでも同様にpytest-covでカバレッジをチェックできるのか確認してみます。
環境
- python:3.6.5
- flask:1.0.2
- pytest:5.3.5
- pytest-cov:2.8.1
簡単なflaskのカバレッジ確認
pytest-covを使用するためには、テスト対象とテストソースが必要なので作成します。
[ pytestでflaskの単体テストをする ]で作成方法を書いているため分からない方はそちらを見てください。
テスト対象のソース
テスト対象のソースは取得したmessageがbyeだったときは、see youに変えて、それ以外の時はそのままmessageを返却しています。
from flask import Flask, jsonify
import datetime
app = Flask(__name__)
@app.route('/greeting/<message>')
def sample(message):
if message == 'bye':
message = 'see you'
return message
テスト方法を書いたソース
messageがbyeとそれ以外のパターンの2通りのテストソースを作成しました。ヘッダをちゃんとすれば答えのb'see you'のb(バイナリ)はなくても良いです。
import pytest
from flask_mod import app
@pytest.fixture
def client():
app.config['TESTING'] = True
test_client = app.test_client()
yield test_client
test_client.delete()
def test_greeting_bye(client):
result = client.get('/greeting/bye')
assert b'see you' == result.data
def test_greeting_hello(client):
result = client.get('/greeting/hello')
assert b'hello' == result.data
単体テストの実行
テスト対象とテスト方法のソースができたため、実行します。
# pytest --cov --cov-branch -v pytest_flask_fixture.py
~~~~ 略 ~~~~~
collected 2 items
pytest_flask_fixture.py .. [100%]
----------- coverage: platform win32, python 3.6.5-final-0 -----------
Name Stmts Miss Branch BrPart Cover
---------------------------------------------------------------
flask_mod.py 7 0 2 0 100%
pytest_flask_fixture.py 13 0 0 0 100%
---------------------------------------------------------------
TOTAL 20 0 2 0 100%
====== 2 passed in 0.74s ======
結果を見ると、flaskの処理を書いたflask_mod.py
のBranchが2でCoverが100%になっていることからflaskのテストもできていることがわかります。
VSCodeで実行する方法
コマンドでpytestを打っても良いのですが、VSCodeで実行できる方法もあるためまとめておきます。
手順
定義の作成手順
- Ctr + Shift + p でコマンドパレットを開く
- python:Configure Tests を選択
- pythest を選択
- テストソースのディレクトリ(テストソースのディレクトリがルートの時は . Root Directory) を選択
- テストソースのディレクトリに
pytest.ini
を作成する。(名前は固定)
[pytest]
junit_family = legacy
addopts = -ra -q --cov --cov-branch
実行手順
- Ctr + Shift + p でコマンドパレットを開く
- python: Run All Tests
- python: Show Test Output
VsCodeでの注意事項
テストソースのファイル名はtestXXXXというようにtest始まりである必要があるようです。
おわりに
pytest-covがflaskでも可能なことを確認できました。WEBサービスは変更や修正等が激しい上に対象にAPIやWEBページがあるため、下手な修正をすると別の場所まで影響がでる可能性があります。そのためにテスト自動化が良くされますがそれと同時にカバレッジのチェックもすればより精度の高い影響確認テストができるのではないかと思います。