diff --git a/tests/test_core.py b/tests/test_core.py index 076da74..d420957 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -11,7 +11,17 @@ class RegistryTests(unittest.TestCase): for entry in palette.PALETTE: cls = core.lookup(entry.name) self.assertIsNotNone(cls, entry.name) - self.assertEqual(cls.ARCHETYPE, entry.archetype) + if entry.name.startswith("Stock"): + # Phase 6: Stock kinds draw in stock.StockWidget, + # whose ARCHETYPE is "Chart" regardless of the + # palette's per-kind archetype (Indicator etc.). + from lightgui.xframe import stock as stock_mod + self.assertIs(cls, stock_mod.StockWidget, entry.name) + elif entry.name.startswith("Inst"): + from lightgui.xframe import instruments as inst_mod + self.assertIs(cls, inst_mod.InstWidget, entry.name) + else: + self.assertEqual(cls.ARCHETYPE, entry.archetype) def test_unknown_kind_is_none(self): self.assertIsNone(core.lookup("GtkNoSuchWidget")) diff --git a/tests/test_phase6.py b/tests/test_phase6.py new file mode 100644 index 0000000..4889403 --- /dev/null +++ b/tests/test_phase6.py @@ -0,0 +1,388 @@ +"""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_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() diff --git a/tests/test_props.py b/tests/test_props.py index 6cd0659..1d15f5a 100644 --- a/tests/test_props.py +++ b/tests/test_props.py @@ -88,12 +88,13 @@ class GenericSetTests(unittest.TestCase): self.assertEqual(props.props_for("GtkNoSuchWidget"), tuple(props.GENERIC_PROPS)) - def test_stock_and_instrument_kinds_generic_only_for_now(self): - # Phase 6 adds their tables; Phase 2 gives them the generic - # set only (plus nothing custom). + def test_stock_and_instrument_kinds_have_phase6_tables(self): + # Phase 6 adds their tables (generic set first, then each + # widget's own props from the C tables). The Ind* indicator + # entries keep the generic set only -- they are out of scope. self.assertEqual(props.custom_props_for("IndRSI"), ()) - self.assertEqual(props.custom_props_for("InstLedRed"), ()) - self.assertEqual(props.custom_props_for("StockLineChart"), ()) + self.assertTrue(props.custom_props_for("InstLedRed")) + self.assertTrue(props.custom_props_for("StockLineChart")) class PerWidgetTests(unittest.TestCase):