|
| 1 | +""" |
| 2 | +Tests for Project 02 — Filtering & Grouping |
| 3 | +
|
| 4 | +These tests verify boolean filtering, .loc[] selection, value_counts(), |
| 5 | +groupby(), and multi-aggregation using small inline DataFrames. |
| 6 | +
|
| 7 | +Why test data analysis functions? |
| 8 | + Even though pandas does the heavy lifting, your functions add logic on |
| 9 | + top (thresholds, column choices, aggregation strategies). Tests verify |
| 10 | + that YOUR logic is correct, not that pandas works. |
| 11 | +
|
| 12 | +Run with: pytest tests/test_project.py -v |
| 13 | +""" |
| 14 | + |
| 15 | +import pandas as pd |
| 16 | +import pytest |
| 17 | + |
| 18 | +from project import ( |
| 19 | + filter_high_grades, |
| 20 | + filter_with_loc, |
| 21 | + count_subjects, |
| 22 | + group_by_subject_mean, |
| 23 | + group_by_subject_multi_agg, |
| 24 | + top_students_per_subject, |
| 25 | +) |
| 26 | + |
| 27 | + |
| 28 | +@pytest.fixture |
| 29 | +def sample_df(): |
| 30 | + """Create a small DataFrame mimicking students.csv. |
| 31 | +
|
| 32 | + This dataset is carefully designed so we know the expected results: |
| 33 | + - 2 students above grade 80 (Alice=92, Diana=95) |
| 34 | + - 2 Math students, 1 Science, 1 English |
| 35 | + - Top per subject: Alice (Math), Bob (Science), Diana (English) |
| 36 | + """ |
| 37 | + return pd.DataFrame({ |
| 38 | + "name": ["Alice", "Bob", "Charlie", "Diana"], |
| 39 | + "subject": ["Math", "Science", "Math", "English"], |
| 40 | + "grade": [92, 78, 75, 95], |
| 41 | + "age": [16, 17, 16, 18], |
| 42 | + }) |
| 43 | + |
| 44 | + |
| 45 | +# ── Test: filter_high_grades returns correct rows ────────────────────── |
| 46 | + |
| 47 | +def test_filter_high_grades_default_threshold(sample_df): |
| 48 | + """filter_high_grades(df, 80) should return only students above 80. |
| 49 | +
|
| 50 | + WHY: Boolean indexing is the primary way to filter data in pandas. |
| 51 | + Getting the threshold comparison wrong (>= vs >, wrong column) would |
| 52 | + silently return wrong results. This test catches those mistakes. |
| 53 | + """ |
| 54 | + result = filter_high_grades(sample_df, threshold=80) |
| 55 | + |
| 56 | + assert len(result) == 2, "Should find exactly 2 students above grade 80" |
| 57 | + assert set(result["name"]) == {"Alice", "Diana"}, ( |
| 58 | + "Alice (92) and Diana (95) should be the high performers" |
| 59 | + ) |
| 60 | + |
| 61 | + |
| 62 | +def test_filter_high_grades_custom_threshold(sample_df): |
| 63 | + """filter_high_grades with a high threshold should return fewer rows. |
| 64 | +
|
| 65 | + WHY: The threshold parameter should actually be used — this test verifies |
| 66 | + that changing the threshold changes the output. A hardcoded filter would |
| 67 | + fail this test. |
| 68 | + """ |
| 69 | + result = filter_high_grades(sample_df, threshold=93) |
| 70 | + |
| 71 | + assert len(result) == 1, "Only Diana (95) is above 93" |
| 72 | + assert result.iloc[0]["name"] == "Diana" |
| 73 | + |
| 74 | + |
| 75 | +# ── Test: filter_with_loc selects Science students ───────────────────── |
| 76 | + |
| 77 | +def test_filter_with_loc_returns_science_only(sample_df): |
| 78 | + """filter_with_loc should return only Science students with name and grade. |
| 79 | +
|
| 80 | + WHY: .loc[] is more explicit than bracket indexing. This test verifies |
| 81 | + both the row filter (subject == 'Science') and the column selection |
| 82 | + (only 'name' and 'grade' columns). |
| 83 | + """ |
| 84 | + result = filter_with_loc(sample_df) |
| 85 | + |
| 86 | + assert len(result) == 1, "Only Bob studies Science" |
| 87 | + assert list(result.columns) == ["name", "grade"], ( |
| 88 | + "Should return only name and grade columns" |
| 89 | + ) |
| 90 | + assert result.iloc[0]["name"] == "Bob" |
| 91 | + |
| 92 | + |
| 93 | +# ── Test: count_subjects tallies correctly ───────────────────────────── |
| 94 | + |
| 95 | +def test_count_subjects_returns_correct_counts(sample_df): |
| 96 | + """count_subjects should count students per subject. |
| 97 | +
|
| 98 | + WHY: value_counts() is the quickest way to see the distribution of a |
| 99 | + categorical variable. This test verifies the counts match our known data. |
| 100 | + """ |
| 101 | + counts = count_subjects(sample_df) |
| 102 | + |
| 103 | + assert counts["Math"] == 2, "Math has 2 students (Alice, Charlie)" |
| 104 | + assert counts["Science"] == 1, "Science has 1 student (Bob)" |
| 105 | + assert counts["English"] == 1, "English has 1 student (Diana)" |
| 106 | + |
| 107 | + |
| 108 | +# ── Test: group_by_subject_mean computes correct averages ────────────── |
| 109 | + |
| 110 | +def test_group_by_subject_mean_values(sample_df): |
| 111 | + """group_by_subject_mean should return the average grade per subject. |
| 112 | +
|
| 113 | + WHY: groupby + mean is the pandas equivalent of SQL's GROUP BY + AVG. |
| 114 | + An incorrect grouping column or aggregation function would give wrong |
| 115 | + numbers. We verify against hand-calculated averages. |
| 116 | + """ |
| 117 | + means = group_by_subject_mean(sample_df) |
| 118 | + |
| 119 | + # Math average: (92 + 75) / 2 = 83.5 |
| 120 | + assert means["Math"] == pytest.approx(83.5), "Math mean should be 83.5" |
| 121 | + # Science average: 78 / 1 = 78.0 |
| 122 | + assert means["Science"] == pytest.approx(78.0), "Science mean should be 78.0" |
| 123 | + # English average: 95 / 1 = 95.0 |
| 124 | + assert means["English"] == pytest.approx(95.0), "English mean should be 95.0" |
| 125 | + |
| 126 | + |
| 127 | +# ── Test: group_by_subject_multi_agg returns mean, max, min ──────────── |
| 128 | + |
| 129 | +def test_group_by_subject_multi_agg_columns(sample_df): |
| 130 | + """group_by_subject_multi_agg should return a table with mean, max, min. |
| 131 | +
|
| 132 | + WHY: agg() with multiple functions is a powerful pattern. This test |
| 133 | + verifies that all three aggregation columns are present and that max/min |
| 134 | + are correct for the Math group (which has 2 students). |
| 135 | + """ |
| 136 | + result = group_by_subject_multi_agg(sample_df) |
| 137 | + |
| 138 | + assert "mean" in result.columns, "Result should have a 'mean' column" |
| 139 | + assert "max" in result.columns, "Result should have a 'max' column" |
| 140 | + assert "min" in result.columns, "Result should have a 'min' column" |
| 141 | + |
| 142 | + # Math: max=92, min=75 |
| 143 | + assert result.loc["Math", "max"] == 92 |
| 144 | + assert result.loc["Math", "min"] == 75 |
| 145 | + |
| 146 | + |
| 147 | +# ── Test: top_students_per_subject finds the best in each ───────────── |
| 148 | + |
| 149 | +def test_top_students_per_subject(sample_df): |
| 150 | + """top_students_per_subject should find the highest-scoring student per subject. |
| 151 | +
|
| 152 | + WHY: Combining groupby with idxmax is a common pattern for finding |
| 153 | + "the best X in each category." This test verifies the combination works |
| 154 | + end-to-end. |
| 155 | + """ |
| 156 | + result = top_students_per_subject(sample_df) |
| 157 | + |
| 158 | + # Convert to a dict of subject -> name for easy checking. |
| 159 | + top_by_subject = dict(zip(result["subject"], result["name"])) |
| 160 | + |
| 161 | + assert top_by_subject["Math"] == "Alice", "Alice has the highest Math grade (92)" |
| 162 | + assert top_by_subject["Science"] == "Bob", "Bob is the only Science student" |
| 163 | + assert top_by_subject["English"] == "Diana", "Diana is the only English student" |
0 commit comments