
Introduction to Unit Testing in Python with pytest
If you’re building software in Python, testing your code is not optional—it’s essential. One of the most popular and beginner-friendly tools for writing tests in Python is pytest. Whether you’re automating bug checks, validating new features, or refactoring code safely, pytest makes unit testing easier and more powerful.
In this guide, you’ll learn what unit testing is, how pytest works, and how to write and run your first test cases.
What is Unit Testing?
Unit testing is the process of testing individual units or functions of code to ensure they behave as expected. It’s your first line of defense against bugs and regressions.
Why Use pytest?
pytest is a widely-used testing framework in Python because it offers:
- Simple syntax — tests are just regular Python functions
- Powerful fixtures system — reusable test setup and teardown
- Detailed error reporting — clear tracebacks when tests fail
- Support for plugins — extendable to suit your project needs
Step 1: Install pytest
bash
Copy code
pip install pytest
After installation, you can run all your tests by simply using the pytest command in your terminal.
Step 2: Writing Your First Test
Create a file named test_math.py:
python
Copy code
def add(x, y):
return x + y
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
- The file name should start with test_
- Each test function should also start with test_
- Use assert statements to verify outcomes
Step 3: Running Tests
Run your tests using the terminal:
bash
Copy code
pytest
You’ll see output showing which tests passed or failed and why.
Step 4: Adding More Tests
python
Copy code
def subtract(x, y):
return x – y
def test_subtract():
assert subtract(10, 5) == 5
assert subtract(0, 4) == -4
This shows how easy it is to test multiple functions in one file.
Step 5: Organize with Fixtures (Optional)
Fixtures let you reuse common setup code. For example:
python
Copy code
import pytest
@pytest.fixture
def sample_data():
return {“x”: 10, “y”: 5}
def test_add(sample_data):
assert add(sample_data[“x”], sample_data[“y”]) == 15
Practice Challenge
Try this:
Write a function to multiply two numbers and create a test case to validate positive, zero, and negative values.
Practicing small unit tests like these will make your development faster and safer.
For a deeper dive into testing and test automation with real projects, check out our Python developer learning path at:
👉 https://www.thefullstack.co.in/courses/
Learn everything from unit testing to CI/CD and deployment with step-by-step mentorship.
You also like this:
What is Backend Development? A Complete Guide for Beginners [2025]
Leave a Reply