"""Check the split match contract without requiring a generated API bundle.""" from __future__ import annotations import copy import json import subprocess import tempfile import unittest from pathlib import Path from typing import Any import yaml ROOT = Path(__file__).resolve().parents[1] CORE = ROOT / "api" / "core" API_ROOT = ROOT / "api" SCHEMA_PATH = CORE / "components" / "schemas" / "match_schemas.yml" ROUTE_PATH = CORE / "routes" / "matches.yml" EXAMPLES_PATH = CORE / "components" / "examples" / "matches.yml" REDOCLY_PATH = API_ROOT / "node_modules" / ".bin" / "redocly" FORBIDDEN_PROPERTIES = { "account_id", "answers", "candidate_name", "candidate_id", "candidate_internal_id", "contact", "contacts", "contact_email", "contact_phone", "email", "full_name", "fsp_hiding_reason", "fsp_reason", "fsp_suppression_reason", "fsp_visibility_reason", "hidden_fsp_reason", "hidden_reason", "min_salary", "phone", "phone_number", "profile_id", "raw_answer", "raw_answers", "salary", "salary_amount", "salary_minimum", "candidate_minimum", "salary_from", "salary_range", "salary_to", "source_text", "telegram", } FORBIDDEN_PROPERTY_FRAGMENTS = { "suppression_reason", "hidden_reason", "fsp_hidden", "fsp_suppress", } UNCONFIRMED_MEASUREMENTS = { "ability_estimate", "percentile", "p", "t", "test_percentile", "theta", } def load_yaml(path: Path) -> dict[str, Any]: with path.open(encoding="utf-8") as stream: value = yaml.safe_load(stream) if not isinstance(value, dict): raise TypeError(f"{path} must contain a YAML mapping") return value def load_contract() -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: schema_document = load_yaml(SCHEMA_PATH) route_document = load_yaml(ROUTE_PATH) examples_document = load_yaml(EXAMPLES_PATH) return ( schema_document.get("schemas", {}), route_document, examples_document, ) def resolve_local(schema: dict[str, Any], schemas: dict[str, Any]) -> dict[str, Any]: current = schema visited: set[str] = set() while "$ref" in current: reference = current["$ref"] if not reference.startswith("#/schemas/"): return current name = reference.rsplit("/", 1)[1] if name in visited: raise AssertionError(f"cyclic local schema reference: {name}") visited.add(name) current = schemas[name] return current def local_reference_name(schema: dict[str, Any]) -> str: reference = schema.get("$ref", "") if not reference.startswith("#/schemas/"): raise AssertionError(f"expected local schema reference, got {reference!r}") return reference.rsplit("/", 1)[1] def walk_schema( schema: dict[str, Any], schemas: dict[str, Any], seen: set[str] | None = None ): """Yield a local schema and its locally referenced child schemas.""" active = set() if seen is None else seen current = schema reference = current.get("$ref") if isinstance(reference, str) and reference.startswith("#/schemas/"): name = reference.rsplit("/", 1)[1] if name in active: return active.add(name) current = schemas[name] yield current for key in ("properties",): properties = current.get(key, {}) if isinstance(properties, dict): for child in properties.values(): if isinstance(child, dict): yield from walk_schema(child, schemas, active) items = current.get("items") if isinstance(items, dict): yield from walk_schema(items, schemas, active) for key in ("oneOf", "anyOf", "allOf"): branches = current.get(key, []) if isinstance(branches, list): for child in branches: if isinstance(child, dict): yield from walk_schema(child, schemas, active) def property_names(schema: dict[str, Any], schemas: dict[str, Any]) -> set[str]: names: set[str] = set() for node in walk_schema(schema, schemas): properties = node.get("properties", {}) if isinstance(properties, dict): names.update(properties) return names def example_value(examples: dict[str, Any], name: str) -> dict[str, Any]: example = examples[name] value = example.get("value") if not isinstance(value, dict): raise TypeError(f"example {name} must contain an object value") return value def card_properties(card: dict[str, Any], schemas: dict[str, Any]) -> set[str]: properties = property_names(card, schemas) return properties def assert_no_sensitive_keys(test: unittest.TestCase, value: Any) -> None: if isinstance(value, dict): for key, child in value.items(): test.assertNotIn(key, FORBIDDEN_PROPERTIES) test.assertFalse( any( fragment in key.lower() for fragment in FORBIDDEN_PROPERTY_FRAGMENTS ), key, ) assert_no_sensitive_keys(test, child) elif isinstance(value, list): for child in value: assert_no_sensitive_keys(test, child) def lint_match_examples( request_examples: dict[str, Any], response_examples: dict[str, Any] ) -> subprocess.CompletedProcess[str]: if not REDOCLY_PATH.is_file(): raise AssertionError(f"Redocly CLI is unavailable: {REDOCLY_PATH}") schema_path = Path("..") / "core" / "components" / "schemas" / "match_schemas.yml" with tempfile.TemporaryDirectory( prefix="match-contract-", dir=API_ROOT ) as directory: temporary = Path(directory) config_path = temporary / "redocly.yml" config_path.write_text( yaml.safe_dump( { "extends": [], "rules": {"no-invalid-media-type-examples": "error"}, }, sort_keys=False, ), encoding="utf-8", ) content: dict[str, Any] = {} if request_examples: content["requestBody"] = { "required": True, "content": { "application/json": { "schema": { "$ref": f"{schema_path.as_posix()}#/schemas/MatchSearchRequest" }, "examples": { name: {"value": value} for name, value in request_examples.items() }, } }, } content["responses"] = { "200": { "description": "Match results", "content": { "application/json": { "schema": { "$ref": f"{schema_path.as_posix()}#/schemas/MatchSearchResponse" }, "examples": { name: {"value": value} for name, value in response_examples.items() }, } }, } } document_path = temporary / "openapi.yml" document_path.write_text( yaml.safe_dump( { "openapi": "3.2.0", "info": {"title": "Match contract test", "version": "1.0.0"}, "paths": {"/matches": {"post": content}}, }, sort_keys=False, ), encoding="utf-8", ) return subprocess.run( [ str(REDOCLY_PATH), "lint", str(document_path), "--config", str(config_path), "--format", "json", ], cwd=API_ROOT, capture_output=True, check=False, text=True, timeout=30, ) class MatchContractTest(unittest.TestCase): @classmethod def setUpClass(cls) -> None: cls.schemas, cls.route, cls.examples = load_contract() def test_request_selects_need_requirements_version_or_bank_filters(self) -> None: request = self.schemas["MatchSearchRequest"] branches = {local_reference_name(branch) for branch in request["oneOf"]} self.assertEqual(branches, {"MatchSearchByNeed", "MatchSearchByBank"}) need = self.schemas["MatchSearchByNeed"] self.assertFalse(need["additionalProperties"]) self.assertEqual(set(need["required"]), {"need_id", "requirements_version"}) self.assertEqual(need["properties"]["need_id"]["format"], "uuid") self.assertEqual( need["properties"]["requirements_version"]["$ref"], "./need_schemas.yml#/schemas/NeedVersion", ) self.assertIn("Need.requirements_version", need["description"]) self.assertNotIn("version", need["properties"]) bank = self.schemas["MatchSearchByBank"] self.assertFalse(bank["additionalProperties"]) self.assertEqual(bank["required"], ["filters"]) filters = resolve_local(bank["properties"]["filters"], self.schemas) self.assertFalse(filters["additionalProperties"]) fields = filters["properties"] self.assertTrue( { "specialization", "confirmed_grade", "confirmed_category", "confirmation_status", "declared_grade", "stack", "conditions", }.issubset(fields) ) self.assertEqual( fields["confirmed_category"]["$ref"], "#/schemas/MatchGradeFilter" ) self.assertEqual( fields["confirmed_grade"]["$ref"], "./catalog_schemas.yml#/schemas/GradeCode", ) self.assertEqual( fields["declared_grade"]["$ref"], "./catalog_schemas.yml#/schemas/GradeCode", ) self.assertIn("separate", fields["declared_grade"]["description"]) self.assertNotIn("salary", fields) need_example = example_value(self.examples, "SearchByNeed") self.assertEqual( set(need_example), {"need_id", "requirements_version", "filters"} ) self.assertGreaterEqual(need_example["requirements_version"], 1) bank_example = example_value(self.examples, "SearchByBank") self.assertEqual(set(bank_example), {"filters"}) self.assertEqual( bank_example["filters"]["confirmed_category"], {"specialization": "backend", "grade": "middle"}, ) self.assertEqual(bank_example["filters"]["declared_grade"], "junior") conditions = resolve_local(fields["conditions"], self.schemas) self.assertEqual( set(conditions["properties"]), {"work_formats", "salary_compatibility"} ) self.assertFalse(conditions["additionalProperties"]) self.assertNotIn("salary_from", conditions["properties"]) self.assertNotIn("salary_minimum", conditions["properties"]) def test_every_local_object_schema_is_closed(self) -> None: for name, schema in self.schemas.items(): with self.subTest(schema=name): for node in walk_schema(schema, self.schemas): if node.get("type") == "object": self.assertIs(node.get("additionalProperties"), False) def test_unconfirmed_schema_keeps_nullable_category_and_strength(self) -> None: unconfirmed = self.schemas["MatchUnconfirmedCandidate"] properties = unconfirmed["properties"] self.assertFalse(unconfirmed["additionalProperties"]) self.assertTrue({"category", "strength"}.issubset(unconfirmed["required"])) self.assertEqual(properties["category"]["type"], "null") self.assertEqual(properties["strength"]["type"], "null") self.assertEqual(properties["confirmation_status"]["enum"], ["unconfirmed"]) components = resolve_local(properties["components"], self.schemas) self.assertEqual(set(components["properties"]), {"fit", "coverage"}) self.assertFalse( UNCONFIRMED_MEASUREMENTS.intersection(components["properties"]) ) self.assertFalse( UNCONFIRMED_MEASUREMENTS.intersection( property_names(unconfirmed, self.schemas) ) ) self.assertEqual( properties["candidate_handle"]["$ref"], "./common_schemas.yml#/schemas/CandidateHandle", ) confirmed_components = resolve_local( self.schemas["MatchConfirmedCandidate"]["properties"]["components"], self.schemas, ) self.assertEqual( set(confirmed_components["properties"]), { "fit", "coverage", "domain", "semantics", "percentile", "competition", "freshness", "responsiveness", "rank_score", }, ) for name, component in confirmed_components["properties"].items(): with self.subTest(component=name): resolved = resolve_local(component, self.schemas) if name == "percentile": self.assertIn("oneOf", resolved) self.assertIn({"type": "null"}, resolved["oneOf"]) else: self.assertEqual(resolved["type"], "number") def test_unknown_flags_are_bounded_and_explain_required_unknowns(self) -> None: reasons = set(self.schemas["MatchUnknownReason"]["enum"]) self.assertTrue( { "ml_unavailable", "cohort_below_30", "no_confirmation_for_specialization", "not_in_public_card", }.issubset(reasons) ) self.assertFalse(any("fsp" in reason.lower() for reason in reasons)) flags = self.schemas["MatchUnknownFlags"] self.assertEqual(flags["maxItems"], len(self.schemas["MatchUnknownComponent"]["enum"])) self.assertIn( "unknown_flags", self.schemas["MatchUnconfirmedCandidate"]["required"] ) def test_result_schema_exposes_only_anonymous_card_allowlist(self) -> None: for name in ("MatchConfirmedCandidate", "MatchUnconfirmedCandidate"): with self.subTest(schema=name): properties = property_names(self.schemas[name], self.schemas) self.assertFalse(FORBIDDEN_PROPERTIES.intersection(properties)) self.assertIn("candidate_handle", properties) self.assertNotIn("candidate_id", properties) self.assertNotIn("email", properties) self.assertNotIn("salary_minimum", properties) context = resolve_local( self.schemas["MatchConfirmedCandidate"]["properties"]["public_context"], self.schemas, ) self.assertEqual( set(context["properties"]), {"stack", "experience_band", "work_formats", "salary_compatibility"}, ) def test_route_declares_protected_no_store_operation_and_source_examples( self, ) -> None: self.assertEqual(self.route["post"]["operationId"], "SearchOrganizationMatches") self.assertEqual( self.route["post"]["security"], [{"sessionCookie": [], "sessionCsrf": []}], ) self.assertEqual( self.route["post"]["parameters"][0]["$ref"], "../components/parameters.yml#/OrganizationId", ) operation = self.route["post"] request_schema_ref = operation["requestBody"]["content"]["application/json"][ "schema" ]["$ref"] self.assertEqual( request_schema_ref, "../components/schemas.yml#/MatchSearchRequest" ) response = operation["responses"]["200"] self.assertEqual( response["headers"]["Cache-Control"]["$ref"], "../components/headers.yml#/CacheControlNoStore", ) self.assertEqual( response["content"]["application/json"]["schema"]["$ref"], "../components/schemas.yml#/MatchSearchResponse", ) example_names = set(self.examples) for collection in ( operation["requestBody"]["content"]["application/json"]["examples"], response["content"]["application/json"]["examples"], ): for example in collection.values(): reference = example["$ref"] self.assertTrue( reference.startswith("../components/examples/matches.yml#/") ) self.assertIn(reference.rsplit("/", 1)[1], example_names) def test_examples_cover_empty_three_groups_and_specialization_independence( self, ) -> None: three_groups = example_value(self.examples, "ThreeGroups") groups = three_groups["groups"] self.assertEqual(set(groups), {"main", "near", "unconfirmed"}) self.assertTrue(groups["main"]) self.assertTrue(groups["near"]) self.assertTrue(groups["unconfirmed"]) self.assertEqual( example_value(self.examples, "Empty")["groups"], {"main": [], "near": [], "unconfirmed": []}, ) backend = groups["main"][0] network = groups["unconfirmed"][0] for card in (*groups["main"], *groups["near"], *groups["unconfirmed"]): with self.subTest(handle=card["candidate_handle"]): self.assertRegex(card["candidate_handle"], r"^cv1_[A-Za-z0-9_-]{43}$") self.assertEqual(backend["specialization"], "backend") self.assertEqual(network["specialization"], "network_engineer") self.assertEqual(backend["confirmation_status"], "confirmed") self.assertEqual(network["confirmation_status"], "unconfirmed") self.assertEqual(backend["candidate_handle"], network["candidate_handle"]) self.assertEqual(backend["category"]["specialization"], "backend") self.assertIsNone(network["category"]) self.assertIsNone(network["strength"]) self.assertEqual( network["unknown_flags"][0]["reason"], "no_confirmation_for_specialization" ) for group_name in ("main", "near"): for card in groups[group_name]: with self.subTest( group=group_name, specialization=card["specialization"] ): self.assertEqual(card["confirmation_status"], "confirmed") self.assertEqual( card["category"]["specialization"], card["specialization"] ) self.assertIn(card["strength"], {"standard", "strong"}) def test_ml_and_small_cohort_examples_use_explicit_unknowns(self) -> None: ml_response = example_value(self.examples, "MLUnavailable") ml_card = ml_response["groups"]["main"][0] self.assertEqual(ml_card["components"]["semantics"], 0.5) self.assertIn( {"component": "semantics", "reason": "ml_unavailable"}, ml_card["unknown_flags"], ) cohort_response = example_value(self.examples, "CohortBelow30") cohort_card = cohort_response["groups"]["main"][0] self.assertIsNone(cohort_card["components"]["percentile"]) self.assertIn( {"component": "percentile", "reason": "cohort_below_30"}, cohort_card["unknown_flags"], ) self.assertNotIn("cohort_size", cohort_card) def test_bank_response_echoes_normalized_filter_snapshot(self) -> None: fields = set(self.schemas["MatchAppliedFilters"]["required"]) self.assertEqual(fields, set(self.schemas["MatchAppliedFilters"]["properties"])) for name in ("ThreeGroups", "Empty", "MLUnavailable", "CohortBelow30"): with self.subTest(example=name): source = example_value(self.examples, name)["source"] self.assertEqual(source["kind"], "bank") self.assertEqual(set(source["filters"]), fields) def test_examples_do_not_contain_private_keys(self) -> None: for name, example in self.examples.items(): with self.subTest(example=name): assert_no_sensitive_keys(self, example.get("value")) def test_source_examples_validate_against_local_and_external_schemas(self) -> None: request_names = ("SearchByNeed", "SearchByBank") request_examples = { name: example_value(self.examples, name) for name in request_names } response_names = tuple( name for name in self.examples if name not in request_names ) response_examples = { name: example_value(self.examples, name) for name in response_names } groups = example_value(self.examples, "ThreeGroups")["groups"] self.assertEqual(set(groups), {"main", "near", "unconfirmed"}) self.assertTrue(groups["main"]) self.assertTrue(groups["near"]) self.assertEqual( example_value(self.examples, "Empty")["groups"], {"main": [], "near": [], "unconfirmed": []}, ) result = lint_match_examples(request_examples, response_examples) self.assertEqual(result.returncode, 0, result.stdout or result.stderr) def test_schema_validation_rejects_private_card_fields(self) -> None: invalid_examples: dict[str, Any] = {} forbidden_values = { "email": "candidate@example.test", "candidate_internal_id": "candidate-123", "salary_minimum": 1000, } baseline = example_value(self.examples, "ThreeGroups") for field, value in forbidden_values.items(): response = copy.deepcopy(baseline) response["groups"]["main"][0][field] = value invalid_examples[field] = response result = lint_match_examples({}, invalid_examples) self.assertNotEqual(result.returncode, 0, result.stdout or result.stderr) try: problems = json.loads(result.stdout).get("problems", []) except json.JSONDecodeError as error: self.fail( f"Redocly did not return JSON diagnostics: {error}: {result.stdout}" ) messages = [problem.get("message", "") for problem in problems] self.assertTrue(messages, result.stdout or result.stderr) for field in forbidden_values: with self.subTest(field=field): self.assertTrue( any( problem.get("ruleId") == "no-invalid-media-type-examples" and field in problem.get("message", "") for problem in problems ), result.stdout or result.stderr, ) if __name__ == "__main__": unittest.main()