1. Home
  2. Blog
  3. Test Automation

Test Automation

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.

10 min read
Pytest tutorial for beginners: fixtures, parametrize and real examples

Key takeaways

  • Pytest finds functions named test_* and checks them with plain assert statements.
  • Fixtures provide reusable setup and cleanup, requested simply by naming them as arguments.
  • @pytest.mark.parametrize runs 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →