diff --git a/src/osw/core.py b/src/osw/core.py index 55605129..3dbcd4de 100644 --- a/src/osw/core.py +++ b/src/osw/core.py @@ -204,20 +204,38 @@ def read_file_if_exists(path: str) -> str: return f.read() +SCHEMA_DEF_KEY = "$defs" +"""Keyword for schema definitions, see AggregateGeneratedSchemasParam.def_key""" +SCHEMA_GEN_DEF_KEY = "generated" +"""Key of the generated section, see AggregateGeneratedSchemasParam.gen_def_key""" + + def remove_generated_schema_section( - schema: dict, def_key: str = "$defs", gen_def_key: str = "generated" -) -> dict: - """Removes the generated section and the allOf entry that points to it. + schema: Any, + def_key: str = SCHEMA_DEF_KEY, + gen_def_key: str = SCHEMA_GEN_DEF_KEY, +) -> Any: + """Removes the generated section and every reference that points to it. aggregate_generated_schemas() merges into an existing generated section and merge_deep() concatenates arrays, so a stale 'required' entry or 'type' would survive every regeneration. Mirrors osl.util.postProcessPage in PageBot.js of - mediawiki-extensions-OpenSemanticLab. Modifies schema in place. + mediawiki-extensions-OpenSemanticLab, which drops the allOf entry and, with + generate_root_ref, the root $ref. Modifies schema in place and returns it. + + A schema that is not an object is returned unchanged. get_slot_content() + returns whatever the slot holds, and a slot stored with a non-json content + model gives a string, for which raising here aborted the whole upload. """ + if not isinstance(schema, dict): + return schema gen_def_pointer = f"#/{def_key}/{gen_def_key}" defs = schema.get(def_key) if isinstance(defs, dict): defs.pop(gen_def_key, None) + # generate_root_ref=True points the root $ref at the section instead of allOf + if schema.get("$ref") == gen_def_pointer: + del schema["$ref"] if isinstance(schema.get("allOf"), list): schema["allOf"] = [ entry @@ -2569,8 +2587,17 @@ def store_entity_( and overwrite_class_param.overwrite == AddOverwriteClassOptions.keep_existing ) + # _apply_overwrite_policy() replaces jsondata, header and footer for + # this policy but returns the page with its remote jsonschema slot, + # so the regeneration below has to start from an empty schema to + # keep the promise that nothing of the remote page survives. + replaced_remote = ( + overwrite_class_param.overwrite + == AddOverwriteClassOptions.replace_remote + ) if not kept_existing and len(meta_category_templates.keys()) > 0: generated_schemas = {} + generation_failed = False try: jsondata = page.get_slot_content("jsondata") if param.remove_empty: @@ -2588,6 +2615,9 @@ def store_entity_( ) generated_schemas[key] = json.loads(schema_str) except Exception as e: + # the loop stops at the first template that fails, so what + # it collected so far is an incomplete generation + generation_failed = True _logger.error( f"Schema generation from template failed for {entity_}: {e}" ) @@ -2601,36 +2631,64 @@ def store_entity_( mode == AggregateGeneratedSchemasParamMode.DEFINITIONS_SECTION ) - stored_schema = page.get_slot_content("jsonschema") or {} - # Regenerate the generated section from scratch. Skip this when - # the generation failed, so the stored section is kept. - if definitions and len(generated_schemas) > 0: - reset_generated_jsonld_context( - stored_schema, - isinstance(stored_schema.get("$defs"), dict) - and "generated" in stored_schema["$defs"], - ) - remove_generated_schema_section(stored_schema) - if definitions: - for generated_schema in generated_schemas.values(): - if "@context" in generated_schema: - merge_generated_jsonld_context( - stored_schema, generated_schema.pop("@context") + # Leave the stored slot alone unless every template rendered. + # The form editor aborts the save in the same case: writing only + # the part that did render would replace the stored section with + # a fragment and drop what the failing templates contribute. + if generated_schemas and not generation_failed: + stored_schema = page.get_slot_content("jsonschema") + if not isinstance(stored_schema, dict): + if stored_schema: + _logger.warning( + f"The jsonschema slot of '{entity_title}' does " + "not hold an object and is replaced." ) - new_schema = aggregate_generated_schemas( - AggregateGeneratedSchemasParam( - target_schema=stored_schema, - generated_schemas=generated_schemas, - mode=mode, + stored_schema = {} + if replaced_remote: + stored_schema = {} + had_generated_section = ( + isinstance(stored_schema.get(SCHEMA_DEF_KEY), dict) + and SCHEMA_GEN_DEF_KEY in stored_schema[SCHEMA_DEF_KEY] ) - ).aggregated_schema - if definitions and isinstance( - (new_schema.get("$defs") or {}).get("generated"), dict - ): - strip_root_members_superseded_by_generated( - new_schema, new_schema["$defs"]["generated"] + # Regenerate the generated section from scratch. + if definitions: + # @context belongs at the root, so it cannot be dropped + # together with the generated section and is reset on its + # own. ROOT_LEVEL is left out on purpose: its templates + # emit parent references only, so reserving a block there + # would insert an empty object into every hand written + # context without ever filling it. + reset_generated_jsonld_context( + stored_schema, had_generated_section + ) + # in both modes, like the form editor: a page that switched + # mode keeps a pointer to a section that no longer exists + remove_generated_schema_section( + stored_schema, SCHEMA_DEF_KEY, SCHEMA_GEN_DEF_KEY + ) + if definitions: + for generated_schema in generated_schemas.values(): + if "@context" in generated_schema: + merge_generated_jsonld_context( + stored_schema, generated_schema.pop("@context") + ) + new_schema = aggregate_generated_schemas( + AggregateGeneratedSchemasParam( + target_schema=stored_schema, + generated_schemas=generated_schemas, + mode=mode, + def_key=SCHEMA_DEF_KEY, + gen_def_key=SCHEMA_GEN_DEF_KEY, + ) + ).aggregated_schema + generated_section = (new_schema.get(SCHEMA_DEF_KEY) or {}).get( + SCHEMA_GEN_DEF_KEY ) - page.set_slot_content("jsonschema", new_schema) + if definitions and isinstance(generated_section, dict): + strip_root_members_superseded_by_generated( + new_schema, generated_section + ) + page.set_slot_content("jsonschema", new_schema) if param.offline is False and not kept_existing: page.edit( param.edit_comment, bot_edit=param.bot_edit diff --git a/tests/conftest.py b/tests/conftest.py index 64ab03a1..f1ff7059 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,13 +9,37 @@ import pytest +from osw.core import OSW from osw.service import config +from osw.wtsite import WtPage # Note: pytest_addoption lives in the repo-root conftest.py - since pytest 9.0 # it is not loaded from this subdirectory conftest via testpaths. The # option-backed fixtures below stay here. +@pytest.fixture +def offline_osw(monkeypatch): + """An OSW whose store_entity() needs no network. + + WtPage.init, the overwrite policy, WtPage.edit and the write verification + are stubbed. A test that is about one of them replaces that stub again, + monkeypatch applies the later call. The schema generation needs a site that + serves the meta categories, see tests/schema_harness.py for that. + """ + # mimic the do_init=False branch of WtPage.__init__, which sets .exists + monkeypatch.setattr(WtPage, "init", lambda self: setattr(self, "exists", False)) + # bypass the overwrite policy: return the page that was built for the entity + monkeypatch.setattr( + OSW, "_apply_overwrite_policy", staticmethod(lambda param: param.page) + ) + monkeypatch.setattr(WtPage, "edit", lambda self, *a, **kw: None) + # the write verification would query the wiki, so report every edited page + # as existing. See tests/test_store_entity_verify.py for its own tests. + monkeypatch.setattr(OSW, "_get_missing_page_titles", lambda self, titles: []) + return OSW.construct(site=object()) + + @pytest.fixture(autouse=True) def _restore_log_prefix(): """Restore ``osw.service.config._LOG_PREFIX`` after each test. diff --git a/tests/schema_harness.py b/tests/schema_harness.py new file mode 100644 index 00000000..47d83068 --- /dev/null +++ b/tests/schema_harness.py @@ -0,0 +1,171 @@ +"""Offline harness for the jsonschema regeneration of store_entity(). + +store_entity() reads the schema templates of the meta categories from the wiki. +FakeSite serves them from a dict, so the schema generation can be exercised +without network. It is shared by the test modules that cover the generation, +instead of a private copy per module. +""" + +import json + +from opensemantic.core.v1 import CharacteristicType + +import osw.model.entity as model +from osw.core import OSW +from osw.wtsite import WtPage + +META_UUID = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d" +META_CATEGORY = "Category:OSW0a1b2c3d4e5f4a6b8c7d9e0f1a2b3c4d" +PARENT_UUID = "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d" +PARENT_CATEGORY = "Category:OSW1a2b3c4d5e6f4a7b8c9d0e1f2a3b4c5d" +CHARACTERISTIC_TYPE = "Category:OSWffe74f291d354037b318c422591c5023" +GEN_POINTER = "#/$defs/generated" + + +def schema_ref(title): + return f"/wiki/{title}?action=raw&slot=jsonschema" + + +class FakePage: + def __init__(self, title, template, schema): + self.title = title + self._slots = { + "schema_template": template, + "jsondata": {}, + "jsonschema": schema, + } + + def get_slot_content(self, slot_key, clone=True): + # the signature mirrors WtPage.get_slot_content, which the code under + # test may call with the clone argument + return self._slots[slot_key] + + +class _FakeGetPageResult: + def __init__(self, pages): + self.pages = pages + + +class FakeSite: + """Serves the meta categories whose templates the generation applies. + + Like in the wiki, the templates are collected along the allOf chain of the + meta category schema, so the meta category refers to CharacteristicType when + `definitions` is set, which selects the definitions section mode. + + parent_template adds a second meta category ahead of the first one, which is + how a template that fails after another one already produced a schema is + reproduced. + """ + + def __init__(self, template, definitions, parent_template=None): + self.template = template + self.definitions = definitions + self.parent_template = parent_template + + def _meta_schema(self): + schema = {"uuid": META_UUID, "allOf": []} + if self.parent_template is not None: + schema["allOf"].append({"$ref": schema_ref(PARENT_CATEGORY)}) + if self.definitions: + schema["allOf"].append({"$ref": schema_ref(CHARACTERISTIC_TYPE)}) + return schema + + def _page(self, title): + if title == META_CATEGORY: + return FakePage(title, self.template, self._meta_schema()) + if title == PARENT_CATEGORY: + return FakePage(title, self.parent_template, {"uuid": PARENT_UUID}) + if title == CHARACTERISTIC_TYPE: + return FakePage( + title, None, {"uuid": "ffe74f29-1d35-4037-b318-c422591c5023"} + ) + return FakePage(title, None, {}) + + def get_page(self, param): + return _FakeGetPageResult([self._page(t) for t in param.titles]) + + +def make_store(monkeypatch): + """Returns a callable that runs store_entity() offline and gives the slot. + + The overwrite policy is wrapped rather than bypassed, so that the stored + jsonschema slot the generation has to merge into is on the page when + store_entity() reads it. + + With offline=False the page counts as existing and the wiki calls of the + save are stubbed, which is the only way to reach the branches that test + page.exists and the overwrite policy. + """ + original_policy = OSW._apply_overwrite_policy + + def _store( + entity, + template, + stored, + definitions=None, + parent_template=None, + overwrite=None, + offline=True, + ): + if definitions is None: + # characteristics select the definitions section mode in the wiki + definitions = isinstance(entity, CharacteristicType) + if not offline: + monkeypatch.setattr( + WtPage, "init", lambda self: setattr(self, "exists", True) + ) + monkeypatch.setattr(WtPage, "edit", lambda self, *a, **kw: None) + monkeypatch.setattr(OSW, "_get_missing_page_titles", lambda s, t: []) + # the success log of store_entity_() builds the page url from the + # mwclient site, which the fake does not have + monkeypatch.setattr( + WtPage, "get_url", lambda self: f"https://example.invalid/{self.title}" + ) + + def policy_with_stored_schema(param): + if stored is not None: + content = json.loads(json.dumps(stored)) if stored else stored + param.page.set_slot_content("jsonschema", content) + return original_policy(param) + + monkeypatch.setattr( + OSW, "_apply_overwrite_policy", staticmethod(policy_with_stored_schema) + ) + osw_obj = OSW.construct( + site=FakeSite(template, definitions, parent_template=parent_template) + ) + store_param = OSW.StoreEntityParam( + entities=[entity], + namespace="Category", + meta_category_title=META_CATEGORY, + offline=offline, + **({} if overwrite is None else {"overwrite": overwrite}), + ) + result = osw_obj.store_entity(store_param) + (page,) = result.pages.values() + assert isinstance(page, WtPage) + return page.get_slot_content("jsonschema") + + return _store + + +def characteristic(): + return CharacteristicType( + uuid="efad8086-4a76-47ca-b278-f5f944e5754b", + name="TestCharacteristic", + label=[{"text": "Test Characteristic"}], + # the default resolves a superclass from a wiki, and oold 2 rejects an + # empty list for this required field + subclass_of=[CHARACTERISTIC_TYPE], + ) + + +def category(): + # store_entity() selects ROOT_LEVEL mode for any entity that is not a + # characteristic, so a plain Item stored in the Category namespace suffices + return model.Item( + uuid="0d0c1c35-4c4d-4e3a-9c9a-6f4a1b2c3d4e", + name="TestCategory", + label=[model.Label(text="Test Category")], + ) diff --git a/tests/test_schema_generation_js_parity.py b/tests/test_schema_generation_js_parity.py new file mode 100644 index 00000000..6254cd2c --- /dev/null +++ b/tests/test_schema_generation_js_parity.py @@ -0,0 +1,388 @@ +"""Reference cases of the schema generation, ported from the wiki form editor. + +store_entity() regenerates the jsonschema slot of a Category page the same way +the form editor does on save. The reference implementation is +osl.util.postProcessPage in PageBot.js of +mediawiki-extensions-OpenSemanticLab: +https://github.com/OpenSemanticLab/mediawiki-extensions-OpenSemanticLab/blob/e19619c/modules/ext.OpenSemanticLab.forms/PageBot.js#L375-L757 + +Each test below names the reference behaviour it pins. The known deviations are +pinned as well, so that a change to them is a deliberate one. +""" + +import pytest + +from osw.core import ( + AddOverwriteClassOptions, + merge_generated_jsonld_context, + remove_generated_schema_section, + reset_generated_jsonld_context, + strip_root_members_superseded_by_generated, +) +from tests.schema_harness import ( + GEN_POINTER, + category, + characteristic, + make_store, +) + + +@pytest.fixture +def store(monkeypatch): + return make_store(monkeypatch) + + +# --------------------------------------------------------------------------- +# remove_generated_schema_section: the "reset generated content" block +# --------------------------------------------------------------------------- + + +def test_remove_generated_section_drops_section_and_allof_pointer(): + schema = { + "title": "hand", + "allOf": [{"$ref": "/wiki/Category:Parent?action=raw"}, {"$ref": GEN_POINTER}], + "$defs": {"generated": {"type": "object"}, "manual": {"type": "string"}}, + } + + remove_generated_schema_section(schema) + + assert "generated" not in schema["$defs"] + assert schema["$defs"]["manual"] == {"type": "string"} + assert schema["allOf"] == [{"$ref": "/wiki/Category:Parent?action=raw"}] + + +def test_remove_generated_section_drops_root_ref_pointer(): + """generate_root_ref=True puts the pointer in the root $ref, not in allOf. + + PageBot.js removes that form too. Leaving it behind pointed the schema at a + $defs entry that had just been deleted. + """ + schema = {"$ref": GEN_POINTER, "$defs": {"generated": {"type": "object"}}} + + remove_generated_schema_section(schema) + + assert "$ref" not in schema + assert "generated" not in schema["$defs"] + + +def test_remove_generated_section_keeps_a_foreign_root_ref(): + schema = {"$ref": "#/$defs/manual", "$defs": {"generated": {}, "manual": {}}} + + remove_generated_schema_section(schema) + + assert schema["$ref"] == "#/$defs/manual" + + +@pytest.mark.parametrize("stored", ["a string", ["a", "list"], 5]) +def test_remove_generated_section_tolerates_a_non_dict_slot(stored): + """A jsonschema slot is not guaranteed to hold an object. + + get_slot_content() returns whatever the slot holds, and a slot stored with a + non-json content model gives a string. Raising here aborted the whole + store_entity() call. + """ + assert remove_generated_schema_section(stored) == stored + + +def test_remove_generated_section_uses_the_given_keys(): + schema = {"defs": {"gen": {}}, "allOf": [{"$ref": "#/defs/gen"}]} + + remove_generated_schema_section(schema, def_key="defs", gen_def_key="gen") + + assert schema["defs"] == {} + assert schema["allOf"] == [] + + +# --------------------------------------------------------------------------- +# reset_generated_jsonld_context +# --------------------------------------------------------------------------- + + +def test_reset_context_empties_the_generated_block_in_place(): + schema = {"@context": ["/wiki/Category:Parent?action=raw", {"v": "ex:v"}]} + + reset_generated_jsonld_context(schema, had_generated_section=True) + + assert schema["@context"] == ["/wiki/Category:Parent?action=raw", {}] + + +def test_reset_context_reserves_a_block_before_a_hand_written_one(): + """Without a previous generated section the first object block is manual. + + Emptying it would delete hand written mappings, so an empty block is + inserted ahead of it to take the generated mappings. + """ + schema = {"@context": ["/wiki/Category:Parent?action=raw", {"manual": "ex:m"}]} + + reset_generated_jsonld_context(schema, had_generated_section=False) + + assert schema["@context"] == [ + "/wiki/Category:Parent?action=raw", + {}, + {"manual": "ex:m"}, + ] + + +def test_reset_context_appends_a_block_when_there_is_none(): + schema = {"@context": ["/wiki/Category:Parent?action=raw"]} + + reset_generated_jsonld_context(schema, had_generated_section=True) + + assert schema["@context"] == ["/wiki/Category:Parent?action=raw", {}] + + +@pytest.mark.parametrize("context", ["/wiki/Category:Parent?action=raw", {"v": "ex:v"}]) +def test_reset_context_leaves_a_string_or_object_context(context): + """Only the array form carries a generated block by convention.""" + schema = {"@context": context} + + reset_generated_jsonld_context(schema, had_generated_section=True) + + assert schema["@context"] == context + + +def test_reset_context_tolerates_an_empty_schema(): + reset_generated_jsonld_context(None, had_generated_section=True) + reset_generated_jsonld_context({}, had_generated_section=True) + + +# --------------------------------------------------------------------------- +# merge_generated_jsonld_context +# --------------------------------------------------------------------------- + + +def test_merge_context_fills_only_the_reserved_block(): + """A manual block placed after the generated one must stay separate. + + oold's aggregate_generated_schemas() collapses every object entry into one, + which fused the two. The next reset would then delete the manual mappings + along with the generated ones. + """ + schema = {"@context": ["/wiki/Category:Parent?action=raw", {}, {"manual": "ex:m"}]} + + merge_generated_jsonld_context(schema, [{"gen": "ex:g"}]) + + assert schema["@context"] == [ + "/wiki/Category:Parent?action=raw", + {"gen": "ex:g"}, + {"manual": "ex:m"}, + ] + + +def test_merge_context_appends_a_new_parent_reference_once(): + schema = {"@context": ["/wiki/Category:P1?action=raw", {}]} + + merge_generated_jsonld_context( + schema, ["/wiki/Category:P1?action=raw", "/wiki/Category:P2?action=raw", {}] + ) + + assert schema["@context"].count("/wiki/Category:P1?action=raw") == 1 + assert "/wiki/Category:P2?action=raw" in schema["@context"] + + +def test_reset_and_merge_drop_the_mappings_of_a_former_parent(): + """The reference case: a Characteristic whose parent changes. + + The term mappings of the old parent must not survive, or JSON-LD expansion + keeps using terms of a superclass the Category no longer declares. + """ + schema = {"@context": ["/wiki/Category:P1?action=raw", {"v": "ex:v"}]} + + reset_generated_jsonld_context(schema, had_generated_section=True) + merge_generated_jsonld_context( + schema, ["/wiki/Category:P2?action=raw", {"w": "ex:w"}] + ) + + (block,) = [e for e in schema["@context"] if isinstance(e, dict)] + assert block == {"w": "ex:w"} + + +def test_reset_and_merge_keep_the_reference_of_a_former_parent(): + """Known deviation, shared with the form editor. + + The string entries of @context are parent schema references. They carry no + marker that tells a stale generated one from a hand written one, so the + reference of a removed superclass stays in the list. Only the term mappings + are rebuilt. Removing the stale reference needs a record of what the last + generation wrote. + """ + schema = {"@context": ["/wiki/Category:P1?action=raw", {"v": "ex:v"}]} + + reset_generated_jsonld_context(schema, had_generated_section=True) + merge_generated_jsonld_context( + schema, ["/wiki/Category:P2?action=raw", {"w": "ex:w"}] + ) + + assert "/wiki/Category:P1?action=raw" in schema["@context"] + + +# --------------------------------------------------------------------------- +# strip_root_members_superseded_by_generated +# --------------------------------------------------------------------------- + + +def test_strip_retires_a_root_copy_but_keeps_manual_siblings(): + """The reference case from PageBot.js: a copied category. + + A member at root takes precedence over the same member pulled in through + allOf, so the root copy of 'default' typed instances as the source category. + The siblings on the same object are hand written and have to survive. + """ + root = { + "properties": { + "type": { + "default": ["Category:Source"], + "items": {"type": "string"}, + "minItems": 1, + } + } + } + generated = {"properties": {"type": {"default": ["Category:Copy"]}}} + + assert strip_root_members_superseded_by_generated(root, generated) is True + assert root["properties"]["type"] == {"items": {"type": "string"}, "minItems": 1} + + +def test_strip_drops_a_container_that_only_held_generated_members(): + root = {"properties": {"gen": {"type": "number"}}} + generated = {"properties": {"gen": {"type": "number"}}} + + strip_root_members_superseded_by_generated(root, generated) + + assert "properties" not in root + + +def test_strip_skips_the_members_promoted_to_root(): + root = { + "title": "Root title", + "description": "Root description", + "$comment": "note", + "@context": [{"v": "ex:v"}], + "$defs": {"generated": {}}, + "$ref": "#/$defs/manual", + } + generated = { + "title": "Generated title", + "description": "Generated description", + "$comment": "generated note", + "@context": [{"v": "ex:v"}], + "$defs": {}, + "$ref": "#/$defs/generated", + } + + assert strip_root_members_superseded_by_generated(root, generated) is False + assert root["title"] == "Root title" + assert root["@context"] == [{"v": "ex:v"}] + assert root["$ref"] == "#/$defs/manual" + + +def test_strip_removes_root_allof_refs_the_generated_section_repeats(): + """The generated section repeats the parent refs in its own allOf. + + Root listed them twice: directly and again through the generated section. + """ + parent = {"$ref": "/wiki/Category:Parent?action=raw"} + root = {"allOf": [parent, {"$ref": GEN_POINTER}]} + generated = {"allOf": [parent]} + + assert strip_root_members_superseded_by_generated(root, generated) is True + assert root["allOf"] == [{"$ref": GEN_POINTER}] + + +def test_strip_reports_nothing_removed_for_a_clean_schema(): + root = {"properties": {"manual": {"type": "string"}}} + generated = {"properties": {"gen": {"type": "number"}}} + + assert strip_root_members_superseded_by_generated(root, generated) is False + assert root["properties"]["manual"] == {"type": "string"} + + +# --------------------------------------------------------------------------- +# store_entity(): the generation as a whole +# --------------------------------------------------------------------------- + + +def test_partial_generation_failure_keeps_the_stored_schema(store): + """One template renders, a later one fails: nothing may be written. + + The form editor aborts the save when any template fails. Writing the part + that did render replaced the stored generated section with a fragment, so a + transient failure of one template silently dropped the rest of the schema. + """ + stored = { + "title": "hand", + "allOf": [{"$ref": GEN_POINTER}], + "$defs": {"generated": {"type": "object", "required": ["type"]}}, + } + good = '{"properties": {"from_parent": {"type": "string"}}}' + broken = '{"title": {{name}}' # not valid JSON + + schema = store(characteristic(), broken, stored, parent_template=good) + + assert schema == stored + + +def test_full_generation_applies_every_template(store): + """The counterpart: with both templates valid, both are applied.""" + good = '{"properties": {"from_parent": {"type": "string"}}}' + template = '{"title": "{{name}}", "properties": {"own": {"type": "number"}}}' + + schema = store(characteristic(), template, None, parent_template=good) + + generated = schema["$defs"]["generated"] + assert generated["properties"]["from_parent"] == {"type": "string"} + assert generated["properties"]["own"] == {"type": "number"} + + +@pytest.mark.parametrize("definitions", [True, False]) +def test_a_non_dict_stored_slot_is_replaced(store, definitions): + """A malformed jsonschema slot must not abort the upload of the entity.""" + entity = characteristic() if definitions else category() + template = '{"title": "{{name}}", "type": "object"}' + + schema = store(entity, template, "this slot is not an object") + + assert isinstance(schema, dict) + assert schema["title"] == entity.name + + +def test_replace_remote_does_not_merge_into_the_remote_schema(store): + """'replace remote' removes what is not in the local entity. + + The policy leaves the remote jsonschema slot on the page object, so the + regeneration merged the new schema into the stale remote one. A page with a + corrupted schema could then not be repaired by storing it again. + """ + stored = {"title": "hand", "properties": {"stale": {"type": "string"}}} + template = '{"title": "{{name}}", "properties": {"gen": {"type": "number"}}}' + + schema = store( + category(), + template, + stored, + overwrite=AddOverwriteClassOptions.replace_remote, + offline=False, + ) + + assert "stale" not in schema["properties"] + assert schema["properties"]["gen"] == {"type": "number"} + + +def test_root_level_second_save_with_a_changed_template_unions(store): + """Known deviation, shared with the form editor. + + ROOT_LEVEL mode merges into the stored schema and merge_deep() concatenates + arrays. Nothing marks which root members the last generation wrote, so an + entry a later template no longer produces cannot be told from a hand written + one and stays. The form editor behaves the same way. Pinned here so that a + change is a deliberate one. + """ + first_template = '{"title": "{{name}}", "required": ["gen"]}' + second_template = '{"title": "{{name}}", "required": ["other"]}' + + first = store(category(), first_template, None) + assert first["required"] == ["gen"] + + second = store(category(), second_template, first) + + assert second["required"] == ["gen", "other"] diff --git a/tests/test_store_entity_failure.py b/tests/test_store_entity_failure.py index 163ccd24..454b879e 100644 --- a/tests/test_store_entity_failure.py +++ b/tests/test_store_entity_failure.py @@ -17,20 +17,8 @@ def _title(entity): return f"{get_namespace(entity)}:{get_title(entity)}" -@pytest.fixture -def offline_osw(monkeypatch): - # no network when a WtPage is constructed with do_init=True; mimic the - # do_init=False branch of WtPage.__init__ which sets .exists - monkeypatch.setattr(WtPage, "init", lambda self: setattr(self, "exists", False)) - # bypass the overwrite policy: return the page that was built for the entity - monkeypatch.setattr( - OSW, "_apply_overwrite_policy", staticmethod(lambda param: param.page) - ) - # the write verification would query the wiki. These tests cover the reporting - # of a failed edit, so report every edited page as existing. The verification - # itself is covered by test_store_entity_verify.py - monkeypatch.setattr(OSW, "_get_missing_page_titles", lambda self, titles: []) - return OSW.construct(site=object()) +# offline_osw comes from tests/conftest.py. These tests are about the reporting +# of a failed edit, so _install_edit() replaces its WtPage.edit stub. def _install_edit(monkeypatch, failing_titles): diff --git a/tests/test_store_entity_keeps_jsonschema.py b/tests/test_store_entity_keeps_jsonschema.py index 877eb6f2..b8f086cc 100644 --- a/tests/test_store_entity_keeps_jsonschema.py +++ b/tests/test_store_entity_keeps_jsonschema.py @@ -10,139 +10,33 @@ existing `$defs/generated` instead of replacing it, so a `required` entry or a `type` from an earlier save survived every regeneration. -These run fully offline: store_entity() runs with offline=True, the meta category -is served by a fake site and the overwrite policy is wrapped to put a stored -jsonschema slot on the page, so no network is required. -""" +The behaviour of the generation as a whole, and the cases ported from the wiki +form editor, are in tests/test_schema_generation_js_parity.py. -import json +These run fully offline, see tests/schema_harness.py. +""" import pytest -from opensemantic.core.v1 import CharacteristicType - -import osw.model.entity as model -from osw.core import OSW -from osw.wtsite import WtPage - -META_UUID = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d" -META_CATEGORY = "Category:OSW0a1b2c3d4e5f4a6b8c7d9e0f1a2b3c4d" -CHARACTERISTIC_TYPE = "Category:OSWffe74f291d354037b318c422591c5023" -GEN_POINTER = "#/$defs/generated" - - -class _FakeMetaCategoryPage: - def __init__(self, title, template, schema): - self.title = title - self._slots = { - "schema_template": template, - "jsondata": {}, - "jsonschema": schema, - } - - def get_slot_content(self, slot_key): - return self._slots[slot_key] - - -class _FakeGetPageResult: - def __init__(self, pages): - self.pages = pages - -class _FakeSite: - """Serves a meta category with the template under test. - - Like in the wiki, the templates follow the allOf chain of the meta category - schema, so the meta category refers to CharacteristicType when `definitions` - is set. - """ - - def __init__(self, template, definitions): - self.template = template - self.definitions = definitions - - def _page(self, title): - if title == META_CATEGORY: - schema = {"uuid": META_UUID} - if self.definitions: - schema["allOf"] = [ - {"$ref": f"/wiki/{CHARACTERISTIC_TYPE}?action=raw&slot=jsonschema"} - ] - return _FakeMetaCategoryPage(title, self.template, schema) - if title == CHARACTERISTIC_TYPE: - return _FakeMetaCategoryPage( - title, None, {"uuid": "ffe74f29-1d35-4037-b318-c422591c5023"} - ) - return _FakeMetaCategoryPage(title, None, {}) - - def get_page(self, param): - return _FakeGetPageResult([self._page(t) for t in param.titles]) +from tests.schema_harness import ( + GEN_POINTER, + META_CATEGORY, + category, + characteristic, + make_store, +) @pytest.fixture def store(monkeypatch): - """Runs store_entity() offline on a page whose jsonschema slot holds `stored`. - - Returns the jsonschema slot that store_entity() wrote. - """ - original_policy = OSW._apply_overwrite_policy - - def _store(entity, template, stored, definitions=None): - if definitions is None: - # characteristics select the definitions section mode in the wiki - definitions = isinstance(entity, CharacteristicType) - - def policy_with_stored_schema(param): - if stored is not None: - param.page.set_slot_content( - "jsonschema", json.loads(json.dumps(stored)) - ) - return original_policy(param) - - monkeypatch.setattr( - OSW, "_apply_overwrite_policy", staticmethod(policy_with_stored_schema) - ) - osw_obj = OSW.construct(site=_FakeSite(template, definitions)) - result = osw_obj.store_entity( - OSW.StoreEntityParam( - entities=[entity], - namespace="Category", - meta_category_title=META_CATEGORY, - offline=True, - ) - ) - (page,) = result.pages.values() - assert isinstance(page, WtPage) - return page.get_slot_content("jsonschema") - - return _store - - -def _characteristic(): - return CharacteristicType( - uuid="efad8086-4a76-47ca-b278-f5f944e5754b", - name="TestCharacteristic", - label=[{"text": "Test Characteristic"}], - # the default resolves a superclass from a wiki, and oold 2 rejects an - # empty list for this required field - subclass_of=[CHARACTERISTIC_TYPE], - ) - - -def _category(): - # store_entity() selects ROOT_LEVEL mode for any entity that is not a - # characteristic, so a plain Item stored in the Category namespace suffices - return model.Item( - uuid="0d0c1c35-4c4d-4e3a-9c9a-6f4a1b2c3d4e", - name="TestCategory", - label=[model.Label(text="Test Category")], - ) + return make_store(monkeypatch) def test_root_level_keeps_hand_written_schema(store): stored = {"title": "hand", "properties": {"manual": {"type": "string"}}} template = '{"title": "{{name}}", "properties": {"gen": {"type": "number"}}}' - schema = store(_category(), template, stored) + schema = store(category(), template, stored) assert schema["properties"]["manual"] == {"type": "string"} assert schema["properties"]["gen"] == {"type": "number"} @@ -153,7 +47,7 @@ def test_definitions_section_keeps_hand_written_schema(store): stored = {"title": "hand", "$defs": {"manual": {"type": "string"}}} template = '{"title": "{{name}}", "type": "object"}' - schema = store(_characteristic(), template, stored) + schema = store(characteristic(), template, stored) assert schema["$defs"]["manual"] == {"type": "string"} assert schema["$defs"]["generated"]["type"] == "object" @@ -170,10 +64,10 @@ def test_definitions_section_replaces_stale_generated_section(store): '{"title": "{{name}}", "properties": {"value": {"type": "number"}}}' ) - first = store(_characteristic(), first_template, stored) + first = store(characteristic(), first_template, stored) assert first["$defs"]["generated"]["required"] == ["type"] - second = store(_characteristic(), second_template, first) + second = store(characteristic(), second_template, first) generated = second["$defs"]["generated"] assert "required" not in generated @@ -194,7 +88,7 @@ def test_failed_generation_keeps_generated_section(store): # not valid JSON, so generation fails and produces no generated schema template = '{"title": {{name}}' - schema = store(_characteristic(), template, stored) + schema = store(characteristic(), template, stored) assert schema == stored @@ -206,8 +100,8 @@ def test_root_level_second_save_does_not_duplicate(store): ' "properties": {"gen": {"type": "number"}}}' ) - first = store(_category(), template, stored) - second = store(_category(), template, first) + first = store(category(), template, stored) + second = store(category(), template, first) assert second == first assert second["required"] == ["gen"] diff --git a/tests/test_store_entity_silent_drop.py b/tests/test_store_entity_silent_drop.py index 8e8db0c0..7a101a90 100644 --- a/tests/test_store_entity_silent_drop.py +++ b/tests/test_store_entity_silent_drop.py @@ -18,28 +18,13 @@ import osw.model.entity as model from osw.core import OSW from osw.utils.wiki import get_namespace, get_title -from osw.wtsite import WtPage def _title(entity): return f"{get_namespace(entity)}:{get_title(entity)}" -@pytest.fixture -def offline_osw(monkeypatch): - # no network when a WtPage is constructed with do_init=True; mimic the - # do_init=False branch of WtPage.__init__ which sets .exists - monkeypatch.setattr(WtPage, "init", lambda self: setattr(self, "exists", False)) - # bypass the overwrite policy: return the page that was built for the entity - monkeypatch.setattr( - OSW, "_apply_overwrite_policy", staticmethod(lambda param: param.page) - ) - monkeypatch.setattr(WtPage, "edit", lambda self, *a, **kw: None) - # the write verification would query the wiki. These tests are not about - # verification, so report every edited page as existing. See - # tests/test_store_entity_verify.py for the write verification tests. - monkeypatch.setattr(OSW, "_get_missing_page_titles", lambda self, titles: []) - return OSW.construct(site=object()) +# offline_osw comes from tests/conftest.py def test_title_failure_is_reported_serial(offline_osw, monkeypatch):