Pytest Tutorial for Beginners: Fixtures, Parametrize and Real Examples
Pytest lets you write Python tests with plain functions and plain assert statements. Build a small test suite step by step, read real failure output and learn the features you will use every day.
- Pytest finds functions named
test_*and checks them with plainassertstatements. - Fixtures provide reusable setup and cleanup, requested simply by naming them as arguments.
@pytest.mark.parametrizeruns one test with many inputs.- Put shared fixtures in
conftest.py, and you do not need to import them.
If you have avoided writing tests because they feel like a chore, this pytest tutorial should change your mind. Pytest removes most of the ceremony: there are no classes to inherit from and no special assertion methods to remember. A test can be just two lines.
We will build a small shopping cart and test it step by step. We ran everything on Python 3.13 with pytest 9.2, and the output shown is real, though we trimmed the file paths and timing details that will differ on your machine.
Why pytest?
Python ships with unittest, which works well, but pytest is usually the more convenient choice. Here is the same check in each:
| Task | unittest | pytest |
|---|---|---|
| Check equality | self.assertEqual(a, b) |
assert a == b |
| Check an exception | self.assertRaises(...) |
pytest.raises(...) |
| Test structure | A class that inherits from TestCase |
A plain function |
| Setup and cleanup | setUp and tearDown methods |
Reusable fixtures |
| Many inputs | subTest loops |
parametrize |
Pytest can also run your existing unittest tests, so you can switch over gradually. It has a large plugin ecosystem as well, including pytest-cov for coverage and pytest-xdist for parallel runs.
Install pytest
Create a virtual environment first, as explained in our Python virtual environment tutorial, and then install it:
pip install pytest
pytest --version
# pytest 9.2.0
Create a project folder containing two files, cart.py and test_cart.py. Pytest finds tests automatically by following naming rules: files named test_*.py or *_test.py, functions starting with test, and classes starting with Test. If a test is not being picked up, a naming mismatch is the first thing to check.
The code to test
# cart.py
class Cart:
def __init__(self):
self.items = []
def add(self, name, price, qty=1):
if qty < 1:
raise ValueError("qty must be at least 1")
self.items.append((name, price, qty))
def total(self, discount=0):
subtotal = sum(price * qty for _, price, qty in self.items)
return round(subtotal * (1 - discount / 100), 2)
Your first tests
# test_cart.py
from cart import Cart
def test_empty_cart_is_free():
assert Cart().total() == 0
That is a complete test. Run pytest from the project folder, and it reports one passing test. If you get an import error, run it as python -m pytest, which adds the current folder to the import path.
Reading failures
This is where pytest really shines. Here is a test with a deliberately wrong expected value:
def test_wrong_total():
c = Cart()
c.add("Keyboard", 1500)
assert c.total() == 1400
And this is what it printed when we ran it:
def test_wrong_total():
c = Cart()
c.add("Keyboard", 1500)
> assert c.total() == 1400
E assert 1500.0 == 1400
E + where 1500.0 = total()
FAILED fail_example.py::test_wrong_total - assert 1500.0 == 1400
============================== 1 failed in 0.12s ==============================
The > marks the failing line, and the E lines show the actual values. You did not have to add a custom message, because pytest rewrites assert statements so they can report what they compared. It does the same for lists and dictionaries, pointing out exactly which items differ.
Testing exceptions
Error handling is behaviour too, and it deserves tests. pytest.raises passes only if the block raises the expected exception:
import pytest
def test_rejects_zero_qty():
with pytest.raises(ValueError, match="at least 1"):
Cart().add("Pen", 10, qty=0)
The optional match argument checks the message using a regular expression, so a different ValueError will not pass by accident. To learn how to raise and handle errors like this one, read our guide to Python exception handling.
Fixtures: reusable setup
Most tests need something prepared first. A fixture is a function that provides it. Decorate it with @pytest.fixture, and any test that names it as an argument receives the result:
@pytest.fixture
def cart():
c = Cart()
c.add("Keyboard", 1500)
c.add("Mouse", 500, qty=2)
return c
def test_total(cart):
assert cart.total() == 2500
Each test gets a fresh cart by default, so tests cannot affect one another. Pytest matches the argument name to the fixture’s name, and you never call the fixture yourself. @pytest.fixture is a decorator, which we explain in Python decorators explained.
Cleanup with yield
Use yield instead of return when you need to clean up afterwards. Code after yield runs when the test finishes, even if it failed:
@pytest.fixture
def temp_db():
print("\nopen db")
yield {"users": []}
print("close db")
def test_db(temp_db):
assert temp_db["users"] == []
Running with -s to show printed output confirmed that the order was open, test, then close.
Fixture scope and conftest.py
By default, a fixture runs once per test. For expensive setup, such as a database or browser, change its lifetime with scope:
| Scope | Created once per |
|---|---|
function (default) |
Test |
class |
Test class |
module |
File |
package |
Package |
session |
Whole test run |
Put fixtures used by several files into a file called conftest.py. Pytest loads it automatically, so tests can use its fixtures with no import. Be careful with shared scopes, though, because a change made by one test can leak into the next.
Parametrize: one test, many inputs
Rather than copying a test for each value, list the cases:
@pytest.mark.parametrize("discount, expected", [
(0, 2500),
(10, 2250),
(100, 0),
])
def test_discount(cart, discount, expected):
assert cart.total(discount) == expected
Each row becomes its own test, and you can see this in the verbose output from our run of the complete file:
test_cart.py::test_total PASSED [ 16%]
test_cart.py::test_discount[0-2500] PASSED [ 33%]
test_cart.py::test_discount[10-2250] PASSED [ 50%]
test_cart.py::test_discount[100-0] PASSED [ 66%]
test_cart.py::test_rejects_zero_qty PASSED [ 83%]
test_cart.py::test_empty_cart_is_free PASSED [100%]
============================== 6 passed in 0.05s ==============================
If one row fails, the others still run, and the name tells you exactly which values caused the problem. Notice that we combined parametrize with the cart fixture. To choose values that are likely to find bugs, use boundary value analysis.
Tip: When your parameters are long or unclear, pass ids=["none", "ten", "full"] to give each case a readable name in the report.
Useful built-in fixtures
Pytest includes several ready-made fixtures. These two are especially handy, and both passed in our run:
def test_write_report(tmp_path):
report = tmp_path / "report.txt"
report.write_text("passed")
assert report.read_text() == "passed"
def read_mode():
return os.environ.get("APP_MODE", "dev")
def test_mode(monkeypatch):
monkeypatch.setenv("APP_MODE", "staging")
assert read_mode() == "staging"
tmp_path gives each test a unique temporary folder, so tests never touch real files. monkeypatch changes environment variables or attributes, and undoes the change when the test ends. Another useful one is capsys, which captures printed output so you can check it.
Markers: skip and xfail
Markers add labels and behaviour to tests:
@pytest.mark.skip(reason="payment sandbox is down")
def test_payment():
assert False
@pytest.mark.xfail(reason="floating point")
def test_rounding():
assert 0.1 + 0.2 == 0.3
skip does not run the test at all. xfail runs it but expects failure, so a known problem does not break your build. With the other extra tests in the same file, our run summarized as 3 passed, 1 skipped, 1 xfailed. That rounding test really does fail, by the way: in floating point arithmetic, 0.1 + 0.2 is not exactly 0.3. Use pytest.approx(0.3) when comparing decimals.
You can also create your own markers, such as @pytest.mark.slow, and run just those with pytest -m slow, or leave them out with -m "not slow". Register custom markers in your configuration file to avoid warnings.
Useful command line flags
| Command | What it does |
|---|---|
pytest -v |
Show each test name |
pytest -q |
Show a shorter summary |
pytest -x |
Stop at the first failure |
pytest -k discount |
Run tests whose names match a word |
pytest -s |
Show print output |
pytest --lf |
Rerun only the last failures |
pytest --pdb |
Open the debugger at a failure |
pytest test_cart.py::test_total |
Run one specific test |
Running pytest in CI
Tests are most valuable when they run automatically on every change. A minimal GitHub Actions job looks like this:
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- run: pip install -r requirements.txt
- run: python -m pytest
Pytest exits with a non-zero code when tests fail, which is what makes the pipeline stop. We did not execute this workflow file, so adapt it to your project. Our GitHub Actions CI/CD guide explains the details. Pytest also works well for browser tests, as our Selenium Python tutorial and Page Object Model tutorial show.
Final thoughts
You now have what you need for most Python test suites: plain asserts, fixtures for setup, parametrize for variations and a few flags for speed. Start small. Pick one function you recently fixed a bug in and write a test for that bug first. If you are unsure what to test at each level, read about unit vs integration testing.
Frequently asked questions
What is pytest used for?
Pytest is a Python testing framework. It is used for unit, integration and API tests, and it also works well with browser tools such as Selenium and Playwright.
Is pytest better than unittest?
Many teams prefer it for its simpler syntax, fixtures and clearer failures. unittest needs no installation, and pytest can run existing unittest tests too.
What is a fixture in pytest?
A fixture is a function that prepares something a test needs, such as data or a connection. Tests receive it by naming it as an argument.
What is conftest.py?
It is a special file for sharing fixtures and hooks across test files. Pytest loads it automatically, so its fixtures need no import statement.
Why is pytest not finding my tests?
Usually it is a naming issue. Files should be named test_*.py or *_test.py, and functions should start with test. Also check that you ran it from the right folder.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.