Test driven development with pytest

Test Driven Development with Python book by Harry Percival is a nice practical introduction to TDD with Python in the web development context. It starts with the development of a simple Django based web app using unittest and Selenium for testing. Very common setup. Here we will develop the same app using Flask and test it with pytest + pytest-splinter and pytest-bdd extensions.

This guide is aimed at developers with some experience in Python and web programming. This means some familiarity with things like “url routing”, “http requests”, “html templating” and the general MVC pattern. Basic knowledge about how to use the command line interface (we’ll use bash) is also assumed.

This is a very basic how-to-get-started-with-testing guide. Hopefully enough to overcome the initial learning barrier. I’m not a “testing expert”, and I don’t want to get into why anybody should be doing TDD or get into the depths of what’s a “unit”, “functional”, “acceptance” or “integration” test. You can read more about testing in Harry’s book, wikipedia and other authoritative sources like this one or that one. http://gojko.net/ is another useful resource.

Both this guide and the source of the app are on GitHub.

Conventions

There are two types of code blocks:

command line – what you need to type in a terminal ($ indicates standard bash shell prompt),

$ whoami
ivan
$ python -V
Python 3.5.0

and Python code – what you need to type inside a text editor (the first line starting with # indicates the path to file relative to project’s root directory.

# path/to/tests/test_file.py
import pytest

def test_sanity():
    assert 2 + 2 == 4