Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 40 additions & 5 deletions src/utils/openapi_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,17 @@ def resolve_refs(spec: dict[str, Any]) -> dict[str, Any]:
# Get the components/schemas section for reference resolution
schemas = spec.get("components", {}).get("schemas", {})

def resolve_schema(obj: Any, visited: dict[str, int] | None = None) -> Any:
"""Recursively resolve $ref in an object."""
def resolve_schema(
obj: Any,
visited: dict[str, int] | None = None,
parent_ref: str | None = None,
subtypes_of: str | None = None,
) -> Any:
"""Recursively resolve $ref in an object.

parent_ref is the schema that lists obj as a subtype; subtypes_of is the
schema obj is the body of.
"""
if visited is None:
visited = {}

Expand All @@ -59,16 +68,26 @@ def resolve_schema(obj: Any, visited: dict[str, int] | None = None) -> Any:
target = schemas[schema_name]
if depth == 1:
target = _without_subtypes(target)
# Listed under its parent, a subtype need not repeat the parent's fields:
# they already apply to the schema that holds the list.
if parent_ref:
target = _without_inherited(target, parent_ref)

visited[ref_path] = depth + 1
resolved = resolve_schema(target, visited)
resolved = resolve_schema(target, visited, subtypes_of=ref_path)
visited[ref_path] = depth
return resolved
else:
# Recursively process all values in the dict
result = {}
for key, value in obj.items():
result[key] = resolve_schema(value, visited)
if subtypes_of and key in _SUBTYPE_KEYS and isinstance(value, list):
result[key] = [
resolve_schema(member, visited, parent_ref=subtypes_of)
for member in value
]
else:
result[key] = resolve_schema(value, visited)
return result

elif isinstance(obj, list):
Expand All @@ -85,11 +104,27 @@ def resolve_schema(obj: Any, visited: dict[str, int] | None = None) -> Any:
return spec


_SUBTYPE_KEYS = ("oneOf", "anyOf")


def _without_subtypes(schema: dict[str, Any]) -> dict[str, Any]:
return {
key: value
for key, value in schema.items()
if key not in ("oneOf", "anyOf", "discriminator")
if key not in (*_SUBTYPE_KEYS, "discriminator")
}


def _without_inherited(schema: dict[str, Any], parent_ref: str) -> dict[str, Any]:
"""Drop the allOf entry that extends parent_ref, and allOf itself if nothing is left."""
members = schema.get("allOf")
if not isinstance(members, list):
return schema
kept = [member for member in members if member != {"$ref": parent_ref}]
return {
key: kept if key == "allOf" else value
for key, value in schema.items()
if key != "allOf" or kept
}


Expand Down
108 changes: 101 additions & 7 deletions tests/test_openapi_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,13 +182,107 @@ def test_resolve_polymorphic_refs(self):

schema = resolved["paths"]["/api/test"]["post"]["requestBody"]["content"]["application/json"]["schema"]
assert "$ref" not in json.dumps(schema)
jq_parent, jq_own = schema["oneOf"][0]["allOf"]
# The subtype keeps the fields it inherits, but not the parent's list of subtypes
assert jq_parent["properties"]["type"] == {"type": "string"}
assert jq_parent["required"] == ["type"]
assert "oneOf" not in jq_parent
assert "discriminator" not in jq_parent
assert jq_own["properties"]["expression"] == {"type": "string"}
# The parent states the inherited fields once, so its subtypes list only their own
assert schema["properties"]["type"] == {"type": "string"}
assert schema["required"] == ["type"]
assert schema["oneOf"] == [
{
"type": "object",
"allOf": [{"type": "object", "properties": {"expression": {"type": "string"}}}],
},
{
"type": "object",
"allOf": [{"type": "object", "properties": {"url": {"type": "string"}}}],
},
]

@staticmethod
def _resolved_body(name, schemas):
"""Resolve a spec whose one request body is schema `name`, and return that body."""
ref = {"$ref": f"#/components/schemas/{name}"}
body = {"content": {"application/json": {"schema": ref}}}
spec = {
"paths": {"/api/test": {"post": {"requestBody": body}}},
"components": {"schemas": schemas},
}
resolved = resolve_refs(spec)["paths"]["/api/test"]["post"]["requestBody"]
return resolved["content"]["application/json"]["schema"]

JQ_OWN = {"type": "object", "properties": {"expression": {"type": "string"}}}
JQ = {"type": "object", "allOf": [{"$ref": "#/components/schemas/Action"}, JQ_OWN]}

def test_resolve_subtype_referenced_directly(self):
"""Test that a subtype reached without its parent keeps the fields it inherits."""
schema = self._resolved_body("Action.JQ", {
"Action": {
"required": ["type"],
"type": "object",
"properties": {"type": {"type": "string"}},
"oneOf": [{"$ref": "#/components/schemas/Action.JQ"}],
},
"Action.JQ": self.JQ,
})

assert "$ref" not in json.dumps(schema)
parent, own = schema["allOf"]
assert parent["properties"]["type"] == {"type": "string"}
assert parent["required"] == ["type"]
assert own == self.JQ_OWN

def test_resolve_subtype_listed_inside_a_property(self):
"""Test that a subtype listed by a property, not by its parent, keeps the parent's fields."""
schema = self._resolved_body("Action", {
"Action": {
"type": "object",
"properties": {
"type": {"type": "string"},
"next": {"oneOf": [{"$ref": "#/components/schemas/Action.JQ"}]},
},
},
"Action.JQ": self.JQ,
})

parent, own = schema["properties"]["next"]["oneOf"][0]["allOf"]
assert parent["properties"]["type"] == {"type": "string"}
assert own == self.JQ_OWN

def test_resolve_subtype_keeps_what_its_parent_does_not_state(self):
"""Test that only the listing parent is dropped from a subtype's allOf."""
audited = {"type": "object", "properties": {"createdBy": {"type": "string"}}}
schema = self._resolved_body("Action", {
"Action": {
"type": "object",
"properties": {"type": {"type": "string"}},
"anyOf": [{"$ref": "#/components/schemas/Action.JQ"}],
},
"Audited": audited,
"Action.JQ": {
"allOf": [
{"$ref": "#/components/schemas/Action"},
{"$ref": "#/components/schemas/Audited"},
self.JQ_OWN,
],
},
})

assert schema["anyOf"] == [{"allOf": [audited, self.JQ_OWN]}]

def test_resolve_subtype_with_nothing_of_its_own(self):
"""Test that a subtype adding no fields is left without an empty allOf."""
schema = self._resolved_body("Action", {
"Action": {
"type": "object",
"properties": {"type": {"type": "string"}},
"anyOf": [{"$ref": "#/components/schemas/Action.Noop"}],
},
"Action.Noop": {
"title": "NOOP",
"type": "object",
"allOf": [{"$ref": "#/components/schemas/Action"}],
},
})

assert schema["anyOf"] == [{"title": "NOOP", "type": "object"}]

def test_resolve_refs_in_arrays(self):
"""Test resolving $refs inside arrays."""
Expand Down
Loading