"""Focused tests for schema normalization and reference handling.""" from __future__ import annotations import importlib.util import os import tempfile import unittest from pathlib import Path from typing import Any import yaml SCRIPT_PATH = Path(__file__).with_name("merge-schemas.py") SPEC = importlib.util.spec_from_file_location("merge_schemas", SCRIPT_PATH) if SPEC is None or SPEC.loader is None: raise RuntimeError(f"cannot load schema merge script at {SCRIPT_PATH}") MERGE = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(MERGE) class MergeSchemasTest(unittest.TestCase): def setUp(self) -> None: self.temporary = tempfile.TemporaryDirectory() self.addCleanup(self.temporary.cleanup) # merge_contract returns resolved paths; resolve the temporary root too because it # may sit behind a symlink (for example /var -> /private/var on macOS). self.contract_root = Path(self.temporary.name).resolve() / "api" (self.contract_root / "components" / "schemas").mkdir(parents=True) (self.contract_root / "routes").mkdir() def write_yaml(self, relative_path: str, value: Any) -> Path: path = self.contract_root / relative_path path.parent.mkdir(parents=True, exist_ok=True) contents = yaml.safe_dump(value, sort_keys=False, allow_unicode=True) descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(descriptor, "w", encoding="utf-8") as stream: stream.write(contents) return path def read_yaml(self, relative_path: str) -> Any: with (self.contract_root / relative_path).open(encoding="utf-8") as stream: return yaml.safe_load(stream) def test_rewrites_nested_refs_and_preserves_nullable_type_arrays(self) -> None: self.write_yaml( "components/schemas/common_schemas.yml", { "schemas": { "entity.Status": {"type": "string"}, "response.Health": { "type": "object", "properties": { "status": {"$ref": "#/schemas/entity.Status"}, "metadata": { "anyOf": [ {"$ref": "#/schemas/entity.Status"}, {"type": ["string", "null"]}, ] }, }, }, } }, ) output = MERGE.merge_contract(self.contract_root) self.assertEqual(output, self.contract_root / "components" / "schemas.yml") document = self.read_yaml("components/schemas.yml") self.assertEqual(list(document), ["Status", "Health"]) self.assertEqual(document["Health"]["properties"]["status"]["$ref"], "#/Status") self.assertEqual( document["Health"]["properties"]["metadata"]["anyOf"][0]["$ref"], "#/Status", ) self.assertEqual( document["Health"]["properties"]["metadata"]["anyOf"][1]["type"], ["string", "null"], ) def test_rebases_cross_file_refs_and_keeps_nested_pointers(self) -> None: self.write_yaml( "components/schemas/common_schemas.yml", { "schemas": { "entity.Contact": { "type": "object", "properties": {"email": {"type": "string"}}, } } }, ) self.write_yaml( "components/schemas/profile_schemas.yml", { "schemas": { "response.Profile": { "type": "object", "properties": { "contact": { "anyOf": [ { "$ref": "./common_schemas.yml#/schemas/entity.Contact/properties/email" } ] } }, } } }, ) MERGE.merge_contract(self.contract_root) document = self.read_yaml("components/schemas.yml") self.assertEqual( document["Profile"]["properties"]["contact"]["anyOf"][0]["$ref"], "#/Contact/properties/email", ) def test_duplicate_normalized_names_fail_without_overwriting_output(self) -> None: self.write_yaml( "components/schemas/auth_schemas.yml", {"schemas": {"response.Health": {"type": "string"}}}, ) self.write_yaml( "components/schemas/common_schemas.yml", {"schemas": {"Health": {"type": "integer"}}}, ) output = self.contract_root / "components" / "schemas.yml" output.write_text("previous output\n", encoding="utf-8") with self.assertRaisesRegex(MERGE.MergeError, "duplicate normalized schema name") as error: MERGE.merge_contract(self.contract_root) self.assertIn("auth_schemas.yml", str(error.exception)) self.assertIn("common_schemas.yml", str(error.exception)) self.assertEqual(output.read_text(encoding="utf-8"), "previous output\n") def test_stale_nested_route_refs_fail_without_writing_output(self) -> None: self.write_yaml( "components/schemas/health_schemas.yml", {"schemas": {"Health": {"type": "object"}}}, ) route_path = self.contract_root / "routes" / "health.yml" route_path.write_text( "get:\n" " responses:\n" " '200':\n" " content:\n" " application/json:\n" " schema:\n" " anyOf:\n" ' - $ref: "../components/schemas.yml#/schemas/response.Health"\n', encoding="utf-8", ) with self.assertRaisesRegex(MERGE.MergeError, "stale schema references"): MERGE.merge_contract(self.contract_root) self.assertFalse((self.contract_root / "components" / "schemas.yml").exists()) def test_route_refs_to_split_schema_files_are_rejected(self) -> None: self.write_yaml( "components/schemas/health_schemas.yml", {"schemas": {"Health": {"type": "object"}}}, ) self.write_yaml( "routes/health.yml", {"get": {"responses": {"200": {"$ref": "../components/schemas/health_schemas.yml#/schemas/Health"}}}}, ) with self.assertRaisesRegex(MERGE.MergeError, "stale schema references"): MERGE.merge_contract(self.contract_root) self.assertFalse((self.contract_root / "components" / "schemas.yml").exists()) def test_contract_roots_are_independent(self) -> None: self.write_yaml( "components/schemas/health_schemas.yml", {"schemas": {"Health": {"type": "object"}}}, ) ml_root = self.contract_root / "ml" (ml_root / "components" / "schemas").mkdir(parents=True) self.write_yaml( "ml/components/schemas/health_schemas.yml", {"schemas": {"Health": {"type": "string"}}}, ) MERGE.merge_contract(self.contract_root) MERGE.merge_contract(ml_root) self.assertEqual(self.read_yaml("components/schemas.yml")["Health"]["type"], "object") self.assertEqual(self.read_yaml("ml/components/schemas.yml")["Health"]["type"], "string") if __name__ == "__main__": unittest.main()