Installing Pytest
Begin by installing pytest as you would any other Python package:Writing a Sample Test
Create a file namedtest_sample.py where we define a simple function alongside its failing test:
FastAPI Route Example
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.
Creating a Simple Calculation Module
To practice testing, let’s build a module that performs basic arithmetic operations. Create a file (for example,app/calculations.py) with:
Writing Tests for the Calculation Module
Next, create a directory namedtests (if it doesn’t already exist) and add a file called test_calculations.py to test the add function:
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.Understanding Assert Statements
Pytest leverages Python’s built-inassert 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 anAssertionErrorand marks the test as failed.
test_add example) will appear in the output when running tests directly with a command like:
Leveraging Pytest’s Auto-Discovery
For seamless test discovery by pytest, adhere to these guidelines:- Name test files with a prefix
test_(for example,test_calculations.py). - Ensure that test function names also begin with
test_(e.g.,def test_add():).
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.Conclusion
In this tutorial, we covered:- Installing pytest using pip
- Writing a basic failing test and analyzing its output
- Creating a simple arithmetic module and writing corresponding tests
- The significance of proper naming conventions for test discovery
- How Python’s
assertstatements help validate code functionality