Imagine this: you change one tiny line of code in your project, something harmless, you think. You rerun your app, and suddenly nothing works. A feature that worked perfectly yesterday is now broken, and you have no idea why.
Every developer has faced this moment. And this is exactly why testing matters.
Testing is simply making sure your code behaves the way you expect it to. Without tests, every change you make becomes a gamble. You might fix one thing and accidentally break something else.
Automated tests solve this problem. They run your checks for you, instantly and consistently, so you can focus on building instead of constantly rechecking everything.
That's where pytest shines.
pytest is one of the simplest and most beginner-friendly testing tools in Python. It doesn't require complicated setup or special classes; you just write normal Python functions and use plain assert statements.
If you've been putting off learning testing, this is the perfect place to start.
What Is pytest?
pytest is a tool that helps you write small, simple tests in Python. Instead of relying on manual checks or print statements, pytest lets you create tiny test functions that verify your code automatically.
Here's why beginners love pytest:
- Minimal setup: Install it once, and you're ready to start testing
- Easy-to-read tests: Tests look like normal Python functions
- Uses plain
assertstatements: Just writeassert something == expected - Automatically finds your tests: Name your file
test_something.py, and pytest discovers it
Installing pytest
Installing pytest is straightforward:
pip install pytest
If you're working in a virtual environment (recommended), make sure it's activated first.
Verify the installation:
pytest --version
You should see something like pytest 9.02. Congratulations, pytest is installed and ready to use!
Writing Your First Test
Let's write your very first test. It's simpler than you might think.
Step 1: Create a simple function
Create a file called calculator.py:
def add_numbers(a, b):
"""Add two numbers together."""
return a + b
Step 2: Write your first test
Create a test file called test_calculator.py:
from calculator import add_numbers
def test_add_numbers():
result = add_numbers(2, 3)
assert result == 5
That's it! This is a complete pytest test:
def test_add_numbers():- Thetest_prefix tells pytest this is a test functionresult = add_numbers(2, 3)- We call our function with test inputsassert result == 5- If the result equals 5, the test passes
Step 3: Run pytest
Open your terminal and run:
pytest
Pytest will automatically find your test file and run it. You should see:
================================================== test session starts ===================================================
platform win32 -- Python 3.12.0, pytest-9.0.2, pluggy-1.6.0
rootdir: D:\GitHub\pytest-article
collected 1 item
test_calculator.py . [100%]
=================================================== 1 passed in 0.04s ====================================================
The dot (.) means your test passed!
What if the test fails?
If a test fails, pytest shows you exactly what went wrong:
================================================== test session starts ===================================================
platform win32 -- Python 3.12.0, pytest-9.0.2, pluggy-1.6.0
rootdir: D:\GitHub\pytest-article
collected 1 item
test_calculator.py F [100%]
======================================================== FAILURES ========================================================
_________________________________________________ test_add_numbers_wrong _________________________________________________
def test_add_numbers_wrong():
result = add_numbers(2, 3)
> assert result == 10 # This is wrong!
^^^^^^^^^^^^^^^^^^^
E assert 5 == 10
test_calculator.py:9: AssertionError
================================================ short test summary info =================================================
FAILED test_calculator.py::test_add_numbers_wrong - assert 5 == 10
=================================================== 1 failed in 0.47s ====================================================
The F means failed, and the error message shows you expected 10 but got 5. Pytest's clear error messages help you fix issues quickly.
Full source code at:
Want to boost your Python skills even faster?
Before you dive deeper into testing, grab my free Python One-Liner Cheat Sheet, a downloadable PDF packed with smart, time-saving tricks for real-world coding. You’ll learn elegant list & dict comprehensions, clever string shortcuts, functional patterns in a single line, quick file-handling snippets, and pro tips to keep your code clean and Pythonic.
How pytest Discovers Tests
Pytest automatically finds your tests using simple naming rules:
- Test files must start with
test_or end with_test.py - Test functions must start with
test_
Valid examples:
test_calculator.pycalculator_test.pydef test_add_numbers():
Invalid examples:
calculator.pydef add_numbers_test():
You can organize tests in a tests folder or keep them next to your code, both work fine. Just follow the naming rules, and pytest will find them automatically.
Understanding pytest Output
Pytest uses simple symbols to show test results:
.(dot) = Test passedF= Test faileds= Test skipped
When you see test_calculator.py ..F, it means:
- First test passed (
.) - Second test passed (
.) - Third test failed (
F)
When a test fails, pytest shows:
- The
>arrow pointing to the exact line that failed - The error message (e.g.,
assert 5 == 10) - The file and line number where it happened
Common errors:
AssertionError: assert X == Y- Your assertion was wrongNameError: name 'X' is not defined- Check your importsTypeError: unsupported operand type(s)- Check your data types
Using Fixtures
As you write more tests, you'll notice many tests need the same setup. Instead of repeating code, use fixtures, reusable setup for your tests.
Example:
This article is for paid members only
To continue reading this article, upgrade your account to get full access.
Subscribe NowAlready have an account? Sign In
