"""Root sheet writer regression: hierarchical parent .kicad_sch.""" from tools.epro2.kicad._sexpr_reader import parse from tools.epro2.kicad.root_sch_writer import ChildSheet, write_root_sheet def _block(parsed, name): return [c for c in parsed if isinstance(c, list) and c and c[0] == name] def test_root_emits_one_sheet_block_per_child(): children = [ ChildSheet("Overview.kicad_sch", "Overview", "uuid-1"), ChildSheet("MCU.kicad_sch", "MCU", "uuid-2"), ChildSheet("Codec.kicad_sch", "Codec", "uuid-3"), ] parsed = parse(write_root_sheet("CoreBoard", children)) sheets = _block(parsed, "sheet") assert len(sheets) == 3 # Each sheet block carries the assigned uuid + Sheetname + Sheetfile titles = [] files = [] uuids = [] for sh in sheets: uuids.append(next(c for c in sh if isinstance(c, list) and c[0] == "uuid")[1]) for c in sh: if isinstance(c, list) and c[0] == "property": if c[1] == "Sheetname": titles.append(c[2]) elif c[1] == "Sheetfile": files.append(c[2]) assert titles == ["Overview", "MCU", "Codec"] assert files == ["Overview.kicad_sch", "MCU.kicad_sch", "Codec.kicad_sch"] assert uuids == ["uuid-1", "uuid-2", "uuid-3"] def test_root_assigns_sequential_page_numbers_starting_at_2(): """Root itself is page 1 of the hierarchy; children start at page 2 so that a child's (sheet_instances (page "")) lines up with the root's (instances ... (page "")).""" children = [ ChildSheet("a.kicad_sch", "A", "u-a"), ChildSheet("b.kicad_sch", "B", "u-b"), ] parsed = parse(write_root_sheet("Project", children)) sheets = _block(parsed, "sheet") page_nums = [] for sh in sheets: inst = next(c for c in sh if isinstance(c, list) and c[0] == "instances") proj = next(c for c in inst if isinstance(c, list) and c[0] == "project") path = next(c for c in proj if isinstance(c, list) and c[0] == "path") page = next(c for c in path if isinstance(c, list) and c[0] == "page") page_nums.append(page[1]) assert page_nums == ["2", "3"] # And the root's own page is 1 root_inst = _block(parsed, "sheet_instances")[0] root_path = next(c for c in root_inst if isinstance(c, list) and c[0] == "path") root_page = next(c for c in root_path if isinstance(c, list) and c[0] == "page") assert root_page[1] == "1" def test_root_handles_zero_children(): """Empty schematic: still emit a valid kicad_sch with no (sheet) blocks.""" parsed = parse(write_root_sheet("Empty", [])) assert parsed[0] == "kicad_sch" assert _block(parsed, "sheet") == [] # sheet_instances still required (KiCad demands at least one path) assert _block(parsed, "sheet_instances")