""" Production test suite — unit + integration + edge cases. Run: pytest tests/test_platform.py -v """ import sys from pathlib import Path import numpy as np import pandas as pd import pytest sys.path.insert(0, str(Path(__file__).parent.parent)) # ── Fixtures ────────────────────────────────────────────────────────────────── @pytest.fixture def regression_df(): np.random.seed(42) n = 300 return pd.DataFrame({ "feat_a": np.random.normal(0, 1, n), "feat_b": np.random.uniform(0, 10, n), "feat_c": np.random.exponential(2, n), "cat_x": np.random.choice(["A", "B", "C"], n), "target": np.random.normal(50, 15, n), }) @pytest.fixture def classification_df(): from sklearn.datasets import make_classification X, y = make_classification(n_samples=400, n_features=10, n_informative=7, random_state=42) df = pd.DataFrame(X, columns=[f"feat_{i}" for i in range(10)]) df["target"] = y return df @pytest.fixture def preprocessed_regression(regression_df): from sklearn.model_selection import train_test_split from src.components.data_preprocessing import DataPreprocessor X = regression_df.drop(columns=["target"]) y = regression_df["target"].values X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=42) proc = DataPreprocessor() X_tr_p = proc.fit_transform(X_tr, target_column="target") X_te_p = proc.transform(X_te) return X_tr_p, X_te_p, y_tr, y_te, proc # ── Config ──────────────────────────────────────────────────────────────────── class TestConfig: def test_singleton(self): from src.config import ConfigManager assert ConfigManager() is ConfigManager() def test_dot_notation(self): from src.config import config val = config.get("training.random_state", 42) assert isinstance(val, int) def test_defaults(self): from src.config import config assert config.random_state == 42 assert 0 < config.test_size < 1 # ── Data Ingestion ──────────────────────────────────────────────────────────── class TestDataIngestion: def test_load_csv_bytes(self, regression_df): from src.components.data_ingestion import DataIngestion df = DataIngestion().load_from_bytes( regression_df.to_csv(index=False).encode(), "test.csv" ) assert df.shape == regression_df.shape def test_analyze_regression(self, regression_df): from src.components.data_ingestion import DataIngestion info = DataIngestion().analyze_dataset(regression_df, "target") assert info.task_type == "regression" assert info.rows == len(regression_df) def test_analyze_classification(self, classification_df): from src.components.data_ingestion import DataIngestion info = DataIngestion().analyze_dataset(classification_df, "target") assert info.task_type == "classification" def test_train_test_split(self, regression_df): from src.components.data_ingestion import DataIngestion X_tr, X_te, y_tr, y_te = DataIngestion().train_test_split(regression_df, "target") assert len(X_tr) + len(X_te) == len(regression_df) def test_sample_datasets_local(self): """Test that sample datasets dict has required structure (customer_churn is always synthetic).""" from src.components.data_ingestion import DataIngestion samples = DataIngestion().get_sample_datasets() # Verify structure for all returned datasets assert len(samples) >= 1 for key, val in samples.items(): assert "df" in val, f"Missing df for {key}" assert "target" in val, f"Missing target for {key}" assert "task" in val, f"Missing task for {key}" # customer_churn is always synthetic — never needs network assert "customer_churn" in samples churn = samples["customer_churn"] assert churn["task"] == "classification" assert len(churn["df"]) > 10 @pytest.mark.skipif(True, reason="california_housing requires network download") def test_sample_datasets_network(self): from src.components.data_ingestion import DataIngestion samples = DataIngestion().get_sample_datasets() assert "california_housing" in samples # ── Data Validation ─────────────────────────────────────────────────────────── class TestDataValidator: def test_clean_data_passes(self, regression_df): from src.components.data_validation import DataValidator r = DataValidator().validate(regression_df) assert r["status"] in ("PASSED", "WARNING") def test_empty_dataframe_fails(self): from src.components.data_validation import DataValidator r = DataValidator().validate(pd.DataFrame()) assert r["status"] == "FAILED" def test_drift_detected(self, regression_df): from src.components.data_validation import DataValidator ref = regression_df.iloc[:150] cur = regression_df.iloc[150:].copy() cur["feat_a"] = cur["feat_a"] * 8 + 100 # inject drift report = DataValidator().detect_drift(ref, cur) assert "feat_a" in report["drifted_features"] def test_schema_generation(self, regression_df): from src.components.data_validation import DataValidator schema = DataValidator().generate_schema(regression_df) assert "target" in schema assert "dtype" in schema["target"] # ── Preprocessing ───────────────────────────────────────────────────────────── class TestDataPreprocessor: def test_output_shape(self, regression_df): from src.components.data_preprocessing import DataPreprocessor X = regression_df.drop(columns=["target"]) proc = DataPreprocessor() out = proc.fit_transform(X, target_column="target") assert out.shape[0] == len(X) assert out.shape[1] >= 1 def test_target_not_leaked(self, regression_df): from src.components.data_preprocessing import DataPreprocessor proc = DataPreprocessor() # Deliberately pass target in numeric list — it must be silently removed proc.fit_transform( regression_df, numeric_features=["feat_a", "feat_b", "feat_c", "target"], target_column="target", ) assert "target" not in proc.numeric_features def test_missing_column_skipped(self, regression_df): from src.components.data_preprocessing import DataPreprocessor X = regression_df.drop(columns=["target"]) proc = DataPreprocessor() # Request a column that doesn't exist — should not crash out = proc.fit_transform( X, numeric_features=["feat_a", "feat_b", "NONEXISTENT"], ) assert out is not None def test_train_test_consistency(self, preprocessed_regression): X_tr, X_te, _, _, _ = preprocessed_regression assert X_tr.shape[1] == X_te.shape[1] def test_feature_names(self, preprocessed_regression): _, _, _, _, proc = preprocessed_regression names = proc.get_feature_names() assert isinstance(names, list) and len(names) > 0 def test_pipeline_summary(self, preprocessed_regression): _, _, _, _, proc = preprocessed_regression s = proc.get_pipeline_summary() assert "numeric_features" in s assert s["fitted"] is True def test_unknown_category_at_inference(self, regression_df): from src.components.data_preprocessing import DataPreprocessor train = regression_df.copy() test = regression_df.copy() test["cat_x"] = "UNSEEN_CATEGORY" # inject unseen category X_tr = train.drop(columns=["target"]) X_te = test.drop(columns=["target"]) proc = DataPreprocessor() proc.fit_transform(X_tr) # Must not raise out = proc.transform(X_te) assert out is not None def test_inference_missing_column(self, regression_df): from src.components.data_preprocessing import DataPreprocessor X_tr = regression_df.drop(columns=["target"]) proc = DataPreprocessor() proc.fit_transform(X_tr) # Remove a column at inference X_te = X_tr.drop(columns=["feat_a"]) out = proc.transform(X_te) # must fill with NaN and proceed assert out is not None # ── Evaluator ───────────────────────────────────────────────────────────────── class TestModelEvaluator: def test_regression_metrics(self): from src.ml.evaluator import ModelEvaluator ev = ModelEvaluator("regression") y_true = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) y_pred = np.array([1.1, 2.1, 2.9, 4.2, 4.8]) m = ev._regression_metrics(y_true, y_pred) assert all(k in m for k in ("mae", "rmse", "r2", "mape", "adjusted_r2")) assert m["r2"] > 0.9 def test_classification_metrics(self): from src.ml.evaluator import ModelEvaluator ev = ModelEvaluator("classification") y_true = np.array([0, 1, 0, 1, 1, 0, 1, 0]) y_pred = np.array([0, 1, 0, 0, 1, 0, 1, 1]) m = ev._classification_metrics(y_true, y_pred) assert all(k in m for k in ("accuracy", "f1_weighted", "cohen_kappa")) assert 0 <= m["accuracy"] <= 1 def test_adj_r2_no_zero_division(self): """Adjusted R² must not raise ZeroDivisionError for tiny datasets.""" from src.ml.evaluator import ModelEvaluator ev = ModelEvaluator("regression") y_true = np.array([1.0, 2.0]) y_pred = np.array([1.0, 2.0]) m = ev._regression_metrics(y_true, y_pred) assert np.isfinite(m["adjusted_r2"]) def test_compute_metrics_regression(self, preprocessed_regression): from sklearn.ensemble import RandomForestRegressor from src.ml.evaluator import ModelEvaluator X_tr, X_te, y_tr, y_te, _ = preprocessed_regression model = RandomForestRegressor(n_estimators=10, random_state=42) model.fit(X_tr, y_tr) m = ModelEvaluator("regression").compute_metrics(model, X_te, y_te) assert m["mae"] >= 0 assert np.isfinite(m["r2"]) # ── Utilities ───────────────────────────────────────────────────────────────── class TestUtils: def test_detect_regression(self): from src.utils import detect_task_type assert detect_task_type(pd.Series(np.random.normal(0, 1, 200))) == "regression" def test_detect_classification(self): from src.utils import detect_task_type assert detect_task_type(pd.Series(np.random.choice([0, 1], 200))) == "classification" def test_json_roundtrip(self, tmp_path): from src.utils import load_json, save_json data = {"a": 1, "b": [1, 2, 3], "c": "hello"} p = tmp_path / "t.json" save_json(data, p) assert load_json(p) == data def test_pickle_roundtrip(self, tmp_path): from src.utils import load_object, save_object obj = {"model": "test", "score": 0.99} p = tmp_path / "obj.pkl" save_object(obj, p) assert load_object(p) == obj def test_sanitize_metric_name(self): from src.utils import sanitize_metric_name assert sanitize_metric_name("F1-Score") == "f1_score" assert " " not in sanitize_metric_name("R² Score") # ── Edge Cases ──────────────────────────────────────────────────────────────── class TestEdgeCases: def test_single_row_dataset(self): from src.components.data_preprocessing import DataPreprocessor df = pd.DataFrame({"a": [1.0], "b": [2.0], "target": [0]}) X = df.drop(columns=["target"]) proc = DataPreprocessor() out = proc.fit_transform(X) assert out.shape[0] == 1 def test_all_null_column(self): from src.components.data_preprocessing import DataPreprocessor df = pd.DataFrame({ "a": [1.0, 2.0, 3.0], "b": [np.nan, np.nan, np.nan], "target": [0, 1, 0], }) X = df.drop(columns=["target"]) proc = DataPreprocessor() out = proc.fit_transform(X) # should not crash assert out is not None def test_single_feature_dataset(self): from src.components.data_preprocessing import DataPreprocessor df = pd.DataFrame({"feat": np.random.randn(50), "target": np.random.randn(50)}) X = df.drop(columns=["target"]) proc = DataPreprocessor() out = proc.fit_transform(X) assert out.shape == (50, 1) def test_missing_target_column_warning(self, regression_df): """Target in numeric_features must be silently removed to prevent leakage.""" from src.components.data_preprocessing import DataPreprocessor proc = DataPreprocessor() # Only pass numeric columns (target among them) — categorical excluded num_cols = list(regression_df.select_dtypes(include=["number"]).columns) out = proc.fit_transform( regression_df, numeric_features=num_cols, # includes "target" categorical_features=[], target_column="target", # should be removed from num_cols internally ) assert out is not None assert "target" not in proc.numeric_features def test_validation_all_missing(self): from src.components.data_validation import DataValidator df = pd.DataFrame({"a": [np.nan]*50, "b": [np.nan]*50}) r = DataValidator().validate(df) assert r["status"] in ("WARNING", "FAILED") assert len(r["warnings"]) > 0 or len(r["issues"]) > 0 # ── Performance Tests ───────────────────────────────────────────────────────── class TestPerformance: """Validate speed and memory improvements in key pipeline stages.""" def test_preprocessing_float32_output(self, regression_df): """Preprocessor must output float32 (not float64) to halve memory.""" from src.components.data_preprocessing import DataPreprocessor X = regression_df.drop(columns=["target"]) proc = DataPreprocessor() out = proc.fit_transform(X) assert out.dtype == np.float32, f"Expected float32, got {out.dtype}" def test_preprocessing_chunk_transform(self): """Chunk-based transform must produce identical output to single-pass.""" from src.components.data_preprocessing import DataPreprocessor n = 500 df = pd.DataFrame(np.random.default_rng(0).standard_normal((n, 5)), columns=[f"f{i}" for i in range(5)]) X_train, X_test = df.iloc[:400], df.iloc[400:] # Single-pass (default chunk_size > n_test) proc1 = DataPreprocessor(chunk_size=10_000) proc1.fit_transform(X_train) out_single = proc1.transform(X_test) # Chunk-based (small chunk forces chunked path) proc2 = DataPreprocessor(chunk_size=40) proc2.fit_transform(X_train) out_chunked = proc2.transform(X_test) np.testing.assert_allclose(out_single, out_chunked, rtol=1e-4) def test_outlier_capping_vectorised(self, regression_df): """IQR capping must produce correct bounds via vectorised path.""" from src.components.data_preprocessing import DataPreprocessor X = regression_df.drop(columns=["target"]) proc = DataPreprocessor(handle_outliers=True) out = proc.fit_transform(X) # Should succeed without element-wise Python loops assert out is not None assert out.shape[0] == len(X) def test_model_skipping_rf_large(self): """Random Forest must be skipped above _RF_LIMIT rows.""" from src.components.model_trainer import _should_skip_model, _RF_LIMIT rf_cfg = {"name": "Random Forest", "class": "RandomForestClassifier", "module": "sklearn.ensemble", "params": {}} assert _should_skip_model(rf_cfg, _RF_LIMIT + 1) is not None assert _should_skip_model(rf_cfg, _RF_LIMIT - 1) is None def test_model_skipping_svm_large(self): """SVM must be skipped above _SVM_LIMIT rows.""" from src.components.model_trainer import _should_skip_model, _SVM_LIMIT svm_cfg = {"name": "SVM", "class": "SVC", "module": "sklearn.svm", "params": {}} assert _should_skip_model(svm_cfg, _SVM_LIMIT + 1) is not None assert _should_skip_model(svm_cfg, _SVM_LIMIT - 1) is None def test_model_skipping_knn_large(self): """KNN must be skipped above _KNN_LIMIT rows.""" from src.components.model_trainer import _should_skip_model, _KNN_LIMIT knn_cfg = {"name": "KNN", "class": "KNeighborsClassifier", "module": "sklearn.neighbors", "params": {}} assert _should_skip_model(knn_cfg, _KNN_LIMIT + 1) is not None assert _should_skip_model(knn_cfg, _KNN_LIMIT - 1) is None def test_adapt_params_reduces_estimators(self): """Hyperparameters must be reduced for large datasets.""" from src.components.model_trainer import _adapt_params_for_size, _LARGE_TH cfg = {"name": "XGBoost", "class": "XGBClassifier", "module": "xgboost", "params": {"n_estimators": 300, "random_state": 42, "verbosity": 0}} small_params = _adapt_params_for_size(cfg, _LARGE_TH - 1) large_params = _adapt_params_for_size(cfg, _LARGE_TH + 1) assert large_params["n_estimators"] <= small_params["n_estimators"] def test_save_object_compressed(self, tmp_path): """Saved objects with compress=3 must be smaller than uncompressed.""" from src.utils.common import save_object import os obj = {"data": list(range(10_000))} p1 = tmp_path / "compressed.pkl" p2 = tmp_path / "raw.pkl" save_object(obj, p1, compress=3) save_object(obj, p2, compress=0) assert os.path.getsize(p1) < os.path.getsize(p2), "Compressed file should be smaller than uncompressed"