Files
cnmcdee 099733b27d Stock chart CSV data: loader in StockData.h, load_csv/add_series_csv on 23 widgets, docs + tests
- xframe::load_ohlcv_csv / parse_ohlcv_csv_text in StockData.h:
  date,open,high,low,close,volume, optional header matched by name
  (Massive exports load as-is), YYYY-MM-DD / ISO / epoch s-ms-ns dates,
  volume optional, malformed rows skipped + counted, error string out.
- 15 single-series widgets gain load_csv() + clear_series();
  8 comparative widgets gain add_series_csv(); failure leaves the
  series untouched. Drawing tools intentionally excluded (coordinates,
  not series); Ind* widgets take CSV only via the constructor.
- Fixtures tests/data/ohlcv_sample.csv (+ _b, 30 rows each) and
  widgets/tests/csv_unit_test.cpp + test_stock_csv.py (23/23 PASS:
  CSV shot differs from template shot, 30 items, bad path exits 2).
- docs/stock-market-csv-data.md + CSV sections in the stock group docs.
2026-12-02 10:15:50 +00:00

359 lines
14 KiB
Python

#!/usr/bin/env python3
"""Stock chart CSV test driver: proves every in-scope Stock* chart widget
plots real CSV data (not just the seeded template series).
- Compiles + runs widgets/tests/csv_unit_test.cpp (parser unit tests).
- For each of the 23 in-scope widgets: screenshots the template-data demo,
then a harness that loads tests/data/ohlcv_sample.csv (30 real OHLCV
rows) via the widget's load_csv()/add_series_csv() and screenshots it.
The two screenshots must differ substantially (CSV data visibly plots),
the CSV shot must be non-blank, and the widget must report 30 items.
- Also checks the failure path: a missing CSV file leaves the series
untouched and the harness exits 2.
- Multi-series widgets load ohlcv_sample.csv as "AAA" and
ohlcv_sample_b.csv as "BBB" after clear_series().
- Xvfb is restarted automatically if it dies mid-run (other jobs on this
server share it; a dead display is retried once per widget).
Re-derives every count from fresh artifacts each round; exits non-zero on
any failure. Attribution: XFrame.
"""
import os, re, subprocess, sys, time
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/stock-csv-shots"
BUILD = "/tmp/stock-csv-build"
CSV_A = os.path.join(REPO, "tests/data/ohlcv_sample.csv")
CSV_B = os.path.join(REPO, "tests/data/ohlcv_sample_b.csv")
DISPLAY = ":93"
ENV = dict(os.environ, DISPLAY=DISPLAY)
SINGLE = ["StockAccumulationDistribution", "StockAreaChart",
"StockBaselineChart", "StockCandlestickChart", "StockHeikinAshi",
"StockHollowCandles", "StockLineChart", "StockMoneyFlowChart",
"StockOBVChart", "StockOHLCBarChart", "StockRenko", "StockVWAP",
"StockVolumeBars", "StockVolumeCandles", "StockVolumeProfile"]
MULTI = ["StockCorrelationView", "StockIndexedComparison",
"StockMultiSymbolChart", "StockOverlayChart", "StockRatioChart",
"StockRelativePerformance", "StockSectorComparison",
"StockSpreadChart"]
WIDGETS = SINGLE + MULTI
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 shot(wid, path):
r = run(["import", "-window", str(wid), path], timeout=15)
return os.path.exists(path) and os.path.getsize(path) > 0
# --- Xvfb management (display can die mid-run; restart on demand) ---
_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
def make_harness(name):
"""Build a harness main from the widget's own demo main: same window,
but the series comes from the CSV file(s) given on argv."""
src = open(os.path.join(COMP, name, f"main_{name}.cpp")).read()
src = src.replace("int main()\n{", "int main(int argc, char** argv)\n{\n (void)argc;", 1)
if "#include <string>" not in src:
src = src.replace(f'#include "{name}.h"',
f'#include "{name}.h"\n#include <string>', 1)
m = re.search(r"^.*\bwidget\(display, screen, window, gc, &styles,.*\);$",
src, re.M)
assert m, f"{name}: construction line not found"
if name in SINGLE:
snippet = ('\n { std::string csv_err; '
'if (!widget.load_csv(argv[1], csv_err)) { '
'std::fprintf(stderr, "csv: %s\\n", csv_err.c_str()); return 2; } }'
'\n std::printf("csv_rows=%d\\n", widget.item_count());')
else:
snippet = ('\n { std::string csv_err; widget.clear_series(); '
'if (!widget.add_series_csv(argv[1], "AAA", csv_err)) return 2; '
'if (!widget.add_series_csv(argv[2], "BBB", csv_err)) return 2; }'
'\n std::printf("csv_rows=%d\\n", widget.item_count());')
src = src[:m.end()] + snippet + src[m.end():]
out = os.path.join(TMP, f"harness_{name}.cpp")
open(out, "w").write(src)
return out
# --- send_delete helper ---
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):
"""Run a demo binary, screenshot its window, exit it cleanly.
Returns (ok, note, stdout_text)."""
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)
try:
for name in WIDGETS:
row = {"name": name, "build": "FAIL", "draw": "FAIL",
"csv_diff": "FAIL", "rows": "FAIL", "badpath": "FAIL",
"notes": ""}
notes = []
# Build the template demo via cmake (isolated build dir).
bdir = os.path.join(BUILD, name)
r = subprocess.run(["cmake", "-S", os.path.join(COMP, name), "-B", bdir,
"-DCMAKE_CXX_FLAGS=-Wall -Wextra"],
capture_output=True, text=True, timeout=120)
out = r.stdout + r.stderr
r2 = subprocess.run(["cmake", "--build", bdir], capture_output=True,
text=True, timeout=180) if r.returncode == 0 else None
out2 = (r2.stdout + r2.stderr) if r2 else ""
binp = os.path.join(bdir, name)
if r.returncode != 0 or (r2 and r2.returncode != 0):
notes.append(f"template build failed: {(out + out2)[-300:]}")
row["notes"] = "; ".join(notes); rows.append(row)
failures.append(f"{name}: template build failed"); continue
if "warning:" in out2:
notes.append("template build warnings")
failures.append(f"{name}: warnings in template build")
# Build the CSV harness with g++ directly.
hsrc = make_harness(name)
hbin = os.path.join(TMP, f"harness_{name}")
r3 = subprocess.run(["g++", "-std=c++17", "-O2", "-Wall", "-Wextra",
"-I", os.path.join(COMP, name), "-I", COMP,
hsrc, "-lX11", "-o", hbin],
capture_output=True, text=True, timeout=120)
if r3.returncode != 0 or "warning:" in r3.stderr:
notes.append(f"harness build failed/warnings: {r3.stderr[-300:]}")
row["notes"] = "; ".join(notes); rows.append(row)
failures.append(f"{name}: harness build failed"); continue
if not (os.path.exists(binp) and os.access(binp, os.X_OK)):
notes.append("template binary missing"); row["notes"] = "; ".join(notes)
rows.append(row); failures.append(f"{name}: binary missing"); continue
row["build"] = "PASS"
# Template screenshot (retry once after an X restart).
tmpl = os.path.join(TMP, name + "_template.png")
ok, note, _ = shoot_demo(binp, name, tmpl, [], "template")
if not ok:
ensure_xvfb()
ok, note, _ = shoot_demo(binp, name, tmpl, [], "template")
if not ok:
notes.append(note)
failures.append(f"{name}: {note}")
row["notes"] = "; ".join(notes); rows.append(row); continue
# CSV harness: bad path must exit 2 without a window.
rb = subprocess.run([hbin, "/tmp/does-not-exist.csv", CSV_B],
capture_output=True, text=True, timeout=20, env=ENV)
if rb.returncode == 2:
row["badpath"] = "PASS"
else:
notes.append(f"bad path rc={rb.returncode} (want 2)")
failures.append(f"{name}: bad path rc={rb.returncode}")
# CSV harness screenshot (retry once after an X restart).
csvshot = os.path.join(TMP, name + "_csv.png")
ok, note, csv_out = shoot_demo(hbin, name, csvshot,
[CSV_A, CSV_B], "csv")
if not ok:
ensure_xvfb()
ok, note, csv_out = shoot_demo(hbin, name, csvshot,
[CSV_A, CSV_B], "csv")
if not ok:
notes.append(note)
failures.append(f"{name}: {note}")
row["notes"] = "; ".join(notes); rows.append(row); continue
nb = nonbg(csvshot)
if nb > 20:
row["draw"] = "PASS"
else:
notes.append(f"csv draw blank: {nb} non-bg px")
failures.append(f"{name}: csv draw blank")
d = diff(tmpl, csvshot)
# Calibrated threshold: the two runs differ ONLY in the series, so
# any diff far above rendering noise proves the CSV drives the
# plot. Clean-tree re-renders are pixel-identical (visreg baseline
# 0.0000%) and the OHLC driver treats a hover diff > 50 as a real
# response; thin-line widgets (OBV, VWAP, overlays) score in the
# low thousands while filled candle/bar charts score far higher.
# 1000 is 20x the hover threshold and far above noise.
if d > 1000:
row["csv_diff"] = "PASS"
else:
notes.append(f"csv vs template diff too small: {d}")
failures.append(f"{name}: csv diff {d} <= 1000")
m = re.search(r"csv_rows=(\d+)", csv_out)
# StockRenko counts bricks, not bars: 30 CSV bars build 25 bricks
# at the default brick size, so it expects 1..30, not exactly 30.
if name == "StockRenko":
rows_ok = bool(m) and 0 < int(m.group(1)) <= 30
want = "1..30"
else:
rows_ok = bool(m) and int(m.group(1)) == 30
want = "30"
if rows_ok:
row["rows"] = "PASS"
else:
notes.append(f"csv_rows={m.group(1) if m else 'missing'} (want {want})")
failures.append(f"{name}: csv_rows != {want}")
row["notes"] = "; ".join(notes)
rows.append(row)
print(f"{name}: build={row['build']} draw={row['draw']} "
f"csv_diff={row['csv_diff']} rows={row['rows']} "
f"badpath={row['badpath']}" +
(f" [{row['notes']}]" if row["notes"] else ""), flush=True)
finally:
if _xvfb is not None:
try:
_xvfb.terminate()
_xvfb.wait(timeout=5)
except Exception:
try:
_xvfb.kill()
except Exception:
pass
try:
os.remove(f"/tmp/.X{DISPLAY[1:]}-lock")
except FileNotFoundError:
pass
with open(os.path.join(TMP, "results.csv"), "w") as f:
f.write("widget,build,draw,csv_diff,rows,badpath,notes\n")
for r in rows:
f.write(",".join([r["name"], r["build"], r["draw"], r["csv_diff"],
r["rows"], r["badpath"],
'"' + r["notes"].replace('"', '""') + '"']) + "\n")
npass = sum(1 for r in rows if all(r[c] == "PASS" for c in
("build", "draw", "csv_diff", "rows", "badpath")))
print(f"CSV group: {npass}/{len(WIDGETS)} widgets fully PASS; "
f"failures={len(failures)}")
for f in failures:
print("FAIL:", f)
sys.exit(0 if not failures and npass == len(WIDGETS) else 1)