From 1507aa707ef1cfb46ae574421cc0d4d2e2eefda8 Mon Sep 17 00:00:00 2001 From: Yevhen Vasko Date: Tue, 17 Nov 2026 08:47:24 -0600 Subject: [PATCH 01/10] fix(mock): match {param} path templates and resolve nested $ref/anyOf/oneOf/allOf/const - MockServer matches requests against templated spec paths after literal paths; the most specific template wins; trailing slash and query handling kept. - generate_instance resolves local $ref at any depth (schemas and responses), handles anyOf/oneOf (non-null preferred), allOf (merged), const and 3.1 type lists, with a cycle/depth guard. - load_routes/parse_openapi keep the {spec_path: {METHOD: body}} shape. Implementation authored by the Factory Coder lane (codex gpt-6.1-sol). FactoryRun: baton-mock-templates-20261117 Built-By: Factory v0.8.29 --- src/baton/mock.py | 161 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 142 insertions(+), 19 deletions(-) diff --git a/src/baton/mock.py b/src/baton/mock.py index 2458187..b237342 100644 --- a/src/baton/mock.py +++ b/src/baton/mock.py @@ -11,6 +11,7 @@ import json import logging import random +import re import string import time from pathlib import Path @@ -24,8 +25,87 @@ logger = logging.getLogger(__name__) -def generate_instance(schema: dict) -> Any: +_unresolved_refs: set[str] = set() + + +def _resolve_ref(value: dict, components: dict, seen: frozenset[str] = frozenset()) -> dict: + """Follow local component references, including response aliases.""" + ref = value.get("$ref") + if not ref: + return value + if ref in seen: + return {} + target: Any = {"components": components} + if isinstance(ref, str) and ref.startswith("#/components/"): + for part in ref[2:].split("/"): + part = part.replace("~1", "/").replace("~0", "~") + target = target.get(part) if isinstance(target, dict) else None + else: + target = None + if not isinstance(target, dict): + if ref not in _unresolved_refs: + logger.debug("Unresolved mock reference: %s", ref) + _unresolved_refs.add(ref) + target = {} + resolved = _resolve_ref(target, components, seen | {ref}) + return {**resolved, **{key: val for key, val in value.items() if key != "$ref"}} + + +def _merge_schema(left: dict, right: dict) -> dict: + """Combine object properties and requirements for an allOf intersection.""" + merged = {**left, **right} + if "properties" in left or "properties" in right: + props = dict(left.get("properties", {})) + for name, prop in right.get("properties", {}).items(): + props[name] = {"allOf": [props[name], prop]} if name in props else prop + merged["properties"] = props + if "required" in left or "required" in right: + merged["required"] = list( + dict.fromkeys(left.get("required", []) + right.get("required", [])) + ) + for key in ("minimum", "minLength", "minItems", "minProperties"): + if key in left and key in right: + merged[key] = max(left[key], right[key]) + for key in ("maximum", "maxLength", "maxItems", "maxProperties"): + if key in left and key in right: + merged[key] = min(left[key], right[key]) + return merged + + +def _expand_schema( + schema: dict, components: dict, depth: int = 0, + seen: frozenset[str] = frozenset(), +) -> dict: + ref = schema.get("$ref") + if depth >= 32 or ref in seen: + return {} + schema = _resolve_ref(schema, components, seen) + if ref: + seen = seen | {ref} + if "allOf" in schema: + merged = {} + for part in schema["allOf"]: + merged = _merge_schema(merged, _expand_schema(part, components, depth + 1, seen)) + schema = _merge_schema(merged, {k: v for k, v in schema.items() if k != "allOf"}) + return schema + + +def generate_instance( + schema: dict, components: dict | None = None, *, + _depth: int = 0, _seen: frozenset[str] = frozenset(), +) -> Any: """Generate a random valid instance from a JSON Schema.""" + components = components or {} + if _depth >= 32 or schema.get("$ref") in _seen: + return {} + # Preserve explicit values before following references or compositions. + for key in ("example", "default", "enum", "const"): + if key in schema: + return schema[key][0] if key == "enum" else schema[key] + ref = schema.get("$ref") + schema = _expand_schema(schema, components, seen=_seen) + if ref: + _seen = _seen | {ref} if "example" in schema: return schema["example"] if "default" in schema: @@ -33,7 +113,27 @@ def generate_instance(schema: dict) -> Any: if "enum" in schema: return schema["enum"][0] + if "const" in schema: + return schema["const"] + + def generate(child: dict) -> Any: + return generate_instance(child, components, _depth=_depth + 1, _seen=_seen) + + for keyword in ("anyOf", "oneOf"): + if keyword in schema: + base = {k: v for k, v in schema.items() if k != keyword} + branches = [_merge_schema(base, branch) for branch in schema[keyword]] + # A reference may itself describe a null branch. Try all non-null + # results before accepting null, keeping declaration order otherwise. + for branch in branches: + value = generate(branch) + if value is not None: + return value + return None + schema_type = schema.get("type", "object") + if isinstance(schema_type, list): + schema_type = next((kind for kind in schema_type if kind != "null"), "null") if schema_type == "string": fmt = schema.get("format", "") @@ -62,7 +162,7 @@ def generate_instance(schema: dict) -> Any: if schema_type == "array": items = schema.get("items", {"type": "string"}) count = schema.get("minItems", 1) - return [generate_instance(items) for _ in range(count)] + return [generate(items) for _ in range(count)] if schema_type == "object": props = schema.get("properties", {}) @@ -70,7 +170,11 @@ def generate_instance(schema: dict) -> Any: obj = {} for name, prop_schema in props.items(): if name in required: - obj[name] = generate_instance(prop_schema) + obj[name] = generate(prop_schema) + additional = schema.get("additionalProperties") + if not props and isinstance(additional, dict): + for index in range(max(1, schema.get("minProperties", 0))): + obj[f"key{index + 1}"] = generate(additional) return obj return None @@ -91,7 +195,7 @@ def parse_openapi(spec_path: str) -> dict[str, dict[str, Any]]: if not spec or "paths" not in spec: return {} - components = spec.get("components", {}).get("schemas", {}) + components = spec.get("components", {}) routes: dict[str, dict[str, Any]] = {} for path_str, methods in spec["paths"].items(): @@ -104,22 +208,18 @@ def parse_openapi(spec_path: str) -> dict[str, dict[str, Any]]: # Find the success response responses = operation.get("responses", {}) success_resp = responses.get("200") or responses.get("201") or {} + success_resp = _resolve_ref(success_resp, components) content = success_resp.get("content", {}) json_content = content.get("application/json", {}) resp_schema = json_content.get("schema", {}) - # Resolve $ref - if "$ref" in resp_schema: - ref_name = resp_schema["$ref"].split("/")[-1] - resp_schema = components.get(ref_name, {}) - # Generate response body if "example" in json_content: body = json_content["example"] elif "example" in resp_schema: body = resp_schema["example"] elif resp_schema: - body = generate_instance(resp_schema) + body = generate_instance(resp_schema, components) else: body = {} @@ -174,6 +274,7 @@ def __init__( node_name: str = "", ): self._route_tables: dict[int, dict[str, dict[str, Any]]] = {} + self._templates: dict[int, list[tuple[re.Pattern, dict[str, Any]]]] = {} self._servers: list[asyncio.Server] = [] self._span_exporter = span_exporter self._node_name = node_name @@ -182,13 +283,31 @@ def __init__( def add_routes(self, port: int, routes: dict[str, dict[str, Any]]) -> None: """Register routes for a port.""" self._route_tables[port] = routes + templates = [] + for path, methods in routes.items(): + segments = path.split("/") + parameters = [ + bool(re.fullmatch(r"\{[^{} /]+\}", segment)) for segment in segments + ] + if any(parameters): + pattern = "/".join( + "[^/]+" if parameter else re.escape(segment) + for segment, parameter in zip(segments, parameters) + ) + specificity = sum( + bool(segment) and not parameter + for segment, parameter in zip(segments, parameters) + ) + templates.append((specificity, re.compile(pattern), methods)) + templates.sort(key=lambda entry: entry[0], reverse=True) + self._templates[port] = [(pattern, methods) for _, pattern, methods in templates] def add_default_routes(self, port: int) -> None: """Add a default health endpoint for a port with no contract.""" - self._route_tables[port] = { + self.add_routes(port, { "/": {"GET": {"status": "mock", "port": port}}, "/health": {"GET": {"status": "ok"}}, - } + }) async def start(self, host: str = "127.0.0.1") -> None: """Start HTTP servers for all registered ports.""" @@ -250,15 +369,19 @@ async def _handle( path = path.split("?")[0] routes = self._route_tables.get(port, {}) - route = routes.get(path, {}) + alt_path = path.rstrip("/") if path != "/" else path + if path in routes: + route = routes[path] + elif alt_path in routes: + route = routes[alt_path] + else: + route = {} + for pattern, methods in self._templates.get(port, []): + if pattern.fullmatch(path) or pattern.fullmatch(alt_path): + route = methods + break body = route.get(method) - if body is None: - # Try without trailing slash - alt_path = path.rstrip("/") if path != "/" else path - route = routes.get(alt_path, {}) - body = route.get(method) - status_code = 200 if body is None: status_code = 404 From 7e6f25429b26b3c45068f3fa5268f62a834b7d7b Mon Sep 17 00:00:00 2001 From: Yevhen Vasko Date: Tue, 17 Nov 2026 08:47:24 -0600 Subject: [PATCH 02/10] test(mock): acceptance tests for path templates and schema composition Covers R1-R11: templated paths, literal/specificity precedence, 404 cases, nested and response $ref, recursion bounds, anyOf/oneOf/allOf/const, and unchanged example/default/enum precedence. Existing tests unchanged. Tests authored independently by the Factory Tester lane (cursor-agent grok-4.7-high). FactoryRun: baton-mock-templates-20261117 Built-By: Factory v0.8.29 --- tests/test_mock.py | 700 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 700 insertions(+) diff --git a/tests/test_mock.py b/tests/test_mock.py index 815985f..ac90aad 100644 --- a/tests/test_mock.py +++ b/tests/test_mock.py @@ -4,6 +4,10 @@ import asyncio import json +import socket +import subprocess +import sys +from contextlib import asynccontextmanager from pathlib import Path import pytest @@ -463,3 +467,699 @@ async def test_mock_no_spans_without_exporter(self): assert len(spans) == 0 finally: await server.stop() + + +# Acceptance coverage for path templates and schema composition. +# Oracles are the lane brief and JSON Schema / OpenAPI semantics. +# Authority is normative unless a docstring says the legacy suite is the source. + + +def _free_port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def _is_json_int(value: object) -> bool: + """JSON integers are not booleans. True is an int subclass in Python.""" + return isinstance(value, int) and not isinstance(value, bool) + + +def _openapi( + paths: dict, + schemas: dict | None = None, + responses: dict | None = None, +) -> dict: + document = { + "openapi": "3.0.3", + "info": {"title": "mock-contract", "version": "1"}, + "paths": paths, + } + components = {} + if schemas is not None: + components["schemas"] = schemas + if responses is not None: + components["responses"] = responses + if components: + document["components"] = components + return document + + +def _ok(schema: dict | None = None, example: object | None = None) -> dict: + media: dict = {} + if schema is not None: + media["schema"] = schema + if example is not None: + media["example"] = example + return { + "200": { + "description": "ok", + "content": {"application/json": media}, + } + } + + +def _search_excerpt() -> dict: + """Minimal stand-in for the current search path and a pricing-shaped hit. + + items is a schema ref to an object whose required rate_cents is an Int + ref. additionalProperties is an Int ref so a resolver that rejects that + keyword fails the load. The contract does not require an extra key. + """ + return _openapi( + { + "/collections/{collectionId}/search": { + "post": { + "responses": _ok({ + "type": "object", + "required": ["hits"], + "properties": { + "hits": { + "type": "array", + "items": {"$ref": "#/components/schemas/Hit"}, + } + }, + }) + } + } + }, + schemas={ + "Int": {"type": "integer"}, + "Hit": { + "type": "object", + "required": ["id", "rate_cents"], + "properties": { + "id": {"type": "string"}, + "rate_cents": {"$ref": "#/components/schemas/Int"}, + }, + "additionalProperties": {"$ref": "#/components/schemas/Int"}, + }, + }, + ) + + +def _write_spec(tmp_path: Path, document: dict, name: str = "spec.json") -> str: + path = tmp_path / name + path.write_text(json.dumps(document), encoding="utf-8") + return str(path) + + +def _load_bounded(spec_path: str, seconds: float = 5.0) -> dict: + """Run load_routes in a child so a recursive schema cannot hang this process. + + The 5 second ceiling is the test's reading of "bounded time": a tiny schema + that does not finish is not bounded. The contract states no byte limit. + """ + script = ( + "import json, sys\n" + "from baton.mock import load_routes\n" + "json.dump(load_routes(sys.argv[1]), sys.stdout)\n" + ) + try: + completed = subprocess.run( + [sys.executable, "-c", script, spec_path], + capture_output=True, + text=True, + timeout=seconds, + check=False, + ) + except subprocess.TimeoutExpired as exc: + raise AssertionError(f"load_routes did not finish within {seconds}s") from exc + assert completed.returncode == 0, completed.stderr[-2000:] + return json.loads(completed.stdout) + + +def _decode_chunked(body: bytes) -> bytes: + chunks = [] + rest = body + while rest: + line, sep, rest = rest.partition(b"\r\n") + if not sep: + break + size_token = line.split(b";", 1)[0].strip() + if not size_token: + break + size = int(size_token, 16) + if size == 0: + break + chunks.append(rest[:size]) + rest = rest[size:] + if rest.startswith(b"\r\n"): + rest = rest[2:] + return b"".join(chunks) + + +def _parse_response(raw: bytes) -> tuple[int, bytes]: + head, _, body = raw.partition(b"\r\n\r\n") + lines = head.decode("iso-8859-1").split("\r\n") + status = int(lines[0].split()[1]) + headers = {} + for line in lines[1:]: + if ":" not in line: + continue + name, value = line.split(":", 1) + headers[name.lower()] = value.strip().lower() + if headers.get("transfer-encoding") == "chunked": + body = _decode_chunked(body) + elif "content-length" in headers: + body = body[: int(headers["content-length"])] + return status, body + + +async def _exchange(port: int, method: str, target: str) -> tuple[int, object]: + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + message = ( + f"{method} {target} HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + ) + if method in {"POST", "PUT", "PATCH"}: + message += "Content-Length: 0\r\n" + writer.write(f"{message}\r\n".encode()) + await writer.drain() + chunks = [] + while True: + chunk = await asyncio.wait_for(reader.read(4096), timeout=5.0) + if not chunk: + break + chunks.append(chunk) + finally: + writer.close() + await writer.wait_closed() + status, body = _parse_response(b"".join(chunks)) + return status, json.loads(body) + + +@asynccontextmanager +async def _running(routes: dict): + server = MockServer() + port = _free_port() + server.add_routes(port, routes) + await server.start() + try: + yield port + finally: + await server.stop() + + +class TestPathTemplates: + """R1–R4. The registered body is the oracle: the request must return the + body of the route the brief says wins, or the stated 404 object. + """ + + async def test_placeholder_matches_one_segment(self): + """R1. GET /invoices/123 and /invoices/456 both return the /invoices/{id} body. + + Falsifier: the template is ignored, or only a hard-coded id matches. + """ + routes = {"/invoices/{id}": {"GET": {"resource": "invoice"}}} + async with _running(routes) as port: + for target in ("/invoices/123", "/invoices/456"): + status, body = await _exchange(port, "GET", target) + assert status == 200 + assert body == {"resource": "invoice"} + + async def test_multiple_placeholders_each_match_one_segment(self): + """R1. Each {param} is one non-empty segment. A missing segment does not match. + + Falsifier: one placeholder consumes several segments, or the last + placeholder is optional. + """ + routes = {"/orgs/{org}/invoices/{id}": {"GET": {"resource": "invoice"}}} + async with _running(routes) as port: + status, body = await _exchange(port, "GET", "/orgs/acme/invoices/9") + assert status == 200 + assert body == {"resource": "invoice"} + status, body = await _exchange(port, "GET", "/orgs/acme/invoices") + assert status == 404 + assert body == {"error": "not found", "path": "/orgs/acme/invoices"} + + async def test_trailing_slash_still_matches_template(self): + """R1. A trailing slash is tolerated and does not become an extra segment. + + Falsifier: /invoices/123/ is rejected or routed as a different path. + """ + routes = {"/invoices/{id}": {"GET": {"resource": "invoice"}}} + async with _running(routes) as port: + status, body = await _exchange(port, "GET", "/invoices/123/") + assert status == 200 + assert body == {"resource": "invoice"} + + async def test_query_string_ignored_for_template(self): + """R1. The query string is not part of template matching. + + Falsifier: /invoices/123?page=1 misses /invoices/{id}. + """ + routes = {"/invoices/{id}": {"GET": {"resource": "invoice"}}} + async with _running(routes) as port: + status, body = await _exchange(port, "GET", "/invoices/123?page=1&sort=asc") + assert status == 200 + assert body == {"resource": "invoice"} + + async def test_literal_path_beats_template(self): + """R2. /collections/wander/search wins over /collections/{collectionId}/search. + + The template is registered first, so first-match-wins fails this test. + A different collection id still uses the template. The wrong method + stays a 404 (R4). + + Falsifier: wander receives the template body, or every collection id + receives the literal body. + """ + routes = { + "/collections/{collectionId}/search": {"POST": {"matched": "template"}}, + "/collections/wander/search": {"POST": {"matched": "literal"}}, + } + async with _running(routes) as port: + status, body = await _exchange(port, "POST", "/collections/wander/search") + assert status == 200 + assert body == {"matched": "literal"} + status, body = await _exchange(port, "POST", "/collections/other/search") + assert status == 200 + assert body == {"matched": "template"} + status, body = await _exchange(port, "GET", "/collections/wander/search") + assert status == 404 + assert body == {"error": "not found", "path": "/collections/wander/search"} + + async def test_more_specific_template_wins(self): + """R3. GET /a/1/b returns the body of /a/{x}/b, not /a/{x}/{y}. + + The less specific template is registered first. /a/1/c does not fit + the literal segment, so it uses /a/{x}/{y}. + + Falsifier: the two templates are tied by length, or a non-matching + literal segment still captures the request. + """ + routes = { + "/a/{x}/{y}": {"GET": {"matched": "two-params"}}, + "/a/{x}/b": {"GET": {"matched": "literal-b"}}, + } + async with _running(routes) as port: + status, body = await _exchange(port, "GET", "/a/1/b") + assert status == 200 + assert body == {"matched": "literal-b"} + status, body = await _exchange(port, "GET", "/a/1/c") + assert status == 200 + assert body == {"matched": "two-params"} + + @pytest.mark.parametrize( + ("method", "target"), + [ + ("GET", "/invoices/123/extra"), + ("GET", "/invoices"), + ("GET", "/invoices//part"), + ("POST", "/invoices/123"), + ("GET", "/missing"), + ], + ) + async def test_non_match_is_json_404(self, method: str, target: str): + """R4. Extra, missing, or empty segments, and the wrong method, are 404. + + The body is exactly {"error": "not found", "path": }. + These targets have no trailing-slash ambiguity, so the request path + is the origin-form target. + + Falsifier: a prefix match, an empty placeholder, or the wrong method + returns 200, or the 404 body omits the path that was requested. + """ + routes = { + "/invoices/{id}": {"GET": {"resource": "invoice"}}, + "/invoices/{id}/part": {"GET": {"resource": "part"}}, + } + async with _running(routes) as port: + status, body = await _exchange(port, method, target) + assert status == 404 + assert body == {"error": "not found", "path": target} + + +class TestSchemaComposition: + """R5–R11. Expected values are the schema's const, example, default, or + declared JSON type. Nothing here is recorded from a server run. + """ + + def test_wander_search_resolves_nested_refs(self, tmp_path: Path): + """R5. A wander search request hits the template and returns resolved refs. + + Excerpt of the current search/pricing shape: POST + /collections/{collectionId}/search, items $ref to an object whose + required rate_cents is $ref Int. additionalProperties is also an Int + ref so a resolver that rejects that keyword fails this load. The + contract does not require a synthesized extra property. + + Falsifier: /collections/wander/search is 404, hits are missing, or + rate_cents is an object instead of an integer. Legacy array behavior + that still stands (R11) is a non-empty array, so an empty hits list + cannot hide an unresolved item ref. + """ + routes = load_routes(_write_spec(tmp_path, _search_excerpt())) + body = routes["/collections/{collectionId}/search"]["POST"] + self._assert_search_body(body) + + async def test_wander_search_serves_resolved_body(self, tmp_path: Path): + """R5 at the HTTP boundary. Same excerpt, served by MockServer. + + The query string is the real search shape and must not affect matching. + Falsifier: the loaded body is right but the server 404s the template, + or the served rate_cents is not an integer. + """ + routes = load_routes(_write_spec(tmp_path, _search_excerpt(), "search.json")) + async with _running(routes) as port: + status, body = await _exchange( + port, "POST", "/collections/wander/search?page=1" + ) + assert status == 200 + self._assert_search_body(body) + + @staticmethod + def _assert_search_body(body: object) -> None: + assert isinstance(body, dict) + hits = body["hits"] + assert isinstance(hits, list) and len(hits) >= 1 + for hit in hits: + assert isinstance(hit, dict) + assert isinstance(hit.get("id"), str) + assert _is_json_int(hit.get("rate_cents")) + + @pytest.mark.parametrize("keyword", ["anyOf", "oneOf"]) + def test_ref_inside_union_prefers_value(self, tmp_path: Path, keyword: str): + """R5 and R8. A $ref inside anyOf/oneOf is resolved, and null loses. + + Null is listed first. The other branch is const "Ada", so the body is + exactly that string. First-branch and unresolved-ref both fail. + + Falsifier: the result is null, or an object standing in for the ref. + """ + spec = _openapi( + {"/name": {"get": {"responses": _ok({ + keyword: [ + {"type": "null"}, + {"$ref": "#/components/schemas/Name"}, + ], + })}}}, + schemas={"Name": {"const": "Ada"}}, + ) + routes = load_routes(_write_spec(tmp_path, spec, f"{keyword}.json")) + assert routes["/name"]["GET"] == "Ada" + + def test_ref_inside_allof_merges_required_fields(self, tmp_path: Path): + """R5 and R9. allOf of two schema refs contains both required consts. + + Falsifier: only the first branch is kept, or a ref is left unresolved + so id or rate_cents is missing or is an object. + """ + spec = _openapi( + {"/price": {"get": {"responses": _ok({ + "allOf": [ + {"$ref": "#/components/schemas/WithId"}, + {"$ref": "#/components/schemas/WithCents"}, + ], + })}}}, + schemas={ + "WithId": { + "type": "object", + "required": ["id"], + "properties": {"id": {"const": "item"}}, + }, + "WithCents": { + "type": "object", + "required": ["rate_cents"], + "properties": {"rate_cents": {"const": 5}}, + }, + }, + ) + routes = load_routes(_write_spec(tmp_path, spec)) + body = routes["/price"]["GET"] + assert isinstance(body, dict) + assert body.get("id") == "item" + assert body.get("rate_cents") == 5 + + def test_response_ref_returns_its_json_body(self, tmp_path: Path): + """R6 and R11. A response $ref returns that response's JSON example. + + The referenced response also has a schema that would generate a + different object. The media-type example still wins. + + Falsifier: the response ref is dropped, or the schema is generated + instead of the example. + """ + spec = _openapi( + {"/status": {"get": {"responses": { + "200": {"$ref": "#/components/responses/Status"}, + }}}}, + responses={ + "Status": { + "description": "ok", + "content": { + "application/json": { + "example": {"status": "ok"}, + "schema": { + "type": "object", + "required": ["other"], + "properties": {"other": {"const": "no"}}, + }, + } + }, + } + }, + ) + path = _write_spec(tmp_path, spec) + routes = load_routes(path) + assert routes["/status"]["GET"] == {"status": "ok"} + assert parse_openapi(path) == routes + + async def test_response_ref_is_served(self, tmp_path: Path): + """R6 at HTTP. The caller receives the referenced response body. + + Falsifier: load_routes followed the ref but the server returns a + different body, or 404s the literal path. + """ + spec = _openapi( + {"/status": {"get": {"responses": { + "200": {"$ref": "#/components/responses/Status"}, + }}}}, + responses={ + "Status": { + "description": "ok", + "content": {"application/json": {"example": {"status": "ok"}}}, + } + }, + ) + routes = load_routes(_write_spec(tmp_path, spec, "response.json")) + async with _running(routes) as port: + status, body = await _exchange(port, "GET", "/status") + assert status == 200 + assert body == {"status": "ok"} + + def test_self_reference_loads_finite_json(self, tmp_path: Path): + """R7. A schema that refers to itself loads as finite JSON. + + child is optional. value is a required integer, so an empty object + does not pass. Falsifier: load_routes raises, does not finish within + 5 seconds, or returns a value json.dumps cannot encode. + """ + spec = _openapi( + {"/node": {"get": {"responses": _ok( + {"$ref": "#/components/schemas/Node"} + )}}}, + schemas={ + "Node": { + "type": "object", + "required": ["value"], + "properties": { + "value": {"type": "integer"}, + "child": {"$ref": "#/components/schemas/Node"}, + }, + } + }, + ) + routes = _load_bounded(_write_spec(tmp_path, spec)) + body = routes["/node"]["GET"] + assert isinstance(body, dict) + assert _is_json_int(body["value"]) + json.dumps(body) + + async def test_self_reference_http_body_is_finite(self, tmp_path: Path): + """R7 served. The HTTP body is the finite JSON load_routes produced. + + Falsifier: the server hangs or returns a body that is not that JSON. + """ + spec = _openapi( + {"/node": {"get": {"responses": _ok( + {"$ref": "#/components/schemas/Node"} + )}}}, + schemas={ + "Node": { + "type": "object", + "required": ["value"], + "properties": { + "value": {"type": "integer"}, + "child": {"$ref": "#/components/schemas/Node"}, + }, + } + }, + ) + routes = _load_bounded(_write_spec(tmp_path, spec, "self.json")) + async with _running(routes) as port: + status, body = await _exchange(port, "GET", "/node") + assert status == 200 + assert body == routes["/node"]["GET"] + assert _is_json_int(body["value"]) + json.dumps(body) + + def test_mutual_reference_loads_finite_json(self, tmp_path: Path): + """R7. Two schemas that refer to each other load in bounded time. + + Falsifier: the cycle raises, hangs past 5 seconds, or yields a value + that is not finite JSON. The required name stays a string. + """ + spec = _openapi( + {"/a": {"get": {"responses": _ok( + {"$ref": "#/components/schemas/A"} + )}}}, + schemas={ + "A": { + "type": "object", + "required": ["name"], + "properties": { + "name": {"type": "string"}, + "b": {"$ref": "#/components/schemas/B"}, + }, + }, + "B": { + "type": "object", + "required": ["name"], + "properties": { + "name": {"type": "string"}, + "a": {"$ref": "#/components/schemas/A"}, + }, + }, + }, + ) + routes = _load_bounded(_write_spec(tmp_path, spec)) + body = routes["/a"]["GET"] + assert isinstance(body, dict) + assert isinstance(body.get("name"), str) + json.dumps(body) + + @pytest.mark.parametrize("keyword", ["anyOf", "oneOf"]) + def test_union_prefers_non_null_branch(self, keyword: str): + """R8. "string or null" yields a string, even when null is listed first. + + The string branch is an enum, so a generator that ignores the union + and emits an arbitrary string still fails. Calling generate_instance + with only the schema must keep working. + + Falsifier: the result is null, or a string outside the enum. + """ + schema = { + keyword: [ + {"type": "null"}, + {"type": "string", "enum": ["alpha", "beta"]}, + ] + } + generated = generate_instance(schema) + assert generated == "alpha" or generated == "beta" + + def test_allof_contains_every_required_property(self): + """R9. The object contains the required properties of every allOf part. + + Falsifier: the second part's rate_cents is missing, or a part's + declared type is replaced with an object. + """ + result = generate_instance({ + "allOf": [ + { + "type": "object", + "required": ["id"], + "properties": {"id": {"type": "string"}}, + }, + { + "type": "object", + "required": ["rate_cents"], + "properties": {"rate_cents": {"type": "integer"}}, + }, + ] + }) + assert isinstance(result, dict) + assert isinstance(result.get("id"), str) + assert _is_json_int(result.get("rate_cents")) + + def test_const_is_the_generated_value(self, tmp_path: Path): + """R10. The generated value equals the const, including through a spec. + + Falsifier: const is ignored and a value of that JSON type is invented, + or parse_openapi and load_routes disagree on the fixed body. + """ + assert generate_instance({"const": 7}) == 7 + assert generate_instance({"const": True}) is True + assert generate_instance({"const": None}) is None + assert generate_instance({"const": {"ready": True}}) == {"ready": True} + spec = _openapi({ + "/obj": {"get": {"responses": _ok({"const": {"ready": True}})}}, + }) + path = _write_spec(tmp_path, spec) + routes = load_routes(path) + assert routes["/obj"]["GET"] == {"ready": True} + assert parse_openapi(path) == routes + + def test_example_default_and_enum_survive_ref(self, tmp_path: Path): + """R11. Schema example, default, and enum still win after a $ref. + + Each keyword is on its own referenced schema, so they do not compete. + Enum asserts membership, not which member: the brief does not rank + members. Inline examples of these keywords already stand in the + legacy tests. + + Falsifier: resolving the ref drops the keyword and emits a free string. + """ + spec = _openapi( + {"/label": {"get": {"responses": _ok({ + "type": "object", + "required": ["by_example", "by_default", "by_enum"], + "properties": { + "by_example": {"$ref": "#/components/schemas/ByExample"}, + "by_default": {"$ref": "#/components/schemas/ByDefault"}, + "by_enum": {"$ref": "#/components/schemas/ByEnum"}, + }, + })}}}, + schemas={ + "ByExample": {"type": "string", "example": "Ada"}, + "ByDefault": {"type": "string", "default": "fallback"}, + "ByEnum": {"type": "string", "enum": ["a", "b", "c"]}, + }, + ) + body = load_routes(_write_spec(tmp_path, spec))["/label"]["GET"] + assert body.get("by_example") == "Ada" + assert body.get("by_default") == "fallback" + enum_value = body.get("by_enum") + assert enum_value == "a" or enum_value == "b" or enum_value == "c" + + async def test_media_example_wins_on_template_path(self, tmp_path: Path): + """R11. A media-type example is the served body of a template route. + + The schema would otherwise require a different const. The path key + stays written as /invoices/{id}. + + Falsifier: template matching works but the example is discarded, or + the route key is rewritten without the placeholder. + """ + spec = _openapi({ + "/invoices/{id}": {"get": {"responses": _ok( + schema={ + "type": "object", + "required": ["generated"], + "properties": {"generated": {"const": "no"}}, + }, + example={"invoice": "kept"}, + )}}, + }) + path = _write_spec(tmp_path, spec) + routes = load_routes(path) + assert "/invoices/{id}" in routes + assert routes["/invoices/{id}"]["GET"] == {"invoice": "kept"} + assert parse_openapi(path) == routes + async with _running(routes) as port: + status, body = await _exchange(port, "GET", "/invoices/123") + assert status == 200 + assert body == {"invoice": "kept"} From e67e00f075946d88b9d3fc62b4092220101792b4 Mon Sep 17 00:00:00 2001 From: Yevhen Vasko Date: Tue, 17 Nov 2026 08:56:24 -0600 Subject: [PATCH 03/10] fix(mock): generate a recursive $ref once before cutting it off A required self-reference returned {} at the first repetition, so e.g. Node.child or Tree.kids were empty objects. Emit one full instance of a directly self-referencing schema and cut only its next link; mutual recursion and the depth guard are unchanged. Implementation authored by the Factory Coder lane (codex gpt-6.1-sol), repair round 1. FactoryRun: baton-mock-templates-20261117 Built-By: Factory v0.8.29 --- src/baton/mock.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/baton/mock.py b/src/baton/mock.py index b237342..7811247 100644 --- a/src/baton/mock.py +++ b/src/baton/mock.py @@ -93,19 +93,25 @@ def _expand_schema( def generate_instance( schema: dict, components: dict | None = None, *, _depth: int = 0, _seen: frozenset[str] = frozenset(), + _last_ref: str | None = None, _self_repeated: bool = False, ) -> Any: """Generate a random valid instance from a JSON Schema.""" components = components or {} - if _depth >= 32 or schema.get("$ref") in _seen: + ref = schema.get("$ref") + repeated = ref in _seen + # Emit one full child for direct self-reference, then cut its next link. + # A link back through another schema remains a mutual-recursion cutoff. + if _depth >= 32 or (repeated and (ref != _last_ref or _self_repeated)): return {} # Preserve explicit values before following references or compositions. for key in ("example", "default", "enum", "const"): if key in schema: return schema[key][0] if key == "enum" else schema[key] - ref = schema.get("$ref") - schema = _expand_schema(schema, components, seen=_seen) + schema = _expand_schema(schema, components, seen=_seen - {ref} if repeated else _seen) if ref: _seen = _seen | {ref} + _last_ref = ref + _self_repeated = repeated if "example" in schema: return schema["example"] if "default" in schema: @@ -117,7 +123,10 @@ def generate_instance( return schema["const"] def generate(child: dict) -> Any: - return generate_instance(child, components, _depth=_depth + 1, _seen=_seen) + return generate_instance( + child, components, _depth=_depth + 1, _seen=_seen, + _last_ref=_last_ref, _self_repeated=_self_repeated, + ) for keyword in ("anyOf", "oneOf"): if keyword in schema: From 032ad80d1d6f461db86de828eab6270dcb3f23d8 Mon Sep 17 00:00:00 2001 From: Yevhen Vasko Date: Tue, 17 Nov 2026 08:56:24 -0600 Subject: [PATCH 04/10] test(mock): cover required recursive references (R7) Required self-reference, required array of self-references (minItems 2) and required mutual recursion must load and serve in bounded time with the first followed instance generated. Tests authored independently by the Factory Tester lane (cursor-agent grok-4.7-high), repair round 1. FactoryRun: baton-mock-templates-20261117 Built-By: Factory v0.8.29 --- tests/test_mock.py | 162 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 162 insertions(+) diff --git a/tests/test_mock.py b/tests/test_mock.py index ac90aad..b764018 100644 --- a/tests/test_mock.py +++ b/tests/test_mock.py @@ -480,6 +480,49 @@ def _free_port() -> int: return sock.getsockname()[1] +def _required_node_followed(body: object) -> bool: + """The node and its required child each carry an integer value. + + The child's own child is the cut-off and is not examined. + """ + if not isinstance(body, dict): + return False + child = body.get("child") + return ( + _is_json_int(body.get("value")) + and isinstance(child, dict) + and _is_json_int(child.get("value")) + ) + + +def _required_tree_followed(body: object) -> bool: + """value is an integer and some kid was generated as a Tree. + + How many kids, and what those kids contain, is the cut-off. + """ + if not isinstance(body, dict) or not _is_json_int(body.get("value")): + return False + kids = body.get("kids") + if not isinstance(kids, list): + return False + return any( + isinstance(kid, dict) and _is_json_int(kid.get("value")) + for kid in kids + ) + + +def _required_mutual_followed(body: object) -> bool: + """A and the required B each have a string name. B's link back is free.""" + if not isinstance(body, dict): + return False + other = body.get("b") + return ( + isinstance(body.get("name"), str) + and isinstance(other, dict) + and isinstance(other.get("name"), str) + ) + + def _is_json_int(value: object) -> bool: """JSON integers are not booleans. True is an int subclass in Python.""" return isinstance(value, int) and not isinstance(value, bool) @@ -1042,6 +1085,125 @@ def test_mutual_reference_loads_finite_json(self, tmp_path: Path): assert isinstance(body.get("name"), str) json.dumps(body) + async def test_required_self_reference_stays_finite(self, tmp_path: Path): + """R7. A required self-reference is followed and still finishes. + + Node.required includes child, so the generator cannot skip the cycle. + value stays an integer on the node that was asked for and on the + required child, which is that same schema. Nothing past the child + is inspected, so the depth at which expansion stops stays free. + + Falsifier: expansion does not finish within 5 seconds, raises, or + the followed node is an empty object instead of a Node. + """ + spec = _openapi( + {"/node": {"get": {"responses": _ok( + {"$ref": "#/components/schemas/Node"} + )}}}, + schemas={ + "Node": { + "type": "object", + "required": ["value", "child"], + "properties": { + "value": {"type": "integer"}, + "child": {"$ref": "#/components/schemas/Node"}, + }, + } + }, + ) + await self._assert_required_recursion( + tmp_path, spec, "required-self.json", "/node", "GET", + _required_node_followed, + ) + + async def test_required_array_recursion_stays_finite(self, tmp_path: Path): + """R7. A required array of at least two self-refs stays finite. + + Tree.kids is required, minItems 2, and each item is a Tree. That + forces the cycle and rejects an expansion that branches without bound. + value stays an integer, and at least one kid is a Tree rather than + an empty object. Kid count and anything inside a kid's kids are free. + + Falsifier: load or serve does not finish within 5 seconds, raises, + or the array items were not generated as Trees. + """ + spec = _openapi( + {"/tree": {"get": {"responses": _ok( + {"$ref": "#/components/schemas/Tree"} + )}}}, + schemas={ + "Tree": { + "type": "object", + "required": ["value", "kids"], + "properties": { + "value": {"type": "integer"}, + "kids": { + "type": "array", + "minItems": 2, + "items": {"$ref": "#/components/schemas/Tree"}, + }, + }, + } + }, + ) + await self._assert_required_recursion( + tmp_path, spec, "required-tree.json", "/tree", "GET", + _required_tree_followed, + ) + + async def test_required_mutual_recursion_stays_finite(self, tmp_path: Path): + """R7. Mutual recursion with both links required stays finite. + + A.b and B.a are required, so neither side can skip the other. + name stays a string on A and on the required B. B's link back to A + is not inspected. + + Falsifier: load or serve does not finish within 5 seconds, raises, + or the followed schema is an empty object. + """ + spec = _openapi( + {"/a": {"get": {"responses": _ok( + {"$ref": "#/components/schemas/A"} + )}}}, + schemas={ + "A": { + "type": "object", + "required": ["name", "b"], + "properties": { + "name": {"type": "string"}, + "b": {"$ref": "#/components/schemas/B"}, + }, + }, + "B": { + "type": "object", + "required": ["name", "a"], + "properties": { + "name": {"type": "string"}, + "a": {"$ref": "#/components/schemas/A"}, + }, + }, + }, + ) + await self._assert_required_recursion( + tmp_path, spec, "required-mutual.json", "/a", "GET", + _required_mutual_followed, + ) + + async def _assert_required_recursion( + self, tmp_path, spec, filename, path, method, field_ok, + ): + routes = _load_bounded(_write_spec(tmp_path, spec, filename)) + loaded = routes[path][method] + json.dumps(loaded) + assert isinstance(loaded, dict) + assert field_ok(loaded), loaded + async with _running(routes) as port: + status, served = await _exchange(port, method, path) + assert status == 200 + assert served == loaded + json.dumps(served) + assert field_ok(served), served + @pytest.mark.parametrize("keyword", ["anyOf", "oneOf"]) def test_union_prefers_non_null_branch(self, keyword: str): """R8. "string or null" yields a string, even when null is listed first. From 9a3c282b354054f42bfc601fd72650ddb6b4d33d Mon Sep 17 00:00:00 2001 From: Yevhen Vasko Date: Tue, 17 Nov 2026 09:20:36 -0600 Subject: [PATCH 05/10] =?UTF-8?q?fix(mock):=20address=20review=20=E2=80=94?= =?UTF-8?q?=20merge=20$ref=20siblings,=20no=20synthetic=20map=20keys?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - $ref sibling keys are merged with the referenced schema (_merge_schema) instead of replacing its properties/required. - Maps (additionalProperties only) get entries only when minProperties requires them; otherwise {} as before. - Single example/default/enum/const precedence check after expansion. - Unresolved-ref log de-duplication is scoped to one spec load. Implementation authored by the Factory Coder lane (codex gpt-6.1-sol), repair round 2. FactoryRun: baton-mock-templates-20261117 Built-By: Factory v0.8.29 --- src/baton/mock.py | 58 ++++++++++++++++++++++++----------------------- 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/src/baton/mock.py b/src/baton/mock.py index 7811247..097bef5 100644 --- a/src/baton/mock.py +++ b/src/baton/mock.py @@ -25,11 +25,13 @@ logger = logging.getLogger(__name__) -_unresolved_refs: set[str] = set() - - -def _resolve_ref(value: dict, components: dict, seen: frozenset[str] = frozenset()) -> dict: +def _resolve_ref( + value: dict, components: dict, seen: frozenset[str] = frozenset(), + unresolved: set[str] | None = None, +) -> dict: """Follow local component references, including response aliases.""" + if unresolved is None: + unresolved = set() ref = value.get("$ref") if not ref: return value @@ -43,12 +45,13 @@ def _resolve_ref(value: dict, components: dict, seen: frozenset[str] = frozenset else: target = None if not isinstance(target, dict): - if ref not in _unresolved_refs: + if ref not in unresolved: logger.debug("Unresolved mock reference: %s", ref) - _unresolved_refs.add(ref) + unresolved.add(ref) target = {} - resolved = _resolve_ref(target, components, seen | {ref}) - return {**resolved, **{key: val for key, val in value.items() if key != "$ref"}} + resolved = _resolve_ref(target, components, seen | {ref}, unresolved) + siblings = {key: val for key, val in value.items() if key != "$ref"} + return _merge_schema(resolved, siblings) def _merge_schema(left: dict, right: dict) -> dict: @@ -74,18 +77,19 @@ def _merge_schema(left: dict, right: dict) -> dict: def _expand_schema( schema: dict, components: dict, depth: int = 0, - seen: frozenset[str] = frozenset(), + seen: frozenset[str] = frozenset(), unresolved: set[str] | None = None, ) -> dict: ref = schema.get("$ref") if depth >= 32 or ref in seen: return {} - schema = _resolve_ref(schema, components, seen) + schema = _resolve_ref(schema, components, seen, unresolved) if ref: seen = seen | {ref} if "allOf" in schema: merged = {} for part in schema["allOf"]: - merged = _merge_schema(merged, _expand_schema(part, components, depth + 1, seen)) + expanded = _expand_schema(part, components, depth + 1, seen, unresolved) + merged = _merge_schema(merged, expanded) schema = _merge_schema(merged, {k: v for k, v in schema.items() if k != "allOf"}) return schema @@ -94,38 +98,35 @@ def generate_instance( schema: dict, components: dict | None = None, *, _depth: int = 0, _seen: frozenset[str] = frozenset(), _last_ref: str | None = None, _self_repeated: bool = False, + _unresolved: set[str] | None = None, ) -> Any: """Generate a random valid instance from a JSON Schema.""" components = components or {} + if _unresolved is None: + _unresolved = set() ref = schema.get("$ref") repeated = ref in _seen # Emit one full child for direct self-reference, then cut its next link. # A link back through another schema remains a mutual-recursion cutoff. if _depth >= 32 or (repeated and (ref != _last_ref or _self_repeated)): return {} - # Preserve explicit values before following references or compositions. - for key in ("example", "default", "enum", "const"): - if key in schema: - return schema[key][0] if key == "enum" else schema[key] - schema = _expand_schema(schema, components, seen=_seen - {ref} if repeated else _seen) + schema = _expand_schema( + schema, components, seen=_seen - {ref} if repeated else _seen, + unresolved=_unresolved, + ) if ref: _seen = _seen | {ref} _last_ref = ref _self_repeated = repeated - if "example" in schema: - return schema["example"] - if "default" in schema: - return schema["default"] - if "enum" in schema: - return schema["enum"][0] - - if "const" in schema: - return schema["const"] + for key in ("example", "default", "enum", "const"): + if key in schema: + return schema[key][0] if key == "enum" else schema[key] def generate(child: dict) -> Any: return generate_instance( child, components, _depth=_depth + 1, _seen=_seen, _last_ref=_last_ref, _self_repeated=_self_repeated, + _unresolved=_unresolved, ) for keyword in ("anyOf", "oneOf"): @@ -182,7 +183,7 @@ def generate(child: dict) -> Any: obj[name] = generate(prop_schema) additional = schema.get("additionalProperties") if not props and isinstance(additional, dict): - for index in range(max(1, schema.get("minProperties", 0))): + for index in range(schema.get("minProperties", 0)): obj[f"key{index + 1}"] = generate(additional) return obj @@ -205,6 +206,7 @@ def parse_openapi(spec_path: str) -> dict[str, dict[str, Any]]: return {} components = spec.get("components", {}) + unresolved: set[str] = set() routes: dict[str, dict[str, Any]] = {} for path_str, methods in spec["paths"].items(): @@ -217,7 +219,7 @@ def parse_openapi(spec_path: str) -> dict[str, dict[str, Any]]: # Find the success response responses = operation.get("responses", {}) success_resp = responses.get("200") or responses.get("201") or {} - success_resp = _resolve_ref(success_resp, components) + success_resp = _resolve_ref(success_resp, components, unresolved=unresolved) content = success_resp.get("content", {}) json_content = content.get("application/json", {}) resp_schema = json_content.get("schema", {}) @@ -228,7 +230,7 @@ def parse_openapi(spec_path: str) -> dict[str, dict[str, Any]]: elif "example" in resp_schema: body = resp_schema["example"] elif resp_schema: - body = generate_instance(resp_schema, components) + body = generate_instance(resp_schema, components, _unresolved=unresolved) else: body = {} From 2ca15f707b9cd2fad10e56d8fa156156d76c9c68 Mon Sep 17 00:00:00 2001 From: Yevhen Vasko Date: Tue, 17 Nov 2026 09:20:36 -0600 Subject: [PATCH 06/10] test(mock): self-explanatory docstrings, drop unused chunked decoder No assertion changes. Tests authored independently by the Factory Tester lane (cursor-agent grok-4.7-high), repair round 2. FactoryRun: baton-mock-templates-20261117 Built-By: Factory v0.8.29 --- tests/test_mock.py | 273 +++++++++++++++++++++------------------------ 1 file changed, 125 insertions(+), 148 deletions(-) diff --git a/tests/test_mock.py b/tests/test_mock.py index b764018..ae2ba0c 100644 --- a/tests/test_mock.py +++ b/tests/test_mock.py @@ -469,9 +469,10 @@ async def test_mock_no_spans_without_exporter(self): await server.stop() -# Acceptance coverage for path templates and schema composition. -# Oracles are the lane brief and JSON Schema / OpenAPI semantics. -# Authority is normative unless a docstring says the legacy suite is the source. +# Path templates and schema composition for the mock server. +# A matching request returns the body registered for the winning route. +# A generated body is the value the schema itself requires: const, example, +# default, an enum member, or the declared JSON type. def _free_port() -> int: @@ -563,11 +564,11 @@ def _ok(schema: dict | None = None, example: object | None = None) -> dict: def _search_excerpt() -> dict: - """Minimal stand-in for the current search path and a pricing-shaped hit. + """Small search spec whose hit list refers to an object. - items is a schema ref to an object whose required rate_cents is an Int - ref. additionalProperties is an Int ref so a resolver that rejects that - keyword fails the load. The contract does not require an extra key. + That object's required rate_cents refers to an integer schema, and so do + any additional properties. A loader that rejects the keyword fails here. + The test does not require an extra property to be invented. """ return _openapi( { @@ -608,10 +609,10 @@ def _write_spec(tmp_path: Path, document: dict, name: str = "spec.json") -> str: def _load_bounded(spec_path: str, seconds: float = 5.0) -> dict: - """Run load_routes in a child so a recursive schema cannot hang this process. + """Load routes in a child process so a recursive schema cannot hang the test. - The 5 second ceiling is the test's reading of "bounded time": a tiny schema - that does not finish is not bounded. The contract states no byte limit. + A schema this small that does not finish within 5 seconds is treated as + unbounded. """ script = ( "import json, sys\n" @@ -632,26 +633,6 @@ def _load_bounded(spec_path: str, seconds: float = 5.0) -> dict: return json.loads(completed.stdout) -def _decode_chunked(body: bytes) -> bytes: - chunks = [] - rest = body - while rest: - line, sep, rest = rest.partition(b"\r\n") - if not sep: - break - size_token = line.split(b";", 1)[0].strip() - if not size_token: - break - size = int(size_token, 16) - if size == 0: - break - chunks.append(rest[:size]) - rest = rest[size:] - if rest.startswith(b"\r\n"): - rest = rest[2:] - return b"".join(chunks) - - def _parse_response(raw: bytes) -> tuple[int, bytes]: head, _, body = raw.partition(b"\r\n\r\n") lines = head.decode("iso-8859-1").split("\r\n") @@ -662,9 +643,7 @@ def _parse_response(raw: bytes) -> tuple[int, bytes]: continue name, value = line.split(":", 1) headers[name.lower()] = value.strip().lower() - if headers.get("transfer-encoding") == "chunked": - body = _decode_chunked(body) - elif "content-length" in headers: + if "content-length" in headers: body = body[: int(headers["content-length"])] return status, body @@ -707,14 +686,16 @@ async def _running(routes: dict): class TestPathTemplates: - """R1–R4. The registered body is the oracle: the request must return the - body of the route the brief says wins, or the stated 404 object. + """A `{name}` segment matches exactly one non-empty path segment. + + The response is the body registered on the route that wins. A request + that matches no route returns 404 and names the path that was sent. """ async def test_placeholder_matches_one_segment(self): - """R1. GET /invoices/123 and /invoices/456 both return the /invoices/{id} body. + """Both /invoices/123 and /invoices/456 return the /invoices/{id} body. - Falsifier: the template is ignored, or only a hard-coded id matches. + Fails if the placeholder is ignored, or if only one hard-coded id matches. """ routes = {"/invoices/{id}": {"GET": {"resource": "invoice"}}} async with _running(routes) as port: @@ -724,10 +705,10 @@ async def test_placeholder_matches_one_segment(self): assert body == {"resource": "invoice"} async def test_multiple_placeholders_each_match_one_segment(self): - """R1. Each {param} is one non-empty segment. A missing segment does not match. + """Each placeholder is one segment, and a missing last segment does not match. - Falsifier: one placeholder consumes several segments, or the last - placeholder is optional. + Fails if one placeholder swallows several segments, or if the last + placeholder is treated as optional. """ routes = {"/orgs/{org}/invoices/{id}": {"GET": {"resource": "invoice"}}} async with _running(routes) as port: @@ -739,9 +720,9 @@ async def test_multiple_placeholders_each_match_one_segment(self): assert body == {"error": "not found", "path": "/orgs/acme/invoices"} async def test_trailing_slash_still_matches_template(self): - """R1. A trailing slash is tolerated and does not become an extra segment. + """A trailing slash is still the same template match. - Falsifier: /invoices/123/ is rejected or routed as a different path. + Fails if /invoices/123/ is rejected or sent to a different route. """ routes = {"/invoices/{id}": {"GET": {"resource": "invoice"}}} async with _running(routes) as port: @@ -750,9 +731,9 @@ async def test_trailing_slash_still_matches_template(self): assert body == {"resource": "invoice"} async def test_query_string_ignored_for_template(self): - """R1. The query string is not part of template matching. + """A query string is ignored when matching a template. - Falsifier: /invoices/123?page=1 misses /invoices/{id}. + Fails if /invoices/123?page=1 does not hit /invoices/{id}. """ routes = {"/invoices/{id}": {"GET": {"resource": "invoice"}}} async with _running(routes) as port: @@ -761,14 +742,14 @@ async def test_query_string_ignored_for_template(self): assert body == {"resource": "invoice"} async def test_literal_path_beats_template(self): - """R2. /collections/wander/search wins over /collections/{collectionId}/search. + """The literal /collections/wander/search wins over the collection template. - The template is registered first, so first-match-wins fails this test. - A different collection id still uses the template. The wrong method - stays a 404 (R4). + The template is registered first, so a first-match implementation fails. + Another collection id still uses the template. GET on the literal path + is 404 because only POST is registered. - Falsifier: wander receives the template body, or every collection id - receives the literal body. + Fails if wander gets the template body, or if every collection id gets + the literal body. """ routes = { "/collections/{collectionId}/search": {"POST": {"matched": "template"}}, @@ -786,13 +767,13 @@ async def test_literal_path_beats_template(self): assert body == {"error": "not found", "path": "/collections/wander/search"} async def test_more_specific_template_wins(self): - """R3. GET /a/1/b returns the body of /a/{x}/b, not /a/{x}/{y}. + """GET /a/1/b uses /a/{x}/b, the template with more literal segments. - The less specific template is registered first. /a/1/c does not fit - the literal segment, so it uses /a/{x}/{y}. + The less specific template is registered first. /a/1/c does not have + the literal segment b, so it uses /a/{x}/{y}. - Falsifier: the two templates are tied by length, or a non-matching - literal segment still captures the request. + Fails if the two templates are treated as equal, or if a literal + segment that does not match still captures the request. """ routes = { "/a/{x}/{y}": {"GET": {"matched": "two-params"}}, @@ -817,14 +798,13 @@ async def test_more_specific_template_wins(self): ], ) async def test_non_match_is_json_404(self, method: str, target: str): - """R4. Extra, missing, or empty segments, and the wrong method, are 404. + """An extra, missing, or empty segment, or the wrong method, is 404. - The body is exactly {"error": "not found", "path": }. - These targets have no trailing-slash ambiguity, so the request path - is the origin-form target. + The body is {"error": "not found", "path": }. + None of these targets ends with a slash, so the path is unambiguous. - Falsifier: a prefix match, an empty placeholder, or the wrong method - returns 200, or the 404 body omits the path that was requested. + Fails if a prefix, an empty placeholder, or the wrong method returns + 200, or if the 404 body leaves out the requested path. """ routes = { "/invoices/{id}": {"GET": {"resource": "invoice"}}, @@ -837,34 +817,35 @@ async def test_non_match_is_json_404(self, method: str, target: str): class TestSchemaComposition: - """R5–R11. Expected values are the schema's const, example, default, or - declared JSON type. Nothing here is recorded from a server run. + """Generated values come from the schema, not from a recorded response. + + A const, example, or default is that value. An enum value is one of its + members. Otherwise the value has the declared JSON type. A `$ref` is + replaced by the schema it names before that rule is applied. """ def test_wander_search_resolves_nested_refs(self, tmp_path: Path): - """R5. A wander search request hits the template and returns resolved refs. - - Excerpt of the current search/pricing shape: POST - /collections/{collectionId}/search, items $ref to an object whose - required rate_cents is $ref Int. additionalProperties is also an Int - ref so a resolver that rejects that keyword fails this load. The - contract does not require a synthesized extra property. - - Falsifier: /collections/wander/search is 404, hits are missing, or - rate_cents is an object instead of an integer. Legacy array behavior - that still stands (R11) is a non-empty array, so an empty hits list - cannot hide an unresolved item ref. + """The search template's hit list resolves nested schema references. + + POST /collections/{collectionId}/search returns hits, each an object + whose required rate_cents refers to an integer schema. additionalProperties + refers to that same integer, so a loader that rejects the keyword fails. + An extra property does not have to be invented. Arrays are still + non-empty, so an empty list cannot hide an unresolved item. + + Fails if the template key is missing, hits are missing, or rate_cents + is an object instead of an integer. """ routes = load_routes(_write_spec(tmp_path, _search_excerpt())) body = routes["/collections/{collectionId}/search"]["POST"] self._assert_search_body(body) async def test_wander_search_serves_resolved_body(self, tmp_path: Path): - """R5 at the HTTP boundary. Same excerpt, served by MockServer. + """The same search body is what the server returns for a wander request. - The query string is the real search shape and must not affect matching. - Falsifier: the loaded body is right but the server 404s the template, - or the served rate_cents is not an integer. + The query string must not change which route matches. Fails if the + server answers 404 for the template, or if the served rate_cents is + not an integer. """ routes = load_routes(_write_spec(tmp_path, _search_excerpt(), "search.json")) async with _running(routes) as port: @@ -886,12 +867,11 @@ def _assert_search_body(body: object) -> None: @pytest.mark.parametrize("keyword", ["anyOf", "oneOf"]) def test_ref_inside_union_prefers_value(self, tmp_path: Path, keyword: str): - """R5 and R8. A $ref inside anyOf/oneOf is resolved, and null loses. - - Null is listed first. The other branch is const "Ada", so the body is - exactly that string. First-branch and unresolved-ref both fail. + """A schema reference inside anyOf or oneOf is used, and null loses. - Falsifier: the result is null, or an object standing in for the ref. + Null is listed first. The other branch is the const string "Ada", so + the body is exactly that string. Fails if the result is null, or if + the reference is left as an empty object. """ spec = _openapi( {"/name": {"get": {"responses": _ok({ @@ -906,10 +886,10 @@ def test_ref_inside_union_prefers_value(self, tmp_path: Path, keyword: str): assert routes["/name"]["GET"] == "Ada" def test_ref_inside_allof_merges_required_fields(self, tmp_path: Path): - """R5 and R9. allOf of two schema refs contains both required consts. + """allOf of two schema references keeps both required constants. - Falsifier: only the first branch is kept, or a ref is left unresolved - so id or rate_cents is missing or is an object. + Fails if only the first branch is kept, or if a reference is unresolved + and id or rate_cents is missing or is an object. """ spec = _openapi( {"/price": {"get": {"responses": _ok({ @@ -938,13 +918,12 @@ def test_ref_inside_allof_merges_required_fields(self, tmp_path: Path): assert body.get("rate_cents") == 5 def test_response_ref_returns_its_json_body(self, tmp_path: Path): - """R6 and R11. A response $ref returns that response's JSON example. - - The referenced response also has a schema that would generate a - different object. The media-type example still wins. + """A response that is only a $ref returns that response's JSON example. - Falsifier: the response ref is dropped, or the schema is generated - instead of the example. + The referenced response also has a schema that would build a different + object. The example on the media type is the body instead. Fails if + the response reference is dropped, or if the schema is generated in + place of the example. parse_openapi and load_routes agree on that body. """ spec = _openapi( {"/status": {"get": {"responses": { @@ -972,10 +951,10 @@ def test_response_ref_returns_its_json_body(self, tmp_path: Path): assert parse_openapi(path) == routes async def test_response_ref_is_served(self, tmp_path: Path): - """R6 at HTTP. The caller receives the referenced response body. + """The server returns the body of a response that was given by $ref. - Falsifier: load_routes followed the ref but the server returns a - different body, or 404s the literal path. + Fails if the loaded body followed the reference but the server returns + something else, or answers 404 for the literal path. """ spec = _openapi( {"/status": {"get": {"responses": { @@ -995,11 +974,11 @@ async def test_response_ref_is_served(self, tmp_path: Path): assert body == {"status": "ok"} def test_self_reference_loads_finite_json(self, tmp_path: Path): - """R7. A schema that refers to itself loads as finite JSON. + """A schema that refers to itself still loads as finite JSON. - child is optional. value is a required integer, so an empty object - does not pass. Falsifier: load_routes raises, does not finish within - 5 seconds, or returns a value json.dumps cannot encode. + child is optional. value is required and is an integer, so an empty + object does not pass. Fails if loading raises, does not finish within + 5 seconds, or returns a value that is not finite JSON. """ spec = _openapi( {"/node": {"get": {"responses": _ok( @@ -1023,9 +1002,10 @@ def test_self_reference_loads_finite_json(self, tmp_path: Path): json.dumps(body) async def test_self_reference_http_body_is_finite(self, tmp_path: Path): - """R7 served. The HTTP body is the finite JSON load_routes produced. + """Serving that self-referencing schema returns the same finite JSON. - Falsifier: the server hangs or returns a body that is not that JSON. + Fails if the server hangs or returns a body other than the one that + was loaded. """ spec = _openapi( {"/node": {"get": {"responses": _ok( @@ -1051,10 +1031,10 @@ async def test_self_reference_http_body_is_finite(self, tmp_path: Path): json.dumps(body) def test_mutual_reference_loads_finite_json(self, tmp_path: Path): - """R7. Two schemas that refer to each other load in bounded time. + """Two schemas that refer to each other load as finite JSON. - Falsifier: the cycle raises, hangs past 5 seconds, or yields a value - that is not finite JSON. The required name stays a string. + Fails if the cycle raises, does not finish within 5 seconds, or yields + a value that is not finite JSON. The required name stays a string. """ spec = _openapi( {"/a": {"get": {"responses": _ok( @@ -1086,15 +1066,14 @@ def test_mutual_reference_loads_finite_json(self, tmp_path: Path): json.dumps(body) async def test_required_self_reference_stays_finite(self, tmp_path: Path): - """R7. A required self-reference is followed and still finishes. + """A required self-reference is followed, and loading still finishes. - Node.required includes child, so the generator cannot skip the cycle. - value stays an integer on the node that was asked for and on the - required child, which is that same schema. Nothing past the child - is inspected, so the depth at which expansion stops stays free. + child is required, so the cycle cannot be skipped. value is an integer + on the node and on that child. Nothing inside the child's own child + is checked, so where expansion stops is not fixed. - Falsifier: expansion does not finish within 5 seconds, raises, or - the followed node is an empty object instead of a Node. + Fails if loading or serving does not finish within 5 seconds, raises, + or leaves the child as an empty object. """ spec = _openapi( {"/node": {"get": {"responses": _ok( @@ -1117,15 +1096,16 @@ async def test_required_self_reference_stays_finite(self, tmp_path: Path): ) async def test_required_array_recursion_stays_finite(self, tmp_path: Path): - """R7. A required array of at least two self-refs stays finite. + """A required array of self-referencing items stays finite. - Tree.kids is required, minItems 2, and each item is a Tree. That - forces the cycle and rejects an expansion that branches without bound. - value stays an integer, and at least one kid is a Tree rather than - an empty object. Kid count and anything inside a kid's kids are free. + kids is required, asks for at least two items, and each item is the + same schema. That both follows the cycle and rejects an expansion + that branches without bound. value is an integer, and at least one + kid is a generated object with its own integer value. How many kids + appear, and what is inside a kid's own kids, is not checked. - Falsifier: load or serve does not finish within 5 seconds, raises, - or the array items were not generated as Trees. + Fails if loading or serving does not finish within 5 seconds, raises, + or the array items are empty objects. """ spec = _openapi( {"/tree": {"get": {"responses": _ok( @@ -1152,13 +1132,13 @@ async def test_required_array_recursion_stays_finite(self, tmp_path: Path): ) async def test_required_mutual_recursion_stays_finite(self, tmp_path: Path): - """R7. Mutual recursion with both links required stays finite. + """Mutual recursion stays finite when both links are required. - A.b and B.a are required, so neither side can skip the other. - name stays a string on A and on the required B. B's link back to A - is not inspected. + A must include B, and B must include A, so neither side can skip the + other. name is a string on A and on that B. B's link back to A is + not inspected. - Falsifier: load or serve does not finish within 5 seconds, raises, + Fails if loading or serving does not finish within 5 seconds, raises, or the followed schema is an empty object. """ spec = _openapi( @@ -1206,13 +1186,11 @@ async def _assert_required_recursion( @pytest.mark.parametrize("keyword", ["anyOf", "oneOf"]) def test_union_prefers_non_null_branch(self, keyword: str): - """R8. "string or null" yields a string, even when null is listed first. + """anyOf and oneOf prefer a string over null when null is listed first. - The string branch is an enum, so a generator that ignores the union - and emits an arbitrary string still fails. Calling generate_instance - with only the schema must keep working. - - Falsifier: the result is null, or a string outside the enum. + The string branch is an enum, so an arbitrary string still fails. + generate_instance is called with the schema alone. Fails if the result + is null, or a string other than "alpha" or "beta". """ schema = { keyword: [ @@ -1224,10 +1202,10 @@ def test_union_prefers_non_null_branch(self, keyword: str): assert generated == "alpha" or generated == "beta" def test_allof_contains_every_required_property(self): - """R9. The object contains the required properties of every allOf part. + """An allOf object contains the required properties of every part. - Falsifier: the second part's rate_cents is missing, or a part's - declared type is replaced with an object. + Fails if rate_cents from the second part is missing, or if a property + declared as a string or integer is generated as an object. """ result = generate_instance({ "allOf": [ @@ -1248,10 +1226,10 @@ def test_allof_contains_every_required_property(self): assert _is_json_int(result.get("rate_cents")) def test_const_is_the_generated_value(self, tmp_path: Path): - """R10. The generated value equals the const, including through a spec. + """A const schema generates that exact value, including from a spec file. - Falsifier: const is ignored and a value of that JSON type is invented, - or parse_openapi and load_routes disagree on the fixed body. + Fails if const is ignored and some other value of that JSON type is + invented, or if parse_openapi and load_routes disagree on the body. """ assert generate_instance({"const": 7}) == 7 assert generate_instance({"const": True}) is True @@ -1266,14 +1244,14 @@ def test_const_is_the_generated_value(self, tmp_path: Path): assert parse_openapi(path) == routes def test_example_default_and_enum_survive_ref(self, tmp_path: Path): - """R11. Schema example, default, and enum still win after a $ref. + """example, default, and enum still apply after a schema reference. - Each keyword is on its own referenced schema, so they do not compete. - Enum asserts membership, not which member: the brief does not rank - members. Inline examples of these keywords already stand in the - legacy tests. + Each keyword sits on its own referenced schema, so they do not compete. + The enum value may be any member; which member is not specified. + The same keywords on an inline schema are already covered above. - Falsifier: resolving the ref drops the keyword and emits a free string. + Fails if following the reference drops the keyword and emits some + other string. """ spec = _openapi( {"/label": {"get": {"responses": _ok({ @@ -1298,13 +1276,12 @@ def test_example_default_and_enum_survive_ref(self, tmp_path: Path): assert enum_value == "a" or enum_value == "b" or enum_value == "c" async def test_media_example_wins_on_template_path(self, tmp_path: Path): - """R11. A media-type example is the served body of a template route. - - The schema would otherwise require a different const. The path key - stays written as /invoices/{id}. + """A media-type example is the body served for a template route. - Falsifier: template matching works but the example is discarded, or - the route key is rewritten without the placeholder. + The schema would otherwise require a different constant. The route + key stays written as /invoices/{id}. Fails if the placeholder route + matches but the example is discarded, or if the key is rewritten + without the placeholder. """ spec = _openapi({ "/invoices/{id}": {"get": {"responses": _ok( From 4e052a09e528a564a73f1b2f8a714fff45ff3288 Mon Sep 17 00:00:00 2001 From: Yevhen Vasko Date: Tue, 17 Nov 2026 09:34:04 -0600 Subject: [PATCH 07/10] fix(mock): trailing slash is optional for spec paths too A spec path ending in / (literal or templated) now matches the request with or without the trailing slash. Exact literal matches still win first. Implementation authored by the Factory Coder lane (codex gpt-6.1-sol), repair round 3. FactoryRun: baton-mock-templates-20261117 Built-By: Factory v0.8.29 --- src/baton/mock.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/baton/mock.py b/src/baton/mock.py index 097bef5..52fc3d2 100644 --- a/src/baton/mock.py +++ b/src/baton/mock.py @@ -296,7 +296,7 @@ def add_routes(self, port: int, routes: dict[str, dict[str, Any]]) -> None: self._route_tables[port] = routes templates = [] for path, methods in routes.items(): - segments = path.split("/") + segments = path.rstrip("/").split("/") parameters = [ bool(re.fullmatch(r"\{[^{} /]+\}", segment)) for segment in segments ] @@ -385,6 +385,8 @@ async def _handle( route = routes[path] elif alt_path in routes: route = routes[alt_path] + elif path != "/" and alt_path + "/" in routes: + route = routes[alt_path + "/"] else: route = {} for pattern, methods in self._templates.get(port, []): From 8d1a8f1e3f45ba0f8c4b0654cdec5924ab26f312 Mon Sep 17 00:00:00 2001 From: Yevhen Vasko Date: Tue, 17 Nov 2026 09:34:04 -0600 Subject: [PATCH 08/10] test(mock): spec paths with a trailing slash Tests authored independently by the Factory Tester lane (cursor-agent grok-4.7-high), repair round 3. FactoryRun: baton-mock-templates-20261117 Built-By: Factory v0.8.29 --- tests/test_mock.py | 88 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/tests/test_mock.py b/tests/test_mock.py index ae2ba0c..6c88986 100644 --- a/tests/test_mock.py +++ b/tests/test_mock.py @@ -816,6 +816,94 @@ async def test_non_match_is_json_404(self, method: str, target: str): assert body == {"error": "not found", "path": target} +class TestSpecTrailingSlash: + """A trailing slash is optional on the spec path and on the request. + + `/x/{id}/` matches `/x/1` and `/x/1/`. `/foo/` matches `/foo` and `/foo/`. + When both `/foo` and `/foo/` are registered, a request that matches one + of them exactly gets that path's body. A matching path with no body for + the request method is 404 and names the path that was sent. + """ + + async def test_template_spec_slash_matches_with_or_without_slash(self): + """A template written with a trailing slash matches either request form. + + `/x` and `/x/` do not match, because the placeholder is still required. + `/x/1/extra` does not match either. Fails if the slash on the spec + path makes `/x/1` miss, or if a missing or extra segment is accepted. + """ + routes = {"/x/{id}/": {"GET": {"resource": "item"}}} + async with _running(routes) as port: + for target in ("/x/1", "/x/1/"): + status, body = await _exchange(port, "GET", target) + assert status == 200 + assert body == {"resource": "item"} + for target in ("/x", "/x/", "/x/1/extra"): + status, body = await _exchange(port, "GET", target) + assert status == 404 + assert body == {"error": "not found", "path": target} + + async def test_literal_spec_slash_matches_with_or_without_slash(self): + """A literal path written with a trailing slash matches either request form. + + `/foo/bar` is a different path. Fails if `/foo` misses `/foo/`, or if + a longer path is treated as the same route. + """ + routes = {"/foo/": {"GET": {"resource": "foo"}}} + async with _running(routes) as port: + for target in ("/foo", "/foo/"): + status, body = await _exchange(port, "GET", target) + assert status == 200 + assert body == {"resource": "foo"} + status, body = await _exchange(port, "GET", "/foo/bar") + assert status == 404 + assert body == {"error": "not found", "path": "/foo/bar"} + + async def test_exact_literal_wins_when_both_slash_forms_exist(self): + """Separate `/foo` and `/foo/` routes keep their own bodies. + + The slash form is registered first. A request equal to one of the + two paths gets that path's body. Fails if the slash is stripped and + both requests receive the same body. + """ + routes = { + "/foo/": {"GET": {"which": "slash"}}, + "/foo": {"GET": {"which": "plain"}}, + } + async with _running(routes) as port: + status, body = await _exchange(port, "GET", "/foo") + assert status == 200 + assert body == {"which": "plain"} + status, body = await _exchange(port, "GET", "/foo/") + assert status == 200 + assert body == {"which": "slash"} + + async def test_wrong_method_on_slash_spec_is_404(self): + """A slash spec that has no body for the request method is 404. + + GET still returns the registered body, so a matcher that rejects + every request does not pass. Fails if POST is served as GET, or if + the 404 body omits the path that was sent. + """ + routes = { + "/foo/": {"GET": {"resource": "foo"}}, + "/x/{id}/": {"GET": {"resource": "item"}}, + } + async with _running(routes) as port: + status, body = await _exchange(port, "GET", "/foo") + assert status == 200 + assert body == {"resource": "foo"} + for method, target in ( + ("POST", "/foo"), + ("POST", "/foo/"), + ("POST", "/x/1"), + ("POST", "/x/1/"), + ): + status, body = await _exchange(port, method, target) + assert status == 404 + assert body == {"error": "not found", "path": target} + + class TestSchemaComposition: """Generated values come from the schema, not from a recorded response. From 7cb8f9d1afe1a47a9b94843c5cb4e4f4e040cf2d Mon Sep 17 00:00:00 2001 From: Yevhen Vasko Date: Tue, 17 Nov 2026 12:29:24 -0600 Subject: [PATCH 09/10] fix(mock): keep both allOf compositions and intersect enum/const - A $ref whose target and sibling both have allOf now keeps both lists, so the referenced schema's required fields are not dropped. - allOf intersects enum/const values instead of overwriting them; an empty intersection falls back to the first part and is logged once at debug. Implementation authored by the Factory Coder lane (codex gpt-6.1-sol), repair round 4 (independent review findings). FactoryRun: baton-mock-templates-20261117 Built-By: Factory v0.8.29 --- src/baton/mock.py | 66 ++++++++++++++++++++++++++++++----------------- 1 file changed, 43 insertions(+), 23 deletions(-) diff --git a/src/baton/mock.py b/src/baton/mock.py index 52fc3d2..63d641f 100644 --- a/src/baton/mock.py +++ b/src/baton/mock.py @@ -27,11 +27,11 @@ def _resolve_ref( value: dict, components: dict, seen: frozenset[str] = frozenset(), - unresolved: set[str] | None = None, + diagnostics: set[str] | None = None, ) -> dict: """Follow local component references, including response aliases.""" - if unresolved is None: - unresolved = set() + if diagnostics is None: + diagnostics = set() ref = value.get("$ref") if not ref: return value @@ -45,18 +45,34 @@ def _resolve_ref( else: target = None if not isinstance(target, dict): - if ref not in unresolved: + if ref not in diagnostics: logger.debug("Unresolved mock reference: %s", ref) - unresolved.add(ref) + diagnostics.add(ref) target = {} - resolved = _resolve_ref(target, components, seen | {ref}, unresolved) + resolved = _resolve_ref(target, components, seen | {ref}, diagnostics) siblings = {key: val for key, val in value.items() if key != "$ref"} - return _merge_schema(resolved, siblings) + return _merge_schema(resolved, siblings, diagnostics) -def _merge_schema(left: dict, right: dict) -> dict: - """Combine object properties and requirements for an allOf intersection.""" +def _merge_schema(left: dict, right: dict, diagnostics: set[str] | None = None) -> dict: + """Combine constraints for an allOf intersection.""" merged = {**left, **right} + if "allOf" in left and "allOf" in right: + merged["allOf"] = left["allOf"] + right["allOf"] + if ("enum" in left or "const" in left) and ("enum" in right or "const" in right): + left_values = [left["const"]] if "const" in left else left["enum"] + right_values = [right["const"]] if "const" in right else right["enum"] + values = [value for value in left_values if value in right_values] + if not values: + message = "Empty mock enum intersection; using a value from the first part" + if diagnostics is None or message not in diagnostics: + logger.debug(message) + if diagnostics is not None: + diagnostics.add(message) + values = left_values or right_values or [None] + merged["enum"] = values + if "const" in merged: + merged["const"] = values[0] if "properties" in left or "properties" in right: props = dict(left.get("properties", {})) for name, prop in right.get("properties", {}).items(): @@ -77,20 +93,22 @@ def _merge_schema(left: dict, right: dict) -> dict: def _expand_schema( schema: dict, components: dict, depth: int = 0, - seen: frozenset[str] = frozenset(), unresolved: set[str] | None = None, + seen: frozenset[str] = frozenset(), diagnostics: set[str] | None = None, ) -> dict: ref = schema.get("$ref") if depth >= 32 or ref in seen: return {} - schema = _resolve_ref(schema, components, seen, unresolved) + schema = _resolve_ref(schema, components, seen, diagnostics) if ref: seen = seen | {ref} if "allOf" in schema: merged = {} for part in schema["allOf"]: - expanded = _expand_schema(part, components, depth + 1, seen, unresolved) - merged = _merge_schema(merged, expanded) - schema = _merge_schema(merged, {k: v for k, v in schema.items() if k != "allOf"}) + expanded = _expand_schema(part, components, depth + 1, seen, diagnostics) + merged = _merge_schema(merged, expanded, diagnostics) + schema = _merge_schema( + merged, {k: v for k, v in schema.items() if k != "allOf"}, diagnostics, + ) return schema @@ -98,12 +116,12 @@ def generate_instance( schema: dict, components: dict | None = None, *, _depth: int = 0, _seen: frozenset[str] = frozenset(), _last_ref: str | None = None, _self_repeated: bool = False, - _unresolved: set[str] | None = None, + _diagnostics: set[str] | None = None, ) -> Any: """Generate a random valid instance from a JSON Schema.""" components = components or {} - if _unresolved is None: - _unresolved = set() + if _diagnostics is None: + _diagnostics = set() ref = schema.get("$ref") repeated = ref in _seen # Emit one full child for direct self-reference, then cut its next link. @@ -112,7 +130,7 @@ def generate_instance( return {} schema = _expand_schema( schema, components, seen=_seen - {ref} if repeated else _seen, - unresolved=_unresolved, + diagnostics=_diagnostics, ) if ref: _seen = _seen | {ref} @@ -126,13 +144,15 @@ def generate(child: dict) -> Any: return generate_instance( child, components, _depth=_depth + 1, _seen=_seen, _last_ref=_last_ref, _self_repeated=_self_repeated, - _unresolved=_unresolved, + _diagnostics=_diagnostics, ) for keyword in ("anyOf", "oneOf"): if keyword in schema: base = {k: v for k, v in schema.items() if k != keyword} - branches = [_merge_schema(base, branch) for branch in schema[keyword]] + branches = [ + _merge_schema(base, branch, _diagnostics) for branch in schema[keyword] + ] # A reference may itself describe a null branch. Try all non-null # results before accepting null, keeping declaration order otherwise. for branch in branches: @@ -206,7 +226,7 @@ def parse_openapi(spec_path: str) -> dict[str, dict[str, Any]]: return {} components = spec.get("components", {}) - unresolved: set[str] = set() + diagnostics: set[str] = set() routes: dict[str, dict[str, Any]] = {} for path_str, methods in spec["paths"].items(): @@ -219,7 +239,7 @@ def parse_openapi(spec_path: str) -> dict[str, dict[str, Any]]: # Find the success response responses = operation.get("responses", {}) success_resp = responses.get("200") or responses.get("201") or {} - success_resp = _resolve_ref(success_resp, components, unresolved=unresolved) + success_resp = _resolve_ref(success_resp, components, diagnostics=diagnostics) content = success_resp.get("content", {}) json_content = content.get("application/json", {}) resp_schema = json_content.get("schema", {}) @@ -230,7 +250,7 @@ def parse_openapi(spec_path: str) -> dict[str, dict[str, Any]]: elif "example" in resp_schema: body = resp_schema["example"] elif resp_schema: - body = generate_instance(resp_schema, components, _unresolved=unresolved) + body = generate_instance(resp_schema, components, _diagnostics=diagnostics) else: body = {} From cba4d13344f8a3c1bd859d2ac192a440f67c8f38 Mon Sep 17 00:00:00 2001 From: Yevhen Vasko Date: Tue, 17 Nov 2026 12:29:26 -0600 Subject: [PATCH 10/10] test(mock): allOf with $ref siblings and overlapping enum/const Tests authored independently by the Factory Tester lane (cursor-agent grok-4.7-high), repair round 4. FactoryRun: baton-mock-templates-20261117 Built-By: Factory v0.8.29 --- tests/test_mock.py | 70 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/tests/test_mock.py b/tests/test_mock.py index 6c88986..2e15a56 100644 --- a/tests/test_mock.py +++ b/tests/test_mock.py @@ -1390,3 +1390,73 @@ async def test_media_example_wins_on_template_path(self, tmp_path: Path): status, body = await _exchange(port, "GET", "/invoices/123") assert status == 200 assert body == {"invoice": "kept"} + + async def test_ref_with_sibling_allof_satisfies_both(self, tmp_path: Path): + """A $ref and a sibling allOf both apply when the target is also an allOf. + + Base requires a string id. The response schema refers to Base and adds + extra, which must be the constant "added". The body is loaded from a + spec file and served. Fails if either part is dropped, id is not a + string, or extra is not "added". + """ + spec = _openapi( + {"/item": {"get": {"responses": _ok({ + "$ref": "#/components/schemas/Base", + "allOf": [{ + "type": "object", + "required": ["extra"], + "properties": {"extra": {"const": "added"}}, + }], + })}}}, + schemas={ + "Base": { + "allOf": [{ + "type": "object", + "required": ["id"], + "properties": {"id": {"type": "string"}}, + }] + } + }, + ) + routes = load_routes(_write_spec(tmp_path, spec)) + loaded = routes["/item"]["GET"] + self._assert_id_and_added(loaded) + async with _running(routes) as port: + status, served = await _exchange(port, "GET", "/item") + assert status == 200 + assert served == loaded + self._assert_id_and_added(served) + + @staticmethod + def _assert_id_and_added(body: object) -> None: + assert isinstance(body, dict) + assert isinstance(body.get("id"), str) + assert body.get("extra") == "added" + + def test_allof_overlapping_enums_use_the_shared_value(self): + """allOf of two enums yields a value allowed by every part. + + The only shared member is "allowed". Fails if the result is "wrong" + or any string outside both lists. + """ + schema = { + "allOf": [ + {"type": "string", "enum": ["allowed"]}, + {"type": "string", "enum": ["wrong", "allowed"]}, + ] + } + assert generate_instance(schema) == "allowed" + + def test_allof_const_must_also_be_in_the_enum(self): + """allOf of a const and an enum equals the const when the enum allows it. + + The enum lists "wrong" first, so taking that member fails. Fails if + the result is not "allowed". + """ + schema = { + "allOf": [ + {"type": "string", "enum": ["wrong", "allowed"]}, + {"const": "allowed"}, + ] + } + assert generate_instance(schema) == "allowed"