Python Testing with unittest and pytest: Runnable Tests, Fixtures and Mocks

Build one score-normalisation example from a plain Python function into unittest and pytest suites, then add fixtures, tmp_path, mocks and boundary exercises.

KnowledgeGate Team

Exam prep & CS education

Updated 11 Nov 20266 min read
Python Testing with unittest and pytest: Runnable Tests, Fixtures and Mocks

A function may pass one example yet fail at a boundary or after a later edit. A useful test is repeatable and checks observable behaviour without manual inspection. A plain function can be tested with unittest and pytest, parametrisation, fixtures, a temporary file, and a mock. If functions, exceptions, or imports still feel unfamiliar, review the Python Course: Concepts, MCQs & Coding first.

Python testing starts with a precise behaviour contract

A unit test gives controlled input to a small unit and checks a result or exception. Arrange correct = 37 and total = 50, call normalize_score(correct, total), then assert 74.0. Test code states the contract; a pass covers only the cases run.

Keep this production function in score.py:

python
def normalize_score(correct: int, total: int) -> float:
    if total <= 0:
        raise ValueError("total must be positive")
    if correct < 0 or correct > total:
        raise ValueError("correct must be between 0 and total")
    return round(correct / total * 100, 2)

For the normal case, 37 / 50 = 0.74; multiplying by 100 gives 74.0, unchanged by rounding to two decimals.

Call

Required behaviour

normalize_score(0, 8)

returns 0.0

normalize_score(10, 10)

returns 100.0

normalize_score(1, 3)

returns 33.33

normalize_score(4, 0)

raises ValueError("total must be positive")

normalize_score(11, 10)

raises ValueError("correct must be between 0 and total")

Use this layout:

Code
project/
├── score.py
└── tests/
    ├── test_score_unittest.py
    └── test_score_pytest.py

The Coding & DSA Courses for Placements page is the broader route for Python and problem-solving practice.

Arrange-Act-Assert flow for normalize_score(37, 50), producing 74.0, with ValueError branches for zero total and excess correct answers.

unittest in Python: write and run the first test class

unittest is in Python's standard library. Create tests/test_score_unittest.py:

python
import unittest

from score import normalize_score


class NormalizeScoreTests(unittest.TestCase):
    def test_typical_score(self):
        self.assertEqual(normalize_score(37, 50), 74.0)

    def test_boundary_scores(self):
        self.assertEqual(normalize_score(0, 8), 0.0)
        self.assertEqual(normalize_score(10, 10), 100.0)

    def test_rejects_non_positive_total(self):
        with self.assertRaisesRegex(ValueError, "total must be positive"):
            normalize_score(4, 0)

    def test_rejects_impossible_correct_count(self):
        with self.assertRaisesRegex(
            ValueError, "correct must be between 0 and total"
        ):
            normalize_score(11, 10)


if __name__ == "__main__":
    unittest.main()

Discovery recognises test methods. self.assertEqual compares return values; assertRaisesRegex checks the exception type and message. Each method gets a fresh TestCase instance. This pure function needs no setUp or tearDown.

Run:

bash
python -m unittest discover -s tests -p "test_*unittest.py" -v

Expected output lists four tests, then Ran 4 tests and OK. Expecting 75.0 for (37, 50) shows actual 74.0; fix the expectation, not correct production logic.

pytest in Python: plain asserts and parametrised cases

Install pytest in the active environment with python -m pip install pytest, then create tests/test_score_pytest.py:

python
import pytest

from score import normalize_score


@pytest.mark.parametrize(
    ("correct", "total", "expected"),
    [
        (37, 50, 74.0),
        (0, 8, 0.0),
        (10, 10, 100.0),
        (1, 3, 33.33),
    ],
)
def test_normalize_score(correct, total, expected):
    assert normalize_score(correct, total) == expected


@pytest.mark.parametrize(
    ("correct", "total", "message"),
    [
        (4, 0, "total must be positive"),
        (11, 10, "correct must be between 0 and total"),
        (-1, 10, "correct must be between 0 and total"),
    ],
)
def test_rejects_invalid_counts(correct, total, message):
    with pytest.raises(ValueError, match=message):
        normalize_score(correct, total)

Parametrisation creates seven cases: four valid and three invalid. python -m pytest tests/test_score_pytest.py -q reports 7 passed. Before adding later tests, python -m pytest -q also discovers the four unittest.TestCase methods and reports 11 passed.

Concern

unittest

pytest

Availability

standard library

separately installed

Basic assertion

self.assertEqual(actual, expected)

rewritten plain assert

Repeated cases

subTest or loops

@pytest.mark.parametrize

Reusable setup

setUp and tearDown

fixtures

Exception checks

assertRaises

pytest.raises

Both frameworks test the same behaviour and can coexist during migration.

pytest fixtures and tmp_path: share setup without shared state

