py.test
is one of several third party testing libraries that are available for Python. It can be installed using pip
with
pip install pytest
Say we are testing an addition function in projectroot/module/code.py
:
# projectroot/module/code.py
def add(a, b):
return a + b
We create a test file in projectroot/tests/test_code.py
. The file must begin with test_
to be recognized as a testing file.
# projectroot/tests/test_code.py
from module import code
def test_add():
assert code.add(1, 2) == 3
From projectroot
we simply run py.test
:
# ensure we have the modules
$ touch tests/__init__.py
$ touch module/__init__.py
$ py.test
================================================== test session starts ===================================================
platform darwin -- Python 2.7.10, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /projectroot, inifile:
collected 1 items
tests/test_code.py .
================================================ 1 passed in 0.01 seconds ================================================