Files
lincodex/scripts/test_merge_schemas.py

294 lines
12 KiB
Python

"""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_rewrites_only_schema_targets_in_discriminator_mappings(self) -> None:
self.write_yaml(
"components/schemas/common_schemas.yml",
{
"schemas": {
"entity.Contact": {"type": "object"},
"entity.Status": {"type": "string"},
}
},
)
profile_path = self.write_yaml(
"components/schemas/profile_schemas.yml",
{
"schemas": {
"response.Profile": {
"type": "object",
"discriminator": {
"propertyName": "kind",
"mapping": {
"profile": "#/schemas/response.Profile",
"status": "#/schemas/entity.Status",
"contact": "./common_schemas.yml#/schemas/entity.Contact",
"external": "https://schemas.example.test/external.yml#/schemas/External",
},
},
"mapping": {"example": "#/schemas/entity.Status"},
"example": {"mapping": {"example": "#/schemas/entity.Status"}},
}
}
},
)
source_schema = MERGE.load_yaml(profile_path)["schemas"]["response.Profile"]
references = MERGE.collect_references(source_schema)
self.assertIn(("#/schemas/response.Profile", "$.discriminator.mapping.profile"), references)
self.assertIn(
(
"./common_schemas.yml#/schemas/entity.Contact",
"$.discriminator.mapping.contact",
),
references,
)
self.assertNotIn(("#/schemas/entity.Status", "$.mapping.example"), references)
MERGE.merge_contract(self.contract_root)
profile = self.read_yaml("components/schemas.yml")["Profile"]
mapping = profile["discriminator"]["mapping"]
self.assertEqual(mapping["profile"], "#/Profile")
self.assertEqual(mapping["status"], "#/Status")
self.assertEqual(mapping["contact"], "#/Contact")
self.assertEqual(
mapping["external"],
"https://schemas.example.test/external.yml#/schemas/External",
)
self.assertEqual(profile["mapping"]["example"], "#/schemas/entity.Status")
self.assertEqual(
profile["example"]["mapping"]["example"], "#/schemas/entity.Status"
)
def test_stale_discriminator_mapping_route_refs_are_rejected(self) -> None:
self.write_yaml(
"components/schemas/health_schemas.yml",
{"schemas": {"response.Health": {"type": "object"}}},
)
self.write_yaml(
"routes/health.yml",
{
"get": {
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"oneOf": [],
"discriminator": {
"propertyName": "kind",
"mapping": {
"health": "../components/schemas.yml#/schemas/response.Health"
},
},
}
}
}
}
}
}
},
)
with self.assertRaisesRegex(MERGE.MergeError, "stale schema references") as error:
MERGE.merge_contract(self.contract_root)
self.assertIn("discriminator.mapping.health", str(error.exception))
self.assertFalse((self.contract_root / "components" / "schemas.yml").exists())
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()