Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Advanced Python

Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises

A test is a line on a checklist your code must pass every time. Catch a discount bug with assert, read the E lines in the pytest report, cover cases with parametrize, share a cart with a fixture, test errors with pytest.raises, and see why a passing test from an AI tool can prove nothing.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Advanced Python

What you will learn

  • Write a test function with assert and run it with pytest
  • Read a pytest failure report and decide whether the code or the test is wrong
  • Cover many cases with parametrize and share setup with a fixture
  • Test expected errors with pytest.raises, and spot weak tests from AI tools

Before you start

  • Python functions and return values
  • Raising exceptions
  • Installing a package in a virtual environment

So far you've checked your code by running it and looking at the result. A test does that looking for you, and it does it every time.

Think about a checklist by your front door: keys, wallet, phone. Each morning you go down the list and tick each line. You don't have to remember anything, because the list remembers it for you. And the day your wallet isn't there, that one line stops you at the door. That's a test: one line on a list that your code has to pass, each time you run it.

This is plain pytest on plain Python. For web apps, see testing FastAPI with pytest.

The code we're testing

def apply_discount(price, percent):
    if price < 0:
        raise ValueError("price cannot be negative")
    if not 0 <= percent <= 100:
        raise ValueError("percent must be 0 to 100")
    return price - price * percent / 100


def add_tax(price, rate):
    return round(price * (1 + rate), 2)


def cart_total(prices):
    return sum(prices)

That's prices.py, with its two checks already in place (we'll add them along the way). A script that calls these functions and prints the results gives 180.0, 50.0 and 20.0. Then your eyes do the work: is ten percent off 200 really 180? Yes. That's the check from checking AI's code. But a script only prints. Change one line next week and it still prints, with no complaint, and nobody's looking.

Say this line gets changed, by you or by an AI tool:

def apply_discount(price, percent):
    return price - percent

It looks harmless and the code still runs. But 200 with 10% now gives 190 instead of 180. Nothing crashes, so nothing tells you.

Your first test

from prices import apply_discount


def test_ten_percent_off():
    assert apply_discount(200, 10) == 180


def test_no_discount():
    assert apply_discount(50, 0) == 50

The file name starts with test_, and so does each function. That's how pytest finds them; there's nothing to register. assert says "this must be true". If it is, nothing happens; if it's false, the test fails. On the right is 180, a number we worked out ourselves, not from the code.

pytest isn't in the standard library, so install it in your virtual environment with pip install pytest. Then, from the project folder, run it on the buggy code:

pytest
============================= test session starts =============================
platform win32 -- Python 3.13.14, pytest-9.2.0, pluggy-1.7.0
rootdir: S04L05_1_Pytest
collected 2 items

test_discount.py F.                                                      [100%]

================================== FAILURES ===================================
____________________________ test_ten_percent_off _____________________________

    def test_ten_percent_off():
>       assert apply_discount(200, 10) == 180
E       assert 190 == 180
E        +  where 190 = apply_discount(200, 10)

test_discount.py:5: AssertionError
=========================== short test summary info ===========================
FAILED test_discount.py::test_ten_percent_off - assert 190 == 180
========================= 1 failed, 1 passed in 0.22s =========================

Reading the report

Read it like a traceback, from the bottom. The last line is the score. The FAILED line names the file and the test. In the failures part, the line with > is the line that failed. The E lines are the key: assert 190 == 180, with the actual value filled in for you, and where that 190 came from. test_discount.py:5 gives the file and line. In the progress line, F means failed and . means passed.

When a test fails, the code and the test disagree. Work out the right answer yourself. If the test is right, fix the code. Never change the expected number just to make it pass. test fails 190 != 180 who is right? work it out yourself test is right fix the code test is wrong fix the test, with reason
A failure means the code and the test disagree. You decide who's right.

Ten percent off 200 is 180, so the test is right and the code is wrong. Fix the code back to price - price * percent / 100, run pytest again, and you get test_discount.py .. and 2 passed. Notice test_no_discount passed even with the bug, because taking away zero changes nothing. One passing test doesn't prove much. You need different cases.

Many cases with parametrize

import pytest
from prices import apply_discount


@pytest.mark.parametrize("price, percent, expected", [
    (100, 0, 100),
    (200, 10, 180),
    (80, 25, 60),
    (50, 100, 0),
])
def test_discount_cases(price, percent, expected):
    assert apply_discount(price, percent) == expected

You name the inputs, give one row per case, and pytest passes each row's values into the function. One function, four tests. Run with pytest -v (verbose, one line per test) on the buggy code, and the report starts:

test_discount_cases.py::test_discount_cases[100-0-100] PASSED            [ 25%]
test_discount_cases.py::test_discount_cases[200-10-180] FAILED           [ 50%]
test_discount_cases.py::test_discount_cases[80-25-60] FAILED             [ 75%]
test_discount_cases.py::test_discount_cases[50-100-0] FAILED             [100%]

and ends:

FAILED test_discount_cases.py::test_discount_cases[200-10-180] - assert 190 =...
FAILED test_discount_cases.py::test_discount_cases[80-25-60] - assert 55 == 60
FAILED test_discount_cases.py::test_discount_cases[50-100-0] - assert -50 == 0
========================= 3 failed, 1 passed in 0.24s =========================

Each line carries its values in square brackets, so you know which case failed. And that's a clue: the only case that passed has zero percent, so the problem is in how we use the percent. With the fix, all four pass.

