Skip to content

Commit 15a8536

Browse files
authored
fix(wtsite): copy the jsonld context before rewriting it
Merge pull request #178 from OpenSemanticLab/fix/177-context-mapping-copy
2 parents 4540308 + ea0cddf commit 15a8536

2 files changed

Lines changed: 177 additions & 34 deletions

File tree

‎src/osw/wtsite.py‎

Lines changed: 38 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1400,19 +1400,43 @@ def _replace_jsonld_context_mapping(
14001400
handle string, list and dict values
14011401
handle mappings direct to iri as well as
14021402
{"@id": "http://example.org/property", @type": "@id"} and scoped contexts
1403+
the given context is not modified: dicts are copied before rewriting
1404+
values of an unhandled type are returned unchanged
14031405
"""
14041406
if isinstance(context, str):
14051407
return context
14061408
if isinstance(context, list):
14071409
return [self._replace_jsonld_context_mapping(e, config) for e in context]
1408-
if isinstance(context, dict):
1409-
context_iter = context.copy()
1410-
for key in context_iter:
1411-
value = context[key]
1412-
if key == "wiki":
1413-
context[key] = f"https://{self._site.host}/id/"
1414-
# print(f"apply https://{self._site.host}/id/ to {key}")
1415-
if isinstance(value, str):
1410+
if not isinstance(context, dict):
1411+
return context
1412+
context = deepcopy(context)
1413+
context_iter = context.copy()
1414+
for key in context_iter:
1415+
value = context[key]
1416+
if key == "wiki":
1417+
context[key] = f"https://{self._site.host}/id/"
1418+
# print(f"apply https://{self._site.host}/id/ to {key}")
1419+
if isinstance(value, str):
1420+
base_key = key.split("*")[0]
1421+
if base_key not in context:
1422+
context[base_key] = value
1423+
# print(f"apply {key} to {base_key}")
1424+
if config.prefer_external_vocal is False:
1425+
base_mapping = context[base_key]
1426+
if isinstance(base_mapping, dict):
1427+
base_mapping = base_mapping["@id"]
1428+
mapping = value
1429+
if mapping.startswith("Property:") and not base_mapping.startswith(
1430+
"Property:"
1431+
):
1432+
context[base_key] = value
1433+
# print(f"apply {key} to {base_key}")
1434+
elif isinstance(value, list):
1435+
context[key] = [
1436+
self._replace_jsonld_context_mapping(e, config) for e in value
1437+
]
1438+
elif isinstance(value, dict):
1439+
if "@id" in value:
14161440
base_key = key.split("*")[0]
14171441
if base_key not in context:
14181442
context[base_key] = value
@@ -1421,37 +1445,17 @@ def _replace_jsonld_context_mapping(
14211445
base_mapping = context[base_key]
14221446
if isinstance(base_mapping, dict):
14231447
base_mapping = base_mapping["@id"]
1424-
mapping = value
1448+
mapping = value["@id"]
14251449
if mapping.startswith(
14261450
"Property:"
14271451
) and not base_mapping.startswith("Property:"):
14281452
context[base_key] = value
14291453
# print(f"apply {key} to {base_key}")
1430-
elif isinstance(value, list):
1431-
context[key] = [
1432-
self._replace_jsonld_context_mapping(e, config) for e in value
1433-
]
1434-
elif isinstance(value, dict):
1435-
if "@id" in value:
1436-
base_key = key.split("*")[0]
1437-
if base_key not in context:
1438-
context[base_key] = value
1439-
# print(f"apply {key} to {base_key}")
1440-
if config.prefer_external_vocal is False:
1441-
base_mapping = context[base_key]
1442-
if isinstance(base_mapping, dict):
1443-
base_mapping = base_mapping["@id"]
1444-
mapping = value["@id"]
1445-
if mapping.startswith(
1446-
"Property:"
1447-
) and not base_mapping.startswith("Property:"):
1448-
context[base_key] = value
1449-
# print(f"apply {key} to {base_key}")
1450-
elif "@context" in value:
1451-
context[key] = self._replace_jsonld_context_mapping(
1452-
value["@context"], config
1453-
)
1454-
return context
1454+
elif "@context" in value:
1455+
context[key] = self._replace_jsonld_context_mapping(
1456+
value["@context"], config
1457+
)
1458+
return context
14551459

14561460
@try_and_renew_token
14571461
def get_jsonld_context_loader(self, params: JsonLdContextLoaderParams = None):
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
"""Unit tests for WtSite._replace_jsonld_context_mapping().
2+
3+
Regression guard for #177: the method rewrote the context object it was given
4+
in place, so a caller that still needed its own dictionary got it modified.
5+
It must now rewrite a copy and leave the argument untouched. An argument of an
6+
unhandled type must be returned unchanged instead of an implicit None.
7+
"""
8+
9+
import threading
10+
11+
from osw.wtsite import WtSite
12+
13+
14+
class _FakeSite:
15+
"""Stands in for mwclient.Site. Only the host is read."""
16+
17+
host = "example.org"
18+
19+
20+
def _make_fake_wtsite():
21+
"""A WtSite that performs no network calls."""
22+
ws = WtSite.__new__(WtSite)
23+
ws._session_lock = threading.RLock()
24+
ws._site = _FakeSite()
25+
return ws
26+
27+
28+
def _params():
29+
return WtSite.JsonLdContextLoaderParams(prefer_external_vocal=False)
30+
31+
32+
def test_dict_argument_is_not_modified():
33+
ws = _make_fake_wtsite()
34+
given = {
35+
"label": {"@id": "skos:prefLabel"},
36+
"label*": {"@id": "Property:HasLabel"},
37+
"wiki": "https://original.example/id/",
38+
}
39+
40+
result = ws._replace_jsonld_context_mapping(given, _params())
41+
42+
assert result is not given
43+
assert given == {
44+
"label": {"@id": "skos:prefLabel"},
45+
"label*": {"@id": "Property:HasLabel"},
46+
"wiki": "https://original.example/id/",
47+
}
48+
49+
50+
def test_dict_argument_is_still_rewritten_in_the_result():
51+
ws = _make_fake_wtsite()
52+
given = {
53+
"label": {"@id": "skos:prefLabel"},
54+
"label*": {"@id": "Property:HasLabel"},
55+
"wiki": "https://original.example/id/",
56+
}
57+
58+
result = ws._replace_jsonld_context_mapping(given, _params())
59+
60+
assert result["label"] == {"@id": "Property:HasLabel"}
61+
assert result["wiki"] == "https://example.org/id/"
62+
63+
64+
def test_string_mapping_is_rewritten_without_touching_the_argument():
65+
ws = _make_fake_wtsite()
66+
given = {"label": "skos:prefLabel", "label*": "Property:HasLabel"}
67+
68+
result = ws._replace_jsonld_context_mapping(given, _params())
69+
70+
assert result["label"] == "Property:HasLabel"
71+
assert given["label"] == "skos:prefLabel"
72+
73+
74+
def test_nested_values_are_not_shared_with_the_argument():
75+
ws = _make_fake_wtsite()
76+
nested = {"@id": "skos:prefLabel", "@type": "@id"}
77+
given = {"label": nested}
78+
79+
result = ws._replace_jsonld_context_mapping(given, _params())
80+
81+
assert result["label"] is not nested
82+
result["label"]["@id"] = "changed"
83+
assert nested["@id"] == "skos:prefLabel"
84+
85+
86+
def test_scoped_context_is_not_modified():
87+
ws = _make_fake_wtsite()
88+
scoped = {
89+
"label": {"@id": "skos:prefLabel"},
90+
"label*": {"@id": "Property:HasLabel"},
91+
}
92+
given = {"statements": {"@context": scoped}}
93+
94+
result = ws._replace_jsonld_context_mapping(given, _params())
95+
96+
assert result["statements"]["label"] == {"@id": "Property:HasLabel"}
97+
assert scoped["label"] == {"@id": "skos:prefLabel"}
98+
99+
100+
def test_list_elements_are_not_modified():
101+
ws = _make_fake_wtsite()
102+
element = {
103+
"label": {"@id": "skos:prefLabel"},
104+
"label*": {"@id": "Property:HasLabel"},
105+
}
106+
given = ["/wiki/Category:Entity?action=raw&slot=jsonschema", element]
107+
108+
result = ws._replace_jsonld_context_mapping(given, _params())
109+
110+
assert result is not given
111+
assert result[0] == "/wiki/Category:Entity?action=raw&slot=jsonschema"
112+
assert result[1] is not element
113+
assert result[1]["label"] == {"@id": "Property:HasLabel"}
114+
assert element["label"] == {"@id": "skos:prefLabel"}
115+
116+
117+
def test_list_value_inside_a_dict_is_not_modified():
118+
ws = _make_fake_wtsite()
119+
element = {
120+
"label": {"@id": "skos:prefLabel"},
121+
"label*": {"@id": "Property:HasLabel"},
122+
}
123+
given = {"statements": [element]}
124+
125+
result = ws._replace_jsonld_context_mapping(given, _params())
126+
127+
assert result["statements"][0]["label"] == {"@id": "Property:HasLabel"}
128+
assert element["label"] == {"@id": "skos:prefLabel"}
129+
130+
131+
def test_string_argument_is_returned_unchanged():
132+
ws = _make_fake_wtsite()
133+
assert ws._replace_jsonld_context_mapping("schema:name", _params()) == "schema:name"
134+
135+
136+
def test_unhandled_type_is_returned_unchanged():
137+
ws = _make_fake_wtsite()
138+
assert ws._replace_jsonld_context_mapping(42, _params()) == 42
139+
assert ws._replace_jsonld_context_mapping(None, _params()) is None

0 commit comments

Comments
 (0)