Skip to content
Merged
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
120 changes: 89 additions & 31 deletions src/osw/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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}"
)
Expand All @@ -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
Expand Down
24 changes: 24 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
171 changes: 171 additions & 0 deletions tests/schema_harness.py
Original file line number Diff line number Diff line change
@@ -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")],
)
Loading
Loading