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