test_compiler.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import copy
  2. from html.parser import HTMLParser
  3. import json
  4. from pathlib import Path
  5. import unittest
  6. from d2c.compiler import compile_project
  7. from d2c.design import normalize_design
  8. def frame(ident="1:1", children=None, **kwargs):
  9. return {"id": ident, "type": "FRAME", "name": "Example", "absoluteBoundingBox": {"x": 100, "y": 50, "width": 800, "height": 600}, "children": children or [], **kwargs}
  10. def label(ident="1:2", text="Hello"):
  11. return {"id": ident, "type": "TEXT", "name": "Title", "characters": text, "style": {"fontFamily": "Inter", "fontSize": 24, "fontWeight": 700}, "fills": [{"type": "SOLID", "color": {"r": 0.1, "g": 0.2, "b": 0.3}}]}
  12. class NodeParser(HTMLParser):
  13. def __init__(self, text):
  14. super().__init__()
  15. self.nodes = {}
  16. self.scripts = []
  17. self.feed(text)
  18. def handle_starttag(self, tag, attrs):
  19. attrs = dict(attrs)
  20. if "data-node-id" in attrs:
  21. self.nodes[attrs["data-node-id"]] = (tag, attrs)
  22. if tag == "script":
  23. self.scripts.append(attrs)
  24. class CompilerTests(unittest.TestCase):
  25. def test_file_and_nodes_selection(self):
  26. first, second = frame(), frame("2:1", [label("2:2")])
  27. payload = {"document": {"id": "0:0", "type": "DOCUMENT", "children": [{"id": "0:1", "type": "CANVAS", "children": [first, second]}]}}
  28. default = normalize_design(payload)
  29. self.assertEqual(default["root"]["id"], "1:1")
  30. self.assertTrue(any("多个" in warning for warning in default["warnings"]))
  31. self.assertEqual(normalize_design(payload, "2-1")["root"]["id"], "2:1")
  32. self.assertEqual(normalize_design({"nodes": {"2:1": {"document": second}}})["stats"]["text_count"], 1)
  33. with self.assertRaisesRegex(ValueError, "未找到"):
  34. normalize_design(payload, "unknown")
  35. def test_hidden_nodes_and_duplicate_ids(self):
  36. design = normalize_design(frame(children=[label(), {**label("1:3"), "visible": False}]))
  37. self.assertEqual(design["stats"]["node_count"], 2)
  38. self.assertEqual(design["stats"]["hidden_count"], 1)
  39. with self.assertRaisesRegex(ValueError, "重复"):
  40. normalize_design(frame(children=[label(), label()]))
  41. def test_node_and_depth_limits(self):
  42. with self.assertRaisesRegex(ValueError, "500"):
  43. normalize_design(frame(children=[label(f"n:{i}") for i in range(500)]))
  44. tree = label("leaf")
  45. for i in range(41):
  46. tree = frame(str(i), [tree])
  47. with self.assertRaisesRegex(ValueError, "40"):
  48. normalize_design(tree)
  49. def test_auto_layout_and_text_styles(self):
  50. tree = frame(children=[{**label(), "layoutSizingHorizontal": "FILL"}], layoutMode="HORIZONTAL", itemSpacing=16, paddingLeft=24, paddingTop=12, counterAxisAlignItems="CENTER", primaryAxisAlignItems="SPACE_BETWEEN")
  51. design = normalize_design(tree)
  52. style = design["root"]["style"]
  53. self.assertEqual((style["display"], style["flexDirection"], style["gap"]), ("flex", "row", "16px"))
  54. self.assertEqual(style["justifyContent"], "space-between")
  55. child = design["root"]["children"][0]
  56. self.assertEqual(child["style"]["flex"], "1 1 0")
  57. self.assertEqual(child["style"]["fontSize"], "24px")
  58. self.assertIn("#1a334c", design["tokens"]["colors"])
  59. def test_absolute_positions_are_relative_to_parent(self):
  60. child = frame("child")
  61. child["absoluteBoundingBox"].update({"x": 135, "y": 72, "width": 50, "height": 30})
  62. style = normalize_design(frame(children=[child]))["root"]["children"][0]["style"]
  63. self.assertEqual((style["position"], style["left"], style["top"]), ("absolute", "35px", "22px"))
  64. def test_artwork_remains_visible_as_placeholders(self):
  65. child = {"id": "vector", "name": "Illustration", "type": "VECTOR", "fills": [{"type": "IMAGE"}, {"type": "GRADIENT_LINEAR"}]}
  66. design = normalize_design(frame(children=[child]))
  67. self.assertEqual(design["stats"]["placeholder_count"], 1)
  68. self.assertTrue(design["warnings"])
  69. preview = compile_project(design)["preview.html"]
  70. for token in ["VECTOR", "图片资源待接入", "GRADIENT_LINEAR", "d2c-placeholder"]:
  71. self.assertIn(token, preview)
  72. def test_text_and_node_id_are_escaped(self):
  73. attack = '</script><img src=x onerror="alert(1)"> {danger}'
  74. tree = frame(children=[label('x" onclick="evil', attack)])
  75. files = compile_project(normalize_design(tree))
  76. self.assertIn("&lt;/script&gt;&lt;img", files["preview.html"])
  77. self.assertNotIn('<img src=x', files["preview.html"])
  78. self.assertIn(json.dumps(attack, ensure_ascii=False), files["src/App.tsx"])
  79. parsed = NodeParser(files["preview.html"])
  80. self.assertIn('x" onclick="evil', parsed.nodes)
  81. self.assertNotIn("onclick", parsed.nodes['x" onclick="evil'][1])
  82. self.assertEqual(parsed.scripts, [])
  83. def test_component_extraction_and_node_mapping(self):
  84. design = normalize_design(frame(children=[label()]))
  85. plan = {"components": [{"node_id": "1:1", "name": "Dashboard", "tag": "main"}, {"node_id": "1:2", "name": "PageTitle", "tag": "h1"}], "notes": []}
  86. files = compile_project(design, plan)
  87. self.assertIn("function Dashboard()", files["src/App.tsx"])
  88. self.assertIn("<PageTitle />", files["src/App.tsx"])
  89. self.assertIn("<Dashboard />", files["src/App.tsx"])
  90. self.assertEqual(NodeParser(files["preview.html"]).nodes["1:2"][0], "h1")
  91. manifest = json.loads(files["manifest.json"])
  92. self.assertEqual({node["id"] for node in manifest["nodes"]}, {"1:1", "1:2"})
  93. def test_invalid_component_plan_is_rejected(self):
  94. design = normalize_design(frame(children=[label()]))
  95. invalid = [
  96. {"node_id": "missing", "name": "Title", "tag": "h1"},
  97. {"node_id": "1:2", "name": "X);evil();//", "tag": "h1"},
  98. {"node_id": "1:2", "name": "App", "tag": "h1"},
  99. {"node_id": "1:2", "name": "Title", "tag": "script"},
  100. {"node_id": "1:1", "name": "Title", "tag": "p"},
  101. ]
  102. for item in invalid:
  103. with self.subTest(item=item), self.assertRaises(ValueError):
  104. compile_project(design, {"components": [item]})
  105. def test_buttons_are_disabled_and_extracted_children_are_phrasing(self):
  106. design = normalize_design(frame(children=[label()]))
  107. plan = {"components": [{"node_id": "1:1", "name": "ContinueButton", "tag": "button"}, {"node_id": "1:2", "name": "ButtonLabel", "tag": "p"}]}
  108. files = compile_project(design, plan)
  109. parser = NodeParser(files["preview.html"])
  110. self.assertEqual(parser.nodes["1:1"][0], "button")
  111. self.assertIn("disabled", parser.nodes["1:1"][1])
  112. self.assertEqual(parser.nodes["1:2"][0], "span")
  113. self.assertIn("function ButtonLabel() {\n return (\n <span", files["src/App.tsx"])
  114. self.assertNotIn("onClick", files["src/App.tsx"])
  115. plan["components"][1]["tag"] = "button"
  116. with self.assertRaisesRegex(ValueError, "嵌套"):
  117. compile_project(design, plan)
  118. def test_css_injection_is_rejected(self):
  119. design = normalize_design(frame())
  120. for value in ['red; } body {display:none', 'url(https://evil.test)', '</style><script>alert(1)</script>', 'u\\72l(x)']:
  121. with self.subTest(value=value), self.assertRaises(ValueError):
  122. mutated = copy.deepcopy(design)
  123. mutated["root"]["style"]["backgroundColor"] = value
  124. compile_project(mutated)
  125. def test_sample_is_complete_and_compilation_is_deterministic(self):
  126. sample = Path(__file__).resolve().parents[1] / "data" / "sample-design.json"
  127. design = normalize_design(json.loads(sample.read_text()))
  128. first, second = compile_project(design), compile_project(design)
  129. self.assertEqual(first, second)
  130. self.assertEqual(design["stats"]["placeholder_count"], 0)
  131. self.assertGreater(design["stats"]["node_count"], 50)
  132. self.assertEqual(len(NodeParser(first["preview.html"]).nodes), design["stats"]["node_count"])
  133. for name in ["package.json", "src/App.tsx", "src/main.tsx", "src/styles.css", "vite.config.ts", "tsconfig.json", "preview.html", "manifest.json"]:
  134. self.assertIn(name, first)
  135. if __name__ == "__main__":
  136. unittest.main()