Installation and Getting Started

Pythons: Python 2.6-3.4, Jython, PyPy-2.3

Platforms: Unix/Posix and Windows

PyPI package name: pytest

dependencies: py, colorama (Windows), argparse (py26).

documentation as PDF: download latest

Installation

Installation options:

pip install -U pytest # or
easy_install -U pytest

To check your installation has installed the correct version:

$ py.test --version
This is pytest version 2.6.1, imported from /home/hpk/p/pytest/.tox/regen/lib/python3.4/site-packages/pytest.py

If you get an error checkout Known Installation issues.

Our first test run

Let’s create a first test file with a simple test function:

# content of test_sample.py
def func(x):
    return x + 1

def test_answer():
    assert func(3) == 5

That’s it. You can execute the test function now:

$ py.test
=========================== test session starts ============================
platform linux -- Python 3.4.0 -- py-1.4.23 -- pytest-2.6.1
collected 1 items

test_sample.py F

================================= FAILURES =================================
_______________________________ test_answer ________________________________

    def test_answer():
>       assert func(3) == 5
E       assert 4 == 5
E        +  where 4 = func(3)

test_sample.py:5: AssertionError
========================= 1 failed in 0.01 seconds =========================

pytest found the test_answer function by following standard test discovery rules, basically detecting the test_ prefixes. We got a failure report because our little func(3) call did not return 5.

Note

You can simply use the assert statement for asserting test expectations. pytest’s Advanced assertion introspection will intelligently report intermediate values of the assert expression freeing you from the need to learn the many names of JUnit legacy methods.

Asserting that a certain exception is raised

If you want to assert that some code raises an exception you can use the raises helper:

# content of test_sysexit.py
import pytest
def f():
    raise SystemExit(1)

def test_mytest():
    with pytest.raises(SystemExit):
        f()

Running it with, this time in “quiet” reporting mode:

$ py.test -q test_sysexit.py
.
1 passed in 0.00 seconds

Todo

For further ways to assert exceptions see the raises

Grouping multiple tests in a class

Once you start to have more than a few tests it often makes sense to group tests logically, in classes and modules. Let’s write a class containing two tests:

# content of test_class.py
class TestClass:
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

The two tests are found because of the standard Conventions for Python test discovery. There is no need to subclass anything. We can simply run the module by passing its filename:

$ py.test -q test_class.py
.F
================================= FAILURES =================================
____________________________ TestClass.test_two ____________________________

self = <test_class.TestClass object at 0x2ad4b005b710>

    def test_two(self):
        x = "hello"
>       assert hasattr(x, 'check')
E       assert hasattr('hello', 'check')

test_class.py:8: AssertionError
1 failed, 1 passed in 0.01 seconds

The first test passed, the second failed. Again we can easily see the intermediate values used in the assertion, helping us to understand the reason for the failure.

Going functional: requesting a unique temporary directory

For functional tests one often needs to create some files and pass them to application objects. pytest provides Builtin fixtures/function arguments which allow to request arbitrary resources, for example a unique temporary directory:

# content of test_tmpdir.py
def test_needsfiles(tmpdir):
    print tmpdir
    assert 0

We list the name tmpdir in the test function signature and pytest will lookup and call a fixture factory to create the resource before performing the test function call. Let’s just run it:

$ py.test -q test_tmpdir.py

================================== ERRORS ==================================
_____________________ ERROR collecting test_tmpdir.py ______________________
/home/hpk/p/pytest/.tox/regen/lib/python3.4/site-packages/_pytest/python.py:463: in _importtestmodule
    mod = self.fspath.pyimport(ensuresyspath=True)
/home/hpk/p/pytest/.tox/regen/lib/python3.4/site-packages/py/_path/local.py:620: in pyimport
    __import__(modname)
E     File "/tmp/doc-exec-187/test_tmpdir.py", line 2
E       print tmpdir
E                  ^
E   SyntaxError: invalid syntax
1 error in 0.03 seconds

Before the test runs, a unique-per-test-invocation temporary directory was created. More info at Temporary directories and files.

You can find out what kind of builtin pytest fixtures: explicit, modular, scalable exist by typing:

py.test --fixtures   # shows builtin and custom fixtures

Where to go next

Here are a few suggestions where to go next:

Known Installation issues

easy_install or pip not found?

Install pip for a state of the art python package installer.

Install setuptools to get easy_install which allows to install .egg binary format packages in addition to source-based ones.

py.test not found on Windows despite installation?

  • Windows: If “easy_install” or “py.test” are not found you need to add the Python script path to your PATH, see here: Python for Windows. You may alternatively use an ActivePython install which does this for you automatically.
  • Jython2.5.1 on Windows XP: Jython does not create command line launchers so py.test will not work correctly. You may install py.test on CPython and type py.test --genscript=mytest and then use jython mytest to run your tests with Jython using pytest.
Usages and Examples for more complex examples