Spaces:
Runtime error
Runtime error
File size: 16,553 Bytes
36a5576 47b08cd 36a5576 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | 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)
|