Skip to content

Beginner

Skip to the problems!

Why use pytest?

News Flash - your code's going to break. When other people depend on your code, and in some cases pay for your code, this causes anxiety and stress.

pytest helps you write tests to catch these breakages early on (hopefully before you've pushed your code into production). Therefore, pytest is a tool to reduce anxiety and stress.

How to use pytest

Setup

Typically, you might have a project with some python modules like this

myproject/
  alligator.py
  crocodile.py

each of which defines some functions and/or classes. For example,

def safe_to_grab(length_feet):
    return length_feet <= 1
def safe_to_grab(length_feet):
    return False

At some point, you'll want to set up tests to confirm these things works as expected. If something breaks, you'll catch the error quickly. And if your tests are good, they'll tell you exactly where to fix the bug.

Where do tests live?

Tests usually live inside a python file named test_something.py or something_test.py. For example, we might create a test_monsters.py file that lives alongside our other python files (i.e. modules).

myproject/
  alligator.py
  crocodile.py
  test_monsters.py
Note

Tests can live anywhere, but by default, pytest looks for python files whose name starts or ends with "test".

What do tests look like?

Test files usually contain a collection of test functions which assert things. For example,

test_monsters.py
import alligator
import crocodile

def test_safe_to_grab_alligator():
    assert alligator.safe_to_grab(0.5) == True

def test_unsafe_to_grab_alligator():
    assert alligator.safe_to_grab(1.5) == False

def test_unsafe_to_grab_crocodile():
    assert crocodile.safe_to_grab(0.5) == False

How do I run tests?

After installing pytest, you should be able to run pytest from your shell / terminal. The pytest command searches your current working directory and all subdirectories for test files. Then it looks for and executes test functions inside those files.

Each successful test function is indicated by a green dot in the output. For example, here's the output of pytest ran against the project designed above.

Failed tests are indicated by a red F. For example, if we add a fourth test designed to fail

import alligator
import crocodile

def test_safe_to_grab_alligator():
    assert alligator.safe_to_grab(0.5) == True

def test_unsafe_to_grab_alligator():
    assert alligator.safe_to_grab(1.5) == False

def test_unsafe_to_grab_crocodile():
    assert crocodile.safe_to_grab(0.5) == False

def test_unsafe_to_grab_crocodile_2():
    assert crocodile.safe_to_grab(0.1) == True

the output of pytest looks like this.