概要
Python初級者レベル教育で、自動テストについても同時に教育したいというオーダーがあったため、
関数について学ぶ前のプログラムを対象に自動テストができるか調査した。
※企業案件のため、以下のプログラムの内容やファイル名等は実際のものとは異なる。
要件
- Pythonによるプログラミング教育がメイン
- テストの重要性を理解して貰いたい
- Gitも使えるようにしたい
- 教育の前半の課題は、関数化していない
- 標準入力を受けとって処理する課題がある
まだGitサーバに何を使うか確定していないため、とりあえず最近使い初めたGitLabで自動テストの手順を確認。
テスト対象のプログラム
chapter_01_1.py
height = input('高さ(m) ')
width = input('底辺(m) ')
area = float(height) * float(width) / 2
print('面積は'+str(area)+'平方メートル')
テスト仕様ファイル
標準入力を受けとるプログラムのため、シェルのリダイレクトを使ってテスト用入力ファイルの内容を流しこむようにした。
tests/test_chapter01.py
def test_chapter01_1(bash):
assert bash.run_script_inline(['python3 chapter_01_1.py < tests/stdin_chapter_01_1.txt']) == '高さ(m) 底辺(m) 面積は1.2平方メートル'
テスト用入力ファイル
入力値の後には改行が必須。
tests/stdin_chapter_01_1.txt
1.2
2.0
ローカルでのテスト実行
テストスクリプト内ではbashと書いているが、当然zshでも動作する。
% pytest
============================================================ test session starts ============================================================
platform darwin -- Python 3.7.3, pytest-5.0.1, py-1.8.0, pluggy-0.12.0
rootdir: /Users/takaiayumu/python-basic
plugins: openfiles-0.3.2, arraydiff-0.3, shell-0.2.3, doctestplus-0.3.0, remotedata-0.3.1, cov-2.8.1
collected 1 items
tests/test_chapter01.py .. [100%]
========================================================= 1 passed in 1.45 seconds ==========================================================
GitLab CI用の設定
Python3のイメージを使うが、ベースになっているAlpine Linuxでは初期状態でbashがインストールされていないためpytest-shellが動作しない。
そのため、apkコマンドでbashをインストールする必要がある。
gitlab-ci.yml
image: python:3-alpine
before_script:
- apk update
- apk add bash
- pip install pytest pytest-cov pytest-shell
test:
script:
- pytest --cov=./tests