Shared setup with a fixture

import pytest
from prices import add_tax, cart_total


@pytest.fixture
def cart():
    return [12.5, 4.0, 3.5]


def test_cart_total(cart):
    assert cart_total(cart) == 20.0


def test_add_item(cart):
    cart.append(10.0)
    assert cart_total(cart) == 30.0


def test_total_with_tax(cart):
    assert add_tax(cart_total(cart), 0.1) == 22.0


def test_empty_cart():
    assert cart_total([]) == 0
test_cart.py::test_cart_total PASSED                                     [ 25%]
test_cart.py::test_add_item PASSED                                       [ 50%]
test_cart.py::test_total_with_tax PASSED                                 [ 75%]
test_cart.py::test_empty_cart PASSED                                     [100%]

============================== 4 passed in 0.05s ==============================

A test with a parameter named cart gets the fixture's result. test_add_item appends 10, making 30. Then test_total_with_tax gets its own fresh cart, back to 20, which with 10% tax is 22. A fixture is shared setup, built fresh for each test, so one test can't disturb another. test_empty_cart doesn't ask for it, so it doesn't get one.

Testing that an error is raised

Sometimes the right answer is an error. apply_discount raises ValueError for a percent outside 0 to 100. A plain call would just fail the test, so wrap it:

import pytest
from prices import apply_discount


def test_percent_over_100_is_rejected():
    with pytest.raises(ValueError):
        apply_discount(100, 150)


def test_error_message():
    with pytest.raises(ValueError, match="0 to 100"):
        apply_discount(100, -5)


def test_negative_price_is_rejected():
    with pytest.raises(ValueError):
        apply_discount(-20, 10)

match means the error message must also contain that text. If the code doesn't raise, the test fails. Here's the third test run before the negative-price check was added to prices.py:

test_errors.py ..F                                                       [100%]

================================== FAILURES ===================================
_______________________ test_negative_price_is_rejected _______________________

    def test_negative_price_is_rejected():
>       with pytest.raises(ValueError):
             ^^^^^^^^^^^^^^^^^^^^^^^^^
E       Failed: DID NOT RAISE ValueError

test_errors.py:16: Failed

So pytest.raises turns an expected error into a pass, and a missing error into a failure. Adding the if price < 0 check makes all three pass.

How pytest finds tests

pytest --collect-only -q
test_cart.py::test_cart_total
test_cart.py::test_add_item
test_cart.py::test_total_with_tax
test_cart.py::test_empty_cart
test_discount.py::test_ten_percent_off
test_discount.py::test_no_discount
test_discount_cases.py::test_discount_cases[100-0-100]
test_discount_cases.py::test_discount_cases[200-10-180]
test_discount_cases.py::test_discount_cases[80-25-60]
test_discount_cases.py::test_discount_cases[50-100-0]
test_errors.py::test_percent_over_100_is_rejected
test_errors.py::test_error_message
test_errors.py::test_negative_price_is_rejected
test_weak_check.py::test_returns_a_number

14 tests collected in 0.04s

It lists tests without running them. prices.py and the print script don't start with test_, so they're skipped. Inside each test file, only functions starting with test_ count, so the cart fixture isn't listed, and the parametrized function shows up four times. pytest -q then runs them all: 14 dots, 14 passed. That's your checklist. Run it after each change.

Weak tests from AI tools

You'll often ask an AI tool for tests too. Here's the kind you might get back:

from prices import apply_discount


def test_returns_a_number():
    result = apply_discount(200, 10)
    assert isinstance(result, (int, float))

Run it on the buggy code that returns 190, and you get 1 passed. 190 is a number. A passing test only proves what it checks, and this one never said what the answer should be. Compare it with == 180, which caught the bug. When you work with an AI tool:

  • The expected numbers come from you. Work out a few cases yourself.
  • Ask for edge cases by name: "Write pytest tests for apply_discount, with 0%, 100% and an invalid percent."
  • Make sure each test can fail. Break the code for a moment and check the test catches it.
  • If a test fails and the tool changes the expected number to make it pass, don't accept that. Decide who's right first.

Quick recap

ToolWhat it does
def test_x(): assert ...one test; found by its test_ name
pytest, -v, -qrun all tests; verbose; quiet
E linesactual vs expected values in a failure
@pytest.mark.parametrizeone function, many cases
@pytest.fixturefresh shared setup for each test
pytest.raises(Err, match=...)the right answer is an error

Try it yourself

Start without the negative-price check. Add test_negative_price_is_rejected, watch it fail with "DID NOT RAISE", then fix the code so it passes.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 36 of 48

Previous
Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
Next post
Async Python: async def, await, asyncio.gather and the Blocking Trap

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy

A regex is a stencil for a shape of text. Watch it slide and back up, build patterns with \d, \w, quantifiers and anchors, use search, findall, sub and split, pull parts out with named groups, and test AI-written patterns on edge cases.

Async Python: async def, await, asyncio.gather and the Blocking Trap

One cook, several pots: async lets one program wait on many things at once. See what async def and await really do, why three awaits in a row are no faster, how gather and TaskGroup bring 0.6 seconds down to 0.2, and the two mistakes that catch almost everyone.

Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose

One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.

One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask

The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.

On this page

  • The code we're testing
  • Your first test
  • Reading the report
  • Many cases with parametrize
  • Shared setup with a fixture
  • Testing that an error is raised
  • How pytest finds tests
  • Weak tests from AI tools
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.