Because there was an order to teach automatic testing at the same time in Python beginner level education We investigated whether automatic testing can be performed on programs before learning about functions.
I haven't decided what to use for the Git server yet, so I checked the automated test procedure at GitLab, which I recently started using.
chapter_01_1.py
height = input('height(m) ')
width = input('Bottom(m) ')
area = float(height) * float(width) / 2
print('The area is'+str(area)+'Square meter')
Since it is a program that accepts standard input, it uses shell redirection to populate the contents of the test input file.
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']) == 'height(m)Bottom(m)Area is 1.2 square meters'
A line break is required after the input value.
tests/stdin_chapter_01_1.txt
1.2
2.0
Although it is written as bash in the test script, it naturally works with 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 ==========================================================
I use the image of Python3, but pytest-shell does not work on the base Alpine Linux because bash is not installed by default. Therefore, you need to install bash with the apk command.
.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
Recommended Posts