-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathtest_wrapper.py
480 lines (400 loc) · 17.2 KB
/
test_wrapper.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
"""Tests the wrapper as user-facing session management interface."""
import filecmp
import multiprocessing
import os
import socket
import time
import unittest
from base64 import b64encode
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
from typing import Optional
from rdflib import XSD, Literal
from simphony_osp.ontology.parser import OntologyParser
from simphony_osp.session.session import Session
from simphony_osp.session.wrapper import Wrapper
from simphony_osp.tools import host
from simphony_osp.utils.datatypes import Vector
from simphony_osp.wrappers import Dataspace, Remote, SQLite
class TestWrapper(unittest.TestCase):
"""Test the full end-user experience of using a wrapper.
The wrapper used for the test is the `SQLite` wrapper.
"""
file_name: str = "TestSQLiteSession"
prev_default_ontology: Session
@classmethod
def setUpClass(cls):
"""Create a TBox and set it as the default ontology.
The new TBox contains SimPhoNy, OWL, RDFS and City.
"""
ontology = Session(identifier="test_tbox", ontology=True)
ontology.load_parser(OntologyParser.get_parser("city"))
cls.prev_default_ontology = Session.default_ontology
Session.default_ontology = ontology
@classmethod
def tearDownClass(cls):
"""Restore the previous default TBox."""
Session.default_ontology = cls.prev_default_ontology
def tearDown(self) -> None:
"""Remove the database file."""
try:
os.remove(self.file_name)
except FileNotFoundError:
pass
def test_wrapper_city(self) -> None:
"""Test adding some entities from the city ontology."""
from simphony_osp.namespaces import city
from simphony_osp.wrappers import SQLite
with SQLite(self.file_name, create=True) as wrapper:
freiburg = city.City(name="Freiburg", coordinates=[20, 58])
freiburg_identifier = freiburg.identifier
marco = city.Citizen(
iri="http://example.org/citizens#Marco", name="Marco", age=50
)
matthias = city.Citizen(name="Matthias", age=37)
freiburg[city.hasInhabitant] = {marco, matthias}
self.assertIn(marco, set(wrapper))
self.assertIn(matthias, set(wrapper))
self.assertIn(freiburg, set(wrapper))
self.assertSetEqual({marco, matthias, freiburg}, set(wrapper))
self.assertTrue(len(wrapper), 3)
self.assertEqual(freiburg.name, "Freiburg")
self.assertEqual(freiburg.coordinates, [20, 58])
self.assertEqual(marco.name, "Marco")
self.assertEqual(marco.age, 50)
self.assertEqual(matthias.name, "Matthias")
self.assertEqual(matthias.age, 37)
wrapper.commit()
freiburg.coordinates = Vector([22, 58])
self.assertEqual(freiburg.coordinates, [22, 58])
with SQLite(self.file_name) as wrapper:
freiburg = wrapper.from_identifier(freiburg_identifier)
citizens = list(freiburg[city.hasInhabitant])
self.assertEqual("Freiburg", freiburg.name)
self.assertEqual([20, 58], freiburg.coordinates)
self.assertSetEqual(
{"Marco", "Matthias"}, {citizen.name for citizen in citizens}
)
self.assertSetEqual(
{50, 37}, {citizen.age for citizen in citizens}
)
everything = {*citizens, freiburg}
self.assertIn(citizens[0], set(wrapper))
self.assertIn(citizens[1], set(wrapper))
self.assertIn(freiburg, set(wrapper))
self.assertSetEqual(everything, set(wrapper))
self.assertTrue(len(wrapper), 3)
wrapper.delete(*citizens)
self.assertEqual(len(wrapper), 1)
self.assertEqual(len(freiburg[city.hasInhabitant]), 0)
wrapper.delete(freiburg)
self.assertEqual(len(wrapper), 0)
wrapper.commit()
pr = city.City(name="Paris", coordinates=[0, 0])
with SQLite(self.file_name) as wrapper:
self.assertEqual(len(wrapper), 0)
wrapper.add(pr)
wrapper.commit()
with SQLite(self.file_name) as wrapper:
self.assertEqual(len(wrapper), 1)
paris = set(wrapper).pop()
self.assertEqual(paris.name, "Paris")
def test_wrapper_sparql(self) -> None:
"""Test SPARQL queries on wrappers."""
from simphony_osp.namespaces import city
from simphony_osp.tools import sparql
from simphony_osp.wrappers import SQLite
with SQLite(self.file_name, create=True):
freiburg = city.City(name="Freiburg", coordinates=[20, 58])
marco = city.Citizen(
iri="http://example.org/citizens#Marco", name="Marco", age=50
)
matthias = city.Citizen(name="Matthias", age=37)
freiburg[city.hasInhabitant] = {marco, matthias}
result = list(
sparql(
f"""
SELECT ?age WHERE {{
<{matthias.iri}> <{city.age.iri}> ?age .
}}
"""
)
)
self.assertEqual(len(result), 1)
self.assertEqual(len(result[0]), 1)
self.assertEqual(Literal("37", datatype=XSD.integer), result[0][0])
class TestDataspaceWrapper(unittest.TestCase):
"""Test the full end-user experience of using a wrapper.
The wrapper used for the test is the `dataspace` wrapper.
"""
prev_default_ontology: Session
dataspace_directory: TemporaryDirectory
second_dataspace_directory: TemporaryDirectory
@classmethod
def setUpClass(cls):
"""Create a TBox and set it as the default ontology.
The new TBox contains SimPhoNy, OWL, RDFS and City.
"""
ontology = Session(identifier="test_tbox", ontology=True)
ontology.load_parser(OntologyParser.get_parser("city"))
cls.prev_default_ontology = Session.default_ontology
Session.default_ontology = ontology
@classmethod
def tearDownClass(cls):
"""Restore the previous default TBox."""
Session.default_ontology = cls.prev_default_ontology
def setUp(self) -> None:
"""Create a temporary directory for files."""
self.dataspace_directory = TemporaryDirectory()
self.second_dataspace_directory = TemporaryDirectory()
def tearDown(self) -> None:
"""Clean the temporary directory for files."""
self.dataspace_directory.cleanup()
self.second_dataspace_directory.cleanup()
def test_wrapper_city(self) -> None:
"""Test adding some entities from the city ontology."""
from simphony_osp.namespaces import city
with Dataspace(self.dataspace_directory.name, True) as wrapper:
freiburg = city.City(name="Freiburg", coordinates=[20, 58])
freiburg_identifier = freiburg.identifier
marco = city.Citizen(
iri="http://example.org/citizens#Marco", name="Marco", age=50
)
matthias = city.Citizen(name="Matthias", age=37)
freiburg[city.hasInhabitant] = {marco, matthias}
self.assertIn(marco, set(wrapper))
self.assertIn(matthias, set(wrapper))
self.assertIn(freiburg, set(wrapper))
self.assertSetEqual({marco, matthias, freiburg}, set(wrapper))
self.assertTrue(len(wrapper), 3)
self.assertEqual(freiburg.name, "Freiburg")
self.assertEqual(freiburg.coordinates, [20, 58])
self.assertEqual(marco.name, "Marco")
self.assertEqual(marco.age, 50)
self.assertEqual(matthias.name, "Matthias")
self.assertEqual(matthias.age, 37)
wrapper.commit()
freiburg.coordinates = Vector([22, 58])
self.assertEqual(freiburg.coordinates, [22, 58])
with Dataspace(self.dataspace_directory.name, False) as wrapper:
freiburg = wrapper.from_identifier(freiburg_identifier)
citizens = list(freiburg[city.hasInhabitant])
self.assertEqual("Freiburg", freiburg.name)
self.assertEqual([20, 58], freiburg.coordinates)
self.assertSetEqual(
{"Marco", "Matthias"}, {citizen.name for citizen in citizens}
)
self.assertSetEqual(
{50, 37}, {citizen.age for citizen in citizens}
)
everything = {*citizens, freiburg}
self.assertIn(citizens[0], set(wrapper))
self.assertIn(citizens[1], set(wrapper))
self.assertIn(freiburg, set(wrapper))
self.assertSetEqual(everything, set(wrapper))
self.assertTrue(len(wrapper), 3)
wrapper.delete(*citizens)
self.assertEqual(len(wrapper), 1)
self.assertEqual(len(freiburg[city.hasInhabitant]), 0)
wrapper.delete(freiburg)
self.assertEqual(len(wrapper), 0)
wrapper.commit()
pr = city.City(name="Paris", coordinates=[0, 0])
with Dataspace(self.dataspace_directory.name, False) as wrapper:
self.assertEqual(len(wrapper), 0)
wrapper.add(pr)
wrapper.commit()
with Dataspace(self.dataspace_directory.name, False) as wrapper:
self.assertEqual(len(wrapper), 1)
paris = set(wrapper).pop()
self.assertEqual(paris.name, "Paris")
wrapper.delete(paris)
wrapper.commit()
with Dataspace(self.dataspace_directory.name, False) as wrapper:
self.assertEqual(len(wrapper), 0)
def test_files(self):
"""Test handling files."""
from simphony_osp.namespaces import simphony
with NamedTemporaryFile("w", suffix=".txt") as os_file:
os_file.write("text")
os_file.flush()
os.fsync(os_file)
# Test creating file object and filling it with a file.
with Dataspace(self.dataspace_directory.name, True) as wrapper:
file = simphony.File()
file_identifier = file.identifier
file.operations.upload(os_file.name)
file_name = b64encode(
bytes(file_identifier, encoding="UTF-8")
).decode("UTF-8")
self.assertFalse(
(
Path(self.dataspace_directory.name)
/ "files"
/ file_name
).is_file()
)
wrapper.commit()
self.assertTrue(
filecmp.cmp(
os_file.name,
Path(self.dataspace_directory.name)
/ "files"
/ file_name,
shallow=False,
)
)
self.assertEqual(b"text", file.operations.handle.read())
# Test recovering the previous file and downloading it.
with Dataspace(self.dataspace_directory.name, False) as wrapper:
file = wrapper.from_identifier(file_identifier)
with TemporaryDirectory() as temp_dir:
destination = Path(temp_dir) / "filename"
self.assertFalse(destination.is_file())
file.operations.download(destination)
self.assertTrue(destination.is_file())
# Test copying the file among data spaces.
with Dataspace(
self.second_dataspace_directory.name, True
) as wrapper_2:
wrapper_2.add(file)
wrapper_2.commit()
with Dataspace(
self.second_dataspace_directory.name, False
) as wrapper_2:
file_2 = wrapper_2.from_identifier(file_identifier)
contents_1 = file.operations.handle.read()
contents_2 = file_2.operations.handle.read()
self.assertEqual(contents_1, contents_2)
self.assertEqual(b"text", contents_1)
# Test deleting the file.
with Dataspace(self.dataspace_directory.name, False) as wrapper:
file = wrapper.from_identifier(file_identifier)
wrapper.delete(file)
wrapper.commit()
self.assertFalse(
any(
(
Path(self.dataspace_directory.name) / "files"
).iterdir()
)
)
self.assertRaises(
KeyError, wrapper.from_identifier, file_identifier
)
wrapper.commit()
# Test that the file remains deleted.
with Dataspace(self.dataspace_directory.name, False) as wrapper:
self.assertRaises(
KeyError, wrapper.from_identifier, file_identifier
)
class TestRemoteSQLite(unittest.TestCase):
"""Test the Remote wrapper.
The wrapper used for the test on the remote side is the `sqlite` wrapper.
"""
server_proc = None
host: str = "127.0.0.1"
port: int = 4745
db_file: str = "test_db_file.db"
server_files_dir: Optional[str] = None
server_files_dir_object: Optional[TemporaryDirectory] = None
prev_default_ontology: Session
@classmethod
def setUpClass(cls):
"""Create a TBox and set it as the default ontology.
The new TBox contains SimPhoNy, OWL, RDFS and City.
"""
ontology = Session(identifier="test_tbox", ontology=True)
ontology.load_parser(OntologyParser.get_parser("city"))
cls.prev_default_ontology = Session.default_ontology
Session.default_ontology = ontology
@classmethod
def tearDownClass(cls):
"""Restore the previous default TBox."""
Session.default_ontology = cls.prev_default_ontology
def setUp(self) -> None:
"""Start the InterfaceServer for a new test."""
self.start_server()
def tearDown(self):
"""Stop the InterfaceServer after a test."""
self.stop_server()
def start_server(self):
"""Start an InterfaceServer."""
if self.server_proc:
self.server_proc.terminate()
self.server_proc.join(30)
self.server_proc.kill()
self.server_proc.join()
self.server_proc.close()
self.server_proc = multiprocessing.Process(target=self.launch_server)
self.server_proc.start()
s = socket.socket()
connected = False
tries = 0
while not connected and tries < 1000:
time.sleep(0.3)
tries += 1
try:
s.connect((self.host, int(self.port)))
connected = True
except socket.error:
pass
finally:
s.close()
def launch_server(self):
"""Launch an InterfaceServer."""
host(
SQLite,
TestRemoteSQLite.db_file,
True,
hostname=self.host,
port=self.port,
username="user",
password="pass",
)
exit(0)
def stop_server(self):
"""Stop a running InterfaceServer."""
if self.server_proc:
self.server_proc.terminate()
self.server_proc.join(30)
self.server_proc.kill()
self.server_proc.join()
self.server_proc.close()
for file in os.listdir():
if self.db_file in file:
os.remove(file)
if self.server_files_dir_object is not None:
self.server_files_dir_object.cleanup()
self.server_files_dir_object = None
self.server_files_dir = None
self.server_proc = None
def wrapper_generator(self) -> Wrapper:
"""Generate a wrapper object using the Remote wrapper."""
wrapper = Remote(f"ws://user:pass@{self.host}:{self.port}")
return wrapper
def test_city(self):
"""Test adding some entities from the city ontology."""
from simphony_osp.namespaces import city
with self.wrapper_generator() as wrapper:
freiburg = city.City(name="Freiburg", coordinates=[0, 0])
klaus = city.Citizen(name="Klaus", age=30)
freiburg[city.hasInhabitant] = klaus
freiburg_identifier = freiburg.identifier
wrapper.commit()
del freiburg
with self.wrapper_generator() as wrapper:
freiburg = wrapper.from_identifier(freiburg_identifier)
klaus = freiburg[city.hasInhabitant].one()
self.assertEqual(freiburg.name, "Freiburg")
self.assertEqual(klaus.name, "Klaus")
self.assertEqual(klaus.age, 30)
wrapper.delete(klaus)
self.assertIsNone(freiburg[city.hasInhabitant].any())
wrapper.commit()
del freiburg
with self.wrapper_generator() as wrapper:
freiburg = wrapper.from_identifier(freiburg_identifier)
self.assertIsNone(freiburg[city.hasInhabitant].any())
if __name__ == "__main__":
unittest.main()