Cotton code
114 lines · 6.1 KB · PythonRaw
#!/usr/bin/env python3"""Synthetic source tests for generation semantics and the duplicate guard."""import importlib.utilimport jsonimport refrom pathlib import Pathimport tempfileimport unittestspec = importlib.util.spec_from_file_location('generator', Path(__file__).with_name('gen-swift-definition-types.py'))gen = importlib.util.module_from_spec(spec)spec.loader.exec_module(gen)def copy_sources(root):    # Every Rust file a model or an enum is read from, cotton-store's included.    for name in {*gen.MODELS.values(), *gen.ENUMS.values(), *gen.VALUES_ENUMS.values(), *gen.UNTAGGED.values(), *gen.TAGGED.values()}:        target = gen.rust_file(root, name)        target.parent.mkdir(parents=True, exist_ok=True)        target.write_text(gen.rust_file(gen.ROOT, name).read_text())class DefinitionGenerationTests(unittest.TestCase):    def test_type_change_alters_output_without_definition_files(self):        # RULE: Only Rust types are generator inputs; product definition bytes must never enter generated code.        with tempfile.TemporaryDirectory() as directory:            root = Path(directory)            target = root / 'crates/cotton-core/src/definitions'            copy_sources(root)            before = gen.generate(root, look=True)            theme = target / 'theme.rs'            theme.write_text(theme.read_text().replace('pub grain: Option<bool>', 'pub grain: Option<String>'))            after = gen.generate(root, look=True)            self.assertNotEqual(before, after)            self.assertIn('public var grain: String?', after)    def test_a_rust_field_added_without_regeneration_is_named(self):        # RULE: A Rust definition field added without regenerating fails the check naming Model.field, so the fix is obvious and the app never lags the core.        with tempfile.TemporaryDirectory() as directory:            root = Path(directory)            target = root / 'crates/cotton-core/src/definitions'            copy_sources(root)            held = gen.generate(root, look=True)            theme = target / 'theme.rs'            theme.write_text(theme.read_text().replace('pub grain: Option<bool>,', 'pub grain: Option<bool>,\n    pub weave: Option<String>,', 1))            self.assertIn('ThemeTexture.weave added in Rust', gen.drift(held, gen.generate(root, look=True)))    def test_serde_rename_and_flatten_are_wire_keys(self):        source = '''pub struct Test {            #[serde(rename = "wire_word")]            pub native_word: Option<String>,            #[serde(flatten, default)]            pub unknown: Map<String, Value>,        }'''        fields = gen.fields(source, 'Test')        self.assertEqual(fields[0]['key'], 'wire_word')        self.assertIn('flatten', fields[1]['attr'])        self.assertEqual(gen.swift_type('Option<Vec<String>>', 'Test'), '[String]?')    def test_storage_is_plain_structs_over_bound_types(self):        # RULE: Generated definition storage is never generic: a 57-parameter generic made the Swift runtime check every parameter's conformances at first use, 90-130 ms of each cold start.        source = gen.generate() + gen.generate(look=True)        self.assertNotRegex(source, r'public struct Definition\w+<')        with self.assertRaisesRegex(ValueError, 'BINDINGS does not name'):            gen.swift_type('UnboundLayout', 'TableDefinition')    def test_the_card_kinds_a_face_reads_are_generated_into_the_plain_values(self):        # RULE: The card enums a face is drawn by are generated into CottonValues alone, importing Foundation only, so a face builds with no core and the kinds have one generated home.        values = gen.generate(values=True)        self.assertEqual(re.findall(r'^import (\w+)', values, re.M), ['Foundation'])        for model in gen.VALUES_ENUMS:            self.assertIn(f'public enum Definition{model}: String', values)            self.assertNotIn(f'enum Definition{model}:', gen.generate())            self.assertNotIn(model, gen.ENUMS)        self.assertIn('DefinitionCardKind', gen.generate())    def test_a_face_id_is_open(self):        # RULE: A card's face is an open id (Loom step 5): the Swift type is string-backed, reads any well-formed id, and names every face the core knows (face_ids.json), so no closed enum decides what a face is.        values = gen.generate(values=True)        self.assertIn('public struct DefinitionCardKind: RawRepresentable, Codable, Hashable, Sendable {', values)        self.assertNotIn('enum DefinitionCardKind', values)        for face in json.loads(gen.FACE_IDS.read_text()):            self.assertIn(f'("{face}")', values)    def test_by_value_faces_round_trip_in_the_definition_reader(self):        swift = gen.generate()        self.assertIn('public var faces: [DefinitionFaceByValue] = []', swift)        self.assertIn('faces = try c.decodeIfPresent([DefinitionFaceByValue].self, forKey: .faces) ?? []', swift)        self.assertIn('if !faces.isEmpty { try c.encode(faces, forKey: .faces) }', swift)        self.assertIn('public var `when`: DefinitionValueMatch', swift)    def test_unsupported_custom_serialization_is_refused(self):        with self.assertRaisesRegex(ValueError, 'unsupported serde'):            gen.fields('pub struct Test { #[serde(serialize_with = "other")] pub value: String, }', 'Test')    def test_renaming_a_handwritten_twin_does_not_evade_scan(self):        # RULE: A handwritten twin is forbidden by shape, regardless of its Swift name, because another name still leaves two truths.        with tempfile.TemporaryDirectory() as directory:            root = Path(directory)            target = root / 'crates/cotton-core/src/definitions'            copy_sources(root)            source = root / 'apps/cotton/Sources'            source.mkdir(parents=True)            (source / 'Twin.swift').write_text('''struct RenamedTwin: Codable {                var grain: Bool?                var shadow: String?                var tilt: Bool?                var unknown: [String: Value]            }''')            with self.assertRaisesRegex(ValueError, 'repeats ThemeTexture'):                gen.scan(root)if __name__ == '__main__': unittest.main()