Pytest: How to Use It (Beginnerโs Guide with Examples)
If you're writing tests in Python, pytest is one of the most powerful, easy-to-use testing frameworks available. Whether you're a beginner or switching from unittest
, this guide will show you how to use pytest effectively โ with simple examples and best practices.
๐ What Is Pytest?
Pytest is a testing framework for Python that allows you to write simple unit tests, complex functional tests, and even parameterized tests with very little boilerplate.
โ Why Use Pytest?
- Super simple syntax
- Supports fixtures, parametrize, and plugins
- Works with any Python codebase
- Auto-discovers test files and functions
๐ฆ How to Install Pytest
Install it via pip:
pip install pytest
Check version:
pytest --version
๐งช Writing Your First Test
test_math.py
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
Thatโs it! No class, no main function โ just a plain function starting with test_
.
๐ How to Run Pytest
Just run this command in your terminal:
pytest
Pytest will automatically discover:
- Files starting with
test_
or ending with_test.py
- Functions starting with
test_
To run a specific file:
pytest test_math.py
To run a specific function:
pytest test_math.py::test_add
๐ Example: Testing with Multiple Inputs
import pytest
@pytest.mark.parametrize("a, b, expected", [
(1, 1, 2),
(2, 3, 5),
(10, -5, 5)
])
def test_add(a, b, expected):
assert a + b == expected
๐ง Pytest Fixtures
Fixtures help you set up resources for your tests (like DB connections, configs, etc.)
import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3]
def test_length(sample_data):
assert len(sample_data) == 3
โ Handling Exceptions
import pytest
def divide(x, y):
return x / y
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError):
divide(1, 0)
๐ Generating Test Reports
Want a nice terminal report?
pytest -v
Generate an HTML report (with plugin):
pip install pytest-html
pytest --html=report.html
๐ Summary
Using pytest is simple and powerful. With just a few lines of code, you can test your Python functions, scale to more complex projects, and integrate with CI/CD pipelines.
โ Quick Recap:
Task | Command or Syntax |
---|---|
Install Pytest | pip install pytest |
Run all tests | pytest |
Run specific test file | pytest test_file.py |
Run single test function | pytest test_file.py::test_func |
Use fixtures | @pytest.fixture |
Parametrize tests | @pytest.mark.parametrize(...) |