From 51fa791e427e5e53a65ee6bd0f65530848436b66 Mon Sep 17 00:00:00 2001 From: LukasGold <41064839+LukasGold@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:10:13 +0100 Subject: [PATCH 1/3] fix(core): flatten $defs/manual before schema code generation (#229) --- src/osw/core.py | 42 ++++- tests/test_fetch_schema_manual_defs.py | 204 +++++++++++++++++++++++++ 2 files changed, 244 insertions(+), 2 deletions(-) create mode 100644 tests/test_fetch_schema_manual_defs.py diff --git a/src/osw/core.py b/src/osw/core.py index 384517b7..49001022 100644 --- a/src/osw/core.py +++ b/src/osw/core.py @@ -530,6 +530,42 @@ def _explicitly_set_empty(entity: OswBaseModel, jsondata: dict) -> dict: } +def _flatten_manual_definitions(schema: dict) -> dict: + """Merge `$defs/manual` into the schema root, like oold's + merge_generated_definitions does for `$defs/generated`. + + Hand-authored schema pages keep their schema in `$defs/manual`. A `$ref` to + such a page with additional keys next to it cannot be resolved by the code + generator unless the definition is flattened. Every root `$ref` and every + `allOf` entry pointing to `#/$defs/manual` is removed, existing root keys win. + The schema is left unchanged if `$defs/manual` is not referenced. + Limit: pointers below `#/$defs/manual/...` are not rewritten, consistent + with `$defs/generated`. + """ + manual_ref = "#/$defs/manual" + manual_content = schema.get("$defs", {}).get("manual") + if not manual_content: + return schema + is_manual_ref = lambda item: ( + isinstance(item, dict) and item.get("$ref") == manual_ref + ) + has_root_ref = schema.get("$ref") == manual_ref + has_allof_ref = any(is_manual_ref(item) for item in schema.get("allOf", [])) + if not (has_root_ref or has_allof_ref): + return schema + if has_root_ref: + schema.pop("$ref") + if has_allof_ref: + schema["allOf"] = [i for i in schema["allOf"] if not is_manual_ref(i)] + if not schema["allOf"]: + del schema["allOf"] + schema = merge_deep(deepcopy(manual_content), schema) + schema["$defs"].pop("manual", None) + if not schema["$defs"]: + del schema["$defs"] + return schema + + class OSW(BaseModel): """Bundles core functionalities of OpenSemanticWorld (OSW)""" @@ -1069,8 +1105,10 @@ def _fetch_schema( else: schema_str = "" if page.get_slot_content("jsonschema"): - schema = merge_generated_definitions( - deepcopy(page.get_slot_content("jsonschema")) + schema = _flatten_manual_definitions( + merge_generated_definitions( + deepcopy(page.get_slot_content("jsonschema")) + ) ) schema_str = json.dumps(schema) if (schema_str is None) or (schema_str == ""): diff --git a/tests/test_fetch_schema_manual_defs.py b/tests/test_fetch_schema_manual_defs.py new file mode 100644 index 00000000..9bfa6b52 --- /dev/null +++ b/tests/test_fetch_schema_manual_defs.py @@ -0,0 +1,204 @@ +"""Tests for flattening `$defs/manual` before code generation in fetch_schema. + +Hand-authored schema pages keep their schema in `$defs/manual`. Like +`$defs/generated`, it has to be merged into the schema root, otherwise +datamodel-code-generator cannot resolve a `$ref` to such a page that has +additional keys next to it. Fully offline. +""" + +import osw.core as osw_core +from osw.core import OSW, _flatten_manual_definitions +from osw.wtsite import WtPage + + +def ref(title): + return f"/wiki/Category:{title}?action=raw&slot=jsonschema" + + +class OfflineSite: + def get_cache_enabled(self): + return False + + def enable_cache(self): + pass + + def disable_cache(self): + pass + + def get_page(self, *args, **kwargs): + raise AssertionError("online fetch attempted") + + +def fetch_offline(schemas, monkeypatch, tmp_path): + pages = {} + for name, schema in schemas.items(): + page = WtPage(title=f"Category:{name}", do_init=False) + page.exists = True + page.set_slot_content("jsonschema", schema) + pages[f"Category:{name}"] = page + monkeypatch.setattr(osw_core, "get_model_dir_path", lambda: str(tmp_path)) + return OSW.construct(site=OfflineSite()).fetch_schema( + OSW.FetchSchemaParam( + schema_title="Category:Test", mode="replace", offline_pages=pages + ) + ) + + +def test_item_via_defs_manual_with_extra_key_beside_ref(monkeypatch, tmp_path): + schemas = { + "Item": { + "allOf": [{"$ref": "#/$defs/manual"}], + "$defs": {"manual": {"type": "string"}}, + }, + "Test": { + "type": "object", + "title": "Test", + "properties": { + "files": { + "type": "array", + "items": {"title*": {"en": "x"}, "$ref": ref("Item")}, + } + }, + }, + } + fetch_offline(schemas, monkeypatch, tmp_path) + + +def test_hand_authored_shape_with_generated_pointing_to_manual(monkeypatch, tmp_path): + schemas = { + "WikiFile": { + "allOf": [{"$ref": "#/$defs/generated"}], + "title": "WikiFile", + "$defs": { + "generated": { + "allOf": [{"$ref": "#/$defs/manual"}], + "uuid": "00000000-0000-4000-8000-000000000001", + "title": "WikiFile", + "title*": {"en": "Wiki File"}, + }, + "manual": {"type": "string", "anyOf": [{"pattern": "^File:.*"}]}, + }, + }, + "Test": { + "type": "object", + "title": "Test", + "properties": { + "files": { + "type": "array", + "items": {"title*": {"en": "x"}, "$ref": ref("WikiFile")}, + } + }, + }, + } + fetch_offline(schemas, monkeypatch, tmp_path) + + +def test_object_rooted_manual_used_as_allof_mixin(monkeypatch, tmp_path): + schemas = { + "Mixin": { + "allOf": [{"$ref": "#/$defs/manual"}], + "$defs": { + "manual": { + "type": "object", + "title": "Mixin", + "properties": { + "values": { + "type": "array", + "items": {"title*": {"en": "x"}, "$ref": ref("Item")}, + } + }, + } + }, + }, + "Item": { + "allOf": [{"$ref": "#/$defs/manual"}], + "$defs": {"manual": {"type": "string"}}, + }, + "Test": {"type": "object", "title": "Test", "allOf": [{"$ref": ref("Mixin")}]}, + } + fetch_offline(schemas, monkeypatch, tmp_path) + + +def test_helper_root_ref_form(): + schema = { + "$ref": "#/$defs/manual", + "$defs": {"manual": {"type": "string"}}, + } + assert _flatten_manual_definitions(schema) == {"type": "string"} + + +def test_helper_allof_form(): + schema = { + "allOf": [{"$ref": "#/$defs/manual"}, {"$ref": "/wiki/Category:Other"}], + "$defs": { + "manual": {"type": "object", "properties": {"a": {"type": "string"}}} + }, + } + assert _flatten_manual_definitions(schema) == { + "allOf": [{"$ref": "/wiki/Category:Other"}], + "type": "object", + "properties": {"a": {"type": "string"}}, + } + + +def test_helper_keeps_other_defs(): + schema = { + "allOf": [{"$ref": "#/$defs/manual"}], + "$defs": {"manual": {"type": "string"}, "other": {"type": "number"}}, + } + assert _flatten_manual_definitions(schema) == { + "type": "string", + "$defs": {"other": {"type": "number"}}, + } + + +def test_helper_unreferenced_manual_unchanged(): + schema = {"title": "T", "$defs": {"manual": {"type": "string"}}} + expected = {"title": "T", "$defs": {"manual": {"type": "string"}}} + assert _flatten_manual_definitions(schema) == expected + + +def test_helper_preserves_root_pointer_inside_manual(): + schema = { + "allOf": [{"$ref": "#/$defs/manual"}], + "$defs": { + "manual": { + "type": "object", + "properties": {"child": {"$ref": "#"}}, + } + }, + } + result = _flatten_manual_definitions(schema) + assert result["properties"]["child"] == {"$ref": "#"} + + +def test_helper_root_keys_win_over_manual_keys(): + schema = { + "title": "Root", + "allOf": [{"$ref": "#/$defs/manual"}], + "$defs": {"manual": {"title": "Manual", "type": "string"}}, + } + result = _flatten_manual_definitions(schema) + assert result["title"] == "Root" + assert result["type"] == "string" + assert "$defs" not in result + + +def test_helper_root_ref_and_allof_entry_both_removed(): + schema = { + "$ref": "#/$defs/manual", + "allOf": [{"$ref": "#/$defs/manual"}], + "$defs": {"manual": {"type": "string"}}, + } + result = _flatten_manual_definitions(schema) + assert result == {"type": "string"} + + +def test_helper_two_allof_entries_both_removed(): + schema = { + "allOf": [{"$ref": "#/$defs/manual"}, {"$ref": "#/$defs/manual"}], + "$defs": {"manual": {"type": "string"}}, + } + result = _flatten_manual_definitions(schema) + assert "#/$defs/manual" not in str(result) + assert result == {"type": "string"} From 8db86738a73756f33ddb6ee875600836d45621a2 Mon Sep 17 00:00:00 2001 From: LukasGold <41064839+LukasGold@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:18:40 +0100 Subject: [PATCH 2/3] Revert "fix(core): flatten $defs/manual before schema code generation (#229)" This reverts commit 51fa791e427e5e53a65ee6bd0f65530848436b66. --- src/osw/core.py | 42 +---- tests/test_fetch_schema_manual_defs.py | 204 ------------------------- 2 files changed, 2 insertions(+), 244 deletions(-) delete mode 100644 tests/test_fetch_schema_manual_defs.py diff --git a/src/osw/core.py b/src/osw/core.py index dcac5905..3dbcd4de 100644 --- a/src/osw/core.py +++ b/src/osw/core.py @@ -548,42 +548,6 @@ def _explicitly_set_empty(entity: OswBaseModel, jsondata: dict) -> dict: } -def _flatten_manual_definitions(schema: dict) -> dict: - """Merge `$defs/manual` into the schema root, like oold's - merge_generated_definitions does for `$defs/generated`. - - Hand-authored schema pages keep their schema in `$defs/manual`. A `$ref` to - such a page with additional keys next to it cannot be resolved by the code - generator unless the definition is flattened. Every root `$ref` and every - `allOf` entry pointing to `#/$defs/manual` is removed, existing root keys win. - The schema is left unchanged if `$defs/manual` is not referenced. - Limit: pointers below `#/$defs/manual/...` are not rewritten, consistent - with `$defs/generated`. - """ - manual_ref = "#/$defs/manual" - manual_content = schema.get("$defs", {}).get("manual") - if not manual_content: - return schema - is_manual_ref = lambda item: ( - isinstance(item, dict) and item.get("$ref") == manual_ref - ) - has_root_ref = schema.get("$ref") == manual_ref - has_allof_ref = any(is_manual_ref(item) for item in schema.get("allOf", [])) - if not (has_root_ref or has_allof_ref): - return schema - if has_root_ref: - schema.pop("$ref") - if has_allof_ref: - schema["allOf"] = [i for i in schema["allOf"] if not is_manual_ref(i)] - if not schema["allOf"]: - del schema["allOf"] - schema = merge_deep(deepcopy(manual_content), schema) - schema["$defs"].pop("manual", None) - if not schema["$defs"]: - del schema["$defs"] - return schema - - class OSW(BaseModel): """Bundles core functionalities of OpenSemanticWorld (OSW)""" @@ -1123,10 +1087,8 @@ def _fetch_schema( else: schema_str = "" if page.get_slot_content("jsonschema"): - schema = _flatten_manual_definitions( - merge_generated_definitions( - deepcopy(page.get_slot_content("jsonschema")) - ) + schema = merge_generated_definitions( + deepcopy(page.get_slot_content("jsonschema")) ) schema_str = json.dumps(schema) if (schema_str is None) or (schema_str == ""): diff --git a/tests/test_fetch_schema_manual_defs.py b/tests/test_fetch_schema_manual_defs.py deleted file mode 100644 index 9bfa6b52..00000000 --- a/tests/test_fetch_schema_manual_defs.py +++ /dev/null @@ -1,204 +0,0 @@ -"""Tests for flattening `$defs/manual` before code generation in fetch_schema. - -Hand-authored schema pages keep their schema in `$defs/manual`. Like -`$defs/generated`, it has to be merged into the schema root, otherwise -datamodel-code-generator cannot resolve a `$ref` to such a page that has -additional keys next to it. Fully offline. -""" - -import osw.core as osw_core -from osw.core import OSW, _flatten_manual_definitions -from osw.wtsite import WtPage - - -def ref(title): - return f"/wiki/Category:{title}?action=raw&slot=jsonschema" - - -class OfflineSite: - def get_cache_enabled(self): - return False - - def enable_cache(self): - pass - - def disable_cache(self): - pass - - def get_page(self, *args, **kwargs): - raise AssertionError("online fetch attempted") - - -def fetch_offline(schemas, monkeypatch, tmp_path): - pages = {} - for name, schema in schemas.items(): - page = WtPage(title=f"Category:{name}", do_init=False) - page.exists = True - page.set_slot_content("jsonschema", schema) - pages[f"Category:{name}"] = page - monkeypatch.setattr(osw_core, "get_model_dir_path", lambda: str(tmp_path)) - return OSW.construct(site=OfflineSite()).fetch_schema( - OSW.FetchSchemaParam( - schema_title="Category:Test", mode="replace", offline_pages=pages - ) - ) - - -def test_item_via_defs_manual_with_extra_key_beside_ref(monkeypatch, tmp_path): - schemas = { - "Item": { - "allOf": [{"$ref": "#/$defs/manual"}], - "$defs": {"manual": {"type": "string"}}, - }, - "Test": { - "type": "object", - "title": "Test", - "properties": { - "files": { - "type": "array", - "items": {"title*": {"en": "x"}, "$ref": ref("Item")}, - } - }, - }, - } - fetch_offline(schemas, monkeypatch, tmp_path) - - -def test_hand_authored_shape_with_generated_pointing_to_manual(monkeypatch, tmp_path): - schemas = { - "WikiFile": { - "allOf": [{"$ref": "#/$defs/generated"}], - "title": "WikiFile", - "$defs": { - "generated": { - "allOf": [{"$ref": "#/$defs/manual"}], - "uuid": "00000000-0000-4000-8000-000000000001", - "title": "WikiFile", - "title*": {"en": "Wiki File"}, - }, - "manual": {"type": "string", "anyOf": [{"pattern": "^File:.*"}]}, - }, - }, - "Test": { - "type": "object", - "title": "Test", - "properties": { - "files": { - "type": "array", - "items": {"title*": {"en": "x"}, "$ref": ref("WikiFile")}, - } - }, - }, - } - fetch_offline(schemas, monkeypatch, tmp_path) - - -def test_object_rooted_manual_used_as_allof_mixin(monkeypatch, tmp_path): - schemas = { - "Mixin": { - "allOf": [{"$ref": "#/$defs/manual"}], - "$defs": { - "manual": { - "type": "object", - "title": "Mixin", - "properties": { - "values": { - "type": "array", - "items": {"title*": {"en": "x"}, "$ref": ref("Item")}, - } - }, - } - }, - }, - "Item": { - "allOf": [{"$ref": "#/$defs/manual"}], - "$defs": {"manual": {"type": "string"}}, - }, - "Test": {"type": "object", "title": "Test", "allOf": [{"$ref": ref("Mixin")}]}, - } - fetch_offline(schemas, monkeypatch, tmp_path) - - -def test_helper_root_ref_form(): - schema = { - "$ref": "#/$defs/manual", - "$defs": {"manual": {"type": "string"}}, - } - assert _flatten_manual_definitions(schema) == {"type": "string"} - - -def test_helper_allof_form(): - schema = { - "allOf": [{"$ref": "#/$defs/manual"}, {"$ref": "/wiki/Category:Other"}], - "$defs": { - "manual": {"type": "object", "properties": {"a": {"type": "string"}}} - }, - } - assert _flatten_manual_definitions(schema) == { - "allOf": [{"$ref": "/wiki/Category:Other"}], - "type": "object", - "properties": {"a": {"type": "string"}}, - } - - -def test_helper_keeps_other_defs(): - schema = { - "allOf": [{"$ref": "#/$defs/manual"}], - "$defs": {"manual": {"type": "string"}, "other": {"type": "number"}}, - } - assert _flatten_manual_definitions(schema) == { - "type": "string", - "$defs": {"other": {"type": "number"}}, - } - - -def test_helper_unreferenced_manual_unchanged(): - schema = {"title": "T", "$defs": {"manual": {"type": "string"}}} - expected = {"title": "T", "$defs": {"manual": {"type": "string"}}} - assert _flatten_manual_definitions(schema) == expected - - -def test_helper_preserves_root_pointer_inside_manual(): - schema = { - "allOf": [{"$ref": "#/$defs/manual"}], - "$defs": { - "manual": { - "type": "object", - "properties": {"child": {"$ref": "#"}}, - } - }, - } - result = _flatten_manual_definitions(schema) - assert result["properties"]["child"] == {"$ref": "#"} - - -def test_helper_root_keys_win_over_manual_keys(): - schema = { - "title": "Root", - "allOf": [{"$ref": "#/$defs/manual"}], - "$defs": {"manual": {"title": "Manual", "type": "string"}}, - } - result = _flatten_manual_definitions(schema) - assert result["title"] == "Root" - assert result["type"] == "string" - assert "$defs" not in result - - -def test_helper_root_ref_and_allof_entry_both_removed(): - schema = { - "$ref": "#/$defs/manual", - "allOf": [{"$ref": "#/$defs/manual"}], - "$defs": {"manual": {"type": "string"}}, - } - result = _flatten_manual_definitions(schema) - assert result == {"type": "string"} - - -def test_helper_two_allof_entries_both_removed(): - schema = { - "allOf": [{"$ref": "#/$defs/manual"}, {"$ref": "#/$defs/manual"}], - "$defs": {"manual": {"type": "string"}}, - } - result = _flatten_manual_definitions(schema) - assert "#/$defs/manual" not in str(result) - assert result == {"type": "string"} From 0dfc8d6725c91b7fc8152ef1806073ed91299f61 Mon Sep 17 00:00:00 2001 From: LukasGold <41064839+LukasGold@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:06:57 +0100 Subject: [PATCH 3/3] fix(core): resolve local root pointers of fetched schemas (#229) - merge targets of local $ref and allOf pointers at the root into the root - root keys win; $defs/generated merge order unchanged - replaces the reverted $defs/manual flattening --- src/osw/core.py | 78 +++++- .../test_fetch_schema_local_root_pointers.py | 241 ++++++++++++++++++ 2 files changed, 317 insertions(+), 2 deletions(-) create mode 100644 tests/test_fetch_schema_local_root_pointers.py diff --git a/src/osw/core.py b/src/osw/core.py index 3dbcd4de..1316ea39 100644 --- a/src/osw/core.py +++ b/src/osw/core.py @@ -474,6 +474,78 @@ def strip(target, generated, is_root): return removed +def _local_pointer_target(schema: dict, ref: Any) -> Optional[dict]: + """Return the dict a local JSON pointer ('#/...') points to in the schema + document, or None if the pointer is not local, bare, or unresolvable.""" + if not isinstance(ref, str) or not ref.startswith("#/"): + return None + node = schema + for token in ref[2:].split("/"): + token = token.replace("~1", "/").replace("~0", "~") + if not isinstance(node, dict) or token not in node: + return None + node = node[token] + return node if isinstance(node, dict) else None + + +def _resolve_local_root_pointers(schema: dict) -> dict: + """Inline local JSON pointers ('#/...') held by the root '$ref' or by entries + of the root 'allOf' of a schema. + + The code generator copies the root of a referenced schema into the referencing + node, where a local pointer would be looked up in the wrong document. The + pointer target is merged first, the keys of the node holding the pointer win + (as in resolveSchema of MwJson_util.js). Unresolvable pointers, remote + references and a pointer that repeats (cycle) are left unchanged. '$defs' is + kept. The input is not modified. + + Limit: local pointers in the root 'anyOf'/'oneOf', in 'properties' and in + content that was inlined from a target are not resolved. + """ + schema = deepcopy(schema) + resolved = set() + while True: + ref = schema.get("$ref") + target = _local_pointer_target(schema, ref) + if target is not None: + if ref in resolved: + break + resolved.add(ref) + rest = {k: v for k, v in schema.items() if k != "$ref"} + schema = merge_deep(deepcopy(target), rest) + continue + all_of = schema.get("allOf") + if not isinstance(all_of, list): + break + refs = [ + entry["$ref"] + for entry in all_of + if isinstance(entry, dict) + and _local_pointer_target(schema, entry.get("$ref")) is not None + ] + if not refs or any(r in resolved for r in refs): + break + base: dict = {} + kept = [] + for entry in all_of: + target = ( + _local_pointer_target(schema, entry.get("$ref")) + if isinstance(entry, dict) + else None + ) + if target is None: + kept.append(entry) + continue + resolved.add(entry["$ref"]) + entry_rest = {k: v for k, v in entry.items() if k != "$ref"} + base = merge_deep(base, merge_deep(deepcopy(target), entry_rest)) + rest = {k: v for k, v in schema.items() if k != "allOf"} + if kept: + rest["allOf"] = kept + schema = merge_deep(base, rest) + return schema + + # Reusable type definitions class OverwriteOptions(Enum): """Options for overwriting properties""" @@ -1087,8 +1159,10 @@ def _fetch_schema( else: schema_str = "" if page.get_slot_content("jsonschema"): - schema = merge_generated_definitions( - deepcopy(page.get_slot_content("jsonschema")) + schema = _resolve_local_root_pointers( + merge_generated_definitions( + deepcopy(page.get_slot_content("jsonschema")) + ) ) schema_str = json.dumps(schema) if (schema_str is None) or (schema_str == ""): diff --git a/tests/test_fetch_schema_local_root_pointers.py b/tests/test_fetch_schema_local_root_pointers.py new file mode 100644 index 00000000..689a3e94 --- /dev/null +++ b/tests/test_fetch_schema_local_root_pointers.py @@ -0,0 +1,241 @@ +"""Local JSON pointers at the root of a fetched schema are resolved, fully offline.""" + +import json +from copy import deepcopy + +import osw.core as osw_core +from osw.core import OSW, _resolve_local_root_pointers +from osw.wtsite import WtPage + +OTHER = {"other": {"type": "object", "properties": {"o": {"type": "string"}}}} + + +def ref(title): + return f"/wiki/Category:{title}?action=raw&slot=jsonschema" + + +TEST_PAGE = { + "type": "object", + "title": "Test", + "properties": { + "files": { + "type": "array", + "items": {"title*": {"en": "x"}, "$ref": ref("Item")}, + } + }, +} + + +class OfflineSite: + def get_cache_enabled(self): + return False + + def enable_cache(self): + pass + + def disable_cache(self): + pass + + def get_page(self, *args, **kwargs): + raise AssertionError("online fetch attempted") + + +def fetch_offline(schemas, monkeypatch, tmp_path): + pages = {} + for name, schema in schemas.items(): + page = WtPage(title=f"Category:{name}", do_init=False) + page.exists = True + page.set_slot_content("jsonschema", schema) + pages[f"Category:{name}"] = page + monkeypatch.setattr(osw_core, "get_model_dir_path", lambda: str(tmp_path)) + return OSW.construct(site=OfflineSite()).fetch_schema( + OSW.FetchSchemaParam( + schema_title="Category:Test", mode="replace", offline_pages=pages + ) + ) + + +def fetch_item(item, monkeypatch, tmp_path, **extra): + fetch_offline({"Test": TEST_PAGE, "Item": item, **extra}, monkeypatch, tmp_path) + code = (tmp_path / "entity.py").read_text(encoding="utf-8") + written = json.loads((tmp_path / "Item.json").read_text(encoding="utf-8")) + return code, written + + +def test_all_of_local_pointer(monkeypatch, tmp_path): + code, _ = fetch_item( + {"allOf": [{"$ref": "#/$defs/other"}], "$defs": OTHER}, monkeypatch, tmp_path + ) + assert "o: " in code + + +def test_chain_via_generated(monkeypatch, tmp_path): + item = { + "allOf": [{"$ref": "#/$defs/generated"}], + "title": "Item", + "$defs": {"generated": {"allOf": [{"$ref": "#/$defs/other"}]}, **OTHER}, + } + code, _ = fetch_item(item, monkeypatch, tmp_path) + assert "o: " in code + + +def test_root_ref_local_pointer(monkeypatch, tmp_path): + item = {"$ref": "#/$defs/other", "title": "Item", "$defs": OTHER} + code, _ = fetch_item(item, monkeypatch, tmp_path) + files_line = next( + line.strip() for line in code.splitlines() if line.strip().startswith("files:") + ) + assert "Any" not in files_line + class_name = files_line.split("list[")[1].split("]")[0] + assert f"class {class_name}(" in code + assert "o: " in code + + +def test_convention_shape(monkeypatch, tmp_path): + item = { + "allOf": [{"$ref": "#/$defs/generated"}], + "type": "object", + "title": "Item", + "properties": {"hand": {"type": "string"}}, + "$defs": { + "generated": { + "type": "object", + "title": "GenItem", + "properties": {"gen": {"type": "string"}}, + } + }, + } + code, _ = fetch_item(item, monkeypatch, tmp_path) + assert "hand: " in code + assert "gen: " in code + + +def test_remote_all_of_kept(monkeypatch, tmp_path): + parent = { + "type": "object", + "title": "Parent", + "properties": {"p": {"type": "string"}}, + } + item = { + "allOf": [{"$ref": ref("Parent")}, {"$ref": "#/$defs/other"}], + "title": "Item", + "$defs": OTHER, + } + _, written = fetch_item(item, monkeypatch, tmp_path, Parent=parent) + refs = [e.get("$ref", "") for e in written["allOf"]] + assert any(r.endswith("Parent.json") for r in refs) + assert "#/$defs/other" not in refs + + +def test_merge_order(monkeypatch, tmp_path): + item = { + "allOf": [{"$ref": "#/$defs/generated"}], + "title": "Item", + "type": "object", + "@context": [{"r": "ex:r"}], + "properties": {"p": {"title": "Root title"}}, + "$defs": { + "generated": { + "type": "object", + "@context": ["/wiki/Category:X?action=raw", {"g": "ex:g"}], + "properties": { + "p": { + "type": "string", + "title": "Gen title", + "description": "gen desc", + } + }, + } + }, + } + _, written = fetch_item(item, monkeypatch, tmp_path) + prop = written["properties"]["p"] + assert prop["title"] == "Root title" + assert prop["type"] == "string" + assert prop["description"] == "gen desc" + context = written["@context"] + assert context.index({"g": "ex:g"}) < context.index({"r": "ex:r"}) + + +def test_root_keys_win(): + schema = { + "$ref": "#/$defs/a", + "title": "Root", + "$defs": {"a": {"title": "A", "type": "object"}}, + } + result = _resolve_local_root_pointers(schema) + assert result["title"] == "Root" + assert result["type"] == "object" + assert "$ref" not in result + assert "$defs" in result + + +def test_later_all_of_entry_wins(): + schema = { + "allOf": [{"$ref": "#/$defs/a"}, {"$ref": "#/$defs/b"}], + "$defs": {"a": {"title": "A", "x": 1}, "b": {"title": "B", "y": 2}}, + } + result = _resolve_local_root_pointers(schema) + assert result["title"] == "B" + assert result["x"] == 1 and result["y"] == 2 + assert "allOf" not in result + + +def test_cycle_terminates(): + schema = { + "allOf": [{"$ref": "#/$defs/a"}], + "$defs": { + "a": {"allOf": [{"$ref": "#/$defs/b"}]}, + "b": {"allOf": [{"$ref": "#/$defs/a"}]}, + }, + } + result = _resolve_local_root_pointers(schema) + assert result["allOf"] == [{"$ref": "#/$defs/a"}] + + +def test_null_defs_left_unchanged(): + schema = {"allOf": [{"$ref": "#/$defs/x"}], "$defs": None} + assert _resolve_local_root_pointers(schema) == schema + + +def test_missing_target_left_unchanged(): + schema = {"$ref": "#/$defs/x", "allOf": [{"$ref": "#/$defs/y"}], "$defs": {}} + assert _resolve_local_root_pointers(schema) == schema + + +def test_remote_entries_kept_in_order(): + schema = { + "allOf": [ + {"$ref": "/wiki/Category:A?action=raw&slot=jsonschema"}, + {"$ref": "#/$defs/a"}, + {"$ref": "/wiki/Category:B?action=raw&slot=jsonschema"}, + ], + "$defs": {"a": {"type": "object"}}, + } + result = _resolve_local_root_pointers(schema) + assert result["allOf"] == [ + {"$ref": "/wiki/Category:A?action=raw&slot=jsonschema"}, + {"$ref": "/wiki/Category:B?action=raw&slot=jsonschema"}, + ] + assert result["type"] == "object" + + +def test_bare_hash_untouched(): + schema = {"$ref": "#", "allOf": [{"$ref": "#"}]} + assert _resolve_local_root_pointers(schema) == schema + + +def test_pointer_escapes(): + schema = {"$ref": "#/$defs/a~1b~0c", "$defs": {"a/b~c": {"type": "object"}}} + assert _resolve_local_root_pointers(schema)["type"] == "object" + + +def test_input_not_mutated(): + schema = { + "allOf": [{"$ref": "#/$defs/a"}], + "$ref": "#/$defs/a", + "$defs": {"a": {"title": "A", "list": [1]}}, + } + before = deepcopy(schema) + _resolve_local_root_pointers(schema) + assert schema == before