-
Notifications
You must be signed in to change notification settings - Fork 3
/
test_core.py
386 lines (290 loc) · 16.2 KB
/
test_core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import os
import sys
import unittest
import json
import yamlpyowl as ypo
import typing
import pydantic
# noinspection PyUnresolvedReferences
from ipydex import IPS, activate_ips_on_exception
BASEPATH = os.path.dirname(os.path.dirname(os.path.abspath(sys.modules.get(__name__).__file__)))
# noinspection PyPep8Naming
class TestCore(unittest.TestCase):
def setUp(self):
# prevent that the tests do influence each other -> create a new world each time
self.world = ypo.owl2.World()
# mark tests which only work for the "old core"
def test_pizza(self):
onto = ypo.OntologyManager("examples/pizza.owl.yml", self.world)
n = onto.n
self.assertEqual(n.mypizza1.hasNumericalValues, [10])
self.assertEqual(n.mypizza2.hasNumericalValues, [12.5, -3])
self.assertEqual(n.mypizza1.hasBase, n.iThinAndCrispyBase)
self.assertEqual(
n.mypizza2.hasStrAttribute,
["Tasty", "Pizza!", "Multi line\nstring\n\nattribute\n", "Second multi line string attribute\n"]
)
self.assertEqual(onto.onto.base_iri, "https://w3id.org/yet/undefined/simplified-pizza-ontology#")
self.assertEqual(n.iMozzarellaTopping.X_hasCombinedTasteValue_RC[1].hasFunctionValue, 0.5)
onto.sync_reasoner(infer_property_values=True, infer_data_property_values=True)
def test_pizza_generic_individuals(self):
"""
:return:
"""
onto = ypo.OntologyManager("examples/pizza.owl.yml", self.world)
n = onto.n
# ensure that an individual `iMozzarellaTopping` exists and that it is an instance of MozzarellaTopping
# note that this individual is not explicitly created in the source file
self.assertTrue(n.MozzarellaTopping in n.iMozzarellaTopping.is_instance_of)
self.assertTrue("iTomatoTopping" in onto.name_mapping)
# explicitly turned of with `_createGenericIndividual=False`
self.assertFalse("iOnionTopping" in onto.name_mapping)
def test_regional_rules(self):
onto = ypo.OntologyManager("examples/regional-rules.owl.yml", self.world)
n = onto.n
self.assertTrue(n.leipzig in n.saxony.hasPart)
self.assertTrue("dresden" in onto.name_mapping)
# test if labels work as expected
# !! not yet implemented
# self.assertTrue("Federal Republic of Germany" in repr(onto.n.germany))
# test proper handling of multiple subclasses
self.assertTrue(issubclass(n.TrainStation, n.Facility))
self.assertTrue(issubclass(n.TrainStation, n.LocationType))
self.assertFalse(issubclass(n.TrainStation, n.FederalState))
# test proper handling of the RelationConcept magic mechanism
self.assertEqual(n.dir_rule1.X_hasDocumentReference_RC[0].hasSection, "§ 1.1")
self.assertTrue(n.dir_rule2.X_hasDocumentReference_RC[0].hasSourceDocument == n.law_book_of_saxony)
self.assertTrue(n.dir_rule2.X_hasDocumentReference_RC[0].hasSection == "§ 1.5")
self.assertEqual(n.munich.X_hasInterRegionRelation_RC[0].hasIRRTarget, n.dresden)
self.assertEqual(n.munich.X_hasInterRegionRelation_RC[0].hasIRRValue, 0.5)
self.assertEqual(n.munich.X_hasInterRegionRelation_RC[2].hasIRRTarget, n.regensburg)
self.assertEqual(n.munich.X_hasInterRegionRelation_RC[2].hasIRRValue, 0.7)
# test Or-Syntax:
self.assertEqual(n.X_hasTesting_RC.domain, [n.Directive | n.Facility])
self.assertEqual(len(n.dresden.hasDirective), 0)
self.assertTrue(n.dir_rule0 in n.germany.hasDirective)
self.assertFalse(n.dir_rule0 in n.saxony.hasDirective)
self.assertFalse(n.dir_rule0 in n.leipzig.hasDirective)
# run the reasoner (which applies transitive properties and swrl-rules)
onto.sync_reasoner(infer_property_values=True, infer_data_property_values=True)
self.assertTrue(n.leipzig in n.germany.hasPart)
# after the reasoner has run, the rules should be applied (due to swrl-rules)
# rule: top_down
self.assertTrue(n.dir_rule0 in n.saxony.hasDirective)
self.assertTrue(n.dir_rule0 in n.leipzig.hasDirective)
self.assertTrue(n.dir_rule0 in n.dresden.hasDirective)
self.assertTrue(n.dir_rule2 in n.dresden.hasDirective)
self.assertTrue(n.dir_rule3 in n.dresden.hasDirective)
# rule2 and rule3 where added manually to munich
self.assertTrue(n.dir_rule2 in n.munich.hasDirective)
self.assertTrue(n.dir_rule3 in n.munich.hasDirective)
# rule2 and rule3 should not apply in any other bavarian region
self.assertFalse(n.dir_rule2 in n.passau.hasDirective)
self.assertFalse(n.dir_rule3 in n.hof.hasDirective)
self.assertEqual(set(n.dir_rule3.affects), {n.dresden, n.passau, n.regensburg})
self.assertFalse(n.leipzig in n.dir_rule3.affects)
# test RC stipulations (InterRegionalRelations, IRR):
tmp = [x.hasIRRTarget for x in n.munich.X_hasInterRegionRelation_RC]
self.assertTrue(tmp == [n.dresden, n.passau, n.regensburg, n.leipzig])
self.assertTrue(n.munich.X_hasInterRegionRelation_RC[0].hasIRRValue == 0.5)
def test_regional_rules_query(self):
# this largely is oriented on calls to query_owlready() in
# https://bitbucket.org/jibalamy/owlready2/src/master/test/regtest.py
om = ypo.OntologyManager("examples/regional-rules.owl.yml", self.world)
q_hasSection1 = f"""
PREFIX P: <{om.iri}>
SELECT ?x WHERE {{
?x P:hasSection "§ 1.1".
}}
"""
r = om.make_query(q_hasSection1)
self.assertEqual(r, {om.n.iX_DocumentReference_RC_0})
q_hasPart1 = f"""
PREFIX P: <{om.iri}>
SELECT ?x WHERE {{
?x P:hasPart P:dresden.
}}
"""
r = om.make_query(q_hasPart1)
self.assertEqual(r, {om.n.saxony})
om.sync_reasoner(infer_property_values=True, infer_data_property_values=True)
r = om.make_query(q_hasPart1)
self.assertEqual(r, {om.n.saxony, om.n.germany})
def test_check_type(self):
obj1 = [3, 4, 5]
obj2 = [3, 4, "5"]
# pass silently
ypo.check_type(obj1, typing.List[pydantic.StrictInt])
with self.assertRaises(TypeError):
ypo.check_type(obj2, typing.List[pydantic.StrictInt])
obj3 = {"key 1": 1.0, "key 2": 2.0, "key 3": 3.0}
ypo.check_type(obj3, typing.Dict[str, pydantic.StrictFloat])
obj3["key 3"] = "3.0"
obj3["key 4"] = 5
with self.assertRaises(TypeError):
ypo.check_type(obj3, typing.Dict[str, pydantic.StrictFloat])
# allow for multiple types:
ypo.check_type(obj3, typing.Dict[str, typing.Union[pydantic.StrictInt, pydantic.StrictFloat, str]])
def test_zebra_puzzle(self):
fpath = "examples/einsteins_zebra_riddle.owl.yml"
om = ypo.OntologyManager(fpath, self.world)
self.assertEqual(om.iri, "https://w3id.org/yet/undefined/einstein-zebra-puzzle-ontology#")
n = om.n
# remember: dog is created as a `Thing` (not a pet before the reasoner is called)
self.assertNotIn(n.Pet, n.dog.is_a)
self.assertTrue(n.house_2.right_to, n.house_1)
self.assertTrue(n.house_1.right_to, ypo.owl2.Nothing)
self.assertTrue(n.house_5.left_to, ypo.owl2.Nothing)
self.assertTrue(n.right_to.is_functional_for(n.House))
self.assertTrue(n.left_to.is_functional_for(n.House))
om.sync_reasoner(infer_property_values=True)
# after the reasoner finished these assertions hold true
self.assertIn(n.Pet, n.dog.is_a)
self.assertIn(n.Pet, n.fox.is_a)
self.assertTrue(n.house_2.left_to, n.house_3)
restriction_tuples = []
# noinspection PyShadowingNames
def append_restriction_tuple(restr, indiv):
restriction_tuples.append((restr, indiv))
# note these restrictions are defined in the yaml-file and are tested here
append_restriction_tuple(n.lives_in.some(n.has_color.value(n.red)), n.Englishman)
# 3. The Spaniard owns the dog.
append_restriction_tuple(n.owns.value(n.dog), n.Spaniard)
# 4. Coffee is drunk in the green house.
append_restriction_tuple(n.Inverse(n.drinks).some(n.lives_in.some(n.has_color.value(n.green))), n.coffee)
# 5. The Ukrainian drinks tea.
# append_restriction_tuple(n.drinks.value(n.tea), n.Ukrainian)
# this is tested directly:
self.assertEqual(n.Ukrainian.drinks, n.tea)
# 6. The green house is immediately to the right of the ivory house.
append_restriction_tuple(n.Inverse(n.has_color).some(n.right_to.some(n.has_color.value(n.ivory))), n.green)
# 7. The Old Gold smoker owns snails.
append_restriction_tuple(n.Inverse(n.smokes).some(n.owns.value(n.snails)), n.Old_Gold)
# 8. Kools are smoked in the yellow house.
append_restriction_tuple(n.Inverse(n.smokes).some(n.lives_in.some(n.has_color.value(n.yellow))), n.Kools)
# 9. Milk is drunk in the middle house.
append_restriction_tuple(n.Inverse(n.drinks).some(n.lives_in.value(n.house_3)), n.milk)
# 10. The Norwegian lives in the first house.
# append_restriction_tuple(n.lives_in.value(n.house_1), n.Norwegian)
# this is tested directly:
self.assertEqual(n.Norwegian.lives_in, n.house_1)
# 11. The man who smokes Chesterfields lives in the house next to the man with the fox.
# right_to ist additional information
append_restriction_tuple(
n.Inverse(n.smokes).some(n.lives_in.some(n.right_to.some(n.Inverse(n.lives_in).some(n.owns.value(n.fox))))),
n.Chesterfields,
)
# 12. Kools are smoked in a house next to the house where the horse is kept.
# left_to ist additional information
append_restriction_tuple(
n.Inverse(n.smokes).some(
n.lives_in.some(n.left_to.some(n.Inverse(n.lives_in).some(n.owns.value(n.horse))))
),
n.Kools,
)
# 13. The Lucky Strike smoker drinks orange juice.
append_restriction_tuple(n.Inverse(n.smokes).some(n.drinks.value(n.orange_juice)), n.Lucky_Strike)
# 14. The Japanese smokes Parliaments.
# append_restriction_tuple(n.smokes.value(n.Parliaments), n.Japanese)
# this is tested directly:
self.assertEqual(n.Japanese.smokes, n.Parliaments)
# 15. The Norwegian lives next to the blue house.
# !! "left_to" is additional knowledge
append_restriction_tuple(n.lives_in.some(n.left_to.some(n.has_color.value(n.blue))), n.Norwegian)
for rstrn, indiv in restriction_tuples:
with self.subTest(rstrn=rstrn, indiv=indiv):
self.assertIn(rstrn, indiv.is_a)
# this is only true if the puzzle is solved completely
self.assertEqual(n.Japanese.owns, n.zebra)
# for historical reasons this class contains newer tests
class TestCore2(unittest.TestCase):
def setUp(self):
# prevent that the tests do influence each other -> create a new world each time
self.world = ypo.owl2.World()
fpath = f"{BASEPATH}/tests/test_ontologies/basic_feature_ontology.owl.yml"
self.om = ypo.OntologyManager(fpath, self.world)
def test_basic_features(self):
# several features are tested in one unit test for better performance
# iri
self.assertEquals(self.om.onto.base_iri, "https://w3id.org/unpublished/yamlpyowl/basic-feature-ontology#")
# annotations of whole ontology
self.assertEqual(len(self.om.onto.metadata.comment), 2)
self.assertTrue("utc_global_annotation" in self.om.onto.metadata.comment[0])
self.assertTrue("utc_global_annotation" in self.om.onto.metadata.comment[1])
# annotations of classes
self.assertEqual(len(self.om.n.Class1.comment), 1)
self.assertTrue("utc_annotation" in self.om.n.Class1.comment[0])
self.assertEqual(len(self.om.n.Class2.comment), 4)
# labels
self.assertEqual(len(self.om.n.Class4.label), 3)
self.assertEqual(self.om.n.Class4.label.first(), "First label")
self.assertTrue("\n" in self.om.n.Class4.label[-1][:-1])
# imports
self.assertEqual(len(self.om.onto.imported_ontologies), 1)
imported_onto = self.om.onto.imported_ontologies[0]
self.assertEqual(imported_onto.name, "bfo")
self.assertEqual(imported_onto.base_iri, "http://purl.obolibrary.org/obo/bfo.owl#")
# import_annotations_dict
iad = json.loads(imported_onto.metadata.comment[-1])
self.assertTrue("download_link" in iad["import_annotations"])
self.assertEqual(iad["import_annotations"]["comment"], "utc_import_annotation_comment")
# this does not work (yet), because bfo uses names like "BFO_0000001" and strings like "entity"
# is stored as a label
# self.assertTrue(imported_onto.entity is not None)
# currently the way to access bfo classes is quite clumsy, but at least it works:
bfo_entity_class = self.om.world["http://purl.obolibrary.org/obo/BFO_0000001"]
self.assertTrue(bfo_entity_class in self.om.n.Class3.is_a)
def test_proxy_individual(self):
# see docstring of core._handle_proxy_individuals for more info
self.assertEquals(self.om.onto.base_iri, "https://w3id.org/unpublished/yamlpyowl/basic-feature-ontology#")
n = self.om.n
self.assertEqual(len(n.Class5.instances()), 4)
self.assertEqual(len(n.Class5a1.instances()), 0)
self.assertEqual(len(n.Class5a2.instances()), 0)
# ensure that the individual exists and is of correct type
self.assertTrue(isinstance(n.iClass5a, n.Class5))
self.assertTrue(type(n.iClass5a), n.Class5a)
def test_equivalent_to(self):
n = self.om.n
self.assertEqual(len(n.Class6.equivalent_to), 1)
self.assertEqual(len(n.Class2.equivalent_to), 0)
self.assertEqual(len(n.Class7.equivalent_to), 1)
self.assertEqual(n.Class7.equivalent_to[0], ypo.owl2.class_construct.Or([n.Class2, n.Class3]))
# we use set(...) here to ensure uniqueness
self.assertEqual(len(set(n.Class8a.instances())), 0)
self.assertEqual(len(set(n.Class8b.instances())), 0)
self.om.sync_reasoner(infer_property_values=True, infer_data_property_values=True)
self.assertEqual(len(n.Class2.equivalent_to), 1)
self.assertEqual(len(set(n.Class8a.instances())), 2)
self.assertEqual(len(set(n.Class8b.instances())), 1)
self.assertEqual(len(set(n.Class8c.instances())), 1)
self.assertEqual(len(set(n.Class8d.instances())), 2)
def test_complex_subclass(self):
n = self.om.n
# owl:Thing and a definied expression
self.assertEqual(len(n.Class9a.is_a), 2)
self.assertFalse(n.Class9a in set(n.Class1.subclasses()))
self.om.sync_reasoner(infer_property_values=True, infer_data_property_values=True)
# Class9a is inferred as a subclass of Class1 due to the domain of `has_demo_function_value`
self.assertTrue(n.Class9a in set(n.Class1.subclasses()))
def test_restriction(self):
n = self.om.n
expected_restriction = n.has_demo_property_value.some(n.Class2)
self.assertIn(expected_restriction, n.Class10a.is_a)
# test for explicit sublcass
self.assertIn(n.Class11a, n.Class11b.is_a)
self.assertNotIn(n.Class4, n.Class10a.is_a)
self.om.sync_reasoner(infer_property_values=True, infer_data_property_values=True)
self.assertIn(n.Class4, n.Class10a.is_a)
def test_axiom_equivalent_to(self):
n = self.om.n
expected_class_expression = n.has_demo_property_value2.some(n.Class2)
self.assertIn(expected_class_expression, n.Class10b.equivalent_to)
self.assertIn(n.Class10d, n.Class10c.equivalent_to)
self.assertIn(n.Class10e, n.Class10d.equivalent_to)
self.assertIn(n.Class10f, n.Class10d.equivalent_to)
self.assertNotIn(n.Class10e, n.Class10c.equivalent_to)
self.assertNotIn(n.Class10f, n.Class10c.equivalent_to)
self.om.sync_reasoner(infer_property_values=True, infer_data_property_values=True)
self.assertIn(n.Class10e, n.Class10c.equivalent_to)
self.assertIn(n.Class10f, n.Class10c.equivalent_to)