|
| 1 | +import json |
| 2 | +from pathlib import Path |
| 3 | +import pygame |
| 4 | +import pytest |
| 5 | +from rlc import Layout, Text, Padding, Direction, FIXED, FIT |
| 6 | +from rlc import LayoutLogger, LayoutLogConfig |
| 7 | + |
| 8 | +@pytest.fixture(autouse=True, scope="session") |
| 9 | +def init_pygame(): |
| 10 | + pygame.init() |
| 11 | + pygame.font.init() |
| 12 | + yield |
| 13 | + pygame.quit() |
| 14 | + |
| 15 | +def build_simple_tree(): |
| 16 | + root = Layout("white", sizing=(FIT(), FIT()), padding=Padding(5, 5, 5, 5), direction=Direction.ROW) |
| 17 | + child1 = Layout("blue", sizing=(FIXED(100), FIXED(50))) |
| 18 | + child2 = Text("Hello World", "Arial", 16) |
| 19 | + root.add_child(child1) |
| 20 | + root.add_child(child2) |
| 21 | + return root |
| 22 | + |
| 23 | + |
| 24 | +@pytest.mark.parametrize("indent", [2, 4]) |
| 25 | +def test_json_and_text_serialization(indent, tmp_path): |
| 26 | + root = build_simple_tree() |
| 27 | + logger = LayoutLogger(LayoutLogConfig()) |
| 28 | + |
| 29 | + # compute and layout to fill logger events |
| 30 | + root.compute_size(logger=logger) |
| 31 | + root.layout(0, 0, logger=logger) |
| 32 | + logger.record_final_tree(root) |
| 33 | + |
| 34 | + # --- JSON string --- |
| 35 | + js = logger.to_json() |
| 36 | + data = json.loads(js) |
| 37 | + assert "config" in data |
| 38 | + assert "events" in data |
| 39 | + assert "final_tree" in data |
| 40 | + assert data["final_tree"]["type"] == "Layout" |
| 41 | + |
| 42 | + # --- Write JSON file --- |
| 43 | + json_path = tmp_path / "layout.json" |
| 44 | + logger.write_json(str(json_path), indent=indent) |
| 45 | + assert json_path.exists() |
| 46 | + parsed = json.loads(json_path.read_text()) |
| 47 | + assert parsed["final_tree"]["type"] == "Layout" |
| 48 | + |
| 49 | + # --- Text tree string --- |
| 50 | + txt = logger.to_text_tree(root) |
| 51 | + assert "Layout" in txt |
| 52 | + assert "Text" in txt |
| 53 | + |
| 54 | + # --- Write text tree file --- |
| 55 | + txt_path = tmp_path / "layout.txt" |
| 56 | + logger.write_text_tree(root, str(txt_path)) |
| 57 | + assert txt_path.exists() |
| 58 | + contents = txt_path.read_text() |
| 59 | + assert "Layout" in contents |
| 60 | + assert "Text" in contents |
0 commit comments