Table of Contents
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:
import pytest
@pytest.fixture
def sample_numbers():
"""Create a list of numbers for testing."""
return [1, 2, 3, 4, 5]
def test_sum_numbers(sample_numbers):
total = sum(sample_numbers)
assert total == 15
def test_list_length(sample_numbers):
assert len(sample_numbers) == 5
How it works:
@pytest.fixturetells pytest this is a fixture- Include the fixture name as a parameter in your test
- Pytest automatically provides the fixture to your test
Fixtures help you avoid repetition, keep tests clean, and ensure consistency across your test suite.
Creating Good Tests
Here are some tips for writing effective tests:
Keep tests short - A good test is usually 5-10 lines. If it's getting long, it might be trying to do too much.
Choose clear test names - Your test name should tell you exactly what it's checking:
test_add_positive_numbers()test_user_login_with_valid_credentials()test1()ortest_add()(too vague)
Test one thing at a time - Each test should verify one specific behaviour. If you're testing multiple things, split them into separate tests.
Write tests as you build - Don't wait until the end. Write tests alongside your code to catch bugs sooner.
Don't worry about being perfect - Any test is better than no test. Start simple with the "happy path" (when everything works), then add edge cases later.
Final Thoughts
Congratulations! You've learned the fundamentals of pytest. You now know how to write tests, run them, read the output, use fixtures, and create good tests. But this is just the beginning, pytest has many more powerful features waiting for you.
Remember, testing is a skill that improves with practice. Don't worry if your first tests aren't perfect, they're still valuable. Every test you write makes your code more reliable and gives you more confidence when making changes.
The most important thing is to start testing. Write your first test today, even if it's just testing a simple function. Then write another one. And another. Before you know it, testing will feel natural, and you'll wonder how you ever coded without it.
Follow me on Twitter: https://twitter.com/DevAsService
Follow me on Instagram: https://www.instagram.com/devasservice/
Follow me on TikTok: https://www.tiktok.com/@devasservice
Follow me on YouTube: https://www.youtube.com/@DevAsService
