Files
cnmcdee 6d2dae20a1 Phase 6 fix: 14/16-segment maps + geometry verbatim from C
The draft segment code used its own segment ids (h/i centre
verticals, j/k/l/m diagonals) and drew diagonals as full-length
round-capped strokes, so I/K/M/V/W were wrong and every glyph was
swamped by a dark X blob ("HELLO" unreadable in the showcase
screenshot). This mirrors the C widgets exactly: segment_map()
strings from InstSeg14/16Display5.h, C ids (i/l centre verticals,
h/j/k/m diagonals), C draw_segment geometry (inset bars, hh/hv
verticals) and C draw_diag polygons that stop short of the centre.
Adds per-segment probe tests: every 14-seg glyph vs C map, 16-seg
M/W clean forms, 7-seg 8 vs 1.
2026-12-01 04:03:26 +00:00

471 lines
20 KiB
Python

"""Phase 6 tests: Stock (37) + Instrumentation (66) widgets.
- Property tables: all 103 kinds have the generic set + their custom
props from the C tables (1008 props, 116 distinct names), with the
corrected StockChart up/down defaults and symbol model-only.
- Headless Cairo draw smoke over all 103 kinds (no crashes, paints
something), including the short-plot guard (<16px) and the
ParallelChannel/Pitchfork 0/1/2-anchor guard (Flag 13, ddaf4bd).
- Live-apply: tank level set_prop updates state and repaints.
- ProgressBar renders as a filled bar (the Rust port's known gap --
renders as a slider -- must not be repeated here).
- Seeded demo series: 250 deterministic bars, OHLC invariants.
- Generator: model-only symbol is a comment, never a set_prop call.
"""
import json
import os
import unittest
import cairo
from lightgui import generator
from lightgui import props
from lightgui.model import Project
from lightgui.xframe import core
from lightgui.xframe import palette
from lightgui.xframe import stock as stock_mod
from lightgui.xframe import instruments as inst_mod
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# The 103 kinds, from the palette (37 Stock* + 66 Inst* registry names).
STOCK_NAMES = [e.name for e in palette.PALETTE
if e.name.startswith("Stock")]
INST_NAMES = [e.name for e in palette.PALETTE
if e.name.startswith("Inst")]
P6_KINDS = sorted({e.kind for e in palette.PALETTE
if e.name.startswith("Stock")
or e.name.startswith("Inst")})
def _draw(widget, width=None, height=None):
"""Draw *widget* on a fresh white surface; return the surface."""
surface = cairo.ImageSurface(
cairo.FORMAT_ARGB32,
max(widget.width + 4, width or 0),
max(widget.height + 4, height or 0))
cr = cairo.Context(surface)
cr.set_source_rgb(1, 1, 1)
cr.paint()
widget.draw(cr)
return surface
def _non_white_pixels(surface):
data = surface.get_data()
stride = surface.get_stride()
count = 0
for y in range(surface.get_height()):
row = data[y * stride:(y + 1) * stride]
for x in range(0, len(row), 4):
b, g, r = row[x], row[x + 1], row[x + 2]
if (r, g, b) != (255, 255, 255):
count += 1
return count
def _pixel(surface, x, y):
"""(r, g, b) 0..255 at (*x*, *y*) of an ARGB32 surface."""
data = surface.get_data()
stride = surface.get_stride()
off = y * stride + x * 4
b, g, r = data[off], data[off + 1], data[off + 2]
return r, g, b
def _count_colour(surface, target, tolerance=30):
"""Pixels within *tolerance* of *target* (r, g, b)."""
data = surface.get_data()
stride = surface.get_stride()
count = 0
for y in range(surface.get_height()):
row = data[y * stride:(y + 1) * stride]
for x in range(0, len(row), 4):
b, g, r = row[x], row[x + 1], row[x + 2]
if (abs(r - target[0]) <= tolerance
and abs(g - target[1]) <= tolerance
and abs(b - target[2]) <= tolerance):
count += 1
return count
class Phase6TableTests(unittest.TestCase):
def test_103_kinds(self):
self.assertEqual(len(STOCK_NAMES), 37)
self.assertEqual(len(INST_NAMES), 66)
self.assertEqual(len(P6_KINDS), 103)
def test_every_kind_has_generic_plus_custom(self):
generic = props.GENERIC_NAMES
for kind in P6_KINDS:
names = props.prop_names(kind)
self.assertTrue(generic <= names,
"%s missing generic props" % kind)
custom = props.custom_props_for(kind)
self.assertTrue(custom, "%s has no custom props" % kind)
# Custom props are never generic names (no shadowing).
self.assertFalse(set(p.name for p in custom) & generic,
"%s custom shadows generic" % kind)
def test_total_1008_props_116_distinct(self):
total = sum(len(props.custom_props_for(k)) for k in P6_KINDS)
self.assertEqual(total, 1008)
distinct = {p.name for k in P6_KINDS
for p in props.custom_props_for(k)}
self.assertEqual(len(distinct), 116)
def test_generated_tables_match_registered_tables(self):
"""props_phase6.TABLES is exactly what props_for serves."""
import lightgui.props_phase6 as p6
self.assertEqual(set(p6.TABLES), set(P6_KINDS))
for kind, table in p6.TABLES.items():
self.assertEqual(tuple(props.custom_props_for(kind)), table,
kind)
self.assertEqual(
tuple(p.name for p in table),
tuple(p.name for p in props.custom_props_for(kind)),
kind)
def test_shadowed_names_keep_generic_set_only(self):
"""Kinds are shared across families: IndVWAP/IndAnchoredVWAP
(kind VWAP) and TArrow (kind Arrow) must NOT inherit the
Phase 6 tables -- they keep the generic set only."""
import lightgui.props_phase6 as p6
self.assertEqual(tuple(p6.SHADOWED),
("IndAnchoredVWAP", "IndVWAP", "TArrow"))
for name in p6.SHADOWED:
self.assertEqual(props.custom_props_for(name), (), name)
self.assertEqual(props.props_for(name),
tuple(props.GENERIC_PROPS), name)
# And they keep their own archetype drawings, not the
# Phase 6 classes.
from lightgui.xframe import core as core_mod
self.assertEqual(core_mod.lookup("IndVWAP").ARCHETYPE,
"Indicator")
self.assertEqual(core_mod.lookup("IndAnchoredVWAP").ARCHETYPE,
"Indicator")
# TArrow keeps its palette archetype (Display), not the
# StockWidget drawing.
self.assertEqual(core_mod.lookup("TArrow").ARCHETYPE, "Display")
self.assertIsNot(core_mod.lookup("TArrow"),
stock_mod.StockWidget)
self.assertIs(core_mod.lookup("StockVWAP"), stock_mod.StockWidget)
self.assertIs(core_mod.lookup("StockArrow"), stock_mod.StockWidget)
def test_stockchart_up_down_defaults(self):
table = {p.name: p for p in
props.custom_props_for("CandlestickChart")}
self.assertEqual(table["up-color"].default, "rgb(0,150,0)")
self.assertEqual(table["down-color"].default, "rgb(200,30,30)")
for kind in ("LineChart", "OHLCBarChart", "HeikinAshi",
"HollowCandles", "AreaChart", "Renko"):
table = {p.name: p for p in props.custom_props_for(kind)}
self.assertEqual(table["up-color"].default, "rgb(0,150,0)",
kind)
self.assertEqual(table["down-color"].default,
"rgb(200,30,30)", kind)
def test_symbol_is_model_only(self):
for kind in ("VolumeBars", "VolumeCandles", "VolumeProfile",
"VWAP", "OBVChart", "MoneyFlowChart",
"AccumulationDistribution"):
self.assertTrue(props.is_model_only(kind, "symbol"), kind)
self.assertFalse(props.is_model_only(kind, "text"), kind)
self.assertFalse(props.is_model_only(kind, "view-first"),
kind)
def test_text_is_first_custom_prop(self):
for kind in P6_KINDS:
self.assertEqual(props.custom_props_for(kind)[0].name,
"text", kind)
def test_classes_dispatch_to_phase6_widgets(self):
for name in STOCK_NAMES:
widget = core.create(name, name + "_001")
self.assertIsInstance(widget, stock_mod.StockWidget, name)
for name in INST_NAMES:
widget = core.create(name, name + "_001")
self.assertIsInstance(widget, inst_mod.InstWidget, name)
class Phase6DrawTests(unittest.TestCase):
def test_all_103_draw_without_crashing(self):
for name in STOCK_NAMES + INST_NAMES:
widget = core.create(name, name + "_001")
try:
_draw(widget)
except Exception as exc: # noqa: BLE001 - report the kind
self.fail("%s draw crashed: %r" % (name, exc))
def test_all_103_draw_something(self):
blank = []
for name in STOCK_NAMES + INST_NAMES:
widget = core.create(name, name + "_001")
if _non_white_pixels(_draw(widget)) == 0:
blank.append(name)
self.assertFalse(blank, "kinds drawing nothing: %s" % blank[:10])
def test_all_103_draw_with_live_props(self):
"""Draw every kind again with a few of its own props set."""
for name in STOCK_NAMES + INST_NAMES:
widget = core.create(name, name + "_001")
for prop in props.custom_props_for(widget.pkind):
if prop.name in ("text", "symbol", "labels",
"annotation-text"):
continue
if prop.kind == "Bool":
value = "true"
elif prop.kind in ("Int", "Double"):
value = prop.default
elif prop.kind == "Color":
value = prop.default or "rgb(10,20,30)"
else:
continue
try:
widget.set_prop(prop.name, value)
except ValueError:
pass
try:
_draw(widget)
except Exception as exc: # noqa: BLE001
self.fail("%s draw with props crashed: %r"
% (name, exc))
def test_short_plot_guard(self):
"""Widgets shorter than 16px must not crash (Rust
plot.rs:250 clamp class: min > max)."""
for name in STOCK_NAMES:
for height in (1, 5, 10, 15):
widget = core.create(name, name + "_001", 0, 0,
200, height)
try:
_draw(widget)
except Exception as exc: # noqa: BLE001
self.fail("%s at height %d crashed: %r"
% (name, height, exc))
for name in INST_NAMES:
widget = core.create(name, name + "_001", 0, 0, 200, 10)
_draw(widget)
def test_candlestick_colours_visible(self):
"""Seeded demo candles paint up green + down red."""
widget = core.create("StockCandlestickChart",
"StockCandlestickChart_001", 0, 0, 400, 200)
surface = _draw(widget)
self.assertGreater(_count_colour(surface, (0, 150, 0)), 50)
self.assertGreater(_count_colour(surface, (200, 30, 30)), 50)
def test_progress_bar_is_a_filled_bar(self):
"""The Rust port's known gap (ProgressBar renders as a
slider) must not be repeated: fraction 0.5 fills the left
half with the bar colour and leaves the trough on the right."""
widget = core.create("GtkProgressBar", "GtkProgressBar_001",
0, 0, 200, 30)
widget.set_prop("fraction", "0.5")
surface = _draw(widget)
left = _pixel(surface, 50, 15)
right = _pixel(surface, 150, 15)
bar = (52, 101, 164)
self.assertTrue(all(abs(left[i] - bar[i]) <= 30
for i in range(3)),
"left half is not the bar colour: %r" % (left,))
self.assertFalse(all(abs(right[i] - bar[i]) <= 30
for i in range(3)),
"right half looks filled too: %r" % (right,))
def test_tank_level_live_apply(self):
"""13.78 -> 80 applies live: the fill grows (C verification)."""
widget = core.create("InstVerticalTankLevel",
"InstVerticalTankLevel_001", 0, 0, 200, 200)
widget.set_prop("level", "13.78")
low = _count_colour(_draw(widget), (40, 120, 200))
widget.set_prop("level", "80")
self.assertEqual(widget.get_prop("level"), "80")
high = _count_colour(_draw(widget), (40, 120, 200))
self.assertGreater(high, low * 3)
def test_seg14_glyphs_match_c_map(self):
"""Each 14-seg glyph lights exactly C's segment set
(InstSeg14Display5.h segment_map): probe every segment of
a single digit and compare lit/dim against the map. This is
the test that catches the wrong-ids / diagonal-blob class:
I/K/M/V/W render differently from the draft's maps."""
from lightgui.xframe.instruments import (
_FOURTEEN_MAP, _seg_rects)
universe = ("a", "b", "c", "d", "e", "f", "g1", "g2",
"h", "i", "j", "k", "l", "m")
for ch in "HELLOIMVWX\"'":
widget = core.create("InstSeg14Display1",
"Seg14_001", 0, 0, 90, 110)
widget.set_prop("value", ch)
surface = _draw(widget)
rects, lines = _seg_rects(10, 10, 70, 90, "fourteen")
expected = set(_FOURTEEN_MAP[ch].split())
for seg in universe:
if seg in rects:
rx, ry, rw, rh = rects[seg]
px, py = int(rx + rw / 2), int(ry + rh / 2)
else:
x0, y0, x1, y1 = lines[seg]
px, py = int((x0 + x1) / 2), int((y0 + y1) / 2)
r, g, b = _pixel(surface, px, py)
lit = (abs(r - 255) <= 40 and abs(g - 176) <= 40
and b <= 40)
self.assertEqual(lit, seg in expected,
"%r seg %s at (%d,%d) = (%d,%d,%d)"
% (ch, seg, px, py, r, g, b))
def test_seg16_mw_clean(self):
"""16-seg M/W use the split forms (C InstSeg16Display5.h):
M lights the top diagonals + centre vertical, W the bottom
diagonals + lower centre vertical."""
from lightgui.xframe.instruments import (
_SIXTEEN_MAP, _seg_rects)
universe = ("a1", "a2", "b", "c", "d1", "d2", "e", "f",
"g1", "g2", "h", "i", "j", "k", "l", "m")
for ch, must_have in (("M", {"h", "i", "j"}),
("W", {"k", "l", "m"})):
widget = core.create("InstSeg16Display1",
"Seg16_001", 0, 0, 90, 110)
widget.set_prop("value", ch)
surface = _draw(widget)
rects, lines = _seg_rects(10, 10, 70, 90, "sixteen")
expected = set(_SIXTEEN_MAP[ch].split())
self.assertTrue(must_have <= expected, (ch, expected))
for seg in must_have:
if seg in rects:
rx, ry, rw, rh = rects[seg]
px, py = int(rx + rw / 2), int(ry + rh / 2)
else:
x0, y0, x1, y1 = lines[seg]
px, py = int((x0 + x1) / 2), int((y0 + y1) / 2)
r, g, b = _pixel(surface, px, py)
self.assertTrue(
abs(r - 255) <= 40 and abs(g - 176) <= 40
and b <= 40,
"%r seg %s should be lit, got (%d,%d,%d)"
% (ch, seg, r, g, b))
def test_seven_seg_8_vs_1(self):
"""7-seg: 8 lights all segments, 1 only b+c (C
DigitalReadout seg[10][7])."""
from lightgui.xframe.instruments import _seg_rects
for ch, lit_segs in (("8", set("abcdefg")), ("1", {"b", "c"})):
widget = core.create("InstLedDigits1",
"Led1_001", 0, 0, 90, 110)
widget.set_prop("value", ch)
surface = _draw(widget)
rects, _lines = _seg_rects(10, 10, 70, 90, "seven")
for seg in "abcdefg":
rx, ry, rw, rh = rects[seg]
px, py = int(rx + rw / 2), int(ry + rh / 2)
r, g, b = _pixel(surface, px, py)
lit = (abs(r - 255) <= 40 and abs(g - 60) <= 40
and abs(b - 35) <= 40)
self.assertEqual(lit, seg in lit_segs,
"%r seg %s = (%d,%d,%d)"
% (ch, seg, r, g, b))
def test_gauge_lamp_segments_render(self):
widget = core.create("InstAnalogGauge", "InstAnalogGauge_001",
0, 0, 200, 200)
widget.set_prop("value", "62")
self.assertGreater(_non_white_pixels(_draw(widget)), 500)
lamp = core.create("InstPanelLampRed", "InstPanelLampRed_001",
0, 0, 100, 100)
lamp.set_prop("on", "true")
surface = _draw(lamp)
self.assertGreater(_count_colour(surface, (220, 30, 30)), 100)
seg = core.create("InstSeg14Display4", "InstSeg14Display4_001",
0, 0, 240, 110)
surface = _draw(seg)
self.assertGreater(_count_colour(surface, (255, 176, 0)), 100)
class Phase6AnchorTests(unittest.TestCase):
def _channel(self, anchors, kind="StockParallelChannel"):
widget = core.create(kind, kind + "_001", 0, 0, 300, 200)
for i, (bar, price) in enumerate(anchors, start=1):
widget.set_prop("anchor-%d-bar" % i, str(bar))
widget.set_prop("anchor-%d-price" % i, str(price))
return widget
def test_parallel_channel_0_1_2_anchors(self):
"""Flag 13 (ddaf4bd): 0-2 anchors must not crash."""
for anchors in ([], [(5, 100)], [(5, 100), (15, 105)]):
widget = self._channel(anchors)
_draw(widget)
self.assertGreater(_non_white_pixels(_draw(widget)), 0)
def test_pitchfork_0_1_2_anchors(self):
for anchors in ([], [(5, 100)], [(5, 100), (15, 105)]):
widget = self._channel(anchors, "StockPitchfork")
_draw(widget)
def test_three_anchors_draw_channel_lines(self):
widget = self._channel([(5, 100), (15, 105), (10, 98)])
surface = _draw(widget)
self.assertGreater(
_count_colour(surface, (0, 120, 200)), 50)
def test_two_anchor_channel_falls_back_to_midline(self):
"""With 2 anchors the outer line falls back to the midline:
the drawing has the main + dashed midline but no third line
colour beyond them -- it must simply draw without crashing
and show the tool colour."""
widget = self._channel([(5, 100), (15, 105)])
surface = _draw(widget)
self.assertGreater(
_count_colour(surface, (0, 120, 200)), 20)
class Phase6SeriesTests(unittest.TestCase):
def test_demo_series_250_deterministic(self):
first = stock_mod.demo_series()
second = stock_mod.demo_series()
self.assertEqual(first, second)
self.assertEqual(len(first), 250)
self.assertEqual(len(stock_mod.DEMO_SERIES), 250)
def test_demo_series_ohlc_invariants(self):
for open_v, high, low, close, volume in stock_mod.DEMO_SERIES:
self.assertGreaterEqual(high, max(open_v, close))
self.assertLessEqual(low, min(open_v, close))
self.assertGreater(close, 0)
self.assertGreater(volume, 0)
def test_demo_series_starts_near_100(self):
self.assertAlmostEqual(stock_mod.DEMO_SERIES[0][0], 100.0)
def test_different_seed_differs(self):
self.assertNotEqual(stock_mod.demo_series(seed=42),
stock_mod.demo_series(seed=43))
class Phase6GeneratorTests(unittest.TestCase):
def test_symbol_emitted_as_model_only_comment(self):
project = Project(title="Demo", class_name="DemoWindow")
widget = project.add_widget("StockVolumeBars", 10, 10, 300, 200)
widget.set_prop("symbol", "AAPL")
# A live prop set to a non-default value is a real set_prop.
widget.set_prop("up-color", "rgb(0,180,0)")
text = generator.generate(project)
self.assertIn("NOTE (model-only, no XFrame setter)", text)
self.assertIn("symbol='AAPL'", text)
self.assertNotIn("set_prop('symbol'", text)
self.assertIn("widget.set_prop('up-color', 'rgb(0,180,0)')",
text)
def test_tank_level_emitted_as_set_prop(self):
project = Project(title="Demo", class_name="DemoWindow")
widget = project.add_widget("InstVerticalTankLevel", 10, 10,
200, 200)
widget.set_prop("level", "80")
text = generator.generate(project)
self.assertIn("widget.set_prop('level', '80')", text)
if __name__ == "__main__":
unittest.main()