Spaces:
Runtime error
Runtime error
Claude Sonnet 4.6
Rebrand: Marketing Mix Intelligence β PRISM Marketing Intelligence; AIRA β NOVA
47b08cd Download tests_runner.py from StrategyForge/PRISM-Marketing-Mix-Intelligence: direct link, hf CLI and curl.
- Browser
- Download file 16.6 kB
-
https://huggingface.co/spaces/StrategyForge/PRISM-Marketing-Mix-Intelligence/resolve/main/tests_runner.py
- Command line
-
hf download hf://spaces/StrategyForge/PRISM-Marketing-Mix-Intelligence/tests_runner.py
-
curl -L -o tests_runner.py https://huggingface.co/spaces/StrategyForge/PRISM-Marketing-Mix-Intelligence/resolve/main/tests_runner.py
16.6 kB
| import urllib.request, urllib.parse, json, sys, time, http.cookiejar | |
| sys.stdout.reconfigure(encoding='utf-8', errors='replace') | |
| BASE = "http://localhost:5001" | |
| results = [] | |
| # ββ Session-aware opener (handles login cookies automatically) βββββββββββββ | |
| _cj = http.cookiejar.CookieJar() | |
| _opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(_cj)) | |
| def _login(username='admin', password='mmm2024'): | |
| """Log in once so all subsequent requests are authenticated.""" | |
| data = urllib.parse.urlencode({'username': username, 'password': password}).encode() | |
| _opener.open(f"{BASE}/login", data, timeout=15) | |
| # Log in before running any tests | |
| _login() | |
| def get(path, as_json=True, timeout=30): | |
| req = urllib.request.Request(f"{BASE}{path}") | |
| with _opener.open(req, timeout=timeout) as r: | |
| raw = r.read() | |
| return (json.loads(raw) if as_json else raw.decode('utf-8', errors='replace')), r.status | |
| def post(path, body={}, timeout=30): | |
| data = json.dumps(body).encode() | |
| req = urllib.request.Request(f"{BASE}{path}", data=data, | |
| headers={"Content-Type": "application/json"}) | |
| with _opener.open(req, timeout=timeout) as r: | |
| return json.loads(r.read()), r.status | |
| def check(label, fn, *args, validators=None, timeout=30): | |
| # pass timeout through to get/post if they accept it | |
| import inspect | |
| sig = inspect.signature(fn) | |
| kwargs = {'timeout': timeout} if 'timeout' in sig.parameters else {} | |
| try: | |
| d, code = fn(*args, **kwargs) | |
| errors = [] | |
| if validators: | |
| for v in validators: | |
| err = v(d) | |
| if err: | |
| errors.append(err) | |
| if errors: | |
| results.append(("WARN", label, "; ".join(errors))) | |
| else: | |
| results.append(("OK", label, str(code))) | |
| except Exception as e: | |
| results.append(("FAIL", label, str(e)[:120])) | |
| def has_keys(*keys): | |
| def v(d): | |
| if not isinstance(d, dict): | |
| return f"expected dict, got {type(d).__name__}" | |
| missing = [k for k in keys if k not in d] | |
| return f"missing keys {missing}" if missing else None | |
| return v | |
| def is_list(): | |
| return lambda d: None if isinstance(d, list) else f"expected list, got {type(d).__name__}" | |
| def has_len(n): | |
| return lambda d: None if len(d) >= n else f"expected >={n} items, got {len(d)}" | |
| def has_charts(min_n=1): | |
| def v(d): | |
| charts = d.get("charts", {}) | |
| n = len(charts) if isinstance(charts, dict) else 0 | |
| return None if n >= min_n else f"only {n} charts (expected >={min_n})" | |
| return v | |
| def has_kpis_with_change(): | |
| def v(d): | |
| kpis = d.get("kpis", []) | |
| if not kpis: | |
| return "no kpis" | |
| missing = [k.get("name") for k in kpis if isinstance(k, dict) and "change" not in k] | |
| return f"missing change key on: {missing}" if missing else None | |
| return v | |
| def alerts_valid(): | |
| def v(d): | |
| if not isinstance(d, dict): | |
| return "expected dict" | |
| alerts = d.get("alerts", []) | |
| summary = d.get("summary", {}) | |
| if not isinstance(alerts, list): | |
| return "alerts not a list" | |
| if not isinstance(summary, dict): | |
| return "summary not a dict" | |
| for cat in ["alert", "worry", "win", "opportunity"]: | |
| if cat not in summary: | |
| return f"summary missing category: {cat}" | |
| return None | |
| return v | |
| # ββ Screen HTML ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("\nTesting HTML screens...") | |
| for path, name in [ | |
| ("/", "Home"), | |
| ("/data/", "Data Harmonization"), | |
| ("/alerts/", "Alerts & Simulation"), | |
| ("/media/", "Media Analysis"), | |
| ("/ads/", "Ad-Level Analysis"), | |
| ("/consumer-promo/", "Consumer Promo"), | |
| ("/trade-promo/", "Trade Promo"), | |
| ("/diagnostics/", "Diagnostics / EDA"), | |
| ("/model/", "Model Results"), | |
| ("/media-effects/", "Media Effects"), | |
| ("/sales/", "Sales Insights"), | |
| ("/strategy/create/", "Strategy Create"), | |
| ("/strategy/illustrative/", "Strategy Illustrative"), | |
| ("/strategy/scenarios/", "Strategy Scenarios"), | |
| ]: | |
| def html_check(html_str): | |
| if 'PRISM Marketing Intelligence' not in html_str and 'sidebar' not in html_str.lower(): | |
| return "HTML missing expected content" | |
| return None | |
| check(f"HTML {name}", get, path, False, validators=[html_check]) | |
| # ββ GET endpoints ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("Testing GET endpoints...") | |
| check("GET data/status", get, "/data/api/data/status", | |
| validators=[is_list(), has_len(5)]) | |
| check("GET data/schema", get, "/data/api/data/schema", | |
| validators=[has_keys("media", "sales", "consumer_promo", "trade_promo", "external_factors")]) | |
| check("GET pipeline/status", get, "/data/api/pipeline/status", | |
| validators=[has_keys("media", "sales")]) | |
| check("GET pipeline/log", get, "/data/api/pipeline/log", | |
| validators=[has_keys("log")]) | |
| check("GET alerts/count", get, "/alerts/api/alerts/count", | |
| validators=[has_keys("count")]) | |
| check("GET ads/filter-options", get, "/ads/api/ads/filter-options", | |
| validators=[has_keys("channels", "campaigns", "ad_formats")]) | |
| check("GET media/filter-options", get, "/media/api/media/filter-options", | |
| validators=[has_keys("channels", "campaigns")]) | |
| check("GET cp/filter-options", get, "/consumer-promo/api/consumer-promo/filter-options", | |
| validators=[has_keys("promo_types", "brands")]) | |
| check("GET tp/filter-options", get, "/trade-promo/api/trade-promo/filter-options", | |
| validators=[has_keys("promo_types", "retailers")]) | |
| check("GET scenarios/list", get, "/strategy/scenarios/api/scenarios/list", | |
| validators=[has_keys("scenarios")]) | |
| # ββ Data pipeline flow βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("Testing data pipeline...") | |
| for src in ["media", "sales", "consumer_promo", "trade_promo", "external_factors"]: | |
| check(f"pipeline load-raw [{src}]", post, "/data/api/pipeline/load-raw", | |
| {"source_type": src}, validators=[has_keys("rows", "columns", "column_names")], timeout=60) | |
| check(f"pipeline auto-map [{src}]", post, "/data/api/pipeline/auto-map", | |
| {"source_type": src}, validators=[has_keys("mappings", "target_columns")], timeout=60) | |
| check(f"pipeline apply-map [{src}]", post, "/data/api/pipeline/apply-mapping", | |
| {"source_type": src, "mappings": {}}, validators=[has_keys("rows", "success")], timeout=60) | |
| check("pipeline to-gold", post, "/data/api/pipeline/to-gold", | |
| {"source_type": "all"}, validators=[has_keys("success", "stats")], timeout=60) | |
| check("pipeline activate-gold", post, "/data/api/pipeline/activate-gold", | |
| {}, validators=[has_keys("success")], timeout=60) | |
| # ββ Data transform endpoints βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("Testing transform endpoints...") | |
| check("transform dates", post, "/data/api/pipeline/transform/dates", | |
| {"source_type": "media", "column": "date", "format": "auto"}, | |
| validators=[has_keys("results", "total_fixed")], timeout=60) | |
| check("transform missing", post, "/data/api/pipeline/transform/missing", | |
| {"source_type": "media", "strategy": "drop"}, | |
| validators=[has_keys("results", "total_imputed")], timeout=60) | |
| check("transform outliers", post, "/data/api/pipeline/transform/outliers", | |
| {"source_type": "media", "column": "spend", "method": "iqr"}, | |
| validators=[has_keys("results", "total_outliers")], timeout=60) | |
| # ββ Screen data APIs (with KPI + chart validation) ββββββββββββββββββββββββββββ | |
| print("Testing screen data APIs...") | |
| check("POST home/data", post, "/api/home/data", {}, | |
| validators=[has_kpis_with_change(), has_charts(5), has_keys("table")]) | |
| check("POST media/data", post, "/media/api/media/data", {}, | |
| validators=[has_kpis_with_change(), has_charts(6), has_keys("table")]) | |
| check("POST ads/data", post, "/ads/api/ads/data", {}, | |
| validators=[has_kpis_with_change(), has_charts(4), has_keys("table")]) | |
| check("POST alerts/data", post, "/alerts/api/alerts/data", {}, | |
| validators=[alerts_valid()]) | |
| check("POST consumer-promo/data", post, "/consumer-promo/api/consumer-promo/data", {}, | |
| validators=[has_kpis_with_change(), has_charts(6), has_keys("table")]) | |
| check("POST trade-promo/data", post, "/trade-promo/api/trade-promo/data", {}, | |
| validators=[has_kpis_with_change(), has_charts(6), has_keys("table")]) | |
| check("POST diagnostics/data", post, "/diagnostics/api/diagnostics/data", {}, | |
| validators=[has_kpis_with_change(), has_charts(8), has_keys("tables")]) | |
| check("POST model/data", post, "/model/api/model-results/data", {}, | |
| validators=[has_kpis_with_change(), has_charts(3), has_keys("table")]) | |
| check("POST media-effects/data", post, "/media-effects/api/media-effects/data", {}, | |
| validators=[has_kpis_with_change(), has_charts(11)]) | |
| check("POST sales/data", post, "/sales/api/sales-insights/data", {}, | |
| validators=[has_kpis_with_change(), has_charts(12)]) | |
| check("POST illustrative/data", post, "/strategy/illustrative/api/illustrative/data", {}, | |
| validators=[has_kpis_with_change(), has_charts(4)]) | |
| check("POST create/simulate", post, "/strategy/create/api/create/simulate", | |
| {"channel": "TV", "adjustment": 15, "metric": "revenue"}, | |
| validators=[has_charts(2), has_keys("kpis", "tables")]) | |
| check("POST create/optimize", post, "/strategy/create/api/create/optimize", | |
| {"total_budget": 2000000, "objective": "maximize_revenue"}, | |
| validators=[has_charts(3), has_keys("kpis", "tables")]) | |
| # ββ Filtered queries βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("Testing filtered queries...") | |
| check("POST media/data filtered (TV+Digital)", post, "/media/api/media/data", | |
| {"media_channels": ["TV", "Digital Display"], "granularity": "weekly"}, | |
| validators=[has_charts(1)]) | |
| check("POST media/data filtered (monthly)", post, "/media/api/media/data", | |
| {"granularity": "monthly"}, | |
| validators=[has_charts(1)]) | |
| check("POST ads/data filtered (campaign)", post, "/ads/api/ads/data", | |
| {"granularity": "monthly"}, | |
| validators=[has_charts(1)]) | |
| check("POST cp/data filtered (promo_type)", post, "/consumer-promo/api/consumer-promo/data", | |
| {"promo_types": ["Coupon"]}, | |
| validators=[has_charts(1)]) | |
| check("POST tp/data filtered (retailer)", post, "/trade-promo/api/trade-promo/data", | |
| {"retailers": []}, | |
| validators=[has_charts(1)]) | |
| check("POST alerts/data by category", post, "/alerts/api/alerts/data", | |
| {"category": "alert"}, | |
| validators=[has_keys("alerts", "summary")]) | |
| # ββ Alert simulation βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("Testing alert simulation...") | |
| check("POST alerts/simulate (TV +10%)", post, "/alerts/api/alerts/simulate", | |
| {"channel": "TV", "metric": "roas", "adjustment": 10}, | |
| validators=[has_keys("channel", "current", "simulated", "impact", "adjustment_pct")]) | |
| check("POST alerts/simulate (Digital -20%)", post, "/alerts/api/alerts/simulate", | |
| {"channel": "Digital Display", "metric": "spend", "adjustment": -20}, | |
| validators=[has_keys("channel", "current", "simulated")]) | |
| # ββ Strategy simulate multi-channel βββββββββββββββββββββββββββββββββββββββββββ | |
| print("Testing strategy engine...") | |
| for ch in ["TV", "Digital Display", "Paid Search", "Social Media"]: | |
| check(f"simulate {ch}", post, "/strategy/create/api/create/simulate", | |
| {"channel": ch, "adjustment": 10, "metric": "revenue"}, | |
| validators=[has_charts(1)]) | |
| for obj in ["maximize_revenue", "maximize_roas", "minimize_cpa"]: | |
| check(f"optimize [{obj}]", post, "/strategy/create/api/create/optimize", | |
| {"total_budget": 1500000, "objective": obj}, | |
| validators=[has_charts(1)]) | |
| # ββ Scenario CRUD ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("Testing scenario CRUD...") | |
| check("POST scenarios/save", post, "/strategy/create/api/create/save", | |
| {"name": "Test Scenario A", "total_budget": 1000000, | |
| "objective": "maximize_revenue", "allocations": {"TV": 500000, "Digital": 500000}}, | |
| validators=[has_keys("id", "success", "name")]) | |
| d_list, _ = get("/strategy/scenarios/api/scenarios/list") | |
| scenarios = d_list.get("scenarios", []) | |
| if scenarios: | |
| sid = scenarios[-1]["id"] | |
| check(f"GET scenarios/load/{sid}", get, | |
| f"/strategy/scenarios/api/scenarios/load/{sid}", | |
| validators=[has_keys("scenario")]) | |
| check("POST scenarios/compare", post, "/strategy/scenarios/api/scenarios/compare", | |
| {"ids": [sid]}, validators=[has_keys("comparison")]) | |
| check("POST scenarios/delete", post, "/strategy/scenarios/api/scenarios/delete", | |
| {"id": sid}, validators=[has_keys("success")]) | |
| # ββ Data quality checks ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("Testing data quality values...") | |
| d_status, _ = get("/data/api/data/status") | |
| for src in d_status: | |
| name = src.get("name", "?") | |
| quality = src.get("quality", 0) | |
| records = src.get("records", 0) | |
| status = src.get("status", "?") | |
| if quality < 95: | |
| results.append(("WARN", f"Data quality [{name}]", f"quality={quality}% (expected >=90%)")) | |
| elif records == 0: | |
| results.append(("WARN", f"Data records [{name}]", "0 records")) | |
| else: | |
| results.append(("OK", f"Data quality [{name}]", f"quality={quality}% records={records} status={status}")) | |
| d_alerts, _ = post("/alerts/api/alerts/data", {}) | |
| alert_count = len(d_alerts.get("alerts", [])) | |
| summary = d_alerts.get("summary", {}) | |
| total_categories = sum(v.get("count", 0) for v in summary.values()) | |
| if alert_count == 0: | |
| results.append(("WARN", "Alert engine", "no alerts generated")) | |
| else: | |
| results.append(("OK", "Alert engine", f"{alert_count} alerts across {len(summary)} categories")) | |
| # ββ Print results ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\n{'='*72}") | |
| print(f" MMM DASHBOARD β FULL TEST RUN | {time.strftime('%Y-%m-%d %H:%M:%S')}") | |
| print(f"{'='*72}") | |
| ok_items = [(l, d) for s, l, d in results if s == "OK"] | |
| warn_items = [(l, d) for s, l, d in results if s == "WARN"] | |
| fail_items = [(l, d) for s, l, d in results if s == "FAIL"] | |
| if fail_items: | |
| print(f"\n FAILURES ({len(fail_items)}):") | |
| for label, detail in fail_items: | |
| print(f" [ERR] {label}") | |
| print(f" {detail}") | |
| if warn_items: | |
| print(f"\n WARNINGS ({len(warn_items)}):") | |
| for label, detail in warn_items: | |
| print(f" [WRN] {label}") | |
| print(f" {detail}") | |
| print(f"\n PASSED ({len(ok_items)}):") | |
| for label, detail in ok_items: | |
| print(f" [OK ] {label}") | |
| print(f"\n{'='*72}") | |
| print(f" PASSED: {len(ok_items)} WARNINGS: {len(warn_items)} FAILED: {len(fail_items)} TOTAL: {len(results)}") | |
| print(f"{'='*72}\n") | |
| sys.exit(1 if fail_items else 0) | |