A fixture is requested by parameter name, and pytest injects its return value:

python
@pytest.fixture
def score_rows():
    return [(37, 50), (42, 60), (18, 20)]


def test_score_rows(score_rows):
    actual = [normalize_score(c, t) for c, t in score_rows]
    assert actual == [74.0, 70.0, 90.0]

Here, 42 / 60 * 100 = 70.0 and 18 / 20 * 100 = 90.0. The default function scope creates a fresh list per test; wider scopes risk mutable-state leaks.

Extend score.py with a filesystem boundary:

python
def write_summary(path, attempts):
    lines = [
        f"{normalize_score(correct, total):.2f}%"
        for correct, total in attempts
    ]
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")

Test the real write in isolation:

python
from score import write_summary


def test_write_summary(tmp_path):
    attempts = [(37, 50), (42, 60)]
    summary = tmp_path / "summary.txt"
    write_summary(summary, attempts)
    assert summary.read_text(encoding="utf-8") == (
        "74.00%\n70.00%\n"
    )

The built-in tmp_path fixture provides a unique temporary directory that pytest cleans up, keeping the repository untouched.

unittest.mock with pytest: verify an interaction at the boundary

Keep testing normalize_score with real values. An external notification client, however, should send nothing during a unit test. Add this to score.py:

python
def notify_result(client, student_id, correct, total):
    score = normalize_score(correct, total)
    if score >= 75:
        client.send(student_id, f"Score: {score:.2f}")
        return True
    return False

Use unittest.mock inside the pytest file:

python
from unittest.mock import Mock

from score import notify_result


def test_notify_result_sends():
    client = Mock()
    result = notify_result(client, "S-17", 42, 50)
    assert result is True
    client.send.assert_called_once_with("S-17", "Score: 84.00")


def test_notify_result_does_not_send_below_threshold():
    client = Mock()
    result = notify_result(client, "S-18", 37, 50)
    assert result is False
    client.send.assert_not_called()

S-17 scores 84.0, so one exact call is required; S-18 scores 74.0, so none is allowed. The mock proves calls and arguments, not delivery. Keep normalize_score real so the business rule executes.

Two notify_result paths show a passing score with one ledger call and a failing score with no calls.

Python test failures and flaky tests: cause, consequence and repair

Trap

Consequence

Repair

Exact 0.1 + 0.2 == 0.3

Binary floating point can fail the intended arithmetic check

Use self.assertAlmostEqual(0.1 + 0.2, 0.3) or assert 0.1 + 0.2 == pytest.approx(0.3)

Shared module-level mutable list

Results depend on order, so tests pass alone and fail together

Return a new list from a function-scoped fixture or rebuild state in setUp

Mocking the function under test

Assertions pass without executing its rules, so defects survive

Mock only slow or external boundaries and keep pure collaborators real

Broad pytest.raises(Exception)

A wrong TypeError can look like the expected validation path

Require ValueError and match total must be positive when the message is contractual

Because normalize_score rounds before returning, its exact results are contractual. Inject clocks or seeded random generators to make varying inputs testable.

Reproduce one test, read the first failing assertion, compare it with the contract, fix the correct layer, rerun the focused test, then run the suite.

unittest and pytest exercises: test boundaries before happy paths

Exercises may ask for equivalence classes, boundaries, exception tests, isolation, failure diffs, or mocking choices. Start from the contract, partition inputs, then assert one representative per partition.

  1. Predict normalize_score(21, 28). Since 21 / 28 = 0.75, the result is 75.0.

  2. Find the smallest case that catches correct >= total. Use (10, 10), which must return 100.0. The correct invalid condition is correct > total.

  3. A test expects 33.3 from (1, 3). The two-decimal contract gives round(1 / 3 * 100, 2) == 33.33, so repair the expected value to 33.33.

Test write_summary with the real function and tmp_path, then assert 74.00%\n70.00%\n exactly. The isolated text file needs no filesystem mock. Unlike a CSV parser, this helper has no header or name fields; the assertion owns only its two percentage lines. In Sorting Algorithms: Complexity and Comparison, duplicate values, already-sorted input, and empty input make useful boundaries. In Dynamic Programming Explained: 0/1 Knapsack, base cases and boundary transitions deserve explicit tests.

Python testing in one workflow and the next step

  1. State the contract.

  2. Keep the unit small.

  3. Arrange fixed inputs.

  4. Assert returned values and exact exception types.

  5. Include boundaries 0/8 and 10/10.

  6. Parametrise repeated cases.

  7. Isolate files with tmp_path and external clients with a mock.

  8. After repairing a focused failure, run the whole suite.

Create both test files and make both commands green. Then deliberately introduce correct >= total and confirm that the 10/10 -> 100.0 boundary test catches it. Once this workflow is clear, use DSA Using Python for broader Python problem-solving practice.