From 1feca8c2d621f507782d6928c059cf2e19d869aa Mon Sep 17 00:00:00 2001 From: Robert Jackson Date: Thu, 23 Apr 2026 12:07:19 -0500 Subject: [PATCH 1/4] ADD: Unit tests for plot_confusion_matrix with mock CSV data Adds tests/test_confusion_matrix.py with five tests covering title, return value, normalization, custom column names, and default-axis behavior. Removes sklearn from conftest mocks (real sklearn is now installed in CI) and adds scikit-learn to the workflow pip install. Co-Authored-By: Claude Sonnet 4.6 --- .github/workflows/tests.yml | 2 +- tests/conftest.py | 9 +++-- tests/test_confusion_matrix.py | 67 ++++++++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 4 deletions(-) create mode 100644 tests/test_confusion_matrix.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 10a7ad6..b9bbe86 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -24,7 +24,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install pytest pytest-asyncio openai python-dotenv Pillow matplotlib pandas aiohttp + pip install pytest pytest-asyncio openai python-dotenv Pillow matplotlib pandas aiohttp scikit-learn pip install -e . - name: Run tests diff --git a/tests/conftest.py b/tests/conftest.py index 9650ec3..ea26b20 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,16 +1,19 @@ import sys +import matplotlib +import matplotlib.pyplot as plt from unittest.mock import MagicMock +matplotlib.use("Agg") + # Mock packages not available in CI (private or heavy scientific deps) for _mod in [ "asksageclient", "xradar", "cmweather", "pip_system_certs", - "sklearn", - "sklearn.metrics", - "sklearn.preprocessing", "torch", "torchvision", ]: sys.modules[_mod] = MagicMock() + +plt.close("all") diff --git a/tests/test_confusion_matrix.py b/tests/test_confusion_matrix.py new file mode 100644 index 0000000..02a8455 --- /dev/null +++ b/tests/test_confusion_matrix.py @@ -0,0 +1,67 @@ +import io +import pytest +import pandas as pd +import matplotlib.pyplot as plt + +CSV_DATA = """\ +label,llm_label +stratiform,stratiform +convective,convective +stratiform,convective +convective,stratiform +anvil,anvil +stratiform,stratiform +""" + + +@pytest.fixture +def sample_df(): + return pd.read_csv(io.StringIO(CSV_DATA)) + + +@pytest.fixture(autouse=True) +def close_figures(): + yield + plt.close("all") + + +def test_title_is_set(sample_df): + from lars.util.confusion_matrix import plot_confusion_matrix + + _, ax = plt.subplots() + plot_confusion_matrix(sample_df, ax=ax) + assert ax.get_title() == "Confusion Matrix" + + +def test_returns_none(sample_df): + from lars.util.confusion_matrix import plot_confusion_matrix + + _, ax = plt.subplots() + result = plot_confusion_matrix(sample_df, ax=ax) + assert result is None + + +def test_normalized(sample_df): + from lars.util.confusion_matrix import plot_confusion_matrix + + _, ax = plt.subplots() + plot_confusion_matrix(sample_df, normalize="true", ax=ax) + assert ax.get_title() == "Confusion Matrix" + + +def test_custom_column_names(sample_df): + from lars.util.confusion_matrix import plot_confusion_matrix + + df = sample_df.rename(columns={"label": "true", "llm_label": "pred"}) + _, ax = plt.subplots() + plot_confusion_matrix(df, label_col="true", pred_col="pred", ax=ax) + assert ax.get_title() == "Confusion Matrix" + + +def test_uses_gca_when_no_ax(sample_df): + from lars.util.confusion_matrix import plot_confusion_matrix + + fig, ax = plt.subplots() + plt.sca(ax) + plot_confusion_matrix(sample_df) + assert ax.get_title() == "Confusion Matrix" From ecf16e1ac40db9603efc8235eaa641d62f7f5325 Mon Sep 17 00:00:00 2001 From: Robert Jackson Date: Thu, 23 Apr 2026 12:12:09 -0500 Subject: [PATCH 2/4] ADD: Assert confusion matrix cell counts match mock dataset Adds test_confusion_matrix_counts (raw integer counts) and test_normalized_confusion_matrix_values (row-normalized floats). Both extract the plotted image array from ax.images[0] and compare against the expected 3x3 matrix derived from the CSV fixture. Co-Authored-By: Claude Sonnet 4.6 --- tests/test_confusion_matrix.py | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/test_confusion_matrix.py b/tests/test_confusion_matrix.py index 02a8455..259ab9d 100644 --- a/tests/test_confusion_matrix.py +++ b/tests/test_confusion_matrix.py @@ -1,5 +1,6 @@ import io import pytest +import numpy as np import pandas as pd import matplotlib.pyplot as plt @@ -65,3 +66,37 @@ def test_uses_gca_when_no_ax(sample_df): plt.sca(ax) plot_confusion_matrix(sample_df) assert ax.get_title() == "Confusion Matrix" + + +def test_confusion_matrix_counts(sample_df): + """Labels sorted alphabetically: anvil=0, convective=1, stratiform=2. + + True \\ Pred anvil convective stratiform + anvil 1 0 0 + convective 0 1 1 + stratiform 0 1 2 + """ + from lars.util.confusion_matrix import plot_confusion_matrix + + expected = np.array([[1, 0, 0], + [0, 1, 1], + [0, 1, 2]]) + + _, ax = plt.subplots() + plot_confusion_matrix(sample_df, ax=ax) + actual = ax.images[0].get_array() + np.testing.assert_array_equal(actual, expected) + + +def test_normalized_confusion_matrix_values(sample_df): + """Row-normalized values for each true class.""" + from lars.util.confusion_matrix import plot_confusion_matrix + + expected = np.array([[1.0, 0.0, 0.0 ], + [0.0, 0.5, 0.5 ], + [0.0, 1.0 / 3.0, 2.0 / 3.0]]) + + _, ax = plt.subplots() + plot_confusion_matrix(sample_df, normalize="true", ax=ax) + actual = ax.images[0].get_array() + np.testing.assert_array_almost_equal(actual, expected) From 001c1a9e1979d10c8e594e8497de79c12fbbf275 Mon Sep 17 00:00:00 2001 From: Robert Jackson Date: Thu, 23 Apr 2026 12:23:04 -0500 Subject: [PATCH 3/4] FIX: Apply sys.modules mocks before matplotlib import in conftest On headless runners (GitHub Actions Ubuntu), importing matplotlib.pyplot before setting the backend can raise if no GUI toolkit (Tk, Qt) is installed, aborting conftest.py before the sys.modules mocks are applied. Without those mocks lars cannot be imported, causing the patch() call in mock_openai to fail with ModuleNotFoundError. Fix: move the sys.modules mock loop to the top of conftest.py, then call matplotlib.use("Agg") before pyplot is imported anywhere. Also set MPLBACKEND=Agg in the workflow as a belt-and-suspenders guard. Co-Authored-By: Claude Sonnet 4.6 --- .github/workflows/tests.yml | 1 + tests/conftest.py | 12 ++++++------ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index b9bbe86..cfeacfc 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -30,4 +30,5 @@ jobs: - name: Run tests env: OPENAI_API_KEY: "test-key-not-real" + MPLBACKEND: Agg run: pytest tests/ -v diff --git a/tests/conftest.py b/tests/conftest.py index ea26b20..582560e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,11 +1,8 @@ import sys -import matplotlib -import matplotlib.pyplot as plt from unittest.mock import MagicMock -matplotlib.use("Agg") - -# Mock packages not available in CI (private or heavy scientific deps) +# Must be first: mocks must be in sys.modules before any lars import chain +# is triggered (e.g. by patch() resolving a target string). for _mod in [ "asksageclient", "xradar", @@ -16,4 +13,7 @@ ]: sys.modules[_mod] = MagicMock() -plt.close("all") +# Must be before pyplot is imported; on headless runners the default backend +# may require a display (Tk, Qt) and raise on import. +import matplotlib +matplotlib.use("Agg") From 78cc957249be767689f1bb4b9a2da206cf92f61f Mon Sep 17 00:00:00 2001 From: Robert Jackson Date: Thu, 23 Apr 2026 12:24:43 -0500 Subject: [PATCH 4/4] FIX: Remove torch/torchvision from sys.modules mocks scipy's is_torch_array() checks sys.modules['torch'] and calls issubclass(cls, mod.Tensor). With torch mocked as MagicMock, Tensor is a MagicMock instance rather than a class, raising TypeError. lars never imports torch or torchvision, so there is nothing to stub. Co-Authored-By: Claude Sonnet 4.6 --- tests/conftest.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 582560e..fcfec51 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -8,8 +8,6 @@ "xradar", "cmweather", "pip_system_certs", - "torch", - "torchvision", ]: sys.modules[_mod] = MagicMock()