Users Pricing

blog

Home Blogs Getting Started with pytest for Python Unit Testing – MindStick
Getting Started with pytest for Python Unit Testing

Getting Started with pytest for Python Unit Testing

Sagar Poudel 91 26 Nov 2026

You change one line in a pricing function. The invoices look fine in your quick check. Two weeks later, someone notices GST is being calculated on the amount before discount, and fifty invoices are wrong.

Automated tests catch that kind of mistake in seconds, every time you change the code. In Python, pytest is the most popular testing tool, mainly because writing a test is as simple as writing a function with an assert.

This tutorial builds a real test suite for a small invoice-pricing module, step by step.

Install

pip install pytest

The code we're testing

A small module that calculates invoice totals with discounts and GST. We use Decimal, not float, because money and binary floating point don't mix well.

The tests

Save tests in a tests folder, in files named test_*.py. pytest finds them automatically.

To let tests import pricing.py from the project root, add a pytest.ini file:

[pytest]
pythonpath = .

Run them:

pytest -q

.......... [100%]
10 passed in 0.03s

That's our actual output: 10 tests (some functions run several times with different data) passing in a few hundredths of a second.

Plain assert

assert result["total"] == Decimal("2360.00")

No special assertion methods to remember. When an assert fails, pytest shows both sides of the comparison:

> assert result["gst"] == Decimal("360.00")
E AssertionError: assert Decimal('320.00') == Decimal('360.00')

Testing that errors are raised

Testing failure cases is as important as testing success. match checks the error message too, using a regular expression.

parametrize: one test, many cases

@pytest.mark.parametrize("category, expected_gst", [
("standard", Decimal("180.00")),
("reduced", Decimal("50.00")),
("exempt", Decimal("0.00")),
])

Instead of copying a test three times, list the inputs and expected results. Each case runs and is reported separately, so you see exactly which one failed. It's the easiest way to cover edge cases: zero, negative numbers, boundaries, empty inputs.

Fixtures: reusable setup

@pytest.fixture
def sample_lines():
return [(3, 199.99), (1, 49.50)]

def test_with_fixture(sample_lines):

A fixture is a function that prepares something a test needs. pytest sees the parameter name sample_lines, runs the fixture and passes in the result.

Put shared fixtures in a conftest.py file and every test in that folder can use them.

Built-in fixtures you'll use often

tmp_path: a fresh temporary folder for each test.

def test_report_file_is_created(tmp_path):
out = tmp_path / "report.csv"
write_report(out)
assert out.read_text().startswith("City,Revenue")

monkeypatch: temporarily change environment variables, attributes or functions.

def test_reads_api_key_from_env(monkeypatch):
monkeypatch.setenv("API_KEY", "test-key")
assert load_settings().api_key == "test-key"

capsys: capture printed output.

Mocking external services

Unit tests shouldn't send real emails, charge real cards or call real APIs. Replace those calls with mocks:

from unittest.mock import patch

def test_order_confirmation_sends_email():
with patch("orders.send_email") as fake_send:
confirm_order(order_id=1042)
fake_send.assert_called_once()
assert "1042" in fake_send.call_args.kwargs["subject"]

Patch the name where it's used (orders.send_email), not where it's defined. Mock at the edges of your system, such as HTTP calls, email and payment gateways, and test your own logic for real.

Useful command-line options

pytest # run everything
pytest -q # quieter output
pytest -x # stop at the first failure
pytest -k gst # run tests whose names contain "gst"
pytest tests/test_pricing.py::test_standard_invoice_total # one test
pytest --lf # re-run only the tests that failed last time
pytest -vv # very detailed output

Measuring coverage

pip install pytest-cov
pytest --cov=pricing --cov-report=term-missing

Coverage shows which lines your tests never executed. Use it to find untested branches, such as an error path you forgot. Don't chase 100%: covered code isn't necessarily well-tested code. Focus on business rules, calculations and error handling.

Running tests automatically

Tests are most valuable when they run on every change. In GitHub Actions:

- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r requirements.txt pytest
- run: pytest -q

Make passing tests a requirement for merging pull requests.

Habits that make tests worth having

- Test behaviour, not implementation. Check results and side effects, not private details that change when you refactor.
- One idea per test, with a descriptive name like test_discount_is_applied_before_gst. The name should explain what broke when it fails.
- Write a test for every bug before fixing it. It proves the fix and stops the bug coming back.
- Keep tests fast. Slow suites don't get run. Mock slow external calls and use in-memory or containerised databases.
- Keep tests independent. Each test should set up its own data and not depend on others running first.

Your next step

With pytest, a test is just a function with an assert. Add parametrize for many cases, fixtures for setup, pytest.raises for errors, mocks for external services, and run everything in CI.

Pick the function in your project you'd least like to break, probably something with money or permissions, and write five tests for it today. That's how a test suite starts.


Sagar Poudel

Senior RF Engineer at Nepal Telecom

Working as Senior RF Engineer with Nepal Telecom in Kathmandu. I have 4 years of experience in mobile network planning and optimisation, and earlier worked with WorldLink Communications as RF Engineer. I graduated from Paschimanchal Campus, Institute of Engineering with a BE in Electronics and Communication Engineering. I am originally from Pokhara, Gandaki Province. In my free time I like hiking around the valley and trekking in the Himalayas.


Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md