"""What this module covers: `models.steps.model_fitting` run by a Hamilton driver built from that module alone, the way a scenario's driver uses it: the temporal split, the classifier chosen by config, the fit and the metrics. Fixtures: `labelled`, forty members with index dates one day apart, one categorical predictor (`resultado`: `A` is always positive, `B` never) and `y`; `_driver` builds the driver with `classifier = "logistic"` unless told otherwise, and `_run` executes nodes with the three required inputs. """ import ast import inspect from datetime import date, timedelta import pandas as pd import pytest from hamilton import driver from sklearn.metrics import brier_score_loss, roc_auc_score from models.steps import model_fitting PREDICTORS = ["resultado"] @pytest.fixture def labelled() -> pd.DataFrame: """Forty members, `pac_id` 1..40, index dates from 2025-01-01 one day apart in reverse `pac_id` order (so the oldest is member 40). Members whose `pac_id` is divisible by 4 have `resultado` `A` and `y` 1, the rest `B` and `y` 0.""" rows = [{"pac_id": n, "fecha_indice": date(2025, 1, 1) + timedelta(days=40 - n), "resultado": "A" if n % 4 == 0 else "B", "y": int(n % 4 == 0)} for n in range(1, 41)] return pd.DataFrame(rows) def _driver(config: dict | None = None): return driver.Builder().with_modules(model_fitting).with_config( {"classifier": "logistic"} if config is None else config).build() def _run(nodes: list[str], labelled: pd.DataFrame, config: dict | None = None, **inputs) -> dict: required = {"labelled_members": labelled, "predictor_columns": PREDICTORS, "train_fraction": 0.75} return _driver(config).execute(nodes, inputs={**required, **inputs}) def test_the_oldest_members_train_and_the_newest_test(labelled): """Pins down the temporal split: with 0.75, the 30 oldest index dates train and the 10 newest test, and every member is in exactly one of them. Fails if the split shuffles, ignores the index date or loses rows.""" result = _run(["train_set", "test_set"], labelled) train, test = result["train_set"], result["test_set"] assert len(train) == 30 and len(test) == 10 assert train["fecha_indice"].max() < test["fecha_indice"].min() assert sorted(train["pac_id"].tolist() + test["pac_id"].tolist()) == list(range(1, 41)) def test_the_driver_needs_only_the_members_the_predictors_the_fraction_and_the_scenarios_routines(labelled): """Pins down the dataflow's external inputs: the three required ones, and `sampling` and `missing_data`, the two routines (ML-01a) only a scenario can write; `target_column`, `split_order`, `max_iter` and `calibration_bins` have defaults. Fails if a node reads a setting from a global or the disk instead of taking it as an input, or if a new input appears without a default.""" required = {v.name for v in _driver().list_available_variables() if v.is_external_input and v.originating_functions and not _has_default(v)} assert required == {"labelled_members", "predictor_columns", "train_fraction", "sampling", "missing_data"} def _has_default(variable) -> bool: for function in variable.originating_functions: parameter = inspect.signature(function).parameters.get(variable.name) if parameter is not None and parameter.default is inspect.Parameter.empty: return False return True def test_the_classifier_is_chosen_by_config(labelled): """Pins down `@config.when`: with `classifier = "logistic"` the prefit node is an unfitted logistic regression, and without a known classifier there's no `prefit_classifier` to fit with. Fails if the classifier is built inside `fitted_pipeline` again or the config key changes.""" prefit = _run(["prefit_classifier"], labelled)["prefit_classifier"] assert type(prefit).__name__ == "LogisticRegression" and not hasattr(prefit, "coef_") with pytest.raises(ValueError): _run(["fitted_pipeline"], labelled, config={"classifier": "unknown"}) def test_fitting_leaves_the_prefit_nodes_unfitted(labelled): """Pins down that `fitted_pipeline` fits copies: the `encoder` and `prefit_classifier` values the driver computed stay unfitted. Fails if the fit mutates them, which would leak one run's fit into anything else that reads them.""" result = _run(["encoder", "prefit_classifier", "fitted_pipeline"], labelled) assert not hasattr(result["prefit_classifier"], "coef_") assert not hasattr(result["encoder"], "transformers_") assert hasattr(result["fitted_pipeline"].named_steps["classify"], "coef_") def test_metrics_are_sklearn_s_on_the_test_set_under_the_names_mlflow_keeps(labelled): """Pins down `metrics`: AUC and Brier computed on the test set's `y` and probabilities, the sizes and rates, with the keys training runs have always recorded. Fails if a metric is computed on the wrong set or a key is renamed (a renamed key splits a model's history in MLflow).""" result = _run(["metrics", "test_set", "test_probabilities"], labelled) test, probabilities, metrics = result["test_set"], result["test_probabilities"], result["metrics"] assert set(metrics) == {"auc", "brier", "n_train", "n_test", "positive_rate_train", "positive_rate_test", "mean_probability_test"} assert metrics["auc"] == pytest.approx(roc_auc_score(test["y"], probabilities)) assert metrics["brier"] == pytest.approx(brier_score_loss(test["y"], probabilities)) assert (metrics["n_train"], metrics["n_test"]) == (30, 10) assert metrics["positive_rate_test"] == pytest.approx(test["y"].mean()) assert probabilities.name == "probabilidad" and probabilities.index.equals(test.index) def test_an_unseen_category_scores_as_none_of_the_known_ones(labelled): """Pins down the encoder's `handle_unknown="ignore"`: a test member with a category training never saw still gets a probability, between the two known categories'. Fails if the encoder raises on unknown categories.""" pipeline = _run(["fitted_pipeline"], labelled)["fitted_pipeline"] a, b, c = pipeline.predict_proba(pd.DataFrame({"resultado": ["A", "B", "C"]}))[:, 1] assert b < c < a def test_no_node_reads_writes_or_logs(): """Pins down that the module imports nothing that does I/O (MLflow, the registry, storage, tracking). Fails if a node starts logging or registering again instead of leaving that to a saver.""" tree = ast.parse(inspect.getsource(model_fitting)) imported = {alias.name for node in ast.walk(tree) if isinstance(node, ast.Import) for alias in node.names} imported |= {node.module for node in ast.walk(tree) if isinstance(node, ast.ImportFrom)} assert not {name for name in imported if name.split(".")[0] in {"mlflow", "persistance"} or name.startswith("models.io")}