ontolutils 0.2.8__tar.gz → 0.2.10__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {ontolutils-0.2.8 → ontolutils-0.2.10}/PKG-INFO +1 -1
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/__init__.py +4 -1
- ontolutils-0.2.10/ontolutils/classes/__init__.py +6 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/classes/decorator.py +1 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/classes/thing.py +175 -25
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils.egg-info/PKG-INFO +1 -1
- {ontolutils-0.2.8 → ontolutils-0.2.10}/setup.cfg +1 -1
- {ontolutils-0.2.8 → ontolutils-0.2.10}/tests/test_classes.py +89 -7
- {ontolutils-0.2.8 → ontolutils-0.2.10}/tests/test_readme.py +14 -1
- ontolutils-0.2.8/ontolutils/classes/__init__.py +0 -6
- {ontolutils-0.2.8 → ontolutils-0.2.10}/LICENSE +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/README.md +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/_version.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/cache.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/classes/query_util.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/classes/typing.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/classes/utils.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/namespacelib/__dev.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/namespacelib/__init__.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/namespacelib/_iana_utils.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/namespacelib/codemeta.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/namespacelib/m4i.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/namespacelib/obo.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/namespacelib/pivmeta.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/namespacelib/qudt_kind.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/namespacelib/qudt_unit.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/namespacelib/schema.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils/namespacelib/ssno.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils.egg-info/SOURCES.txt +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils.egg-info/dependency_links.txt +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils.egg-info/requires.txt +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/ontolutils.egg-info/top_level.txt +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/pyproject.toml +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/setup.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/tests/test_decorator.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/tests/test_namespaces.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/tests/test_query.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/tests/test_typing.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/tests/test_utils.py +0 -0
- {ontolutils-0.2.8 → ontolutils-0.2.10}/tests/test_version.py +0 -0
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import logging
|
|
3
3
|
|
|
4
4
|
from ._version import __version__
|
|
5
|
-
from .classes import Thing
|
|
5
|
+
from .classes import Thing, get_urirefs, get_namespaces
|
|
6
6
|
from .classes import namespaces, urirefs
|
|
7
7
|
from .classes import query, dquery
|
|
8
8
|
from .classes.utils import merge_jsonld
|
|
@@ -35,4 +35,7 @@ __all__ = ['Thing',
|
|
|
35
35
|
'query',
|
|
36
36
|
'set_logging_level',
|
|
37
37
|
'merge_jsonld',
|
|
38
|
+
'dquery',
|
|
39
|
+
'get_urirefs',
|
|
40
|
+
'get_namespaces',
|
|
38
41
|
]
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Classes for working with ontology data"""
|
|
2
|
+
from .decorator import namespaces, urirefs
|
|
3
|
+
from .query_util import query, dquery
|
|
4
|
+
from .thing import Thing, get_urirefs, get_namespaces
|
|
5
|
+
|
|
6
|
+
__all__ = ['namespaces', 'urirefs', 'Thing', 'query', 'dquery', 'get_urirefs', 'get_namespaces']
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import abc
|
|
2
2
|
import json
|
|
3
3
|
import logging
|
|
4
|
+
import pathlib
|
|
4
5
|
import rdflib
|
|
6
|
+
import warnings
|
|
5
7
|
from datetime import datetime
|
|
6
8
|
from pydantic import HttpUrl, FileUrl, BaseModel, ConfigDict
|
|
7
9
|
from typing import Dict, Union, Optional
|
|
@@ -25,11 +27,69 @@ class ThingModel(BaseModel, abc.ABC):
|
|
|
25
27
|
"""Returns the HTML representation of the class"""
|
|
26
28
|
|
|
27
29
|
|
|
30
|
+
def resolve_iri(iri: str, context: Dict) -> str:
|
|
31
|
+
"""Resolves short iri string which uses prefix, e.g.
|
|
32
|
+
converts 'foaf:firstName' to 'http://xmlns.com/foaf/0.1/firstName'
|
|
33
|
+
if the prefix is not found in context, the input iri string is
|
|
34
|
+
returned.
|
|
35
|
+
"""
|
|
36
|
+
if iri.startswith('http'):
|
|
37
|
+
return iri
|
|
38
|
+
ns, key = split_URIRef(iri)
|
|
39
|
+
prefix_iri = context.get(ns, None)
|
|
40
|
+
if prefix_iri is None:
|
|
41
|
+
return iri
|
|
42
|
+
return f'{prefix_iri}{key}'
|
|
43
|
+
|
|
44
|
+
|
|
28
45
|
@namespaces(owl='http://www.w3.org/2002/07/owl#',
|
|
29
46
|
rdfs='http://www.w3.org/2000/01/rdf-schema#')
|
|
30
47
|
@urirefs(Thing='owl:Thing', label='rdfs:label')
|
|
31
48
|
class Thing(ThingModel):
|
|
32
|
-
"""owl:Thing
|
|
49
|
+
"""Most basic concept class owl:Thing (see also https://www.w3.org/TR/owl-guide/)
|
|
50
|
+
|
|
51
|
+
This class is basis to model other concepts.
|
|
52
|
+
|
|
53
|
+
Example for `prov:Person`:
|
|
54
|
+
|
|
55
|
+
>>> @namespaces(prov='http://www.w3.org/ns/prov#',
|
|
56
|
+
>>> foaf='http://xmlns.com/foaf/0.1/')
|
|
57
|
+
>>> @urirefs(Person='prov:Person', first_name='foaf:firstName')
|
|
58
|
+
>>> class Person(Thing):
|
|
59
|
+
>>> first_name: str = None
|
|
60
|
+
>>> last_name: str = None
|
|
61
|
+
|
|
62
|
+
>>> p = Person(first_name='John', last_name='Doe', age=30)
|
|
63
|
+
>>> # Note, that age is not defined in the class! This is allowed, but may not be
|
|
64
|
+
>>> # serialized into an IRI although the ontology defines it
|
|
65
|
+
|
|
66
|
+
>>> print(p.model_dump_jsonld())
|
|
67
|
+
>>> {
|
|
68
|
+
>>> "@context": {
|
|
69
|
+
>>> "prov": "http://www.w3.org/ns/prov#",
|
|
70
|
+
>>> "foaf": "http://xmlns.com/foaf/0.1/",
|
|
71
|
+
>>> "first_name": "foaf:firstName"
|
|
72
|
+
>>> },
|
|
73
|
+
>>> "@id": "N23036f1a4eb149edb7db41b2f5f4268c",
|
|
74
|
+
>>> "@type": "prov:Person",
|
|
75
|
+
>>> "foaf:firstName": "John",
|
|
76
|
+
>>> "last_name": "Doe",
|
|
77
|
+
>>> "age": "30" # Age appears as a field without context!
|
|
78
|
+
>>> }
|
|
79
|
+
|
|
80
|
+
Note, that values are validated, as `Thing` is a subclass of `pydantic.BaseModel`:
|
|
81
|
+
|
|
82
|
+
>>> Person(first_name=1)
|
|
83
|
+
|
|
84
|
+
Will lead to a validation error:
|
|
85
|
+
|
|
86
|
+
>>> # Traceback (most recent call last):
|
|
87
|
+
>>> # ...
|
|
88
|
+
>>> # pydantic_core._pydantic_core.ValidationError: 1 validation error for Person
|
|
89
|
+
>>> # first_name
|
|
90
|
+
>>> # Input should be a valid string [type=string_type, input_value=1, input_type=int]
|
|
91
|
+
>>> # For further information visit https://errors.pydantic.dev/2.4/v/string_type
|
|
92
|
+
|
|
33
93
|
"""
|
|
34
94
|
id: Union[str, HttpUrl, FileUrl, BlankNodeType, None] = None # @id
|
|
35
95
|
label: str = None # rdfs:label
|
|
@@ -46,7 +106,8 @@ class Thing(ThingModel):
|
|
|
46
106
|
|
|
47
107
|
def get_jsonld_dict(self,
|
|
48
108
|
context: Optional[Union[Dict, str]] = None,
|
|
49
|
-
exclude_none: bool = True
|
|
109
|
+
exclude_none: bool = True,
|
|
110
|
+
resolve_keys: bool = False) -> Dict:
|
|
50
111
|
"""Return the JSON-LD dictionary of the object. This will include the context
|
|
51
112
|
and the fields of the object.
|
|
52
113
|
|
|
@@ -57,6 +118,42 @@ class Thing(ThingModel):
|
|
|
57
118
|
be interpreted as an import statement and will be added to the context.
|
|
58
119
|
exclude_none: bool=True
|
|
59
120
|
Exclude fields with None values
|
|
121
|
+
resolve_keys: bool=False
|
|
122
|
+
If True, then attributes of a Thing class will be resolved to the full IRI and
|
|
123
|
+
explained in the context.
|
|
124
|
+
|
|
125
|
+
Example:
|
|
126
|
+
|
|
127
|
+
In the following example, first_name refers to foaf:firstName:
|
|
128
|
+
|
|
129
|
+
>>> @namespaces(foaf='http://xmlns.com/foaf/0.1/')
|
|
130
|
+
>>> @urirefs(Person='foaf:Person', first_name='foaf:firstName')
|
|
131
|
+
>>> class Person(Thing):
|
|
132
|
+
>>> first_name: str = None
|
|
133
|
+
|
|
134
|
+
>>> p = Person(first_name='John')
|
|
135
|
+
>>> p.model_dump_jsonld(resolve_keys=True)
|
|
136
|
+
|
|
137
|
+
This will result "first_name": "foaf:firstName" showing up in the context:
|
|
138
|
+
|
|
139
|
+
>>> {
|
|
140
|
+
>>> "@context": {
|
|
141
|
+
>>> "foaf": "http://xmlns.com/foaf/0.1/",
|
|
142
|
+
>>> "first_name": "foaf:firstName"
|
|
143
|
+
>>> },
|
|
144
|
+
>>> "@type": "foaf:Person",
|
|
145
|
+
>>> "foaf:firstName": "John"
|
|
146
|
+
>>> }
|
|
147
|
+
|
|
148
|
+
While resolve_keys=False will result in:
|
|
149
|
+
|
|
150
|
+
>>> {
|
|
151
|
+
>>> "@context": {
|
|
152
|
+
>>> "foaf": "http://xmlns.com/foaf/0.1/"
|
|
153
|
+
>>> },
|
|
154
|
+
>>> "@type": "foaf:Person",
|
|
155
|
+
>>> "foaf:firstName": "John"
|
|
156
|
+
>>> }
|
|
60
157
|
|
|
61
158
|
Returns
|
|
62
159
|
-------
|
|
@@ -66,7 +163,7 @@ class Thing(ThingModel):
|
|
|
66
163
|
logger.debug('Initializing RDF graph to dump the Thing to JSON-LD')
|
|
67
164
|
|
|
68
165
|
# lets auto-generate the context
|
|
69
|
-
at_context: Dict = NamespaceManager.get(self.__class__, {})
|
|
166
|
+
at_context: Dict = NamespaceManager.get(self.__class__, {}).copy()
|
|
70
167
|
|
|
71
168
|
if context is None:
|
|
72
169
|
context = {}
|
|
@@ -108,6 +205,7 @@ class Thing(ThingModel):
|
|
|
108
205
|
|
|
109
206
|
uri_ref_manager = URIRefManager.get(obj.__class__, None)
|
|
110
207
|
at_context.update(NamespaceManager.get(obj.__class__, {}))
|
|
208
|
+
|
|
111
209
|
if uri_ref_manager is None:
|
|
112
210
|
return obj
|
|
113
211
|
|
|
@@ -121,7 +219,13 @@ class Thing(ThingModel):
|
|
|
121
219
|
if _is_http_url(iri):
|
|
122
220
|
serialized_fields[iri] = value
|
|
123
221
|
if isinstance(value, str): # this turn URLs into base strings
|
|
124
|
-
|
|
222
|
+
ns, key = split_URIRef(iri)
|
|
223
|
+
if key != k and not resolve_keys:
|
|
224
|
+
at_context[k] = resolve_iri(iri,
|
|
225
|
+
at_context) # the key is not resolved, hence the key and iri is put into context dict:
|
|
226
|
+
serialized_fields[k] = str(value)
|
|
227
|
+
else:
|
|
228
|
+
serialized_fields[iri] = str(value)
|
|
125
229
|
else:
|
|
126
230
|
serialized_fields[iri] = value
|
|
127
231
|
else:
|
|
@@ -137,13 +241,13 @@ class Thing(ThingModel):
|
|
|
137
241
|
except AttributeError as e:
|
|
138
242
|
raise AttributeError(f"Could not serialize {obj} ({obj.__class__}). Orig. err: {e}") from e
|
|
139
243
|
|
|
140
|
-
if obj.model_config['extra'] == 'allow':
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
244
|
+
# if obj.model_config['extra'] == 'allow':
|
|
245
|
+
# for k, v in obj.model_extra.items():
|
|
246
|
+
# iri = uri_ref_manager.get(k, k)
|
|
247
|
+
# if _is_http_url(iri):
|
|
248
|
+
# serialized_fields[k] = v
|
|
249
|
+
# else:
|
|
250
|
+
# serialized_fields[iri] = v
|
|
147
251
|
|
|
148
252
|
# datetime
|
|
149
253
|
for k, v in serialized_fields.copy().items():
|
|
@@ -179,7 +283,8 @@ class Thing(ThingModel):
|
|
|
179
283
|
def model_dump_jsonld(self,
|
|
180
284
|
context: Optional[Dict] = None,
|
|
181
285
|
exclude_none: bool = True,
|
|
182
|
-
rdflib_serialize: bool = False
|
|
286
|
+
rdflib_serialize: bool = False,
|
|
287
|
+
resolve_keys: bool = False) -> str:
|
|
183
288
|
"""Similar to model_dump_json() but will return a JSON string with
|
|
184
289
|
context resulting in a JSON-LD serialization. Using `rdflib_serialize=True`
|
|
185
290
|
will use the rdflib to serialize. This will make the output a bit cleaner
|
|
@@ -199,6 +304,11 @@ class Thing(ThingModel):
|
|
|
199
304
|
If True, the output will be serialized using rdflib. This results in a cleaner
|
|
200
305
|
output but is not needed in most cases and just takes a bit more time (and requires
|
|
201
306
|
an internet connection). Will also generate a blank node if no ID is set.
|
|
307
|
+
resolve_keys: bool=False
|
|
308
|
+
If True, then attributes of a Thing class will be resolved to the full IRI and
|
|
309
|
+
explained in the context.
|
|
310
|
+
|
|
311
|
+
.. seealso:: `Thing.get_jsonld_dict`
|
|
202
312
|
|
|
203
313
|
Returns
|
|
204
314
|
-------
|
|
@@ -207,7 +317,8 @@ class Thing(ThingModel):
|
|
|
207
317
|
"""
|
|
208
318
|
jsonld_dict = self.get_jsonld_dict(
|
|
209
319
|
context=context,
|
|
210
|
-
exclude_none=exclude_none
|
|
320
|
+
exclude_none=exclude_none,
|
|
321
|
+
resolve_keys=resolve_keys
|
|
211
322
|
)
|
|
212
323
|
jsonld_str = json.dumps(jsonld_dict, indent=4)
|
|
213
324
|
if not rdflib_serialize:
|
|
@@ -244,9 +355,38 @@ class Thing(ThingModel):
|
|
|
244
355
|
return f"{self.__class__.__name__}({repr_fields})"
|
|
245
356
|
|
|
246
357
|
@classmethod
|
|
247
|
-
def from_jsonld(cls,
|
|
248
|
-
|
|
358
|
+
def from_jsonld(cls,
|
|
359
|
+
source: Optional[Union[str, pathlib.Path]] = None,
|
|
360
|
+
data: Optional[Dict] = None,
|
|
361
|
+
limit: Optional[int] = None,
|
|
362
|
+
context: Optional[Dict] = None):
|
|
363
|
+
"""Initialize the class from a JSON-LD source
|
|
364
|
+
|
|
365
|
+
Note the inconsistency in the schema.org protocol. Codemeta for instance uses http whereas
|
|
366
|
+
https is the current standard. This repo only works with https. If you have a http schema,
|
|
367
|
+
this method will replace http with https.
|
|
368
|
+
|
|
369
|
+
Parameters
|
|
370
|
+
----------
|
|
371
|
+
source: Optional[Union[str, pathlib.Path]]=None
|
|
372
|
+
The source of the JSON-LD data (filename). Must be given if data is None.
|
|
373
|
+
data: Optional[str]=None
|
|
374
|
+
The JSON-LD data as a string. Must be given if source is None.
|
|
375
|
+
limit: Optional[int]=None
|
|
376
|
+
The limit of the number of objects to return. If None, all objects will be returned.
|
|
377
|
+
If limit is 1, then the first object will be returned, else a list of objects.
|
|
378
|
+
context: Optional[Dict]=None
|
|
379
|
+
The context to use for the JSON-LD serialization. If a string is given, it will
|
|
380
|
+
be interpreted as an import statement and will be added to the context.
|
|
381
|
+
|
|
382
|
+
"""
|
|
249
383
|
from . import query
|
|
384
|
+
if data is not None and isinstance(data, str):
|
|
385
|
+
if 'http://schema.org/' in data:
|
|
386
|
+
warnings.warn('Replacing http with https in the JSON-LD data. '
|
|
387
|
+
'This is a workaround for the schema.org inconsistency.',
|
|
388
|
+
UserWarning)
|
|
389
|
+
data = data.replace('http://schema.org/', 'https://schema.org/')
|
|
250
390
|
return query(cls, source=source, data=data, limit=limit, context=context)
|
|
251
391
|
|
|
252
392
|
@classmethod
|
|
@@ -277,17 +417,27 @@ class Thing(ThingModel):
|
|
|
277
417
|
ns_iri = NamespaceManager[cls].get(ns, None)
|
|
278
418
|
return f'{ns_iri}{key}'
|
|
279
419
|
|
|
280
|
-
@classmethod
|
|
281
|
-
def get_context(cls):
|
|
282
|
-
"""Return the context of the class"""
|
|
283
|
-
return NamespaceManager[cls]
|
|
284
|
-
|
|
285
420
|
@property
|
|
286
|
-
def namespaces(self):
|
|
421
|
+
def namespaces(self) -> Dict:
|
|
287
422
|
"""Return the namespaces of the class"""
|
|
288
|
-
return
|
|
423
|
+
return get_namespaces(self.__class__)
|
|
289
424
|
|
|
290
425
|
@property
|
|
291
|
-
def urirefs(self):
|
|
292
|
-
"""Return the
|
|
293
|
-
return
|
|
426
|
+
def urirefs(self) -> Dict:
|
|
427
|
+
"""Return the urirefs of the class"""
|
|
428
|
+
return get_urirefs(self.__class__)
|
|
429
|
+
|
|
430
|
+
@classmethod
|
|
431
|
+
def get_context(cls) -> Dict:
|
|
432
|
+
"""Return the context of the class"""
|
|
433
|
+
return get_namespaces(cls)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def get_urirefs(cls: Thing) -> Dict:
|
|
437
|
+
"""Return the URIRefs of the class"""
|
|
438
|
+
return URIRefManager[cls]
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def get_namespaces(cls: Thing) -> Dict:
|
|
442
|
+
"""Return the namespaces of the class"""
|
|
443
|
+
return NamespaceManager[cls]
|
|
@@ -4,7 +4,7 @@ import pydantic
|
|
|
4
4
|
import unittest
|
|
5
5
|
from pydantic import EmailStr
|
|
6
6
|
|
|
7
|
-
from ontolutils import Thing, urirefs, namespaces
|
|
7
|
+
from ontolutils import Thing, urirefs, namespaces, get_urirefs, get_namespaces
|
|
8
8
|
from ontolutils import set_logging_level
|
|
9
9
|
from ontolutils.classes import decorator
|
|
10
10
|
|
|
@@ -14,6 +14,7 @@ LOG_LEVEL = logging.DEBUG
|
|
|
14
14
|
class TestNamespaces(unittest.TestCase):
|
|
15
15
|
|
|
16
16
|
def setUp(self):
|
|
17
|
+
self.maxDiff = None
|
|
17
18
|
logger = logging.getLogger('ontolutils')
|
|
18
19
|
self.INITIAL_LOG_LEVEL = logger.level
|
|
19
20
|
|
|
@@ -25,6 +26,22 @@ class TestNamespaces(unittest.TestCase):
|
|
|
25
26
|
set_logging_level(self.INITIAL_LOG_LEVEL)
|
|
26
27
|
assert logging.getLogger('ontolutils').level == self.INITIAL_LOG_LEVEL
|
|
27
28
|
|
|
29
|
+
def test_thing_custom_prop(self):
|
|
30
|
+
"""It is helpful to have the properties equal to the urirefs keys,
|
|
31
|
+
however, this should not be required!"""
|
|
32
|
+
|
|
33
|
+
@namespaces(foaf='http://xmlns.com/foaf/0.1/',
|
|
34
|
+
prov='http://www.w3.org/ns/prov#')
|
|
35
|
+
@urirefs(Person='prov:Person',
|
|
36
|
+
first_name='foaf:firstName',
|
|
37
|
+
lastName='foaf:lastName')
|
|
38
|
+
class Person(Thing):
|
|
39
|
+
first_name: str = None
|
|
40
|
+
lastName: str
|
|
41
|
+
|
|
42
|
+
p = Person(first_name='John', lastName='Doe')
|
|
43
|
+
print(p.model_dump_jsonld(resolve_keys=False))
|
|
44
|
+
|
|
28
45
|
def test_sort_classes(self):
|
|
29
46
|
thing1 = Thing(label='Thing 1')
|
|
30
47
|
thing2 = Thing(label='Thing 2')
|
|
@@ -161,6 +178,51 @@ class TestNamespaces(unittest.TestCase):
|
|
|
161
178
|
'https://git.rwth-aachen.de/nfdi4ing/metadata4ing/metadata4ing/-/raw/master/m4i_context.jsonld'
|
|
162
179
|
)
|
|
163
180
|
|
|
181
|
+
def test_model_dump_jsonld_and_load_with_import(self):
|
|
182
|
+
@namespaces(foaf="http://xmlns.com/foaf/0.1/")
|
|
183
|
+
@urirefs(Agent='foaf:Agent',
|
|
184
|
+
mbox='foaf:mbox')
|
|
185
|
+
class Agent(Thing):
|
|
186
|
+
"""Pydantic Model for http://xmlns.com/foaf/0.1/Agent
|
|
187
|
+
Parameters
|
|
188
|
+
----------
|
|
189
|
+
mbox: EmailStr = None
|
|
190
|
+
Email address (foaf:mbox)
|
|
191
|
+
"""
|
|
192
|
+
mbox: EmailStr = None
|
|
193
|
+
|
|
194
|
+
agent = Agent(
|
|
195
|
+
label='Agent 1',
|
|
196
|
+
mbox='my@email.com'
|
|
197
|
+
)
|
|
198
|
+
ns = agent.namespaces
|
|
199
|
+
jsonld_string = agent.model_dump_jsonld(
|
|
200
|
+
context={
|
|
201
|
+
"@import": 'https://raw.githubusercontent.com/matthiasprobst/pivmeta/main/pivmeta_context.jsonld'
|
|
202
|
+
}
|
|
203
|
+
)
|
|
204
|
+
self.assertDictEqual(agent.namespaces, ns)
|
|
205
|
+
self.assertTrue('@import' in json.loads(jsonld_string)['@context'])
|
|
206
|
+
loaded_agent = Agent.from_jsonld(data=jsonld_string, limit=1)
|
|
207
|
+
self.assertDictEqual(loaded_agent.namespaces, ns)
|
|
208
|
+
self.assertEqual(loaded_agent.mbox, agent.mbox)
|
|
209
|
+
|
|
210
|
+
def test_schema_http(self):
|
|
211
|
+
@namespaces(foaf="http://xmlns.com/foaf/0.1/",
|
|
212
|
+
schema="https://schema.org/")
|
|
213
|
+
@urirefs(Agent='foaf:Agent',
|
|
214
|
+
name='schema:name')
|
|
215
|
+
class Agent(Thing):
|
|
216
|
+
name: str
|
|
217
|
+
|
|
218
|
+
agent = Agent(name='John Doe')
|
|
219
|
+
self.assertEqual(agent.name, 'John Doe')
|
|
220
|
+
agent_jsonld = agent.model_dump_jsonld()
|
|
221
|
+
print(agent_jsonld.replace('https://schema', 'http://schema'))
|
|
222
|
+
with self.assertWarns(UserWarning):
|
|
223
|
+
agent.from_jsonld(data=agent_jsonld.replace('https://schema', 'http://schema'),
|
|
224
|
+
limit=1)
|
|
225
|
+
|
|
164
226
|
def test_model_dump_jsonld_nested(self):
|
|
165
227
|
@namespaces(foaf="http://xmlns.com/foaf/0.1/")
|
|
166
228
|
@urirefs(Agent='foaf:Agent',
|
|
@@ -255,15 +317,19 @@ class TestNamespaces(unittest.TestCase):
|
|
|
255
317
|
pass
|
|
256
318
|
|
|
257
319
|
mt = CustomPerson()
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
320
|
+
# custom person has no
|
|
321
|
+
self.assertDictEqual(mt.urirefs, get_urirefs(Thing))
|
|
322
|
+
self.assertDictEqual(mt.urirefs, {'Thing': 'owl:Thing', 'label': 'rdfs:label'})
|
|
323
|
+
self.assertDictEqual(mt.namespaces, get_namespaces(Thing))
|
|
324
|
+
self.assertDictEqual(mt.namespaces, {'owl': 'http://www.w3.org/2002/07/owl#',
|
|
325
|
+
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#'})
|
|
261
326
|
|
|
262
327
|
mt = CustomPerson(first_name='John', last_name='Doe')
|
|
263
328
|
with self.assertRaises(AttributeError):
|
|
264
329
|
mt.namespaces = 'http://xmlns.com/foaf/0.1/'
|
|
265
330
|
with self.assertRaises(AttributeError):
|
|
266
331
|
mt.urirefs = 'foaf:lastName'
|
|
332
|
+
|
|
267
333
|
mt.namespaces['foaf'] = 'http://xmlns.com/foaf/0.1/'
|
|
268
334
|
mt.urirefs['first_name'] = 'foaf:firstName'
|
|
269
335
|
mt.urirefs['last_name'] = 'foaf:lastName'
|
|
@@ -276,10 +342,26 @@ class TestNamespaces(unittest.TestCase):
|
|
|
276
342
|
},
|
|
277
343
|
"@type": "CustomPerson",
|
|
278
344
|
"foaf:firstName": "John",
|
|
279
|
-
"foaf:lastName": "Doe"
|
|
280
|
-
|
|
345
|
+
"foaf:lastName": "Doe"
|
|
346
|
+
}
|
|
347
|
+
jsonld_dict = json.loads(mt.model_dump_jsonld(resolve_keys=True))
|
|
348
|
+
jsonld_dict.pop('@id')
|
|
349
|
+
self.assertDictEqual(jsonld_dict,
|
|
350
|
+
ref_jsonld)
|
|
351
|
+
|
|
352
|
+
ref_jsonld = {
|
|
353
|
+
"@context": {
|
|
354
|
+
"owl": "http://www.w3.org/2002/07/owl#",
|
|
355
|
+
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
|
|
356
|
+
"foaf": "http://xmlns.com/foaf/0.1/",
|
|
357
|
+
"first_name": "http://xmlns.com/foaf/0.1/firstName",
|
|
358
|
+
"last_name": "http://xmlns.com/foaf/0.1/lastName"
|
|
359
|
+
},
|
|
360
|
+
"@type": "CustomPerson",
|
|
361
|
+
"first_name": "John",
|
|
362
|
+
"last_name": "Doe"
|
|
281
363
|
}
|
|
282
|
-
jsonld_dict = json.loads(mt.model_dump_jsonld())
|
|
364
|
+
jsonld_dict = json.loads(mt.model_dump_jsonld(resolve_keys=False))
|
|
283
365
|
jsonld_dict.pop('@id')
|
|
284
366
|
self.assertDictEqual(jsonld_dict,
|
|
285
367
|
ref_jsonld)
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
"""Testing code used in the README.md file"""
|
|
2
2
|
import pathlib
|
|
3
|
-
|
|
4
3
|
from pydantic import EmailStr
|
|
5
4
|
|
|
6
5
|
from ontolutils import Thing, namespaces, urirefs
|
|
@@ -38,3 +37,17 @@ found_agent = found_agents[0]
|
|
|
38
37
|
print(found_agent.mbox)
|
|
39
38
|
|
|
40
39
|
pathlib.Path("agent.json").unlink(missing_ok=True)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@namespaces(prov='http://www.w3.org/ns/prov#',
|
|
43
|
+
|
|
44
|
+
foaf='http://xmlns.com/foaf/0.1/')
|
|
45
|
+
@urirefs(Person='prov:Person', first_name='foaf:firstName')
|
|
46
|
+
class Person(Thing):
|
|
47
|
+
first_name: str = None
|
|
48
|
+
last_name: str = None
|
|
49
|
+
|
|
50
|
+
p = Person(first_name='John', last_name='Doe', age=30)
|
|
51
|
+
print(p.model_dump_jsonld())
|
|
52
|
+
|
|
53
|
+
# Person(first_name=1)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|