def test_can_get_node_by_id_when_not_cached(self): node = Node() self.graph.create(node) Node.cache.clear() assert remote(node).uri not in Node.cache got = self.graph.node(remote(node)._id) assert remote(got)._id == remote(node)._id
def test_can_create_dbms_with_trailing_slash(self): uri = "http://localhost:7474/" dbms = DBMS(uri) assert repr(dbms).startswith("<DBMS") assert remote(dbms).uri == uri index = remote(dbms).get().content assert "data" in index
def test_can_create_dbms_with_bolt_uri(self): uri = "bolt://localhost/" dbms = DBMS(uri) assert repr(dbms).startswith("<DBMS") assert remote(dbms).uri == "http://localhost:7474/" index = remote(dbms).get().content assert "data" in index
def test_can_create_dbms_with_settings(self): uri = "http://127.0.0.1:7474/" dbms = DBMS(host="127.0.0.1") assert repr(dbms).startswith("<DBMS") assert remote(dbms).uri == uri index = remote(dbms).get().content assert "data" in index
def test_can_create_remote_node(self): a = Node("Person", name="Alice", age=33) self.graph.create(a) assert set(a.labels()) == {"Person"} assert dict(a) == {"name": "Alice", "age": 33} assert remote(a).ref.startswith("node/") assert repr(remote(a))
def test_graph(self): a = Node() b = Node() r = Relationship(a, "TO", b) self.graph.create(r) assert remote(r) assert remote(r).graph == Graph("http://localhost:7474/db/data/")
def test_can_bind_node_to_resource(self): uri = "http://localhost:7474/db/data/node/1" node = Node() node.__remote__ = RemoteEntity(uri) assert remote(node) assert isinstance(remote(node), Resource) assert remote(node).uri == uri
def api_v1_topology_nodes(): edges = [] for record in neo4j_connect.data('MATCH (n) return n'): source = record['n'] for rel in neo4j_connect.match(source, rel_type='isl'): dest = rel.end_node() s = Link() s.label = source['name'] s.id = py2neo.remote(source)._id t = Link() t.label = dest['name'] t.id = py2neo.remote(dest)._id edge = Edge() edge.value = "{} to {}".format(s.label, t.label) edge.source = s edge.target = t edges.append(edge) edges.sort(key=lambda x: (x.source['id'], x.target['id'])) nodes = Nodes() nodes.edges = edges return nodes.toJSON()
def test_can_get_relationship_by_id_when_not_cached(self): a = Node() b = Node() r = Relationship(a, "TO", b) self.graph.create(r) Relationship.cache.clear() got = self.graph.relationship(remote(r)._id) assert remote(got)._id == remote(r)._id
def test_minimal_node_hydrate(self): dehydrated = { "self": "http://localhost:7474/db/data/node/0", } hydrated = Node.hydrate(dehydrated) assert isinstance(hydrated, Node) assert remote(hydrated) assert remote(hydrated).uri == dehydrated["self"]
def test_can_create_entity_with_initial_uri_and_metadata(self): uri = "http://localhost:7474/db/data/node/1" metadata = {"foo": "bar"} entity = Node() entity.__remote__ = RemoteEntity(uri, metadata) assert remote(entity) assert remote(entity).uri == uri assert remote(entity).metadata == metadata
def test_can_merge_with_arguments(self): a = Node("A", a=1) b = Node("B", b=2) self.graph.create(a | b) a_id = remote(a)._id b_id = remote(b)._id node = Node("A", "B", a=1, b=2) self.graph.merge(node, "A", "a") assert remote(node)._id == a_id assert remote(node)._id != b_id
def test_can_create_relationship(self): a = Node("Person", name="Alice") b = Node("Person", name="Bob") r = Relationship(a, "KNOWS", b, since=1999) with self.graph.begin() as tx: tx.create(r) assert remote(a) assert remote(b) assert remote(r) assert r.start_node() == a assert r.end_node() == b
def test_merge_with_primary_key_list(self): a = Node("A", a=1) b = Node("B", b=2) self.graph.create(a | b) a_id = remote(a)._id b_id = remote(b)._id node = Node("A", "B", a=1, b=2) node.__primarylabel__ = "B" node.__primarykey__ = ["b"] self.graph.merge(node, "A", "a") assert remote(node)._id != a_id assert remote(node)._id == b_id
def test_merge_with_magic_values_overrides_arguments(self): a = Node("A", a=1) b = Node("B", b=2) self.graph.create(a | b) a_id = remote(a)._id b_id = remote(b)._id node = Node("A", "B", a=1, b=2) node.__primarylabel__ = "B" node.__primarykey__ = "b" self.graph.merge(node, "A", "a") assert remote(node)._id != a_id assert remote(node)._id == b_id
def test_can_bind_relationship_to_resource(self): uri = "http://localhost:7474/db/relationship/1" metadata = { "start": "http://localhost:7474/db/node/1", "end": "http://localhost:7474/db/node/2", } relationship = Relationship({}, "", {}) # Pass in metadata to avoid callback to server relationship.__remote__ = RemoteEntity(uri, metadata=metadata) assert remote(relationship) assert isinstance(remote(relationship), Resource) assert remote(relationship).uri == uri
def test_node_hydrate_with_properties(self): dehydrated = { "self": "http://localhost:7474/db/data/node/0", "data": { "name": "Alice", "age": 33, }, } hydrated = Node.hydrate(dehydrated) assert isinstance(hydrated, Node) assert dict(hydrated) == dehydrated["data"] assert remote(hydrated) assert remote(hydrated).uri == dehydrated["self"]
def test_can_merge_relationship_that_does_not_exist(self): alice = Node("Person", name="Alice") bob = Node("Person", name="Bob") ab = Relationship(alice, "KNOWS", bob) old_order = order(self.graph) old_size = size(self.graph) self.graph.merge(ab) assert remote(alice) assert remote(bob) assert remote(ab) assert self.graph.exists(alice | bob | ab) new_order = order(self.graph) new_size = size(self.graph) assert new_order == old_order + 2 assert new_size == old_size + 1
def add(current_user_id, task_id, data): all_attributes = ["client", "date", "message", "user"] date_created = str(datetime.datetime.now()).replace(' ', 'T') + "Z" try: new_note = Node("Note", client=data['client'], date=data['date'], message=data['message']) except KeyError as e: return {"message": f"You are missing a key element: {e}"} new_note['date_created'] = date_created new_note['user'] = current_user_id graph.create(new_note) task = graph.run( f"MATCH (task:Task) WHERE ID(task)={task_id} RETURN task" ).evaluate() note_task_rel = Relationship(new_note, 'IS_NOTE_OF', task) graph.create(note_task_rel) new_note['id'] = remote(new_note)._id return new_note
def add(data): date_created = str(datetime.datetime.now()).replace(' ', 'T') + "Z" try: new_project = Node("Project", name=data['name'], deadline=data['deadline'], priority=data['priority'], client=data['client'], state=data['state']) new_project['date_created'] = date_created admins = data['admins'] users = data['users'] except KeyError as e: return {"message": f"You are missing a key element: {e}"} graph.create(new_project) admins = data.get('admins') users = data.get('users') users_msg = Project.make_connections(users, new_project, "IS_USER") admins_msg = Project.make_connections(admins, new_project, "IS_ADMIN") if users_msg.get('message'): return users_msg if admins_msg.get('message'): return admins_msg new_project['id'] = remote(new_project)._id return new_project
def test_can_init_server_plugin(self): remote_graph = remote(self.graph) metadata = remote_graph.metadata metadata["extensions"]["FakePlugin"] = {} self.graph.__remote__ = Resource(remote_graph.uri, metadata) plugin = FakePlugin(self.graph) assert plugin.resources == {}
def create_task(current_user): data = request.get_json() new_task = Node("Task", name=data['name'], priority=data['priority'], state=data['state'], thumbnail=data['thumbnail'], deadline=data['deadline'], download=data['download'], created=data['created'], finished=data['finished'], upload=data['upload'], description=data['description']) graph.create(new_task) project_id = data["project"] project = graph.run( f"MATCH (project:Project) WHERE ID(project)={project_id} RETURN project" ).data()[0]["project"] task_project = Relationship(new_task, 'IS_TASK_OF', project) graph.create(task_project) new_task['project'] = project_id new_task['id'] = remote(new_task)._id return jsonify(new_task)
def login(): auth = request.authorization if not auth or not auth.username or not auth.password: return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required"'}) #user = session.query(User).filter_by(email=auth.username).first() user = graph.run("MATCH (user:Person) WHERE user.email = '{authuser}' RETURN user".format(authuser=auth.username)) user_id = remote(user.evaluate())._id print(user_id) user = graph.run("MATCH (user:Person) WHERE user.email = '{authuser}' RETURN user".format(authuser=auth.username)) user_data = list(user)[0][0] print(user_data) print(user_data["password"]) if not user: return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required"'}) if check_password_hash(user_data["password"], auth.password): token = jwt.encode({'user_id': user_id}, app.config['SECRET_KEY']) # if user.check_password(auth.password): # token = jwt.encode({'user_id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY']) return jsonify({'token': token.decode('UTF-8')}) return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required"'})
def test_bound_node_equality(self): alice_1 = Node(name="Alice") alice_1.__remote__ = RemoteEntity("http://localhost:7474/db/data/node/1") Node.cache.clear() alice_2 = Node(name="Alice") alice_2.__remote__ = RemoteEntity(remote(alice_1).uri) assert alice_1 == alice_2
def test_can_cast_node(self): alice = Node(name="Alice") self.graph.create(alice) casted = cast(alice) assert isinstance(casted, Node) assert remote(casted) assert casted["name"] == "Alice"
def test_can_get_relationship_by_id_when_cached(self): a = Node() b = Node() r = Relationship(a, "TO", b) self.graph.create(r) got = self.graph.relationship(remote(r)._id) assert got is r
def set_link_props(tx, isl, props): match = _make_match(isl) q = textwrap.dedent(""" MATCH (target:link_props { src_switch: $src_switch, src_port: $src_port, dst_switch: $dst_switch, dst_port: $dst_port}) RETURN target""") logger.debug('link_props lookup query:\n%s', q) cursor = tx.run(q, match) try: target = db.fetch_one(cursor)['target'] except exc.DBEmptyResponse: raise exc.DBRecordNotFound(q, match) origin, update = _locate_changes(target, props) if update: q = textwrap.dedent(""" MATCH (target:link_props) WHERE id(target)=$target_id """) + db.format_set_fields(db.escape_fields(update), field_prefix='target.') logger.debug('Push link_props properties: %r', update) tx.run(q, {'target_id': py2neo.remote(target)._id}) sync_with_link_props(tx, isl, *update.keys()) return origin
def createNewNodeWithLabel(self, nodeName, label): """Creates a new node with the given label """ tx = self.begin(autocommit=False) newNode = Node(label, name=nodeName) tx.create(newNode) tx.commit() return remote(newNode)._id
def get_projects_of_user(current_user, umcn): selector = NodeSelector(graph) users = selector.select("Person", umcn=umcn) user = list(users)[0] myprojects = [] for rel in graph.match(start_node=user, rel_type="IS_USER"): project = rel.end_node() myprojects.append(project) projects_list = [] for project in myprojects: users_list = [] for rel in graph.match(end_node=project, rel_type="IS_USER"): user_umcn = rel.start_node()["umcn"] users_list.append(user_umcn) admin = "" for rel in graph.match(end_node=project, rel_type="IS_ADMIN"): admin_umcn = rel.start_node()["umcn"] admin = admin_umcn project_obj = ({"id": remote(project)._id, "name": project['name'], "client": project['client'], "deadline": project['deadline'], "priority": project['priority'], "users": users_list, "admin": admin }) projects_list.append(project_obj) return jsonify(Projects=projects_list)
def find_users(task, connection_type): users_list = [] for rel in graph.match(end_node=task, rel_type=connection_type): user_id = remote(rel.start_node())._id users_list.append(user_id) return users_list
def create_node(new_node): node = Node(new_node["label"], **new_node["properties"]) graph.create(node) response = { "label": new_node["label"], "id": remote(node)._id, "properties": dict(node) } return json.jsonify({"node":response})
def create_link(new_node_data): s = graph.node(int(new_node_data["source_id"])) t = graph.node(int(new_node_data["target_id"])) relationship = Relationship(s, new_node_data["label"], t, **new_node_data["properties"]) graph.merge(relationship) response = { "label": relationship.type(), "id": remote(relationship)._id, "source": new_node_data["source_id"], "target": new_node_data["target_id"], "properties": new_node_data["properties"] } return json.jsonify({"link": response})
def get_property_keys(self): if not self.property_keys: self.property_keys = sorted(remote(self.graph).resolve("propertykeys").get().content) return self.property_keys
def get_constraints(self): if not self.constraints: data = remote(self.graph).resolve("schema/constraint").get().content self.constraints = sort_dict_by_key(data, "label") return self.constraints
def get_indexes(self): if not self.indexes: data = remote(self.graph).resolve("schema/index").get().content self.indexes = sort_dict_by_key(data, "label") return self.indexes