Cotton code
130 lines · 7.8 KB · PythonRaw
#!/usr/bin/env python3"""The face registry generator's rules, on invented face files in a scratch tree."""import importlib.utilimport jsonimport pathlibimport tempfileimport unittestHERE = pathlib.Path(__file__).resolve().parentspec = importlib.util.spec_from_file_location('gen', HERE / 'gen-faces-registry.py')gen = importlib.util.module_from_spec(spec)spec.loader.exec_module(gen)def face(type_name, face_id, stock='framed', lays=None, ground='paper'):    lays = (stock != 'own') if lays is None else lays    paper = f'.onCardPaper({type_name}.stock.laid(nil))' if lays else ''    lies = f'    public static let ground: FaceGround = .{ground}\n' if ground else ''    return (f'struct {type_name}: View {{ var body: some View {{ EmptyView(){paper} }} }}\n\n'            f'extension {type_name} {{\n    public static let stock: FaceStock = .{stock}\n{lies}'            f'    public static let face = Face(id: "{face_id}", specimens: []) {{ _, _, _ in {type_name}() }}\n}}\n')class Registry(unittest.TestCase):    def tree(self, files):        root = pathlib.Path(tempfile.mkdtemp())        for name, text in files.items():            (root / name).parent.mkdir(parents=True, exist_ok=True)            (root / name).write_text(text)        return root    # RULE: The registry lists every face file's face, sorted by id, with the app folder it lives in.    def test_every_face_by_id(self):        root = self.tree({'Cotton/PhotoFace.swift': face('PhotoFace', 'photo'), 'Nancy/ChefFace.swift': face('ChefFace', 'kitchen.chef'), 'Shared/FaceParts.swift': 'struct HeavyType {}\n'})        found = gen.faces(root)        self.assertEqual(found, [('kitchen.chef', 'ChefFace', 'Nancy', 'Nancy/ChefFace.swift', 'framed', 'paper'), ('photo', 'PhotoFace', 'Cotton', 'Cotton/PhotoFace.swift', 'framed', 'paper')])        self.assertIn('        ChefFace.face,\n        PhotoFace.face,\n', gen.render_registry(found))        self.assertEqual(json.loads(gen.render_catalogue(found))[0], {'id': 'kitchen.chef', 'app': 'Nancy', 'file': 'Sources/CottonFaces/Nancy/ChefFace.swift'})    # RULE: A generic face registers in its catalogue entry, an enum beside it.    def test_a_catalogue_entry_registers(self):        text = ('struct PhotoFace<Photo: View>: View { var body: some View { EmptyView().onCardPaper(PhotoFaceCatalogue.stock.laid(nil)) } }\n\n'                'public enum PhotoFaceCatalogue {\n    public static let stock: FaceStock = .framed\n'                '    public static let ground: FaceGround = .paper\n'                '    public static let face = Face(id: "photo", specimens: []) { _, _, _ in EmptyView() }\n}\n')        self.assertEqual(gen.faces(self.tree({'Cotton/PhotoFace.swift': text})), [('photo', 'PhotoFaceCatalogue', 'Cotton', 'Cotton/PhotoFace.swift', 'framed', 'paper')])    # RULE: The registry keeps each face's stock by its id, as the face's file declares it.    def test_the_registry_keeps_each_faces_stock(self):        root = self.tree({'Cotton/TodoFace.swift': face('TodoFace', 'todo', 'pace'), 'Cotton/TicketFace.swift': face('TicketFace', 'ticket', 'own')})        registry = gen.render_registry(gen.faces(root))        self.assertIn('    private static let stocks: [String: FaceStock] = [\n        "ticket": .own,\n        "todo": .pace,\n    ]', registry)    # RULE: The registry keeps each face's ground by its id, as the face's file declares it.    def test_the_registry_keeps_each_faces_ground(self):        root = self.tree({'Cotton/CassetteFace.swift': face('CassetteFace', 'playlist.cassette', 'own', ground='felt'), 'Cotton/NoteFace.swift': face('NoteFace', 'note')})        registry = gen.render_registry(gen.faces(root))        self.assertIn('    private static let grounds: [String: FaceGround] = [\n        "note": .paper,\n        "playlist.cassette": .felt,\n    ]', registry)    # RULE: A face declares one ground beside it, of the grounds a face lies on.    def test_a_face_declares_its_ground(self):        for text, said in [(face('A', 'a', ground=None), 'declares 0 grounds'), (face('A', 'a', ground='granite'), 'declares ground .granite')]:            with self.assertRaises(SystemExit) as raised:                gen.faces(self.tree({'Cotton/A.swift': text}))            self.assertIn(said, str(raised.exception))    # RULE: A face declares one stock beside it, of the stocks a face is printed on.    def test_a_face_declares_its_stock(self):        bare = 'struct A: View {}\n\nextension A {\n    public static let ground: FaceGround = .paper\n    public static let face = Face(id: "a", specimens: []) { _, _, _ in A() }\n}\n'        for text, said in [(bare, 'declares 0 stocks'), (face('A', 'a', 'velvet'), 'declares stock .velvet')]:            with self.assertRaises(SystemExit) as raised:                gen.faces(self.tree({'Cotton/A.swift': text}))            self.assertIn(said, str(raised.exception))    # RULE: A face lays the stock it declares, and a face that draws its own sheet lays none.    def test_a_face_lays_the_stock_it_declares(self):        for text, said in [(face('A', 'a', 'framed', lays=False), 'nothing lays it'), (face('A', 'a', 'own', lays=True), 'declares stock .own but lays paper')]:            with self.assertRaises(SystemExit) as raised:                gen.faces(self.tree({'Cotton/A.swift': text}))            self.assertIn(said, str(raised.exception))    # RULE: One file per face — a file declaring two faces is refused.    def test_one_face_per_file(self):        root = self.tree({'Cotton/Two.swift': face('A', 'a') + face('B', 'b')})        with self.assertRaises(SystemExit) as raised:            gen.faces(root)        self.assertIn('one file per face', str(raised.exception))    # RULE: A face id is declared once across every app folder.    def test_an_id_is_declared_once(self):        root = self.tree({'Cotton/A.swift': face('A', 'photo'), 'Sharmila/B.swift': face('B', 'photo')})        with self.assertRaises(SystemExit) as raised:            gen.faces(root)        self.assertIn('declared twice', str(raised.exception))    # RULE: A face lives in an app folder (Cotton, Sharmila, Nancy, Rigby, Shared), never loose in the module.    def test_a_face_lives_in_an_app_folder(self):        root = self.tree({'Loose.swift': face('A', 'a')})        with self.assertRaises(SystemExit) as raised:            gen.faces(root)        self.assertIn('outside an app folder', str(raised.exception))    # RULE: A face named in a comment is not a face.    def test_a_comment_is_not_a_face(self):        root = self.tree({'Cotton/Doc.swift': '// static let face = Face(id: "ghost"\n/* static let face = Face(id: "ghost2" */\n'})        self.assertEqual(gen.faces(root), [])    # RULE: A face id is lowercase words of letters, digits and _, each a letter first, joined by . — a kit names it as data.    def test_a_face_id_is_lowercase_words(self):        root = self.tree({'Cotton/A.swift': face('A', 'Photo-Face')})        with self.assertRaises(SystemExit) as raised:            gen.faces(root)        self.assertIn('declares face id "Photo-Face"', str(raised.exception))    # RULE: A face that moves into Loom leaves faces-pending.json; the ids a kit may name are the moved and the pending together.    def test_a_moved_face_leaves_pending(self):        root = self.tree({'Cotton/PhotoFace.swift': face('PhotoFace', 'photo'), 'pending.json': '["todo", "photo"]'})        written = gen.outputs(root, root / 'pending.json')        self.assertEqual(json.loads(written[gen.PENDING]), ['todo'])        self.assertEqual(json.loads(written[gen.KNOWN]), ['photo', 'todo'])    # RULE: faces-pending.json holds face ids only.    def test_pending_holds_face_ids(self):        with self.assertRaises(SystemExit) as raised:            gen.pending([], ['todo', 'Not An Id'])        self.assertIn('Not An Id', str(raised.exception))if __name__ == '__main__':    unittest.main()