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
pytest is a tool to reduce anxiety and stress.
How to use pytest¶
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
something_test.py. For example, we might
test_monsters.py file that lives alongside our other python files (i.e. modules).
myproject/ alligator.py crocodile.py test_monsters.py
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,
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
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
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.