Python Language Setting up py.test


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

The Code to Test

Say we are testing an addition function in projectroot/module/

# projectroot/module/
def add(a, b):
    return a + b

The Testing Code

We create a test file in projectroot/tests/ The file must begin with test_ to be recognized as a testing file.

# projectroot/tests/
from module import code

def test_add():
    assert code.add(1, 2) == 3

Running The Test

From projectroot we simply run py.test:

# ensure we have the modules
$ touch tests/
$ touch module/
$ 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/ .

================================================ 1 passed in 0.01 seconds ================================================