def test_create_from_cuds_object(self): """Test copying cuds_objects to different session.""" default_session = CoreSession() Cuds._session = default_session a = city.City(name="Freiburg") self.assertIs(a.session, default_session) with TestWrapperSession() as session: w = city.CityWrapper(session=session) with EngineContext(session): b = create_from_cuds_object(a, session) self.assertEqual(b.name, "Freiburg") self.assertEqual(b.uid, a.uid) self.assertEqual(set(default_session._registry.keys()), {a.uid}) self.assertIs(default_session._registry.get(a.uid), a) self.assertEqual(set(session._registry.keys()), {b.uid, w.uid}) self.assertIs(session._registry.get(b.uid), b) self.assertEqual( session._buffers, [[dict(), dict(), dict()], [{ b.uid: b }, dict(), dict()]], ) b.name = "Emmendingen" x = city.Citizen(age=54, name="Franz", session=default_session) b.add(x, rel=city.hasInhabitant) y = city.Citizen(age=21, name="Rolf", session=default_session) a.add(y, rel=city.hasInhabitant) c = create_from_cuds_object(a, session) self.assertIs(b, c) self.assertEqual(c.name, "Freiburg") self.assertEqual(len(c.get(rel=cuba.relationship)), 1) self.assertEqual(c._neighbors[city.hasInhabitant], {y.uid: [city.Citizen]}) self.assertEqual(set(default_session._registry.keys()), {a.uid, x.uid, y.uid}) self.assertIs(default_session._registry.get(a.uid), a) self.assertEqual( session._buffers, [[{ x.uid: x }, { c.uid: c }, dict()], [dict(), dict(), dict()]], )
def test_branch(self): """Test the branch function.""" x = branch( branch(city.City(name="Freiburg"), city.Citizen(name="Peter"), city.Citizen(name="Maria"), rel=city.hasInhabitant), city.Neighborhood(name="Herdern"), city.Neighborhood(name="Vauban")) self.assertEqual(x.name, "Freiburg") self.assertEqual({"Herdern", "Vauban"}, set( map(lambda x: x.name, x.get(oclass=city.Neighborhood)))) self.assertEqual({"Peter", "Maria"}, set( map(lambda x: x.name, x.get(rel=city.hasInhabitant))))
def test_update(self): """Test updating the sqlite table.""" c = city.City(name="Paris") p1 = city.Citizen(name="Peter") c.add(p1, rel=city.hasInhabitant) with DataspaceSession(URI) as session: wrapper = city.CityWrapper(session=session) cw = wrapper.add(c) session.commit() p2 = city.Citizen(name="Georg") cw.add(p2, rel=city.hasInhabitant) cw.name = "Freiburg" session.commit() check_state(self, c, p1, p2, db=DB)
def test_load_from_session(self): """Test loading from the remote side.""" with TestWrapperSession() as s1: c = city.City(name="Freiburg", uid=1) w = city.CityWrapper(session=s1, uid=3) cw = w.add(c) with EngineContext(s1): p = city.Citizen(name="Peter", age=12, uid=2) cw.add(p, rel=city.hasInhabitant) server = TransportSessionServer(TestWrapperSession, None, None) server.session_objs["user"] = s1 s1._expired |= {c.uid, w.uid} result = server._load_from_session( '{"uids": [{"UUID": 1}, {"UUID": 3}]}', "user") self.maxDiff = None assertJsonLdEqual(self, json.loads(result[0]), SERIALIZED_BUFFERS3) self.assertEqual(result[1], [])
def test_delete(self): """Test to delete cuds_objects from the sqlite table.""" c = city.City(name="Freiburg") p1 = city.Citizen(name="Peter") p2 = city.Citizen(name="Georg") p3 = city.Citizen(name="Hans") c.add(p1, p2, p3, rel=city.hasInhabitant) with DataspaceSession(URI) as session: wrapper = city.CityWrapper(session=session) cw = wrapper.add(c) session.commit() cw.remove(p3.uid) session.prune() session.commit() check_state(self, c, p1, p2, db=DB)
def get_test_city(): """Set up a test City for the tests.""" c = city.City(name="Freiburg", coordinates=[1, 2]) p1 = city.Citizen(name="Rainer") p2 = city.Citizen(name="Carlos") p3 = city.Citizen(name="Maria") n1 = city.Neighborhood(name="Zähringen", coordinates=[2, 3]) n2 = city.Neighborhood(name="St. Georgen", coordinates=[3, 4]) s1 = city.Street(name="Lange Straße", coordinates=[4, 5]) c.add(p1, p2, p3, rel=city.hasInhabitant) p1.add(p3, rel=city.hasChild) p2.add(p3, rel=city.hasChild) c.add(n1, n2) n1.add(s1) n2.add(s1) s1.add(p2, p3, rel=city.hasInhabitant) return [c, p1, p2, p3, n1, n2, s1]
def test_get_subtree(self): """Tests the get_subtree method.""" c = city.City(name="a city") p = city.Citizen() n = city.Neighborhood(name="a neighborhood") s = city.Street(name="The street") c.add(p, rel=city.hasInhabitant) c.add(n) n.add(s) registry = c.session._registry self.assertEqual(registry.get_subtree(c.uid), set([c, p, n, s])) self.assertEqual( registry.get_subtree(c.uid, rel=cuba.activeRelationship), set([c, p, n, s])) self.assertEqual(registry.get_subtree(n.uid), set([c, p, n, s])) self.assertEqual( registry.get_subtree(n.uid, rel=cuba.activeRelationship), set([n, s]))
def test_cuds_with_iri(self): """Try to assign IRIs as UIDs for CUDS objects.""" c = city.City( name="Freiburg", iri="http://example.org/namespace" "#Freiburg" ) with SqliteSession(DB) as session: wrapper = city.CityWrapper(session=session) wrapper.add(c) session.commit() with SqliteSession(DB) as session: wrapper = city.CityWrapper(session=session) self.assertEqual( set(session._registry.keys()), {c.uid, wrapper.uid} ) self.assertEqual(wrapper.get(c.uid).name, "Freiburg") self.assertEqual(wrapper.get(c.uid).oclass, city.City)
def test_load_missing(self): """Test if missing objects are loaded automatically.""" c = city.City(name="Freiburg") p1 = city.Citizen(name="Peter") p2 = city.Citizen(name="Anna") p3 = city.Citizen(name="Julia") c.add(p1, p2, p3, rel=city.hasInhabitant) p1.add(p3, rel=city.hasChild) p2.add(p3, rel=city.hasChild) with SqliteSession(DB) as session: wrapper = city.CityWrapper(session=session) wrapper.add(c) session.commit() with TransportSessionClient(SqliteSession, URI, path=DB) as session: wrapper = city.CityWrapper(session=session) self.assertEqual(set(session._registry.keys()), {c.uid, wrapper.uid}) cw = wrapper.get(c.uid) p1w = cw.get(p1.uid) p2w = cw.get(p2.uid) p3w = p1w.get(p3.uid) self.assertEqual( set(session._registry.keys()), {c.uid, wrapper.uid, p1.uid, p2.uid, p3.uid}, ) self.assertEqual(p1w.name, "Peter") self.assertEqual(p2w.name, "Anna") self.assertEqual(p3w.name, "Julia") self.assertEqual( p3w._neighbors[city.isChildOf], { p1.uid: p1.oclasses, p2.uid: p2.oclasses }, ) self.assertEqual(p2w._neighbors[city.hasChild], {p3.uid: p3.oclasses}) self.assertEqual( p2w._neighbors[city.INVERSE_OF_hasInhabitant], {c.uid: c.oclasses}, )
def test_get_relationships_between(self): """Test the get_the_relationship_between two cuds entities.""" c = city.City(name="Freiburg") p = city.Citizen(name="Peter") self.assertEqual(get_relationships_between(c, p), set()) self.assertEqual(get_relationships_between(p, c), set()) c.add(p, rel=city.hasInhabitant) self.assertEqual(get_relationships_between(c, p), {city.hasInhabitant}) self.assertEqual(get_relationships_between(p, c), {city.INVERSE_OF_hasInhabitant}) c.add(p, rel=city.hasWorker) self.assertEqual( get_relationships_between(c, p), {city.hasInhabitant, city.hasWorker}, ) self.assertEqual( get_relationships_between(p, c), {city.INVERSE_OF_hasInhabitant, city.worksIn}, )
def test_get_not_reachable(self): """Test the pruning method.""" cities = list() for i in range(3): c = city.City(name="city %s" % i) cities.append(c) for j in range(2): n = city.Neighborhood(name="neighborhood %s %s" % (i, j)) c.add(n) for k in range(2): s = city.Street(name="street %s %s %s" % (i, j, k)) n.add(s) registry = cities[0].session._registry result = registry._get_not_reachable(cities[2].uid) self.assertEqual( set([k.name for k in result]), set([ "city 0", "city 1", "neighborhood 0 0", "neighborhood 0 1", "neighborhood 1 0", "neighborhood 1 1", "street 0 0 0", "street 0 0 1", "street 0 1 0", "street 0 1 1", "street 1 0 0", "street 1 0 1", "street 1 1 0", "street 1 1 1", ]), ) roots = [ n for n in cities[0].get() if n.name.startswith("neighborhood 0") ] registry.prune(*roots, rel=cuba.passiveRelationship) self.assertEqual( set([k.name for k in registry.values()]), set(["neighborhood 0 0", "neighborhood 0 1", "city 0"]), )
def setUp(self): """Start the timer.""" if not RUN_PERFORMANCE_TEST: return self.iterations = 100000 self.c = city.City(name="A big city") for i in range(10): j = i * 9 self.c.add(city.Citizen(uid=j + 0), rel=city.hasInhabitant) self.c.add(city.Citizen(uid=j + 1), rel=city.encloses) self.c.add(city.Citizen(uid=j + 2), rel=city.hasPart) self.c.add(city.Neighborhood(name="", uid=j + 3), rel=city.hasInhabitant) self.c.add(city.Neighborhood(name="", uid=j + 4), rel=city.encloses) self.c.add(city.Neighborhood(name="", uid=j + 5), rel=city.hasPart) self.c.add(city.Street(name="", uid=j + 6), rel=city.hasInhabitant) self.c.add(city.Street(name="", uid=j + 7), rel=city.encloses) self.c.add(city.Street(name="", uid=j + 8), rel=city.hasPart) self.start = time.time()
def test_creation(self): """Tests the instantiation and type of the objects.""" self.assertRaises( TypeError, city.City, name="name", coordinates=[1, 2], uid=0, unwanted="unwanted", ) self.assertRaises(TypeError, city.City) c = city.City(name="a city") p = city.Person() self.assertEqual(c.oclass, city.City) self.assertEqual(p.oclass, city.Person) self.assertRaises(TypeError, cuba.Nothing) self.assertRaises(TypeError, cuba.Wrapper) cuba.Wrapper(session=CoreSession())
def test_remove_throws_exception(self): """Tests the remove() method for unusual behaviors. - Removing with a wrong key - Removing something non-existent - Removing with a not allowed argument combination """ c = city.City(name="a city") n = city.Neighborhood(name="a neighborhood") # Wrong key self.assertRaises(TypeError, c.remove, "not a proper key") # Non-existent self.assertRaises(RuntimeError, c.remove, n.uid) self.assertRaises(RuntimeError, c.remove, rel=city.hasPart) self.assertRaises(RuntimeError, c.remove, oclass=city.Street) self.assertRaises(RuntimeError, c.remove, n.uid, rel=city.hasPart) # Wrong arguments self.assertRaises(TypeError, c.remove, n.uid, oclass=city.Street)
def test_update(self): """Tests the standard, normal behavior of the update() method.""" c = city.City(name="a city") n = city.Neighborhood(name="a neighborhood") new_n = create_from_cuds_object(n, CoreSession()) new_s = city.Street(name="a new street") new_n.add(new_s) c.add(n) old_neighborhood = c.get(n.uid) old_streets = old_neighborhood.get(oclass=city.Street) self.assertEqual(old_streets, []) c.update(new_n) new_neighborhood = c.get(n.uid) self.assertIs(new_neighborhood, n) new_streets = new_neighborhood.get(oclass=city.Street) self.assertEqual(new_streets, [new_s]) self.assertRaises(ValueError, c.update, n)
def test_prune(self): """Test the pruning method.""" cities = list() for i in range(3): c = city.City(name="city %s" % i) cities.append(c) for j in range(2): n = city.Neighborhood(name="neighborhood %s %s" % (i, j)) c.add(n) for k in range(2): s = city.Street(name="street %s %s %s" % (i, j, k)) n.add(s) registry = cities[0].session._registry registry.prune(*[c.uid for c in cities[0:2]]) self.assertEqual( set([k.name for k in registry.values()]), set([ "city 0", "city 1", "neighborhood 0 0", "neighborhood 0 1", "neighborhood 1 0", "neighborhood 1 1", "street 0 0 0", "street 0 0 1", "street 0 1 0", "street 0 1 1", "street 1 0 0", "street 1 0 1", "street 1 1 0", "street 1 1 1", ]), ) (root, ) = [n for n in cities[0].get() if n.name == "neighborhood 0 0"] registry.prune(root, rel=cuba.activeRelationship) self.assertEqual( set([k.name for k in registry.values()]), set(["neighborhood 0 0", "street 0 0 0", "street 0 0 1"]), )
def test_notify_delete_call(self): """Tests if notify_delete is called, when we call prune.""" deleted = set() session = TestSession(notify_delete=lambda x: deleted.add(x)) w = city.CityWrapper(session=session) cities = list() for i in range(3): c = city.City(name="city %s" % i) cw = w.add(c) cities.append(cw) for j in range(2): n = city.Neighborhood(name="neighborhood %s %s" % (i, j)) cw.add(n) nw = cw.get(n.uid) for k in range(2): s = city.Street(name="street %s %s %s" % (i, j, k)) nw.add(s) w.remove(cities[1].uid, cities[2].uid) expected_deletion = { x.uid for x in session._registry.values() if (hasattr(x, "name") and x.name in { "city 2", "neighborhood 2 0", "neighborhood 2 1", "street 2 0 0", "street 2 0 1", "street 2 1 0", "street 2 1 1", "city 1", "neighborhood 1 0", "neighborhood 1 1", "street 1 0 0", "street 1 0 1", "street 1 1 0", "street 1 1 1" }) } session.prune(rel=None) self.assertEqual( set([ "wrapper" if k.is_a(cuba.Wrapper) else k.name for k in session._registry.values() ]), set([ "city 0", "neighborhood 0 0", "neighborhood 0 1", "street 0 0 0", "street 0 0 1", "street 0 1 0", "street 0 1 1", "wrapper" ])) self.assertEqual(set([d.uid for d in deleted]), expected_deletion)
def test_delete_cuds_object_recursively(self): """Test the delete_cuds_object_recursively function.""" with TestWrapperSession() as session: wrapper = city.CityWrapper(session=session) a = city.City(name='freiburg', session=session) b = city.Citizen(name='peter', session=session) branch(wrapper, branch(a, b, rel=city.hasInhabitant)) self.maxDiff = None session._reset_buffers(BufferContext.USER) delete_cuds_object_recursively(a) self.assertEqual(session._buffers, [ [{}, { wrapper.uid: wrapper }, { a.uid: a, b.uid: b }], [{}, {}, {}], ]) self.assertEqual(wrapper.get(rel=cuba.relationship), []) self.assertEqual(a.get(rel=cuba.relationship), []) self.assertEqual(b.get(rel=cuba.relationship), [])
def test_load(self): """Test loading from server.""" client = TransportSessionClient(TestWrapperSession, None) client.root = 1 c1 = create_recycle(oclass=city.City, kwargs={"name": "Freiburg"}, uid=1, session=client, fix_neighbors=False) c2 = city.City(name="London", uid=2) c3 = create_recycle(oclass=city.City, kwargs={"name": "Paris"}, uid=3, session=client, fix_neighbors=False) client._reset_buffers(BufferContext.USER) client.expire(c3.uid) def on_send(command, data): with EngineContext(client): create_from_cuds_object(c2, client) return [c2, None] client._engine = MockEngine(on_send) result = list( client.load(uuid.UUID(int=1), uuid.UUID(int=2), uuid.UUID(int=3))) self.assertEqual(client._engine._sent_command, LOAD_COMMAND) self.assertEqual( client._engine._sent_data, '{"expired": [{"UUID": "00000000-0000-0000-0000-000000000003"}], ' '"uids": [{"UUID": "00000000-0000-0000-0000-000000000002"}, ' '{"UUID": "00000000-0000-0000-0000-000000000003"}]}') self.assertEqual(result, [c1, c2, None]) self.assertEqual(set(client._registry.keys()), {c1.uid, c2.uid}) self.assertEqual( client._buffers, [[dict(), dict(), dict()], [dict(), dict(), dict()]]) client.close()
def test_dummy_sim_wrapper(self): """Create a dummy simulation syntactic layer + test.""" with SimDummySession() as session: wrapper = city.CitySimWrapper(numSteps=1, session=session) c = city.City(name="Freiburg") p1 = city.Person(name="Hans", age=34) p2 = city.Person(name="Renate", age=54) cw, _, _ = wrapper.add(c, p1, p2) session.run() self.assertEqual( len(wrapper.get(oclass=city.Person, rel=city.hasPart)), 1) self.assertEqual( len(cw.get(oclass=city.Citizen, rel=city.hasInhabitant)), 1) self.assertEqual(wrapper.get(p2.uid).name, "Renate") self.assertEqual(wrapper.get(p2.uid).age, 55) self.assertEqual(cw.get(p1.uid).name, "Hans") self.assertEqual(cw.get(p1.uid).age, 35) session.run() wrapper.add(city.Person(name="Peter")) self.assertRaises(RuntimeError, session.run)
def test_application_json_doc_city(self): """Test importing the `application/ld+json` mime type from doc dict. This test uses a city ontology instead. """ # Importing test_data_path = str( Path(__file__).parent / "test_importexport_city_import.json") with open(test_data_path, "r") as file: json_doc = json.loads(file.read()) with CoreSession(): cuds = import_cuds(json_doc, format="application/ld+json") self.assertTrue(cuds.is_a(city.Citizen)) self.assertEqual(cuds.name, "Peter") self.assertEqual(cuds.age, 23) export_file = io.StringIO() export_cuds(cuds, file=export_file, format="application/ld+json") export_file.seek(0) assertJsonLdEqual(self, json_doc, json.loads(export_file.read())) # Exporting test_data_path = str( Path(__file__).parent / "test_importexport_city_export.json") with open(test_data_path, "r") as file: json_doc = json.loads(file.read()) with CoreSession(): c = branch( city.City(name="Freiburg", uid=1), branch( city.Neighborhood(name="Littenweiler", uid=2), city.Street(name="Schwarzwaldstraße", uid=3), ), ) export_file = io.StringIO() export_cuds(c, file=export_file, format="application/ld+json") export_file.seek(0) assertJsonLdEqual(self, json.loads(export_file.read()), json_doc)
def test_load_by_oclass(self): """Load elements by ontology class via transport + db session.""" c = city.City(name="Freiburg") p1 = city.Citizen(name="Peter") p2 = city.Citizen(name="Anna") p3 = city.Citizen(name="Julia") c.add(p1, p2, p3, rel=city.hasInhabitant) p1.add(p3, rel=city.hasChild) p2.add(p3, rel=city.hasChild) with TransportSessionClient(SqliteSession, URI, path=DB) as session: wrapper = city.CityWrapper(session=session) wrapper.add(c) session.commit() with TransportSessionClient(SqliteSession, URI, path=DB) as session: wrapper = city.CityWrapper(session=session) cs = wrapper.get(c.uid) r = session.load_by_oclass(city.City) self.assertIs(next(iter(r)), cs) r = session.load_by_oclass(city.Citizen) self.assertEqual(set(r), {p1, p2, p3}) r = session.load_by_oclass(city.Person) self.assertEqual(set(r), {p1, p2, p3})
def test_default_session_context_manager(self): """Test changing the default session with a session context manager.""" default_session = CoreSession() Cuds._session = default_session bern = city.City(name="Bern") with TestSession() as session1: freiburg = city.City(name="Freiburg") with TestSession() as session2: berlin = city.City(name="Berlin") with TestSession() as session3: madrid = city.City(name="Madrid") with TestSession() as session4: beijing = city.City(name="北京") self.assertIs(freiburg.session, session1) self.assertIs(berlin.session, session2) self.assertIs(madrid.session, session3) self.assertIs(beijing.session, session4) paris = city.City(name="Paris") self.assertIs(berlin.session, paris.session) self.assertIsNot(berlin.session, beijing.session) tokyo = city.City(name="Tokyo") # Test default session restore. self.assertIs(bern.session, tokyo.session) self.assertIs(bern.session, default_session)
def test_sparql(self): """Test SPARQL by creating a city and performing a very simple query. Create a city with a single inhabitant and perform a very simple SPARQL query using both the `sparql` function from utils and the sparql method of the session. """ def is_freiburg(iri): value = str(iri) if value == "Freiburg": return True else: return False freiburg = city.City(name="Freiburg") karl = city.Citizen(name="Karl", age=47) freiburg.add(karl, rel=city.hasInhabitant) core_session = freiburg.session query = f"""SELECT ?city_name ?citizen ?citizen_age ?citizen_name WHERE {{ ?city a <{city.City.iri}> . ?city <{city.name.iri}> ?city_name . ?city <{city.hasInhabitant.iri}> ?citizen . ?citizen <{city.name.iri}> ?citizen_name . ?citizen <{city.age.iri}> ?citizen_age . }} """ datatypes = dict( citizen="cuds", citizen_age=int, citizen_name=str, city_name=is_freiburg, ) results_none = sparql(query, session=None) results_core_session = sparql(query, session=core_session) results_core_session_method = core_session.sparql(query) self.assertEqual(len(results_none), 1) self.assertEqual(len(results_core_session), 1) self.assertEqual(len(results_core_session_method), 1) results = ( next(results_none(**datatypes)), next(results_core_session(**datatypes)), next(results_core_session_method(**datatypes)), ) self.assertTrue( all(result["citizen"].is_a(karl.oclass) for result in results)) self.assertTrue( all(result["citizen_age"] == karl.age for result in results)) self.assertTrue( all(result["citizen_name"] == karl.name for result in results)) self.assertTrue(all(result["city_name"] for result in results)) results = ( next(iter(results_none)), next(iter(results_core_session)), next(iter(results_core_session_method)), ) self.assertTrue( all(result["citizen"] == karl.iri for result in results)) self.assertTrue( all(type(result["citizen_age"]) != int for result in results))
def test_deserialize_buffers(self): """Test de-serialization of buffers.""" # buffer context user with TestWrapperSession() as s1: ws1 = city.CityWrapper(session=s1, uid=123) c = city.City(name="Freiburg", uid=1) p1 = city.Citizen(uid=uuid.UUID(int=3)) p2 = city.Citizen(uid=uuid.UUID(int=4)) c.add(p1, p2, rel=city.hasInhabitant) ws1.add(c) s1._reset_buffers(BufferContext.USER) s1.expire(p2) additional = deserialize_buffers( s1, buffer_context=BufferContext.USER, data=json.dumps(SERIALIZED_BUFFERS_EXPIRED)) self.assertEqual(additional, { "args": [42], "kwargs": { "name": "London" } }) self.assertEqual( set(s1._registry.keys()), { uuid.UUID(int=123), uuid.UUID(int=2), uuid.UUID(int=3), uuid.UUID(int=4) }) cn = ws1.get(uuid.UUID(int=2)) self.assertEqual(cn.name, "Paris") self.assertEqual(ws1._neighbors[city.hasPart], {cn.uid: [city.City]}) self.assertEqual(set(ws1._neighbors.keys()), {city.hasPart}) self.assertEqual(cn._neighbors[city.isPartOf], {ws1.uid: [city.CityWrapper]}) self.assertEqual(set(cn._neighbors.keys()), {city.isPartOf}) self.assertEqual(s1._expired, {uuid.UUID(int=3), uuid.UUID(int=4)}) self.assertEqual(s1._buffers, [[{ cn.uid: cn }, { ws1.uid: ws1 }, { c.uid: c }], [dict(), dict(), dict()]]) self.setUp() # buffer context engine with TestWrapperSession() as s1: ws1 = city.CityWrapper(session=s1, uid=123) c = city.City(name="Freiburg", uid=1) p1 = city.Citizen(uid=uuid.UUID(int=3)) p2 = city.Citizen(uid=uuid.UUID(int=4)) c.add(p1, p2, rel=city.hasInhabitant) ws1.add(c) s1._reset_buffers(BufferContext.USER) s1.expire(p2) additional = deserialize_buffers( s1, buffer_context=BufferContext.ENGINE, data=json.dumps(SERIALIZED_BUFFERS_EXPIRED)) self.assertEqual(additional, { "args": [42], "kwargs": { "name": "London" } }) self.assertEqual(s1._buffers, [[dict(), dict(), dict()], [{ cn.uid: cn }, { ws1.uid: ws1 }, { c.uid: c }]]) self.assertEqual( set(s1._registry.keys()), { uuid.UUID(int=123), uuid.UUID(int=2), uuid.UUID(int=3), uuid.UUID(int=4) }) cn = ws1.get(uuid.UUID(int=2)) self.assertEqual(cn.name, "Paris") self.assertEqual(ws1._neighbors[city.hasPart], {cn.uid: [city.City]}) self.assertEqual(set(ws1._neighbors.keys()), {city.hasPart}) self.assertEqual(cn._neighbors[city.isPartOf], {ws1.uid: [city.CityWrapper]}) self.assertEqual(set(cn._neighbors.keys()), {city.isPartOf}) self.assertEqual(s1._expired, {uuid.UUID(int=3), uuid.UUID(int=4)}) self.assertEqual(s1._buffers, [[dict(), dict(), dict()], [dict(), dict(), dict()]])
def test_serialize_buffers(self): """Test if serialization of buffers works.""" # no expiration with TestWrapperSession() as s1: ws1 = city.CityWrapper(session=s1, uid=123) c = city.City(name="Freiburg", uid=1) ws1.add(c) s1._reset_buffers(BufferContext.USER) cn = city.City(name="Paris", uid=2) ws1.add(cn) ws1.remove(c.uid) s1.prune() self.assertEqual( ('{"expired": [], "args": [42], "kwargs": {"name": "London"}}', []), serialize_buffers(s1, buffer_context=None, additional_items={ "args": [42], "kwargs": { "name": "London" } })) added, updated, deleted = s1._buffers[BufferContext.USER] self.assertEqual(added.keys(), {uuid.UUID(int=2)}) self.assertEqual(updated.keys(), {uuid.UUID(int=123)}) self.assertEqual(deleted.keys(), {uuid.UUID(int=1)}) self.assertEqual(s1._buffers[BufferContext.ENGINE], [dict(), dict(), dict()]) self.maxDiff = None result = serialize_buffers(s1, buffer_context=BufferContext.USER, additional_items={ "args": [42], "kwargs": { "name": "London" } }) assertJsonLdEqual(self, json.loads(result[0]), SERIALIZED_BUFFERS) self.assertEqual(result[1], []) self.assertEqual(s1._buffers, [[dict(), dict(), dict()], [dict(), dict(), dict()]]) s1._expired = {uuid.UUID(int=123), uuid.UUID(int=2)} # with expiration with TestWrapperSession() as s1: ws1 = city.CityWrapper(session=s1, uid=123) c = city.City(name="Freiburg", uid=1) ws1.add(c) s1._reset_buffers(BufferContext.USER) cn = city.City(name="Paris", uid=2) ws1.add(cn) ws1.remove(c.uid) s1.prune() s1._expired = {uuid.UUID(int=3)} self.assertEqual( ('{"expired": [{"UUID": ' '"00000000-0000-0000-0000-000000000003"}], ' '"args": [42], "kwargs": {"name": "London"}}', []), serialize_buffers(s1, buffer_context=None, additional_items={ "args": [42], "kwargs": { "name": "London" } })) added, updated, deleted = s1._buffers[BufferContext.USER] self.assertEqual(added.keys(), {uuid.UUID(int=2)}) self.assertEqual(updated.keys(), {uuid.UUID(int=123)}) self.assertEqual(deleted.keys(), {uuid.UUID(int=1)}) self.assertEqual(s1._buffers[BufferContext.ENGINE], [dict(), dict(), dict()]) self.maxDiff = 3000 result = serialize_buffers(s1, buffer_context=BufferContext.USER, additional_items={ "args": [42], "kwargs": { "name": "London" } }) assertJsonLdEqual(self, SERIALIZED_BUFFERS_EXPIRED, json.loads(result[0])) self.assertEqual([], result[1]) self.assertEqual(s1._buffers, [[dict(), dict(), dict()], [dict(), dict(), dict()]]) s1._expired = {uuid.UUID(int=123), uuid.UUID(int=2)}
"""An example explaining the API of CUDS objects.""" # Please install the city ontology: $pico install city # If you did not install the city ontology # (pico install city), # you have to execute these commands first: # from osp.core import Parser # p = Parser() # p.parse("city") from osp.core.namespaces import city print("Creating a City object, c...") c = city.City(name="Freiburg", coordinates=[47, 7]) print(" uid of c: " + str(c.uid)) print(" IRI of c: " + str(c.iri)) print(" oclass of c: " + str(c.oclass) + "\n") print("Creating Citizen objects, p1, p2...") p1 = city.Citizen(name="Peter") p2 = city.Citizen(name="Anne") print(" uid of p1: " + str(p1.uid)) print(" IRI of p1: " + str(p1.iri)) print(" oclass of p1: " + str(p1.oclass) + "\n") print(" uid of p2: " + str(p2.uid)) print(" IRI of p2: " + str(p2.iri)) print(" oclass of p2: " + str(p2.oclass) + "\n") print("Checking attributes of the CUDS objects...") print(f"Name of c: {c.name}. Coordinates of c: {c.coordinates}.")
from rdflib import URIRef from osp.core.namespaces import city from osp.core.utils import branch, export_cuds, import_cuds, pretty_print from osp.wrappers.sqlite import SqliteSession uuid_re = re.compile( r".*(http://www\.osp-core\.com/cuds#" r"([a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}" r"-[a-z0-9]{4}-[a-z0-9]{12})).*" ) # Create CUDS structure c = branch( branch( city.City(name="Freiburg"), city.City(name="Pablo"), city.City(name="Yoav"), rel=city.hasInhabitant, ), city.Neighborhood(name="Stühlinger"), city.Neighborhood(name="Herdern"), ) # Export from Core Session export_cuds(path="test.rdf", format="ttl") # Check output with open("test.rdf", encoding="utf-8") as f: print("Exported from Core Session") for line in f:
server.startListening() exit(0) args = ["python3", "examples/transport_session_example.py", "server"] try: p = subprocess.Popen(args) except FileNotFoundError: args[0] = "python" p = subprocess.Popen(args) time.sleep(5) try: # Construct the Datastructure. c = city.City(name="Freiburg") p1 = city.Citizen(name="Peter") p2 = city.Citizen(name="Hans") p3 = city.Citizen(name="Michel") n = city.Neighborhood(name="Zähringen") s = city.Street(name="Le street") b = city.Building(name="Theater") a = city.Address(postalCode=79123, name='Le street', number=12) c.add(p1, p2, p3, rel=city.hasInhabitant) c.add(n).add(s).add(b).add(a) print("Connect to DB via transport session") with TransportSessionClient( SqliteSession, "ws://localhost:8688", path="test.db" ) as session: wrapper = city.CityWrapper(session=session)
"wrapper for SimPhoNy is required!") from e # import logging # logger = logging.getLogger("osp.core") # logger.setLevel(logging.DEBUG) print("Input data to connect to Postgres table!") user = input("User: "******"Password: "******"Database name: ") host = input("Host: ") port = int(input("Port [5432]: ") or 5432) postgres_url = 'postgresql://%s:%s@%s:%s/%s' % (user, pwd, host, port, db_name) # Let's build an EMMO compatible city! emmo_town = city.City(name='EMMO town') emmo_town.add(city.Citizen(name='Emanuele Ghedini'), rel=city.hasInhabitant) emmo_town.add(city.Citizen(name='Adham Hashibon'), rel=city.hasInhabitant) emmo_town.add(city.Citizen(name='Jesper Friis'), city.Citizen(name='Gerhard Goldbeck'), city.Citizen(name='Georg Schmitz'), city.Citizen(name='Anne de Baas'), rel=city.hasInhabitant) emmo_town.add(city.Neighborhood(name="Ontology")) emmo_town.add(city.Neighborhood(name="User cases")) ontology_uid = None for neighborhood in emmo_town.get(oclass=city.Neighborhood): if neighborhood.name == "Ontology":