Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 11 / Topic 12 of 12

Putting it together: testing a grade calculator

examples/grade_calculator.py turns marks into grades:

Average Grade
90 and above A+
75 to below 90 A
60 to below 75 B
40 to below 60 C (pass mark is 40)
below 40 F

It raises ValueError for marks outside 0-100 or an empty list, and logs a warning for a student with no marks. It uses logger = logging.getLogger(__name__) but never calls basicConfig; the program that uses it decides that.

tests/test_grade_calculator.py uses everything from this part:

import grade_calculator as gc
import pytest

@pytest.fixture
def class_results():
    return {"Asha": [95, 88, 92], "Meera": [30, 41, 35], "Kiran": []}

@pytest.mark.parametrize(
    ("marks", "expected"),
    [(90, "A+"), (89.99, "A"), (75, "A"), (74, "B"), (40, "C"), (39.5, "F")],
)
def test_grade_for_boundaries(marks, expected):
    assert gc.grade_for(marks) == expected

@pytest.mark.parametrize("marks", [-1, 100.5])
def test_grade_for_rejects_marks_outside_0_to_100(marks):
    with pytest.raises(ValueError, match="0-100"):
        gc.grade_for(marks)

def test_average_of_three_marks():
    assert gc.average([70, 85, 90]) == pytest.approx(81.6667, abs=0.001)

def test_report_skips_students_without_marks(class_results):
    report = gc.class_report(class_results)
    assert "Kiran" not in report
    assert report["Meera"] == {"average": 35.33, "grade": "F", "passed": False}

Run all tests of this part, from this part's folder:

python -m pytest -q tests
.....................................                                    [100%]
37 passed in 0.05s

Then run the real program, 07_grade_report.py:

WARNING grade_calculator: No marks for Kiran, skipping
INFO grade_calculator: Report ready for 3 of 4 students
Name     Average  Grade  Result
Asha       91.67  A+     PASS
Ravi       55.00  C      PASS
Meera      35.33  F      FAIL

The log lines name the module (grade_calculator) they came from.

Done here? The practice set for Part 11 — 7 exercises with solutions — is on the part page.

Search the guide