Files
lincodex/scripts/test_assessment_contract.py

590 lines
28 KiB
Python

"""Pin assessment mode, correction-chain, and read-side-effect contracts."""
from __future__ import annotations
import unittest
from pathlib import Path
from typing import Any
import yaml
API_DIR = Path(__file__).resolve().parents[1] / "api"
CORE_BUNDLE = API_DIR / "core" / "openapi.bundle.yml"
def load_bundle() -> dict[str, Any]:
with CORE_BUNDLE.open(encoding="utf-8") as stream:
document = yaml.safe_load(stream)
if not isinstance(document, dict):
raise AssertionError(f"{CORE_BUNDLE} is not an OpenAPI document")
return document
def resolve_schema(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("#/components/schemas/"):
raise AssertionError(f"unexpected bundled schema reference: {reference}")
name = reference.rsplit("/", 1)[1]
if name in visited:
raise AssertionError(f"cyclic schema reference: {name}")
visited.add(name)
current = schemas[name]
return current
def referenced_schema_name(schema: dict[str, Any]) -> str:
reference = schema.get("$ref", "")
if not reference.startswith("#/components/schemas/"):
raise AssertionError(f"expected a bundled schema reference, got {reference!r}")
return reference.rsplit("/", 1)[1]
def properties_across_all_of(
schema: dict[str, Any], schemas: dict[str, Any]
) -> dict[str, Any]:
resolved = resolve_schema(schema, schemas)
properties = dict(resolved.get("properties", {}))
for part in resolved.get("allOf", []):
properties.update(properties_across_all_of(part, schemas))
return properties
def union_enum_values(schema: dict[str, Any], schemas: dict[str, Any]) -> set[str]:
resolved = resolve_schema(schema, schemas)
values: set[str] = set()
for branch in resolved.get("oneOf", []):
branch_properties = properties_across_all_of(branch, schemas)
format_schema = branch_properties.get("format", {})
values.update(format_schema.get("enum", []))
return values
def required_across_all_of(schema: dict[str, Any], schemas: dict[str, Any]) -> set[str]:
resolved = resolve_schema(schema, schemas)
required = set(resolved.get("required", []))
for part in resolved.get("allOf", []):
required.update(required_across_all_of(part, schemas))
return required
def example_value(example: dict[str, Any], examples: dict[str, Any]) -> dict[str, Any]:
current = example
visited: set[str] = set()
while "$ref" in current:
reference = current["$ref"]
if not reference.startswith("#/components/examples/"):
raise AssertionError(f"unexpected bundled example reference: {reference}")
name = reference.rsplit("/", 1)[1]
if name in visited:
raise AssertionError(f"cyclic example reference: {name}")
visited.add(name)
current = examples[name]
value = current.get("value")
if not isinstance(value, dict):
raise AssertionError("assessment example must contain an object value")
return value
class AssessmentContractTest(unittest.TestCase):
def setUp(self) -> None:
self.document = load_bundle()
self.schemas = self.document["components"]["schemas"]
self.paths = self.document["paths"]
def test_create_has_disjoint_real_corrective_and_express_shapes(self) -> None:
self.assertEqual(
set(self.schemas["AssessmentMode"]["enum"]),
{"demo_basic", "demo_express", "adaptive"},
)
self.assertEqual(
set(self.schemas["AssessmentRealMode"]["enum"]),
{"demo_basic", "adaptive"},
)
create = resolve_schema(self.schemas["AssessmentAttemptCreate"], self.schemas)
self.assertEqual(len(create["oneOf"]), 3)
self.assertEqual(create["discriminator"]["propertyName"], "kind")
self.assertEqual(
set(create["discriminator"]["mapping"]),
{"root", "corrective", "demo_express"},
)
variants = {
referenced_schema_name(branch): resolve_schema(branch, self.schemas)
for branch in create["oneOf"]
}
self.assertIn("AssessmentQualifiedAttemptCreate", variants)
self.assertIn("AssessmentCorrectiveAttemptCreate", variants)
self.assertIn("AssessmentExpressAttemptCreate", variants)
real = variants["AssessmentQualifiedAttemptCreate"]
corrective = variants["AssessmentCorrectiveAttemptCreate"]
express = variants["AssessmentExpressAttemptCreate"]
self.assertFalse(real.get("additionalProperties", True))
self.assertNotIn("root_attempt_id", real.get("properties", {}))
self.assertEqual(real["properties"]["kind"]["enum"], ["root"])
self.assertFalse(corrective.get("additionalProperties", True))
self.assertIn("root_attempt_id", corrective["required"])
self.assertNotIn("chain_deadline", corrective.get("properties", {}))
self.assertEqual(corrective["properties"]["kind"]["enum"], ["corrective"])
self.assertEqual(express["required"], ["kind"])
self.assertEqual(express["properties"]["kind"]["enum"], ["demo_express"])
self.assertEqual(set(express["properties"]), {"kind"})
availability = resolve_schema(
self.schemas["AssessmentGradeAvailability"], self.schemas
)
mode = availability["properties"]["mode"]["oneOf"][0]
self.assertEqual(referenced_schema_name(mode), "AssessmentRealMode")
def test_attempt_and_result_one_of_keep_express_out_of_qualification(self) -> None:
attempt = resolve_schema(self.schemas["AssessmentAttempt"], self.schemas)
self.assertEqual(attempt["discriminator"]["propertyName"], "kind")
self.assertEqual(
set(attempt["discriminator"]["mapping"]),
{"root", "corrective", "demo_express"},
)
attempt_variants = {
referenced_schema_name(branch): branch for branch in attempt["oneOf"]
}
self.assertEqual(
set(attempt_variants),
{
"AssessmentQualifiedAttempt",
"AssessmentCorrectiveAttempt",
"AssessmentExpressAttempt",
},
)
corrective_properties = properties_across_all_of(
attempt_variants["AssessmentCorrectiveAttempt"], self.schemas
)
corrective_required = required_across_all_of(
attempt_variants["AssessmentCorrectiveAttempt"], self.schemas
)
self.assertTrue({"root_attempt_id", "chain_deadline"}.issubset(corrective_properties))
self.assertTrue({"root_attempt_id", "chain_deadline"}.issubset(corrective_required))
self.assertEqual(corrective_properties["chain_deadline"]["$ref"], "#/components/schemas/Timestamp")
qualified_attempt = resolve_schema(
attempt_variants["AssessmentQualifiedAttempt"], self.schemas
)
qualified_attempt_properties = properties_across_all_of(
attempt_variants["AssessmentQualifiedAttempt"], self.schemas
)
self.assertEqual(
set(qualified_attempt_properties["mode"]["enum"]),
{"demo_basic", "adaptive"},
)
self.assertEqual(qualified_attempt_properties["root_attempt_id"]["type"], "null")
self.assertEqual(qualified_attempt_properties["chain_deadline"]["type"], "null")
self.assertTrue(
{"root_attempt_id", "chain_deadline"}.issubset(
required_across_all_of(
attempt_variants["AssessmentQualifiedAttempt"], self.schemas
)
)
)
self.assertNotIn("not", qualified_attempt["allOf"][1])
express_attempt = properties_across_all_of(
attempt_variants["AssessmentExpressAttempt"], self.schemas
)
self.assertEqual(express_attempt["mode"]["enum"], ["demo_express"])
for name in ("specialization", "target_grade", "task_language", "root_attempt_id", "chain_deadline"):
self.assertEqual(express_attempt[name]["type"], "null", name)
result = resolve_schema(self.schemas["AssessmentResult"], self.schemas)
self.assertEqual(result["discriminator"]["propertyName"], "kind")
self.assertEqual(
set(result["discriminator"]["mapping"]),
{"root", "corrective", "demo_express"},
)
result_variants = {referenced_schema_name(branch): branch for branch in result["oneOf"]}
self.assertEqual(
set(result_variants),
{"AssessmentQualifiedResult", "AssessmentCorrectiveResult", "AssessmentExpressResult"},
)
qualified_properties = properties_across_all_of(
result_variants["AssessmentQualifiedResult"], self.schemas
)
self.assertEqual(
set(qualified_properties["mode"]["enum"]),
{"demo_basic", "adaptive"},
)
corrective_properties = properties_across_all_of(
result_variants["AssessmentCorrectiveResult"], self.schemas
)
for variant_name, variant, properties, expected_type in (
(
"qualified",
result_variants["AssessmentQualifiedResult"],
qualified_properties,
"null",
),
(
"corrective",
result_variants["AssessmentCorrectiveResult"],
corrective_properties,
"string",
),
):
required = required_across_all_of(variant, self.schemas)
self.assertTrue({"root_attempt_id", "chain_deadline"}.issubset(required), variant_name)
self.assertEqual(properties["root_attempt_id"]["type"], expected_type, variant_name)
if expected_type == "null":
self.assertEqual(properties["chain_deadline"]["type"], "null", variant_name)
else:
self.assertEqual(
properties["chain_deadline"]["$ref"],
"#/components/schemas/Timestamp",
variant_name,
)
express = resolve_schema(result_variants["AssessmentExpressResult"], self.schemas)
express_properties = express["properties"]
self.assertEqual(express_properties["mode"]["enum"], ["demo_express"])
for name in ("specialization", "target_grade", "confirmed_grade", "strength", "uncertainty", "basic_score"):
self.assertEqual(express_properties[name]["type"], "null", name)
self.assertEqual(express_properties["outcome"]["enum"], ["demonstration"])
self.assertEqual(express_properties["limitations"]["items"]["enum"], ["demonstration_only"])
self.assertIn("$ref", express_properties["practices"]["items"])
self.assertIn("$ref", express_properties["gaps"]["items"])
self.assertIn("$ref", express_properties["next_steps"]["items"])
self.assertFalse(express.get("additionalProperties", True))
self.assertNotIn("percentile", express_properties)
self.assertNotIn("score", express_properties)
self.assertIn("summary", express_properties)
def test_assessment_examples_match_discriminators_and_chain_pairs(self) -> None:
examples = self.document["components"]["examples"]
def operation_examples(path: str, method: str, location: tuple[str, ...]) -> list[dict[str, Any]]:
value: Any = self.paths[path][method]
for key in location:
value = value[key]
return [example_value(item, examples) for item in value.values()]
create_requests = operation_examples(
"/api/v1/me/assessment-attempts",
"post",
("requestBody", "content", "application/json", "examples"),
)
self.assertEqual({value["kind"] for value in create_requests}, {"root", "corrective", "demo_express"})
requests_by_kind = {value["kind"]: value for value in create_requests}
self.assertNotIn("root_attempt_id", requests_by_kind["root"])
self.assertIn("root_attempt_id", requests_by_kind["corrective"])
self.assertNotIn("chain_deadline", requests_by_kind["corrective"])
self.assertEqual(set(requests_by_kind["demo_express"]), {"kind"})
created_attempts = operation_examples(
"/api/v1/me/assessment-attempts",
"post",
("responses", "201", "content", "application/json", "examples"),
)
self.assertEqual({value["kind"] for value in created_attempts}, {"root", "corrective", "demo_express"})
for value in created_attempts:
if value["kind"] == "corrective":
self.assertIsNotNone(value["root_attempt_id"])
self.assertIsNotNone(value["chain_deadline"])
else:
self.assertIsNone(value["root_attempt_id"])
self.assertIsNone(value["chain_deadline"])
results = operation_examples(
"/api/v1/me/assessment-attempts/{attempt_id}/result",
"get",
("responses", "200", "content", "application/json", "examples"),
)
self.assertEqual({value["kind"] for value in results}, {"root", "corrective", "demo_express"})
for value in results:
if value["kind"] == "corrective":
self.assertIsNotNone(value["root_attempt_id"])
self.assertIsNotNone(value["chain_deadline"])
elif value["kind"] == "root":
self.assertIsNone(value["root_attempt_id"])
self.assertIsNone(value["chain_deadline"])
else:
self.assertNotIn("root_attempt_id", value)
self.assertNotIn("chain_deadline", value)
def test_session_start_is_explicit_versioned_and_idempotent(self) -> None:
operation = self.paths[
"/api/v1/me/assessment-attempts/{attempt_id}/sessions"
]["post"]
body = operation["requestBody"]["content"]["application/json"]["schema"]
session_start = resolve_schema(body, self.schemas)
self.assertEqual(session_start["required"], ["expected_version"])
self.assertIn(
"#/components/parameters/IdempotencyKey",
[parameter.get("$ref") for parameter in operation["parameters"]],
)
self.assertIn("412", operation["responses"])
self.assertIn("sessionCsrf", operation["security"][0])
def test_get_attempt_and_result_are_read_only_projections(self) -> None:
attempt = self.paths["/api/v1/me/assessment-attempts/{attempt_id}"]["get"]
result = self.paths[
"/api/v1/me/assessment-attempts/{attempt_id}/result"
]["get"]
for operation in (attempt, result):
self.assertNotIn("requestBody", operation)
self.assertIn("read-only", operation["description"].lower())
self.assertNotIn("sessionCsrf", operation["security"][0])
self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}"])
self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}/result"])
def test_attempt_items_and_answers_keep_the_public_formats(self) -> None:
expected = {
"choice",
"number",
"string",
"order",
"find_error",
"configuration",
"practice",
}
# A lab item is served like the others, but its lab is submitted only
# with SubmitMyAssessmentLab, so `lab` is not an answer format.
self.assertEqual(union_enum_values(self.schemas["ItemContent"], self.schemas), expected | {"lab"})
self.assertEqual(union_enum_values(self.schemas["AssessmentAnswer"], self.schemas), expected)
def test_candidate_schemas_do_not_name_secrets_or_employer_access(self) -> None:
forbidden = {"answer_key", "answer_keys", "seed", "hidden_seed", "hidden_checks"}
for name in ("AssessmentAttemptCommon", "AssessmentRealResultCommon", "AssessmentExpressResult"):
schema = self.schemas[name]
self.assertFalse(forbidden.intersection(schema.get("properties", {})), name)
attempt_description = self.paths[
"/api/v1/me/assessment-attempts/{attempt_id}"
]["get"]["description"].lower()
result_description = self.paths[
"/api/v1/me/assessment-attempts/{attempt_id}/result"
]["get"]["description"].lower()
self.assertIn("employer", attempt_description)
self.assertIn("employer", result_description)
self.assertIn("404", self.paths["/api/v1/me/assessment-attempts/{attempt_id}"]["get"]["responses"])
def test_practice_runs_never_name_hidden_checks_or_scores(self) -> None:
forbidden = {"hidden", "hidden_checks", "hidden_groups", "seed", "score", "verdict", "source_code"}
run_schemas = (
"PracticeRun",
"PracticeRunResult",
"PracticeRunTestResult",
)
for name in run_schemas:
schema = self.schemas[name]
self.assertFalse(forbidden.intersection(schema.get("properties", {})), name)
self.assertFalse(schema.get("additionalProperties", True), name)
create = self.paths["/api/v1/me/assessment-attempts/{attempt_id}/practice-runs"]["post"]
read = self.paths["/api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}"]["get"]
self.assertEqual(create["operationId"], "CreateMyAssessmentPracticeRun")
self.assertEqual(read["operationId"], "GetMyAssessmentPracticeRun")
for operation, status in ((create, "202"), (read, "200")):
response = operation["responses"][status]["content"]["application/json"]["schema"]
self.assertEqual(referenced_schema_name(response), "PracticeRun")
self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}"])
def test_signal_operation_is_bounded_private_and_separate_from_results(self) -> None:
operation = self.paths[
"/api/v1/me/assessment-attempts/{attempt_id}/signals"
]["post"]
self.assertEqual(operation["operationId"], "RecordMyAssessmentAttemptSignals")
self.assertIn("sessionCsrf", operation["security"][0])
self.assertIn("IdempotencyKey", [
parameter.get("$ref", "").rsplit("/", 1)[-1]
for parameter in operation["parameters"]
])
self.assertIn("413", operation["responses"])
self.assertIn("429", operation["responses"])
self.assertIn("32 KiB", operation["description"])
self.assertIn("10,000", operation["description"])
request_schema = resolve_schema(
operation["requestBody"]["content"]["application/json"]["schema"],
self.schemas,
)
self.assertFalse(request_schema.get("additionalProperties", True))
self.assertEqual(request_schema["required"], ["events"])
self.assertEqual(request_schema["properties"]["events"]["maxItems"], 50)
event_schema = resolve_schema(
request_schema["properties"]["events"]["items"], self.schemas
)
variants = [resolve_schema(branch, self.schemas) for branch in event_schema["oneOf"]]
self.assertEqual(
{tuple(sorted(variant["properties"])) for variant in variants},
{
("duration_ms", "item_instance_id", "kind", "occurred_at"),
("item_instance_id", "kind", "occurred_at", "size_bytes"),
("item_instance_id", "kind", "occurred_at"),
},
)
for variant in variants:
self.assertFalse(variant.get("additionalProperties", True))
receipt_schema = resolve_schema(
operation["responses"]["200"]["content"]["application/json"]["schema"],
self.schemas,
)
self.assertEqual(
set(receipt_schema["properties"]), {"status", "accepted_events", "received_at"}
)
self.assertTrue(
{"answer", "answer_text", "clipboard", "content", "score", "threshold"}.isdisjoint(
receipt_schema["properties"]
)
)
def schema_references(value: Any) -> set[str]:
if isinstance(value, dict):
references = set()
reference = value.get("$ref", "")
if reference.startswith("#/components/schemas/"):
references.add(reference.rsplit("/", 1)[-1])
for child in value.values():
references.update(schema_references(child))
return references
if isinstance(value, list):
references: set[str] = set()
for child in value:
references.update(schema_references(child))
return references
return set()
attempt_result_operations = (
self.paths["/api/v1/me/assessment-attempts/{attempt_id}"],
self.paths["/api/v1/me/assessment-attempts/{attempt_id}/result"],
)
for path_item in attempt_result_operations:
self.assertFalse(
any(name.startswith("AssessmentSignal") for name in schema_references(path_item)),
"attempt and result responses must remain independent of signal storage",
)
for path, path_item in self.paths.items():
if not path.startswith("/api/v1/organizations"):
continue
self.assertFalse(
any(name.startswith("AssessmentSignal") for name in schema_references(path_item)),
f"organization operation {path} must not reach assessment signal schemas",
)
def test_result_history_excludes_training_and_keeps_legacy_grade_unknown(self) -> None:
operation = self.paths["/api/v1/me/assessment-results"]["get"]
self.assertEqual(operation["operationId"], "ListMyAssessmentResults")
self.assertEqual(operation["security"], [{"sessionCookie": []}])
self.assertEqual({"200", "400", "401", "403"} - set(operation["responses"]), set())
limit = next(parameter for parameter in operation["parameters"] if parameter.get("name") == "limit")
self.assertEqual(limit["schema"]["maximum"], 50)
self.assertTrue(any(parameter.get("$ref", "").endswith("/PageCursor") for parameter in operation["parameters"]))
page = resolve_schema(self.schemas["AssessmentResultHistoryPage"], self.schemas)
self.assertEqual(set(page["required"]), {"items", "page"})
self.assertEqual(page["properties"]["items"]["maxItems"], 50)
real_results = resolve_schema(page["properties"]["items"]["items"], self.schemas)
self.assertEqual(set(real_results["discriminator"]["mapping"]), {"root", "corrective"})
self.assertEqual(len(real_results["oneOf"]), 2)
common = resolve_schema(self.schemas["AssessmentRealResultCommon"], self.schemas)
self.assertIn("category_decision", common["properties"])
self.assertNotIn("category_decision", common["required"])
express = resolve_schema(self.schemas["AssessmentExpressResult"], self.schemas)
self.assertNotIn("category_decision", express["properties"])
decision = resolve_schema(self.schemas["AssessmentCategoryDecisionView"], self.schemas)
self.assertEqual(
set(decision["properties"]),
{"status", "previous_confirmed_grade", "current_confirmed_grade", "method", "source", "calibration_status"},
)
self.assertFalse(decision.get("additionalProperties", True))
def test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data(self) -> None:
own = self.paths["/api/v1/me/evidence"]["get"]
organization = self.paths[
"/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence"
]["get"]
self.assertEqual(own["operationId"], "ListMyEvidence")
self.assertEqual(organization["operationId"], "GetOrganizationCandidateEvidence")
for operation in (own, organization):
self.assertEqual(operation["security"], [{"sessionCookie": []}])
self.assertEqual({"200", "400", "401", "403", "default"} - set(operation["responses"]), set())
self.assertIn("Cache-Control", operation["responses"]["200"]["headers"])
self.assertEqual({"404", "429"} - set(organization["responses"]), set())
self.assertTrue(any(parameter.get("$ref", "").endswith("/PageCursor") for parameter in own["parameters"]))
self.assertEqual(self.schemas["EvidenceKind"]["enum"], ["claim", "measurement"])
trust = self.schemas["EvidenceTrustLevel"]
self.assertEqual((trust["minimum"], trust["maximum"]), (0, 3))
for name in (
"EvidenceFact", "EvidenceSource", "EvidenceResult", "EvidenceFactList",
"OrganizationEvidenceFact", "OrganizationEvidence",
):
schema = self.schemas[name]
self.assertFalse(schema.get("additionalProperties", True), name)
self.assertEqual(set(schema["required"]), set(schema["properties"]), name)
# One event is one fact: the tags are a non-empty set inside the fact.
skills = self.schemas["EvidenceFact"]["properties"]["skills"]
self.assertTrue(skills["uniqueItems"])
self.assertEqual(skills["minItems"], 1)
# An organization reads the skill, grade, trust, year, and the basis and
# calibration of one fact for each category: no identifier, no source,
# no exact time.
self.assertEqual(
set(self.schemas["OrganizationEvidenceFact"]["properties"]),
{"skill", "grade", "trust", "basis", "calibration_status", "observed_year"},
)
self.assertEqual(self.schemas["OrganizationEvidence"]["properties"]["items"]["maxItems"], 9)
raw_properties = {
"answer", "answers", "answer_key", "reference_answer", "raw_score", "basic_score", "pass_points",
"scored_items", "uncertainty", "weak_domains", "practice_results", "signals", "events",
"item_instance_id", "seed", "variant", "hidden_checks", "category_decision", "band", "reasons",
"attempt_id",
}
def reachable(value: Any, found: set[str]) -> None:
if isinstance(value, dict):
reference = value.get("$ref", "")
if reference.startswith("#/components/schemas/"):
name = reference.rsplit("/", 1)[-1]
if name not in found:
found.add(name)
reachable(self.schemas[name], found)
for child in value.values():
reachable(child, found)
elif isinstance(value, list):
for child in value:
reachable(child, found)
def property_names(value: Any, found: set[str]) -> None:
if isinstance(value, dict):
for key, child in value.items():
if key == "properties" and isinstance(child, dict):
found.update(child)
property_names(child, found)
elif isinstance(value, list):
for child in value:
property_names(child, found)
walked = 0
for path, path_item in self.paths.items():
if not (path.startswith("/api/v1/organizations") or path == "/api/v1/me/evidence"):
continue
walked += 1
schemas: set[str] = set()
reachable(path_item, schemas)
names: set[str] = set()
property_names(path_item, names)
for schema_name in schemas:
property_names(self.schemas[schema_name], names)
self.assertFalse(
schema_name.startswith(("Assessment", "Practice", "ItemContent"))
or "Signal" in schema_name
or "Review" in schema_name,
f"{path} reaches the assessment schema {schema_name}",
)
self.assertEqual(raw_properties.intersection(names), set(), path)
if path == "/api/v1/me/evidence":
self.assertTrue({"EvidenceFact", "EvidenceResult"} <= schemas, "the walk must reach the evidence schemas")
self.assertGreaterEqual(walked, 10)
if __name__ == "__main__":
unittest.main()