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

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:
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 |
|---|---|
| returns |
| returns |
| returns |
| raises |
| raises |
Use this layout:
project/
├── score.py
└── tests/
├── test_score_unittest.py
└── test_score_pytest.pyThe Coding & DSA Courses for Placements page is the broader route for Python and problem-solving practice.

unittest in Python: write and run the first test class
unittest is in Python's standard library. Create tests/test_score_unittest.py:
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:
python -m unittest discover -s tests -p "test_*unittest.py" -vExpected 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:
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 |
| rewritten plain |
Repeated cases |
|
|
Reusable setup |
| fixtures |
Exception checks |
|
|
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:
@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:
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:
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:
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 FalseUse unittest.mock inside the pytest file:
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.

Python test failures and flaky tests: cause, consequence and repair
Trap | Consequence | Repair |
|---|---|---|
Exact | Binary floating point can fail the intended arithmetic check | Use |
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 |
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 | A wrong | Require |
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.
Predict
normalize_score(21, 28). Since21 / 28 = 0.75, the result is75.0.Find the smallest case that catches
correct >= total. Use(10, 10), which must return100.0. The correct invalid condition iscorrect > total.A test expects
33.3from(1, 3). The two-decimal contract givesround(1 / 3 * 100, 2) == 33.33, so repair the expected value to33.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
State the contract.
Keep the unit small.
Arrange fixed inputs.
Assert returned values and exact exception types.
Include boundaries
0/8and10/10.Parametrise repeated cases.
Isolate files with
tmp_pathand external clients with a mock.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.
Keep learning
Python Dictionaries Explained: Keys, Methods, Worked Examples and Exam Traps
Learn how Python dictionaries store, retrieve and mutate values. Trace a complete frequency counter, then practise the membership, aliasing and duplicate-key traps that make output questions tricky.
Python Conditional Statements Explained: if, elif, else, Nested Logic and Worked Examples
Learn a reliable way to trace Python branches, from Boolean expressions and short-circuiting to nested decisions, truthiness, boundary checks, and a complete scholarship classifier.
Python Scope and Flow Explained: Worked Examples and Exam Question Patterns
Learn to separate Python name resolution from execution order with a nested-function trace, an UnboundLocalError repair, module examples, and exam-style checks.
Asyncio in Python: Event Loops, Coroutines and Runnable Examples
Build a clear mental model of Python's event loop, then run two dependency-free examples covering concurrent waits, result ordering, timeouts and cleanup.





