This guide walks you through creating your first test using the pytest framework, covering installation, writing tests, and understanding assertions.
In this guide, we’ll walk you through creating your very first test using the pytest framework. If you’re new to pytest, consider searching for its documentation online to familiarize yourself with its setup and capabilities. We will cover installing pytest, writing an intentionally failing test to learn from its output, and building a simple test suite for a basic calculation module.
Begin by installing pytest as you would any other Python package:
Copy
Ask AI
pip install pytest
After installation, confirm that the pytest command is available by running:
Copy
Ask AI
pytest
A successful run displays output similar to:
Copy
Ask AI
================================ test session starts =============================platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-1.x.ycachedir: $PYTHON_PREFIX/.pytest_cacherootdir: $REGENDOC_IMPDIRcollected 1 itemtest_sample.py [100%]============================= FAILURES ============================================___________________________ test_answer ___________________________________________def test_answer():> assert inc(3) == 5E assert 4 == 5E + where 4 = inc(3)test_sample.py:6: AssertionError============================== short test summary info ============================FAILED test_sample.py::test_answer - AssertionError: assert 4 == 5
This output indicates that a test failure occurred as expected. The failure stems from an error in the test setup, which we will address in the next section.
Below is an example snippet of a FastAPI route, demonstrating how to implement a login endpoint. This snippet also emphasizes that test outputs might include details about the runtime environment:
Even if pytest sometimes displays “collected 0 items” (e.g., due to naming conventions or missing tests), always double-check that your tests follow the appropriate naming patterns.
Next, create a directory named tests (if it doesn’t already exist) and add a file called test_calculations.py to test the add function:
Copy
Ask AI
from app.calculations import adddef test_add(): print("testing add function") # 5 + 3 should equal 8 assert add(5, 3) == 8
Pytest automatically discovers tests in files whose names start with test_ and functions that begin with test_. If your file or function naming deviates from this convention (e.g., using mytest.py or testing_add()), pytest will not run the tests unless explicitly specified.
Pytest leverages Python’s built-in assert statement to confirm that conditions are met:
A true assertion (e.g., assert True) results in a passing test.
A false assertion (e.g., assert False) raises an AssertionError and marks the test as failed.
Consider these basic examples:
Copy
Ask AI
def test_assert_true(): assert True # This test passesdef test_assert_false(): assert False # This test fails
When running these tests, pytest provides visual feedback—a green dot for passing tests and a red dot for failing ones—accompanied by detailed error messages for debugging.Keep in mind that print statements (like in the earlier test_add example) will appear in the output when running tests directly with a command like:
Copy
Ask AI
py -3 tests/test_calculations.py
However, pytest manages output differently when running an entire test suite.
If pytest reports “collected 0 items”, verify that your test files and functions correctly follow the naming conventions and that an init.py file is present in your tests directory if required.