def test_transaction_close_tx_from_parent(self): remote_conn = create_connection_to_gtx() g = traversal().withRemote(remote_conn) drop_graph_check_count(g) tx1 = g.tx() tx2 = g.tx() # open up two sessions and create stuff gtx1 = tx1.begin() gtx2 = tx2.begin() add_node_validate_transaction_state(g, gtx1, 0, 0, [tx1, tx2]) add_node_validate_transaction_state(g, gtx2, 0, 0, [tx1, tx2]) add_node_validate_transaction_state(g, gtx2, 0, 1, [tx1, tx2]) add_node_validate_transaction_state(g, gtx2, 0, 2, [tx1, tx2]) # someone gets lazy and doesn't commit/rollback and just calls close() but on the parent # DriverRemoteConnection for all the session that were created via tx() - the graph # will decide how to treat the transaction, but for neo4j/gremlin server in this # test configuration it should rollback remote_conn.close() assert not tx1.isOpen() assert not tx2.isOpen() verify_gtx_closed(gtx1) verify_gtx_closed(gtx2) remote_conn = create_connection_to_gtx() g = traversal().withRemote(remote_conn) assert g.V().count().next() == 0 drop_graph_check_count(g)
def go(): conn = DriverRemoteConnection( 'ws://localhost:45940/gremlin', 'gmodern', pool_size=4) g = traversal().withRemote(conn) yield gen.sleep(0) assert len(g.V().toList()) == 6 conn.close()
def setup_graph(conn_string=DEFAULT_LOCAL_CONNECTION_STRING): """ Establish the connection to a property graph service using the connection string and return the gremlin graph. :param conn_string: connection parameter :return: gremlin graph """ try: graph = Graph() logging.debug('Trying To Connect') # new style connection = DriverRemoteConnection(conn_string, 'g') connection.close() connection = DriverRemoteConnection(conn_string, 'g') logging.debug('Connected') # The connection should be closed on shut down to close open connections with connection.close() # g = graph.traversal().withRemote(connection) # Deprecated instantiation of traversal g = traversal().withRemote(connection) logging.info('Successfully connected to the graph server') except Exception as e: # Shouldn't really be so broad logging.error("Could not connect to the Gremlin server. Run for example:" \ "\n'docker run --rm --name janusgraph-default janusgraph/janusgraph:latest' OR" \ "\n'docker run --name gremlin-server -p 8182:8182 tinkerpop/gremlin-server'") raise ConnectionError("Could not connect to the Gremlin server.") return g
def test_side_effect_close(self, remote_connection): g = traversal().withRemote(remote_connection) t = g.V().aggregate('a').aggregate('b') t.toList() # The 'a' key should return some side effects results = t.side_effects.get('a') assert results # Close result is None results = t.side_effects.close() assert not results # Shouldn't get any new info from server # 'b' isn't in local cache results = t.side_effects.get('b') assert not results # But 'a' should still be cached locally results = t.side_effects.get('a') assert results # 'a' should have been added to local keys cache, but not 'b' results = t.side_effects.keys() assert len(results) == 1 a, = results assert a == 'a' # Try to get 'b' directly from server, should throw error with pytest.raises(Exception): t.side_effects.value_lambda('b')
def traversal_source(self): """Create a GraphTraversalSource and return. Once `g` has been created using a connection, we can start to write Gremlin traversals to query the remote graph. Raises: RuntimeError: If the interactive script is not running. Examples: .. code:: python sess = graphscope.session() graph = load_modern_graph(sess, modern_graph_data_dir) interactive = sess.gremlin(graph) g = interactive.traversal_source() print(g.V().both()[1:3].toList()) print(g.V().both().name.toList()) Returns: `GraphTraversalSource` """ if self._status != InteractiveQueryStatus.Running: raise RuntimeError( "Interactive query is unavailable with %s status.", str(self._status)) return traversal().withRemote( DriverRemoteConnection(self._graph_url, "g"))
def prepare_traversal_source(scenario): # some tests create data - create a fresh remote to the empty graph and clear that graph prior to each test remote = __create_remote("ggraph") scenario.context.remote_conn["empty"] = remote scenario.context.traversals = world.gremlins.get(scenario.sentence, None) g = traversal().withRemote(remote) g.V().drop().iterate()
def test_multi_commit_and_rollback(self, remote_transaction_connection): # Start a transaction traversal. g = traversal().withRemote(remote_transaction_connection) start_count = g.V().count().next() # Create two transactions. tx1, tx2 = g.tx(), g.tx() # Generate two GraphTraversalSource's for each transaction with begin. gtx1, gtx2 = tx1.begin(), tx2.begin() verify_tx_state([tx1, tx2], True) # Add node to gtx1, which should be visible to gtx1, not gtx2. add_node_validate_transaction_state(g, gtx1, start_count, start_count, [tx1, tx2]) # Add node to gtx2, which should be visible to gtx2, not gtx2 add_node_validate_transaction_state(g, gtx2, start_count, start_count, [tx1, tx2]) # Add node to gtx1, which should be visible to gtx1, not gtx2. Note previous node also added. add_node_validate_transaction_state(g, gtx1, start_count, start_count + 1, [tx1, tx2]) tx1.commit() verify_tx_state([tx1], False) verify_tx_state([tx2], True) assert g.V().count().next() == start_count + 2 tx2.rollback() verify_tx_state([tx1, tx2], False) assert g.V().count().next() == start_count + 2
def graph_traversal(neptune_endpoint=None, neptune_port=NEPTUNE_PORT, show_endpoint=True, connection=None): def _remote_connection(neptune_endpoint=None, neptune_port=None, show_endpoint=True): neptune_gremlin_endpoint = '{protocol}://{neptune_endpoint}:{neptune_port}/{suffix}'.format( protocol='wss', neptune_endpoint=neptune_endpoint, neptune_port=neptune_port, suffix='gremlin') if show_endpoint: print('[INFO] gremlin: {}'.format(neptune_gremlin_endpoint), file=sys.stderr) retry_count = 0 while True: try: return DriverRemoteConnection(neptune_gremlin_endpoint, 'g') except HTTPError as ex: exc_info = sys.exc_info() if retry_count < 3: retry_count += 1 print('[DEBUG] Connection timeout. Retrying...', file=sys.stderr) else: raise exc_info[0].with_traceback(exc_info[1], exc_info[2]) if connection is None: connection = _remote_connection(neptune_endpoint, neptune_port, show_endpoint) return traversal().withRemote(connection)
def main(): # connect to a remote server that is compatible with the Gremlin Server protocol. for those who # downloaded and are using Gremlin Server directly be sure that it is running locally with: # # bin/gremlin-server.sh console # # which starts it in "console" mode with an empty in-memory TinkerGraph ready to go bound to a # variable named "g" as referenced in the following line. g = traversal().withRemote( DriverRemoteConnection('ws://localhost:8182/gremlin', 'g')) # add some data - be sure to use a terminating step like iterate() so that the traversal # "executes". iterate() does not return any data and is used to just generate side-effects # (i.e. write data to the database) g.addV('person').property('name', 'marko').as_('m'). \ addV('person').property('name', 'vadas').as_('v'). \ addE('knows').from_('m').to('v').iterate() # retrieve the data from the "marko" vertex print("marko: " + to_string(g.V().has('person', 'name', 'marko').valueMap().next())) # find the "marko" vertex and then traverse to the people he "knows" and return their data print("who marko knows: " + to_string(g.V().has( 'person', 'name', 'marko').out('knows').valueMap().next()))
def __create_lookup_e(remote): g = traversal().withRemote(remote) # hold a map of the "name"/edge for use in asserting results - "name" in this context is in the form of # outgoingV-label->incomingV return g.E().group(). \ by(lambda: ("it.outVertex().value('name') + '-' + it.label() + '->' + it.inVertex().value('name')", "gremlin-groovy")). \ by(tail()).next()
def tbfs(source_node): """ Perform Temporal BFS from Source Node :param source_node: :return: """ g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin', 'g')) print g.V(source_node).toList()
def test_strategies(self, remote_connection): statics.load_statics(globals()) g = traversal().withRemote(remote_connection). \ withStrategies(TraversalStrategy("SubgraphStrategy", {"vertices": __.hasLabel("person"), "edges": __.hasLabel("created")}, "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.SubgraphStrategy")) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert 4 == g.V().filter( lambda: ("x -> true", "gremlin-groovy")).count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(vertices=__.hasLabel("person"), edges=__.hasLabel("created"))) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(edges=__.hasLabel("created"))) assert 6 == g.V().count().next() assert 4 == g.E().count().next() assert 1 == g.E().label().dedup().count().next() assert "created" == g.E().label().dedup().next() # g = g.withoutStrategies(SubgraphStrategy). \ withComputer(vertices=__.has("name", "marko"), edges=__.limit(0)) assert 1 == g.V().count().next() assert 0 == g.E().count().next() assert "person" == g.V().label().next() assert "marko" == g.V().name.next() # g = traversal().withRemote(remote_connection).withComputer() assert 6 == g.V().count().next() assert 6 == g.E().count().next() # g = traversal().withRemote(remote_connection). \ withStrategies(ReservedKeysVerificationStrategy(throw_exception=True)) try: g.addV("person").property("id", "please-don't-use-id").iterate() assert False except GremlinServerError as gse: assert gse.status_code == 500
def _connect(self): ''' Connect to an instance of a gremlin server hosted at port:8182 ''' self.g = traversal().withRemote( DriverRemoteConnection(f'ws://localhost:{self.port}/gremlin', 'g')) return
def __create_lookup_e(remote): g = traversal().withRemote(remote) # hold a map of the "name"/edge for use in asserting results - "name" in this context is in the form of # outgoingV-label->incomingV return g.E().group(). \ by(lambda: ("it.outVertex().value('name') + '-' + it.label() + '->' + it.inVertex().value('name')", "gremlin-groovy")). \ by(tail()).next()
def start_up(self, **kwargs): # it can cause exceptions when starting all at once! # This solves it currently... ( TODO why does it not allow multiple connections consistently?) sleep(random.randint(1, 15)) # This generates a connection to the gremlin server self.conn = DriverRemoteConnection(kwargs["gremlin_url"], kwargs["gremlin_traversal_source"], pool_size=1) self.remote_graph = traversal().withRemote(self.conn)
def handle_request(): try: remote_connection = DriverRemoteConnection("ws://localhost:45940/gremlin", "g") g = traversal().withRemote(remote_connection) g.V().limit(1).toList() remote_connection.close() return True except RuntimeError: return False
def get_connection(): try: g = traversal().withRemote( DriverRemoteConnection(os.environ["JANUS_HOST"], "g")) return g except Exception as e: logging.warning("Error: Unable to connect to the database") logging.info(e) exit(e)
def test_enforce_anonymous_child_traversal(self): g = traversal().withGraph(Graph()) g.V(0).addE("self").to(__.V(1)) try: g.V(0).addE("self").to(g.V(1)) assert False except TypeError: pass
def test_traversals(self, remote_connection): statics.load_statics(globals()) g = traversal().withRemote(remote_connection) assert long(6) == g.V().count().toList()[0] # # assert Vertex(1) == g.V(1).next() assert 1 == g.V(1).id().next() assert Traverser(Vertex(1)) == g.V(1).nextTraverser() assert 1 == len(g.V(1).toList()) assert isinstance(g.V(1).toList(), list) results = g.V().repeat(out()).times(2).name results = results.toList() assert 2 == len(results) assert "lop" in results assert "ripple" in results # # assert 10 == g.V().repeat(both()).times(5)[0:10].count().next() assert 1 == g.V().repeat(both()).times(5)[0:1].count().next() assert 0 == g.V().repeat(both()).times(5)[0:0].count().next() assert 4 == g.V()[2:].count().next() assert 2 == g.V()[:2].count().next() # # results = g.withSideEffect('a', ['josh', 'peter']).V(1).out('created').in_('created').values('name').where(P.within('a')).toList() assert 2 == len(results) assert 'josh' in results assert 'peter' in results # # results = g.V().out().profile().toList() assert 1 == len(results) assert 'metrics' in results[0] assert 'dur' in results[0] # # results = g.V().has('name', 'peter').as_('a').out('created').as_('b').select('a', 'b').by( __.valueMap()).toList() assert 1 == len(results) assert 'peter' == results[0]['a']['name'][0] assert 35 == results[0]['a']['age'][0] assert 'lop' == results[0]['b']['name'][0] assert 'java' == results[0]['b']['lang'][0] assert 2 == len(results[0]['a']) assert 2 == len(results[0]['b']) # # results = g.V(1).inject(g.V(2).next()).values('name').toList() assert 2 == len(results) assert 'marko' in results assert 'vadas' in results # # results = g.V().has('person', 'name', 'marko').map(lambda: ("it.get().value('name')", "gremlin-groovy")).toList() assert 1 == len(results) assert 'marko' in results # # # this test just validates that the underscored versions of steps conflicting with Gremlin work # properly and can be removed when the old steps are removed - TINKERPOP-2272 results = g.V().filter_(__.values('age').sum_().and_( __.max_().is_(gt(0)), __.min_().is_(gt(0)))).range_(0, 1).id_().next() assert 1 == results
def __init__(self, gremlin_server_url): self.connection = DriverRemoteConnection(gremlin_server_url, 'g') if gremlin_server_url is None: raise Exception( "Invalid gremlin_server_url. example: ws://127.0.0.1:8182/gremlin" ) self.g = traversal().withRemote(self.connection) self.vertex = Vertex(self) self.edge = Edge(self)
def g(self): server=self.server url='ws://%s:%d/gremlin' % (server.host,server.port) # https://github.com/orientechnologies/orientdb-gremlin/issues/143 #username="******" #password="******" self.remoteConnection=DriverRemoteConnection(url,server.alias,username=server.username,password=server.password) g = traversal().withRemote(self.remoteConnection) return g
def __init__(self, *, key_property_name: str, remote_connection: DriverRemoteConnection) -> None: # these might vary from datastore type to another, but if you change these while talking to the same instance # without migration, it will go poorly self.key_property_name: str = key_property_name # safe this for use in _submit self.remote_connection: DriverRemoteConnection = remote_connection self._g: GraphTraversalSource = traversal().withRemote(self.remote_connection)
def test_lambda_traversals(self, remote_connection): statics.load_statics(globals()) assert "remoteconnection[ws://localhost:45940/gremlin,gmodern]" == str(remote_connection) g = traversal().withRemote(remote_connection) assert 24.0 == g.withSack(1.0, lambda: ("x -> x + 1", "gremlin-groovy")).V().both().sack().sum().next() assert 24.0 == g.withSack(lambda: ("{1.0d}", "gremlin-groovy"), lambda: ("x -> x + 1", "gremlin-groovy")).V().both().sack().sum().next() assert 48.0 == g.withSack(1.0, lambda: ("x, y -> x + y + 1", "gremlin-groovy")).V().both().sack().sum().next() assert 48.0 == g.withSack(lambda: ("{1.0d}", "gremlin-groovy"), lambda: ("x, y -> x + y + 1", "gremlin-groovy")).V().both().sack().sum().next()
def create_graph_traversal_source(**kwargs: Any) -> GraphTraversalSource: assert all(e not in kwargs for e in ('url', 'traversal_source')), \ f'do not pass traversal_source or url in {kwargs}' prepared_request = override_prepared_request_parameters( endpoints.gremlin_endpoint().prepare_request(), override_uri=override_uri) kwargs['traversal_source'] = 'g' remote_connection = DriverRemoteConnection(url=prepared_request, **kwargs) return traversal().withRemote(remote_connection)
def __connect_to_neptune(self, server: str, port: int, ssl: bool): """Creates a connection to Neptune and returns the traversal source""" hostname = f'{server}:{port}' if ssl: endpoint = f'wss://{hostname}/gremlin' else: endpoint = f'ws://{hostname}/gremlin' self.logger.info(endpoint) connection = DriverRemoteConnection(endpoint, 'g') gts = traversal().withRemote(connection) return (gts, connection)
def test_promise(self, remote_connection): g = traversal().withRemote(remote_connection) future = g.V().aggregate('a').promise() t = future.result() assert len(t.toList()) == 6 a, = t.side_effects.keys() assert a == 'a' results = t.side_effects.get('a') assert results results = t.side_effects.close() assert not results
def get_traversal_source(host=None, port=None): """Get a Traversal Source from a Gremlin Server connection.""" if not host: host = DEFAULT_HOST if not port: port = DEFAULT_PORT connection_string = 'ws://{0}:{1}/gremlin'.format(host, port) g = traversal().withRemote(DriverRemoteConnection(connection_string, 'g')) return g
def _get_traversal(self) -> GraphTraversal: """ :return: """ remote_connection = DriverRemoteConnection( "{0}://{1}:{2}/gremlin".format(self._connection_method, self._neptune_cluster_endpoint, self._neptune_cluster_port), "g") return traversal().withRemote(remote_connection)
def get_traversal() -> anonymous_traversal: """ connect to the gremlin server""" # pylint: disable=global-statement global G_BACKING, G_CONNECTION if G_BACKING is None: config = f'ws://{host()}:8182/gremlin' print(f'host: "{config}"') G_CONNECTION = DriverRemoteConnection(config, 'g') G_BACKING = traversal().withRemote(G_CONNECTION) return G_BACKING
def test_no_sugar_for_magic_methods(self): g = traversal().withGraph(Graph()) t = g.V().age assert 2 == len(t.bytecode.step_instructions) try: t = g.V().__len__ fail("can't do sugar with magic") except AttributeError as err: assert str( err ) == 'Python magic methods or keys starting with double underscore cannot be used for Gremlin sugar - prefer values(__len__)'
def test_strategies(self, remote_connection): statics.load_statics(globals()) # g = traversal().withRemote(remote_connection). \ withStrategies(TraversalStrategy("SubgraphStrategy", {"vertices": __.hasLabel("person"), "edges": __.hasLabel("created")})) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert 4 == g.V().filter( lambda: ("lambda x: True", "gremlin-python")).count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(vertices=__.hasLabel("person"), edges=__.hasLabel("created"))) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(edges=__.hasLabel("created"))) assert 6 == g.V().count().next() assert 4 == g.E().count().next() assert 1 == g.E().label().dedup().count().next() assert "created" == g.E().label().dedup().next() # g = g.withoutStrategies(SubgraphStrategy). \ withComputer(vertices=__.has("name", "marko"), edges=__.limit(0)) assert 1 == g.V().count().next() assert 0 == g.E().count().next() assert "person" == g.V().label().next() assert "marko" == g.V().name.next() # g = traversal().withRemote(remote_connection).withComputer() assert 6 == g.V().count().next() assert 6 == g.E().count().next()
def test_strategies(self, remote_connection): statics.load_statics(globals()) # g = traversal().withRemote(remote_connection). \ withStrategies(TraversalStrategy("SubgraphStrategy", {"vertices": __.hasLabel("person"), "edges": __.hasLabel("created")})) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert 4 == g.V().filter(lambda: ("lambda x: True", "gremlin-python")).count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(vertices=__.hasLabel("person"), edges=__.hasLabel("created"))) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(edges=__.hasLabel("created"))) assert 6 == g.V().count().next() assert 4 == g.E().count().next() assert 1 == g.E().label().dedup().count().next() assert "created" == g.E().label().dedup().next() # g = g.withoutStrategies(SubgraphStrategy). \ withComputer(vertices=__.has("name", "marko"), edges=__.limit(0)) assert 1 == g.V().count().next() assert 0 == g.E().count().next() assert "person" == g.V().label().next() assert "marko" == g.V().name.next() # g = traversal().withRemote(remote_connection).withComputer() assert 6 == g.V().count().next() assert 6 == g.E().count().next()
def test_traversals(self, remote_connection): statics.load_statics(globals()) assert "remoteconnection[ws://localhost:45940/gremlin,gmodern]" == str(remote_connection) g = traversal().withRemote(remote_connection) assert long(6) == g.V().count().toList()[0] # # assert Vertex(1) == g.V(1).next() assert 1 == g.V(1).id().next() assert Traverser(Vertex(1)) == g.V(1).nextTraverser() assert 1 == len(g.V(1).toList()) assert isinstance(g.V(1).toList(), list) results = g.V().repeat(out()).times(2).name results = results.toList() assert 2 == len(results) assert "lop" in results assert "ripple" in results # # assert 10 == g.V().repeat(both()).times(5)[0:10].count().next() assert 1 == g.V().repeat(both()).times(5)[0:1].count().next() assert 0 == g.V().repeat(both()).times(5)[0:0].count().next() assert 4 == g.V()[2:].count().next() assert 2 == g.V()[:2].count().next() # # results = g.withSideEffect('a', ['josh', 'peter']).V(1).out('created').in_('created').values('name').where( within('a')).toList() assert 2 == len(results) assert 'josh' in results assert 'peter' in results # # results = g.V().out().profile().toList() assert 1 == len(results) assert 'metrics' in results[0] assert 'dur' in results[0] # # results = g.V().has('name', 'peter').as_('a').out('created').as_('b').select('a', 'b').by( __.valueMap()).toList() assert 1 == len(results) assert 'peter' == results[0]['a']['name'][0] assert 35 == results[0]['a']['age'][0] assert 'lop' == results[0]['b']['name'][0] assert 'java' == results[0]['b']['lang'][0] assert 2 == len(results[0]['a']) assert 2 == len(results[0]['b']) # # results = g.V(1).inject(g.V(2).next()).values('name').toList() assert 2 == len(results) assert 'marko' in results assert 'vadas' in results
def prepare_traversal_source(scenario): # some tests create data - create a fresh remote to the empty graph and clear that graph prior to each test if not("graphson" in world.config.user_data): raise ValueError('test configuration requires setting of --user-data="graphson=*" to one of [v2,v3]') if world.config.user_data["graphson"] == "v3": s = serializer.GraphSONSerializersV3d0() elif world.config.user_data["graphson"] == "v2": s = serializer.GraphSONSerializersV2d0() else: raise ValueError('serializer set with --user-data="graphson=v2" must be one of [v2,v3]') remote = DriverRemoteConnection('ws://localhost:45940/gremlin', "ggraph", message_serializer=s) scenario.context.remote_conn["empty"] = remote g = traversal().withRemote(remote) g.V().drop().iterate()
def _executor(q, conn): close = False if not conn: # This isn't a fixture so close manually close = True conn = DriverRemoteConnection( 'ws://localhost:45940/gremlin', 'gmodern', pool_size=4) try: g = traversal().withRemote(conn) future = g.V().promise() t = future.result() assert len(t.toList()) == 6 except: q.put(sys.exc_info()[0]) else: q.put('success!') # Close conn if close: conn.close()
def test_iteration(self, remote_connection): statics.load_statics(globals()) assert "remoteconnection[ws://localhost:45940/gremlin,gmodern]" == str(remote_connection) g = traversal().withRemote(remote_connection) t = g.V().count() assert t.hasNext() assert t.hasNext() assert t.hasNext() assert t.hasNext() assert t.hasNext() assert 6 == t.next() assert not(t.hasNext()) assert not(t.hasNext()) assert not(t.hasNext()) assert not(t.hasNext()) assert not(t.hasNext()) t = g.V().has('name', P.within('marko', 'peter')).values('name').order() assert "marko" == t.next() assert t.hasNext() assert t.hasNext() assert t.hasNext() assert t.hasNext() assert t.hasNext() assert "peter" == t.next() assert not(t.hasNext()) assert not(t.hasNext()) assert not(t.hasNext()) assert not(t.hasNext()) assert not(t.hasNext()) try: t.next() assert False except StopIteration: assert True
def __create_lookup_v(remote): g = traversal().withRemote(remote) # hold a map of name/vertex for use in asserting results return g.V().group().by('name').by(tail()).next()
def choose_graph(step, graph_name): step.context.graph_name = graph_name step.context.g = traversal().withRemote(step.context.remote_conn[graph_name])
def test_side_effects(self, remote_connection): statics.load_statics(globals()) # g = traversal().withRemote(remote_connection) ### t = g.V().hasLabel("project").name.iterate() assert 0 == len(t.side_effects.keys()) with pytest.raises(Exception): m = t.side_effects["m"] ### t = g.V().out("created").groupCount("m").by("name") results = t.toSet() assert 2 == len(results) assert Vertex(3) in results assert Vertex(5) in results assert 1 == len(t.side_effects.keys()) assert "m" in t.side_effects.keys() m = t.side_effects["m"] assert isinstance(m, dict) assert 2 == len(m) assert 3 == m["lop"] assert 1 == m["ripple"] assert isinstance(m["lop"], long) assert isinstance(m["ripple"], long) # check status attributes assert "host" in t.side_effects.status_attributes ## t = g.V().out("created").groupCount("m").by("name").name.aggregate("n") results = t.toSet() assert 2 == len(results) assert "lop" in results assert "ripple" in results assert 2 == len(t.side_effects.keys()) assert "m" in t.side_effects.keys() assert "n" in t.side_effects.keys() n = t.side_effects.get("n") assert isinstance(n, dict) assert 2 == len(n) assert "lop" in n.keys() assert "ripple" in n.keys() assert 3 == n["lop"] assert 1 == n["ripple"] t = g.withSideEffect('m', 32).V().map(lambda: "x: x.sideEffects('m')") results = t.toSet() assert 1 == len(results) assert 32 == list(results)[0] assert 32 == t.side_effects['m'] assert 1 == len(t.side_effects.keys()) with pytest.raises(Exception): x = t.side_effects["x"] a = g.V().has("name", "marko").next() b = g.V().has("name", "peter").next() edge = g.withSideEffect("b", b).V(a).addE("knows").to("b").next() assert "knows" == edge.label assert a == edge.outV assert b == edge.inV g.V().has("name", "marko").outE("knows").where(__.inV().has("name", "peter")).drop().iterate() ## edge = g.withSideEffect("a", a).withSideEffect("b", b).V().limit(1).addE("knows").from_("a").to("b").next() assert "knows" == edge.label assert a == edge.outV assert b == edge.inV g.V().has("name", "marko").outE("knows").where(__.inV().has("name", "peter")).drop().iterate()