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
each of which defines some functions and/or classes. For example,
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).
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,
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
the output of pytest
looks like this.