diff --git a/src/baton/mock.py b/src/baton/mock.py index 2458187..63d641f 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,16 +25,145 @@ logger = logging.getLogger(__name__) -def generate_instance(schema: dict) -> Any: +def _resolve_ref( + value: dict, components: dict, seen: frozenset[str] = frozenset(), + diagnostics: set[str] | None = None, +) -> dict: + """Follow local component references, including response aliases.""" + if diagnostics is None: + diagnostics = set() + 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 diagnostics: + logger.debug("Unresolved mock reference: %s", ref) + diagnostics.add(ref) + target = {} + 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, diagnostics) + + +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(): + 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(), diagnostics: set[str] | None = None, +) -> dict: + ref = schema.get("$ref") + if depth >= 32 or ref in seen: + return {} + 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, 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 + + +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, + _diagnostics: set[str] | None = None, +) -> Any: """Generate a random valid instance from a JSON Schema.""" - if "example" in schema: - return schema["example"] - if "default" in schema: - return schema["default"] - if "enum" in schema: - return schema["enum"][0] + components = components or {} + 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. + # A link back through another schema remains a mutual-recursion cutoff. + if _depth >= 32 or (repeated and (ref != _last_ref or _self_repeated)): + return {} + schema = _expand_schema( + schema, components, seen=_seen - {ref} if repeated else _seen, + diagnostics=_diagnostics, + ) + if ref: + _seen = _seen | {ref} + _last_ref = ref + _self_repeated = repeated + 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, + _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, _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: + 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 +192,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 +200,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(schema.get("minProperties", 0)): + obj[f"key{index + 1}"] = generate(additional) return obj return None @@ -91,7 +225,8 @@ 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", {}) + diagnostics: set[str] = set() routes: dict[str, dict[str, Any]] = {} for path_str, methods in spec["paths"].items(): @@ -104,22 +239,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, diagnostics=diagnostics) 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, _diagnostics=diagnostics) else: body = {} @@ -174,6 +305,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 +314,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.rstrip("/").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 +400,21 @@ 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] + elif path != "/" and 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 diff --git a/tests/test_mock.py b/tests/test_mock.py index 815985f..2e15a56 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,996 @@ async def test_mock_no_spans_without_exporter(self): assert len(spans) == 0 finally: await server.stop() + + +# 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: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + 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) + + +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: + """Small search spec whose hit list refers to an object. + + 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( + { + "/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: + """Load routes in a child process so a recursive schema cannot hang the test. + + A schema this small that does not finish within 5 seconds is treated as + unbounded. + """ + 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 _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 "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: + """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): + """Both /invoices/123 and /invoices/456 return the /invoices/{id} body. + + 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: + 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): + """Each placeholder is one segment, and a missing last segment does not match. + + 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: + 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): + """A trailing slash is still the same template match. + + Fails if /invoices/123/ is rejected or sent to a different route. + """ + 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): + """A query string is ignored when matching a template. + + Fails if /invoices/123?page=1 does not hit /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): + """The literal /collections/wander/search wins over the collection template. + + 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. + + Fails if wander gets the template body, or if every collection id gets + 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): + """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 have + the literal segment b, so it uses /a/{x}/{y}. + + 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"}}, + "/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): + """An extra, missing, or empty segment, or the wrong method, is 404. + + The body is {"error": "not found", "path": }. + None of these targets ends with a slash, so the path is unambiguous. + + 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"}}, + "/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 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. + + 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): + """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): + """The same search body is what the server returns for a wander request. + + 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: + 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): + """A schema reference inside anyOf or oneOf is used, and null loses. + + 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({ + 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): + """allOf of two schema references keeps both required constants. + + 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({ + "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): + """A response that is only a $ref returns that response's JSON 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": { + "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): + """The server returns the body of a response that was given by $ref. + + 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": { + "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): + """A schema that refers to itself still loads as finite JSON. + + 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( + {"$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): + """Serving that self-referencing schema returns the same finite JSON. + + Fails if the server hangs or returns a body other than the one that + was loaded. + """ + 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): + """Two schemas that refer to each other load as finite JSON. + + 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( + {"$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) + + async def test_required_self_reference_stays_finite(self, tmp_path: Path): + """A required self-reference is followed, and loading still finishes. + + 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. + + 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( + {"$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): + """A required array of self-referencing items stays finite. + + 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. + + 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( + {"$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): + """Mutual recursion stays finite when both links are required. + + 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. + + Fails if loading or serving 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): + """anyOf and oneOf prefer a string over null when null is listed first. + + 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: [ + {"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): + """An allOf object contains the required properties of every part. + + 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": [ + { + "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): + """A const schema generates that exact value, including from a spec file. + + 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 + 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): + """example, default, and enum still apply after a schema reference. + + 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. + + Fails if following the reference drops the keyword and emits some + other 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): + """A media-type example is the body served for a template route. + + 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( + 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"} + + 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"