#!/usr/bin/env python3 """Ind* indicator CSV test driver: proves every Ind* widget recomputes its lines from real CSV data (not just the seeded template series). - Compiles + runs widgets/tests/csv_unit_test.cpp (parser unit tests). - For each of the 250 Ind* widgets: builds widgets/tests/ind_csv_harness.cpp against that widget's header and runs it in `numeric` mode under Xvfb: template (250 seeded bars) -> load_csv(ohlcv_sample.csv, 30 rows) -> set_series(ohlcv_sample_b.csv) -> failed load leaves data untouched -> clear_series() (0 items, empty lines, draw must not crash). The CSV checksums must differ from the template on at least one line, and the B-series checksums must differ from the A-series. - Screenshots a broad sample (every 8th widget + named extras): template vs CSV renders must differ substantially and the CSV shot must be non-blank. - Builds all 250 demo mains to catch regressions in existing demo code. Re-derives every count from fresh artifacts each round; exits non-zero on any failure. Attribution: XFrame. """ import glob import os import re import subprocess import sys import time from concurrent.futures import ThreadPoolExecutor from PIL import Image, ImageChops WIDGETS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) REPO = os.path.dirname(WIDGETS_DIR) COMP = os.path.join(WIDGETS_DIR, "components") TMP = "/tmp/ind-csv-shots" BUILD = "/tmp/ind-csv-build" CSV_A = os.path.join(REPO, "tests/data/ohlcv_sample.csv") CSV_B = os.path.join(REPO, "tests/data/SPY_fake_long.csv") CSV_B_ROWS = 1170 # verified: loader reads 1170 rows, 0 skipped DISPLAY = ":94" ENV = dict(os.environ, DISPLAY=DISPLAY) NPROC = 8 NAMES = sorted(os.path.basename(d)[3:] if False else os.path.basename(d) for d in glob.glob(os.path.join(COMP, "Ind*"))) # NAMES are the directory names (IndSMA, ...); the class names match. WIDGETS = NAMES os.makedirs(TMP, exist_ok=True) os.makedirs(BUILD, exist_ok=True) failures = [] rows = [] def run(*a, timeout=30, **k): return subprocess.run(*a, capture_output=True, text=True, timeout=timeout, env=ENV, **k) def check(cond, msg): if not cond: failures.append(msg) return cond def nonbg(path): im = Image.open(path).convert("L") h = im.histogram() modal = max(range(256), key=lambda v: h[v]) return sum(c for v, c in enumerate(h) if abs(v - modal) > 10) def diff(a, b): ia = Image.open(a).convert("RGB") ib = Image.open(b).convert("RGB") if ia.size != ib.size: ib = ib.resize(ia.size) return sum(ImageChops.difference(ia, ib).convert("L").histogram()[31:]) def line_accessor(name): src = open(os.path.join(COMP, name, name + ".h")).read() return "line_values" if "line_values(" in src else "line" def shot(wid, path): r = run(["import", "-window", str(wid), path], timeout=15) return os.path.exists(path) and os.path.getsize(path) > 0 _xvfb = None def xvfb_alive(): r = subprocess.run(["xdpyinfo", "-display", DISPLAY], capture_output=True, timeout=5) return r.returncode == 0 def restart_xvfb(): global _xvfb if _xvfb is not None: try: _xvfb.terminate() _xvfb.wait(timeout=5) except Exception: try: _xvfb.kill() except Exception: pass _xvfb = None subprocess.run(["pkill", "-f", f"Xvfb {DISPLAY}"], capture_output=True, timeout=10) time.sleep(0.5) try: os.remove(f"/tmp/.X{DISPLAY[1:]}-lock") except FileNotFoundError: pass _xvfb = subprocess.Popen(["Xvfb", DISPLAY, "-screen", "0", "1024x768x24"]) for _ in range(20): if xvfb_alive(): return True time.sleep(0.25) return False def ensure_xvfb(): if not xvfb_alive(): return restart_xvfb() return True def wait_window(name, proc, tries=50): for _ in range(tries): if proc.poll() is not None: return None rr = run(["xdotool", "search", "--name", f"{name} - XFrame demo"], timeout=10) if rr.stdout.strip(): return rr.stdout.strip().split()[0] time.sleep(0.2) return None sd = "/tmp/send_delete" if not os.path.exists(sd): subprocess.run(["cc", os.path.join(REPO, "widgets", "test-driver", "send_delete.c"), "-lX11", "-o", sd], capture_output=True, timeout=60) def shoot_demo(binp, name, outpng, args, tag): logout = open(os.path.join(TMP, f"{name}_{tag}.stdout"), "w") logf = open(os.path.join(TMP, f"{name}_{tag}.stderr"), "wb") p = subprocess.Popen([binp] + args, env=ENV, stdout=logout, stderr=logf) wid = wait_window(name, p) if wid is None: rc = p.poll() try: p.wait(timeout=3) except Exception: p.kill() p.wait(timeout=5) logf.close(); logout.close() return False, f"{tag}: no window rc={rc}", "" time.sleep(0.4) ok = shot(wid, outpng) if p.poll() is None: run([sd, str(wid)], timeout=10) try: p.wait(timeout=5) except Exception: p.kill(); p.wait(timeout=5) logf.close(); logout.close() if not ok: return False, f"{tag}: screenshot failed", "" return True, "", open(os.path.join(TMP, f"{name}_{tag}.stdout")).read() # --- 0. parser unit test --- unit_src = os.path.join(WIDGETS_DIR, "tests", "csv_unit_test.cpp") unit_bin = os.path.join(TMP, "csv_unit_test") r = subprocess.run(["g++", "-std=c++17", "-Wall", "-Wextra", "-I", COMP, unit_src, "-o", unit_bin], capture_output=True, text=True, timeout=120) check(r.returncode == 0 and "warning:" not in r.stderr, f"csv_unit_test compile failed/warnings: {r.stderr[:400]}") if r.returncode == 0: r2 = subprocess.run([unit_bin], capture_output=True, text=True, timeout=30, cwd=REPO) check(r2.returncode == 0, f"csv_unit_test rc={r2.returncode}: {r2.stdout}") print("csv_unit_test:", r2.stdout.strip().splitlines()[-1] if r2.stdout else "no output", flush=True) if not restart_xvfb(): print("FATAL: Xvfb never answered", flush=True) sys.exit(1) # --- 1. build one harness per widget (parallel) --- HARNESS = os.path.join(WIDGETS_DIR, "tests", "ind_csv_harness.cpp") def build_one(name): hbin = os.path.join(BUILD, f"harness_{name}") r = subprocess.run( ["g++", "-std=c++17", "-O2", "-Wall", "-Wextra", "-I", COMP, f"-DIND_HEADER={name}/{name}.h", f"-DIND_NAME={name}", f"-DIND_LINE_FN={line_accessor(name)}", HARNESS, "-lX11", "-o", hbin], capture_output=True, text=True, timeout=300) return name, r.returncode == 0 and "warning:" not in r.stderr, r.stderr[-500:] print(f"building {len(WIDGETS)} harnesses ...", flush=True) built = {} with ThreadPoolExecutor(max_workers=NPROC) as ex: for name, ok, err in ex.map(build_one, WIDGETS): built[name] = ok if not ok: failures.append(f"{name}: harness build failed: {err}") print(f"harnesses built: {sum(built.values())}/{len(WIDGETS)}", flush=True) LINE_RE = re.compile( r"^(template|csv|csvB|after_badpath|clear) line (\d+) n=(\d+) finite=(\d+) " r"last=(\S+) sum=(\S+) sumsq=(\S+)$", re.M) HEAD_RE = re.compile(r"^(template|csv|csvB|after_badpath|clear) lines=(\d+) items=(\d+)$", re.M) def parse_dump(out): heads = {m.group(1): (int(m.group(2)), int(m.group(3))) for m in HEAD_RE.finditer(out)} lines = {} for m in LINE_RE.finditer(out): lines.setdefault(m.group(1), {})[int(m.group(2))] = ( int(m.group(3)), int(m.group(4)), m.group(5), m.group(6), m.group(7)) return heads, lines def sig(lines_dict): """Per-line checksum signature (n, finite, last, sum, sumsq).""" return {k: v for k, v in lines_dict.items()} def run_numeric(name): hbin = os.path.join(BUILD, f"harness_{name}") row = {"name": name, "build": "PASS" if built[name] else "FAIL", "numeric": "FAIL", "notes": ""} if not built[name]: return row try: r = run([hbin, "numeric", CSV_A, CSV_B], timeout=60) except subprocess.TimeoutExpired: row["notes"] = "numeric run timed out" failures.append(f"{name}: numeric timeout") return row out = r.stdout or "" notes = [] if r.returncode != 0: notes.append(f"numeric rc={r.returncode}: {out[-300:]} {r.stderr[-200:]}") failures.append(f"{name}: numeric rc={r.returncode}") row["notes"] = "; ".join(notes) return row heads, lines = parse_dump(out) ok = True def need(cond, msg): nonlocal ok if not cond: ok = False notes.append(msg) need(heads.get("template", (0, 0))[1] == 250, "template items != 250") need(heads.get("csv", (0, 0))[1] == 30, "csv items != 30") need(heads.get("csvB", (0, 0))[1] == CSV_B_ROWS, "csvB items != 1170") need("csv_load ok items=30" in out, "csv_load not ok") need(f"set_series ok items={CSV_B_ROWS}" in out, "set_series not ok") need(f"badpath ok=1 err_set=1 items={CSV_B_ROWS}" in out, "badpath did not preserve series") need(heads.get("clear", (0, 0))[1] == 0, "clear items != 0") need(all(v[0] == 0 for v in lines.get("clear", {}).values()), "clear lines not empty") need("NUMERIC DONE" in out, "numeric did not finish") t, c, b = lines.get("template", {}), lines.get("csv", {}), lines.get("csvB", {}) ab = lines.get("after_badpath", {}) need(t.keys() == c.keys() == b.keys() and len(t) >= 1, "line sets differ") need(c != t, "CSV lines identical to template (no recompute?)") need(b != c, "csvB lines identical to csv (set_series no-op?)") # The 1170-row B series must satisfy every warm-up: at least one line # carries finite values (a 30-row file leaves long-period indicators # all-NaN, which is correct behaviour, not a failure). need(any(v[1] > 0 for v in b.values()), "csvB lines all-NaN (warm-up not satisfied?)") need(ab == b, "series changed after failed load") row["numeric"] = "PASS" if ok else "FAIL" if not ok: failures.append(f"{name}: numeric: {'; '.join(notes)}") row["notes"] = "; ".join(notes) return row print("running numeric checks ...", flush=True) with ThreadPoolExecutor(max_workers=NPROC) as ex: for row in ex.map(run_numeric, WIDGETS): rows.append(row) npass = sum(1 for r in rows if r["numeric"] == "PASS") print(f"numeric: {npass}/{len(WIDGETS)} PASS", flush=True) for r in rows: if r["numeric"] != "PASS": print(" FAIL", r["name"], r["notes"], flush=True) # --- 2. screenshots: broad sample --- SAMPLE = sorted(set(WIDGETS[::8]) | { "IndBollingerBands", "IndMACD", "IndRSI", "IndSMA", "IndEMA", "IndGuppyMMA", "IndADX", "IndStochastic", "IndVWAP", "IndIchimoku", } & set(WIDGETS)) print(f"screenshots: sampling {len(SAMPLE)} widgets ...", flush=True) for name in SAMPLE: row = next(r for r in rows if r["name"] == name) row["shot"] = "FAIL" hbin = os.path.join(BUILD, f"harness_{name}") if not built.get(name): row["notes"] += "; shot skipped: harness did not build" failures.append(f"{name}: shot skipped: harness did not build") continue tmpl = os.path.join(TMP, name + "_template.png") ok, note, _ = shoot_demo(hbin, name, tmpl, ["shot-template"], "template") if not ok: ensure_xvfb() ok, note, _ = shoot_demo(hbin, name, tmpl, ["shot-template"], "template") if not ok: failures.append(f"{name}: template shot: {note}") row["notes"] += f"; template shot: {note}" continue csvshot = os.path.join(TMP, name + "_csv.png") ok, note, _ = shoot_demo(hbin, name, csvshot, ["shot-csv", CSV_A], "csv") if not ok: ensure_xvfb() ok, note, _ = shoot_demo(hbin, name, csvshot, ["shot-csv", CSV_A], "csv") if not ok: failures.append(f"{name}: csv shot: {note}") row["notes"] += f"; csv shot: {note}" continue nb = nonbg(csvshot) d = diff(tmpl, csvshot) row["shot_diff"] = d row["shot_nonbg"] = nb if nb > 20 and d > 5000: row["shot"] = "PASS" else: failures.append(f"{name}: shot diff={d} nonbg={nb}") row["notes"] += f"; shot diff={d} nonbg={nb}" spass = sum(1 for r in rows if r.get("shot") == "PASS") print(f"screenshots: {spass}/{len(SAMPLE)} PASS", flush=True) # --- 3. build all demo mains (regression: existing demo code still compiles) --- print("building 250 demo mains ...", flush=True) def build_main(name): src = os.path.join(COMP, name, f"main_{name}.cpp") out = os.path.join(BUILD, f"main_{name}") r = subprocess.run( ["g++", "-std=c++17", "-O2", "-Wall", "-Wextra", "-I", os.path.join(COMP, name), "-I", COMP, src, "-lX11", "-o", out], capture_output=True, text=True, timeout=300) return name, r.returncode == 0, r.stderr[-500:] mbad = [] with ThreadPoolExecutor(max_workers=NPROC) as ex: for name, ok, err in ex.map(build_main, WIDGETS): if not ok: mbad.append(name) failures.append(f"{name}: demo main build failed: {err}") print(f"demo mains built: {len(WIDGETS) - len(mbad)}/{len(WIDGETS)}", flush=True) # --- report --- with open(os.path.join(TMP, "ind_csv_report.tsv"), "w") as f: f.write("name\tbuild\tnumeric\tshot\tshot_diff\tshot_nonbg\tnotes\n") for r in rows: f.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % ( r["name"], r.get("build", ""), r.get("numeric", ""), r.get("shot", ""), r.get("shot_diff", ""), r.get("shot_nonbg", ""), r.get("notes", "").replace("\t", " "))) print("=" * 60) print(f"IND CSV: harnesses {sum(built.values())}/{len(WIDGETS)}, " f"numeric {npass}/{len(WIDGETS)}, shots {spass}/{len(SAMPLE)}, " f"mains {len(WIDGETS) - len(mbad)}/{len(WIDGETS)}") if failures: print(f"FAILURES ({len(failures)}):") for msg in failures[:40]: print(" -", msg) sys.exit(1) print("IND CSV: ALL PASS")