Testing
Testing helps make software more stable. At its core testing is about checking whether certain conditions will produce certain output, testing functions, classes, requests and more. To test something we assert a condition.
assert add(10,15) == 25 The standard library has built in tests with the unittest library, but we’re going to be using pytest as it’s more
pleasant to use.
To install pytest run the command below:
pip install -U pytest pytest looks for all files in the directory of the form test_*.py (or *_test.py as well). Create a
test file starting with test_*.py.
def add(a,b):
return a + b
def test_add():
assert add(5,1) == 6 Any function beginning with test_ will be marked as a test for pytest to run, the output should like
something like:
pytest
=============================================================================== test session starts ===============================================================================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/intermediate-python
collected 1 item
test_add.py . [100%]
================================================================================ 1 passed in 0.03s ================================================================================
Tests can live anywhere in the project, although they are usually placed inside a dedicated tests folder
for organisation.
Writing tests
At a basic level writing tests is quite simple, it always an assertion, but knowing what to test is harder. Let’s go over an example scenario of a small game, with the structure:
project/
player.py
guns.py
tests/
test_player.py
test_guns.py class Player:
def __init__(self):
self.health = 100
self.position = [0,0,0]
def is_alive(self):
return self.health > 0
def move(self,x,y,z):
self.position[0] += x
self.position[1] += y
self.position[2] += z To determine what kind of tests are important it’s good to come up with things that need to happen, for example every player should start with full health.
from player import Player
def test_player_start_health():
p1 = Player()
assert player.health == 100 Now this condition is guaranteed to always be true as long as the test is passing.
Doc tests
Doctests are tests written in documentation that can
be run using pytest. Doc tests are written in comments, as an interactive code session with the output being
the expected result.
def square(num):
"""
Square a number
>>> square(10)
100
"""
return num * num To run doctests in module use pytest with the --doctest-modules option.
pytest --doctest-modules