コード例 #1
0
 def test_traversals(self):
     statics.load_statics(globals())
     connection = DriverRemoteConnection('ws://localhost:8182/gremlin', 'g')
     assert "remoteconnection[ws://localhost:8182/gremlin,g]" == str(
         connection)
     #
     g = Graph().traversal().withRemote(connection)
     #
     assert 6L == 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.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].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()
     # todo: need a traversal metrics deserializer
     g.V().out().profile().next()
     connection.close()
コード例 #2
0
    def test_side_effects(self):
        statics.load_statics(globals())
        connection = DriverRemoteConnection('ws://localhost:45940/gremlin',
                                            'g')
        #
        g = Graph().traversal().withRemote(connection)
        ###
        t = g.V().hasLabel("project").name.iterate()
        assert 0 == len(t.side_effects.keys())
        try:
            m = t.side_effects["m"]
            raise Exception(
                "Accessing a non-existent key should throw an error")
        except KeyError:
            pass
        ###
        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)
        ###
        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())
        try:
            x = t.side_effects["x"]
            raise Exception(
                "Accessing a non-existent key should throw an error")
        except KeyError:
            pass
        connection.close()
コード例 #3
0
 def test_edge(self):
     x = Edge(123, Vertex(1, 'person'), "developed", Vertex(10, "software"))
     output = self.graphbinary_reader.readObject(
         self.graphbinary_writer.writeObject(x))
     assert x == output
     assert x.inV == output.inV
     assert x.outV == output.outV
コード例 #4
0
 async def test_traversals(self, remote_connection):
     statics.load_statics(globals())
     g = Graph().traversal().withRemote(remote_connection)
     result = await g.V().count().toList()
     assert long(6) == result[0]
     # #
     assert Vertex(1) == await g.V(1).next()
     assert 1 == await g.V(1).id().next()
     assert Traverser(Vertex(1)) == await g.V(1).nextTraverser()
     result = await g.V(1).toList()
     assert 1 == len(result)
     result = await g.V(1).toList()
     assert isinstance(result, list)
     results = g.V().repeat(out()).times(2).name
     results = await results.toList()
     assert 2 == len(results)
     assert "lop" in results  # FIXME : Test fails here.
     assert "ripple" in results
     # # #
     assert 10 == await g.V().repeat(both()).times(5)[0:10].count().next()
     assert 1 == await g.V().repeat(both()).times(5)[0:1].count().next()
     assert 0 == await g.V().repeat(both()).times(5)[0:0].count().next()
     assert 4 == await g.V()[2:].count().next()
     assert 2 == await g.V()[:2].count().next()
     # # #
     results = await 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
     # # # todo: need a traversal metrics deserializer
     # g.V().out().profile().next()
     await remote_connection.close()
コード例 #5
0
    def test_traversals(self, remote_connection):
        statics.load_statics(globals())
        assert "remoteconnection[ws://localhost:45940/gremlin,g]" == str(
            remote_connection)
        g = Graph().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
        # # todo: need a traversal metrics deserializer
        g.V().out().profile().next()
コード例 #6
0
 def _read_edge(cls, b, r):
     edgeid = r.readObject(b)
     edgelbl = r.toObject(b, DataType.string, False)
     inv = Vertex(r.readObject(b), r.toObject(b, DataType.string, False))
     outv = Vertex(r.readObject(b), r.toObject(b, DataType.string, False))
     edge = Edge(edgeid, outv, edgelbl, inv)
     b.read(4)
     return edge
コード例 #7
0
    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
コード例 #8
0
ファイル: test_graphsonV3d0.py プロジェクト: zjxian/tinkerpop
 def test_path(self):
     path = self.graphson_reader.readObject(
         """{"@type":"g:Path","@value":{"labels":{"@type":"g:List","@value":[{"@type":"g:Set","@value":["a"]},{"@type":"g:Set","@value":["b","c"]},{"@type":"g:Set","@value":[]}]},"objects":{"@type":"g:List","@value":[{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":1},"label":"person","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int64","@value":0},"value":"marko","label":"name"}}],"age":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int64","@value":1},"value":{"@type":"g:Int32","@value":29},"label":"age"}}]}}},{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":3},"label":"software","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int64","@value":4},"value":"lop","label":"name"}}],"lang":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int64","@value":5},"value":"java","label":"lang"}}]}}},"lop"]}}}"""
     )
     assert isinstance(path, Path)
     assert "path[v[1], v[3], lop]" == str(path)
     assert Vertex(1) == path[0]
     assert Vertex(1) == path["a"]
     assert "lop" == path[2]
     assert 3 == len(path)
コード例 #9
0
def test_parse_gremlin_path_elements(gremlin_parser):
    # parse path with elements
    v = Vertex("foo")
    v2 = Vertex("bar")
    e1 = Edge("e1", "foo", "label", "bar")
    p = Path(labels=["vertex", "label", "vertex"], objects=[v, e1, v2])
    out = gremlin_parser.gremlin_results_to_dict([p])
    df = pd.DataFrame.from_records(out)
    row = df.iloc[0]
    assert df.shape == (1, 3)
    assert row[0] == {"id": "foo", "label": "vertex"}
    assert row[1] == {"id": "e1", "label": "label", "outV": "foo", "inV": "bar"}
    assert row[2] == {"id": "bar", "label": "vertex"}

    # parse path with multiple elements
    e2 = Edge("bar", "out1", "label", "in2")
    v3 = Vertex("in2")
    p1 = Path(labels=["vertex", "label", "vertex"], objects=[v2, e2, v3])
    out = gremlin_parser.gremlin_results_to_dict([p, p1])
    df = pd.DataFrame.from_records(out)
    row = df.iloc[1]
    assert df.shape == (2, 3)
    assert row[0] == {"id": "bar", "label": "vertex"}
    assert row[1] == {"id": "bar", "label": "label", "outV": "out1", "inV": "in2"}
    assert row[2] == {"id": "in2", "label": "vertex"}

    # parse path with maps
    p = Path(
        labels=["vertex", "label", "vertex"],
        objects=[{"name": "foo", "age": 29}, {"dist": 32}, {"name": "bar", "age": 40}],
    )
    out = gremlin_parser.gremlin_results_to_dict([p])
    df = pd.DataFrame.from_records(out)
    row = df.iloc[0]
    assert df.shape == (1, 3)
    assert row[0]["name"] == "foo"
    assert row[0]["age"] == 29
    assert row[1]["dist"] == 32
    assert row[2]["name"] == "bar"
    assert row[2]["age"] == 40

    # parse path with mixed elements and maps
    p = Path(
        labels=["vertex", "label", "vertex"],
        objects=[{"name": "foo", "age": 29}, Edge("bar", "out1", "label", "in2"), {"name": "bar", "age": 40}],
    )
    out = gremlin_parser.gremlin_results_to_dict([p])
    df = pd.DataFrame.from_records(out)
    row = df.iloc[0]
    assert df.shape == (1, 3)
    assert row[0]["name"] == "foo"
    assert row[0]["age"] == 29
    assert row[1] == {"id": "bar", "label": "label", "outV": "out1", "inV": "in2"}
    assert row[2]["name"] == "bar"
    assert row[2]["age"] == 40
コード例 #10
0
 def test_path(self):
     path = GraphSONReader.readObject(
         """{"@type":"g:Path","@value":{"labels":[["a"],["b","c"],[]],"objects":[{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":1},"label":"person","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int64","@value":0},"value":"marko","label":"name"}}],"age":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int64","@value":1},"value":{"@type":"g:Int32","@value":29},"label":"age"}}]}}},{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":3},"label":"software","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int64","@value":4},"value":"lop","label":"name"}}],"lang":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int64","@value":5},"value":"java","label":"lang"}}]}}},"lop"]}}"""
     )
     assert isinstance(path, Path)
     if six.PY3:
         assert "[v[1], v[3], 'lop']" == str(path)
     else:
         assert "[v[1], v[3], u'lop']" == str(path)
     assert Vertex(1) == path[0]
     assert Vertex(1) == path["a"]
     assert "lop" == path[2]
     assert 3 == len(path)
コード例 #11
0
 async def test_side_effects(self, remote_connection):
     statics.load_statics(globals())
     g = Graph().traversal().withRemote(remote_connection)
     t = await g.V().hasLabel("project").name.iterate()
     keys = await t.side_effects.keys()
     assert 0 == len(keys)
     with pytest.raises(Exception):
         m = await t.side_effects["m"]
     t = g.V().out("created").groupCount("m").by("name")
     results = await t.toSet()
     assert 2 == len(results)
     assert Vertex(3) in results
     assert Vertex(5) in results
     keys = await t.side_effects.keys()
     assert 1 == len(keys)
     assert "m" in keys
     m = await 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)
     # ##
     t = g.V().out("created").groupCount("m").by("name").name.aggregate("n")
     results = await t.toSet()
     assert 2 == len(results)
     assert "lop" in results
     assert "ripple" in results
     keys = await t.side_effects.keys()
     assert 2 == len(keys)
     assert "m" in keys
     assert "n" in keys
     n = await 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 = await t.toSet()
     assert 1 == len(results)
     assert 32 == list(results)[0]
     assert 32 == await t.side_effects['m']
     keys = await t.side_effects.keys()
     assert 1 == len(keys)
     with pytest.raises(Exception):
         x = await t.side_effects["x"]
     await remote_connection.close()
コード例 #12
0
    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
コード例 #13
0
    def test_group_returnvertex_groupby_notspecified(self):
        vertex = Vertex(id='1')

        gn = GremlinNetwork()
        gn.add_vertex(vertex)
        node = gn.graph.nodes.get('1')
        self.assertEqual(node['group'], 'vertex')
コード例 #14
0
 def test_graph(self):
     vertex = self.graphson_reader.readObject(
         """{"@type":"g:Vertex", "@value":{"id":{"@type":"g:Int32","@value":1},"label":"person","outE":{"created":[{"id":{"@type":"g:Int32","@value":9},"inV":{"@type":"g:Int32","@value":3},"properties":{"weight":{"@type":"g:Double","@value":0.4}}}],"knows":[{"id":{"@type":"g:Int32","@value":7},"inV":{"@type":"g:Int32","@value":2},"properties":{"weight":{"@type":"g:Double","@value":0.5}}},{"id":{"@type":"g:Int32","@value":8},"inV":{"@type":"g:Int32","@value":4},"properties":{"weight":{"@type":"g:Double","@value":1.0}}}]},"properties":{"name":[{"id":{"@type":"g:Int64","@value":0},"value":"marko"}],"age":[{"id":{"@type":"g:Int64","@value":1},"value":{"@type":"g:Int32","@value":29}}]}}}""")
     assert isinstance(vertex, Vertex)
     assert "person" == vertex.label
     assert 1 == vertex.id
     assert isinstance(vertex.id, int)
     assert vertex == Vertex(1)
コード例 #15
0
def traversal_mult_note_result():
    vert_0 = Vertex(id=7700, label='Note')
    vert_1 = Vertex(id=7800, label='Note')

    result = [{'p': VertexProperty(id=7701, label='name', value='D3', vertex=None),
               'v': vert_0},
              {'p': VertexProperty(id=7702, label='length', value=16, vertex=None),
               'v': vert_0},
              {'p': VertexProperty(id=7703, label='dot', value=0, vertex=None),
               'v': vert_0},
              {'p': VertexProperty(id=7710, label='name', value='F3', vertex=None),
               'v': vert_1},
              {'p': VertexProperty(id=7712, label='length', value=8, vertex=None),
               'v': vert_1},
              {'p': VertexProperty(id=7713, label='dot', value=1, vertex=None),
               'v': vert_1}]

    return result
コード例 #16
0
def traversal_note_result():
    vert = Vertex(id=7700, label='Note')
    result = [{'p': VertexProperty(id=7701, label='name', value='D3', vertex=None),
               'v': vert},
              {'p': VertexProperty(id=7702, label='length', value=16, vertex=None),
               'v': vert},
              {'p': VertexProperty(id=7703, label='dot', value=0, vertex=None),
               'v': vert}]
    return result
コード例 #17
0
 def test_path(self):
     path = Path(
         [set(["a", "b"]), set(["c", "b"]),
          set([])], [1, Vertex(1), "hello"])
     assert "path[1, v[1], hello]" == str(path)
     assert 1 == path["a"]
     assert Vertex(1) == path["c"]
     assert [1, Vertex(1)] == path["b"]
     assert path[0] == 1
     assert path[1] == Vertex(1)
     assert path[2] == "hello"
     assert 3 == len(path)
     assert "hello" in path
     assert "goodbye" not in path
     assert Vertex(1) in path
     assert Vertex(123) not in path
     #
     try:
         temp = path[3]
         raise Exception(
             "Accessing beyond the list index should throw an index error")
     except IndexError:
         pass
     #
     try:
         temp = path["zz"]
         raise Exception("Accessing nothing should throw a key error")
     except KeyError:
         pass
     #
     try:
         temp = path[1:2]
         raise Exception("Accessing using slices should throw a type error")
     except TypeError:
         pass
     #
     assert path == path
     assert hash(path) == hash(path)
     path2 = Path(
         [set(["a", "b"]), set(["c", "b"]),
          set([])], [1, Vertex(1), "hello"])
     assert path == path2
     assert hash(path) == hash(path2)
     assert path != Path(
         [set(["a"]), set(["c", "b"]), set([])], [1, Vertex(1), "hello"])
     assert path != Path(
         [set(["a", "b"]), set(["c", "b"]),
          set([])], [3, Vertex(1), "hello"])
コード例 #18
0
def test_parse_gremlin_vertex_elements(gremlin_parser):
    # parse vertex elements
    v = Vertex("foo")
    input = [v]
    out = gremlin_parser.gremlin_results_to_dict(input)
    df = pd.DataFrame.from_records(out)
    row = df.iloc[0]
    assert df.shape == (1, 2)
    assert row["id"] == "foo"
    assert row["label"] == "vertex"

    # parse multiple vertex elements
    v1 = Vertex("bar")
    input = [v, v1]
    out = gremlin_parser.gremlin_results_to_dict(input)
    df = pd.DataFrame.from_records(out)
    row = df.iloc[1]
    assert df.shape == (2, 2)
    assert row["id"] == "bar"
    assert row["label"] == "vertex"
コード例 #19
0
ファイル: test_graphsonV3d0.py プロジェクト: rkhaja/tinkerpop
    def test_graph(self):
        # TODO: this assert is not compatible with python 3 and now that we test with both 2 and 3 it fails
        assert {"@type": "g:Vertex",
                "@value": {"id": {"@type": "g:Int64", "@value": 12}, "label": "person"}} == json.loads(
            self.graphson_writer.writeObject(Vertex(long(12), "person")))

        assert {"@type": "g:Edge", "@value": {"id": {"@type": "g:Int32", "@value": 7},
                                              "outV": {"@type": "g:Int32", "@value": 0},
                                              "outVLabel": "person",
                                              "label": "knows",
                                              "inV": {"@type": "g:Int32", "@value": 1},
                                              "inVLabel": "dog"}} == json.loads(
            self.graphson_writer.writeObject(Edge(7, Vertex(0, "person"), "knows", Vertex(1, "dog"))))
        assert {"@type": "g:VertexProperty", "@value": {"id": "blah", "label": "keyA", "value": True,
                                                        "vertex": "stephen"}} == json.loads(
            self.graphson_writer.writeObject(VertexProperty("blah", "keyA", True, Vertex("stephen"))))

        assert {"@type": "g:Property",
                "@value": {"key": "name", "value": "marko", "element": {"@type": "g:VertexProperty",
                                                                        "@value": {
                                                                            "vertex": "vertexId",
                                                                            "id": {"@type": "g:Int32", "@value": 1234},
                                                                            "label": "aKey"}}}} == json.loads(
            self.graphson_writer.writeObject(
                Property("name", "marko", VertexProperty(1234, "aKey", 21345, Vertex("vertexId")))))

        vertex = self.graphson_reader.readObject(self.graphson_writer.writeObject(Vertex(1, "person")))
        assert 1 == vertex.id
        assert "person" == vertex.label

        edge = self.graphson_reader.readObject(
            self.graphson_writer.writeObject(Edge(3, Vertex(1, "person"), "knows", Vertex(2, "dog"))))
        assert "knows" == edge.label
        assert 3 == edge.id
        assert 1 == edge.outV.id
        assert 2 == edge.inV.id

        vertex_property = self.graphson_reader.readObject(
            self.graphson_writer.writeObject(VertexProperty(1, "age", 32, Vertex(1))))
        assert 1 == vertex_property.id
        assert "age" == vertex_property.key
        assert 32 == vertex_property.value

        property = self.graphson_reader.readObject(self.graphson_writer.writeObject(Property("age", 32.2, Edge(1,Vertex(2),"knows",Vertex(3)))))
        assert "age" == property.key
        assert 32.2 == property.value
コード例 #20
0
    def test_group_returnvertex_groupby_id(self):
        vertex = Vertex(id='1')

        gn = GremlinNetwork(group_by_property="id")
        gn.add_vertex(vertex)
        node = gn.graph.nodes.get('1')
        self.assertEqual(node['group'], '1')

        gn = GremlinNetwork(group_by_property="T.id")
        gn.add_vertex(vertex)
        node = gn.graph.nodes.get('1')
        self.assertEqual(node['group'], '')
コード例 #21
0
ファイル: test_graphsonV3d0.py プロジェクト: zjxian/tinkerpop
 def test_graph(self):
     vertex = self.graphson_reader.readObject("""
     {"@type":"g:Vertex", "@value":{"id":{"@type":"g:Int32","@value":1},"label":"person","outE":{"created":[{"id":{"@type":"g:Int32","@value":9},"inV":{"@type":"g:Int32","@value":3},"properties":{"weight":{"@type":"g:Double","@value":0.4}}}],"knows":[{"id":{"@type":"g:Int32","@value":7},"inV":{"@type":"g:Int32","@value":2},"properties":{"weight":{"@type":"g:Double","@value":0.5}}},{"id":{"@type":"g:Int32","@value":8},"inV":{"@type":"g:Int32","@value":4},"properties":{"weight":{"@type":"g:Double","@value":1.0}}}]},"properties":{"name":[{"id":{"@type":"g:Int64","@value":0},"value":"marko"}],"age":[{"id":{"@type":"g:Int64","@value":1},"value":{"@type":"g:Int32","@value":29}}]}}}"""
                                              )
     assert isinstance(vertex, Vertex)
     assert "person" == vertex.label
     assert 1 == vertex.id
     assert isinstance(vertex.id, int)
     assert vertex == Vertex(1)
     ##
     vertex = self.graphson_reader.readObject("""
     {"@type":"g:Vertex", "@value":{"id":{"@type":"g:Float","@value":45.23}}}"""
                                              )
     assert isinstance(vertex, Vertex)
     assert 45.23 == vertex.id
     assert isinstance(vertex.id, FloatType)
     assert "vertex" == vertex.label
     assert vertex == Vertex(45.23)
     ##
     vertex_property = self.graphson_reader.readObject("""
     {"@type":"g:VertexProperty", "@value":{"id":"anId","label":"aKey","value":true,"vertex":{"@type":"g:Int32","@value":9}}}"""
                                                       )
     assert isinstance(vertex_property, VertexProperty)
     assert "anId" == vertex_property.id
     assert "aKey" == vertex_property.label
     assert vertex_property.value
     assert vertex_property.vertex == Vertex(9)
     ##
     vertex_property = self.graphson_reader.readObject("""
     {"@type":"g:VertexProperty", "@value":{"id":{"@type":"g:Int32","@value":1},"label":"name","value":"marko"}}"""
                                                       )
     assert isinstance(vertex_property, VertexProperty)
     assert 1 == vertex_property.id
     assert "name" == vertex_property.label
     assert "marko" == vertex_property.value
     assert vertex_property.vertex is None
     ##
     edge = self.graphson_reader.readObject("""
     {"@type":"g:Edge", "@value":{"id":{"@type":"g:Int64","@value":17},"label":"knows","inV":"x","outV":"y","inVLabel":"xLab","properties":{"aKey":"aValue","bKey":true}}}"""
                                            )
     # print edge
     assert isinstance(edge, Edge)
     assert 17 == edge.id
     assert "knows" == edge.label
     assert edge.inV == Vertex("x", "xLabel")
     assert edge.outV == Vertex("y", "vertex")
     ##
     property = self.graphson_reader.readObject("""
     {"@type":"g:Property", "@value":{"key":"aKey","value":{"@type":"g:Int64","@value":17},"element":{"@type":"g:Edge","@value":{"id":{"@type":"g:Int64","@value":122},"label":"knows","inV":"x","outV":"y","inVLabel":"xLab"}}}}"""
                                                )
     # print property
     assert isinstance(property, Property)
     assert "aKey" == property.key
     assert 17 == property.value
     assert Edge(122, Vertex("x"), "knows", Vertex("y")) == property.element
コード例 #22
0
    def test_graph(self):
        # TODO: this assert is not compatible with python 3 and now that we test with both 2 and 3 it fails
        assert {"@type": "g:Vertex", "@value": {"id": {"@type": "g:Int64", "@value": 12}, "label": "person"}} == json.loads(self.graphson_writer.writeObject(Vertex(long(12), "person")))

        assert {"@type": "g:Edge", "@value": {"id": {"@type": "g:Int32", "@value": 7},
                                              "outV": {"@type": "g:Int32", "@value": 0},
                                              "outVLabel": "person",
                                              "label": "knows",
                                              "inV": {"@type": "g:Int32", "@value": 1},
                                              "inVLabel": "dog"}} == json.loads(
            self.graphson_writer.writeObject(Edge(7, Vertex(0, "person"), "knows", Vertex(1, "dog"))))
        assert {"@type": "g:VertexProperty", "@value": {"id": "blah", "label": "keyA", "value": True,
                                                        "vertex": "stephen"}} == json.loads(
            self.graphson_writer.writeObject(VertexProperty("blah", "keyA", True, Vertex("stephen"))))

        assert {"@type": "g:Property",
                "@value": {"key": "name", "value": "marko", "element": {"@type": "g:VertexProperty",
                                                                        "@value": {
                                                                            "vertex": "vertexId",
                                                                            "id": {"@type": "g:Int32", "@value": 1234},
                                                                            "label": "aKey"}}}} == json.loads(
            self.graphson_writer.writeObject(
                Property("name", "marko", VertexProperty(1234, "aKey", 21345, Vertex("vertexId")))))
コード例 #23
0
ファイル: test_graphson.py プロジェクト: leoYY/tinkerpop
    def test_graph(self):
        assert {"@type": "g:Vertex",
                "@value": {"id": {"@type": "g:Int64", "@value": 12}, "label": "person"}} == json.loads(
            self.graphson_writer.writeObject(Vertex(12l, "person")))
        assert {"@type": "g:Edge", "@value": {"id": {"@type": "g:Int32", "@value": 7},
                                              "outV": {"@type": "g:Int32", "@value": 0},
                                              "outVLabel": "person",
                                              "label": "knows",
                                              "inV": {"@type": "g:Int32", "@value": 1},
                                              "inVLabel": "dog"}} == json.loads(
            self.graphson_writer.writeObject(Edge(7, Vertex(0, "person"), "knows", Vertex(1, "dog"))))
        assert {"@type": "g:VertexProperty", "@value": {"id": "blah", "label": "keyA", "value": True,
                                                        "vertex": "stephen"}} == json.loads(
            self.graphson_writer.writeObject(VertexProperty("blah", "keyA", True, Vertex("stephen"))))

        assert {"@type": "g:Property",
                "@value": {"key": "name", "value": "marko", "element": {"@type": "g:VertexProperty",
                                                                        "@value": {
                                                                            "vertex": "vertexId",
                                                                            "id": "anId",
                                                                            "label": "aKey"}}}} == json.loads(
            self.graphson_writer.writeObject(
                Property("name", "marko", VertexProperty("anId", "aKey", 21345, Vertex("vertexId")))))
コード例 #24
0
def __find_cached_element(ctx, graph_name, identifier, element_type):
    if graph_name == "empty":
        cache = world.create_lookup_v(
            ctx.remote_conn["empty"]
        ) if element_type == "v" else world.create_lookup_e(
            ctx.remote_conn["empty"])
    else:
        cache = ctx.lookup_v[
            graph_name] if element_type == "v" else ctx.lookup_e[graph_name]

    # try to lookup the element - if it can't be found then it must be a reference Vertex
    if identifier in cache:
        return cache[identifier]
    else:
        return Vertex(identifier)
コード例 #25
0
 def test_graph_objects(self):
     vertex = Vertex(1)
     assert "v[1]" == str(vertex)
     assert "vertex" == vertex.label
     assert "person" == Vertex(1, "person").label
     assert vertex == Vertex(1)
     #
     edge = Edge(2, Vertex(1), "said", Vertex("hello", "phrase"))
     assert "e[2][1-said->hello]" == str(edge)
     assert Vertex(1) == edge.outV
     assert Vertex("hello") == edge.inV
     assert "said" == edge.label
     assert "phrase" == edge.inV.label
     assert edge.inV != edge.outV
     #
     vertex_property = VertexProperty(long(24), "name", "marko")
     assert "vp[name->marko]" == str(vertex_property)
     assert "name" == vertex_property.label
     assert "name" == vertex_property.key
     assert "marko" == vertex_property.value
     assert long(24) == vertex_property.id
     assert isinstance(vertex_property.id, long)
     assert vertex_property == VertexProperty(long(24), "name", "marko")
     #
     property = Property("age", 29)
     assert "p[age->29]" == str(property)
     assert "age" == property.key
     assert 29 == property.value
     assert isinstance(property.value, int)
     assert property == Property("age", 29)
     if not six.PY3:
         assert property != Property("age", long(29))
     #
     for i in [vertex, edge, vertex_property, property]:
         for j in [vertex, edge, vertex_property, property]:
             if type(i) != type(j):
                 assert i != j
             else:
                 assert i == j
                 assert i.__hash__() == hash(i)
コード例 #26
0
 def objectify(cls, d, reader):
     vertex = Vertex(reader.toObject(
         d.get("vertex"))) if "vertex" in d else None
     return VertexProperty(reader.toObject(d["id"]), d["label"],
                           reader.toObject(d["value"]), vertex)
コード例 #27
0
 def objectify(cls, d, reader):
     return Edge(
         reader.toObject(d["id"]),
         Vertex(reader.toObject(d["outV"]), d.get("outVLabel", "vertex")),
         d.get("label", "edge"),
         Vertex(reader.toObject(d["inV"]), d.get("inVLabel", "vertex")))
コード例 #28
0
 def objectify(cls, d, reader):
     return Vertex(reader.toObject(d["id"]), d.get("label", "vertex"))
コード例 #29
0
 def test_vertex(self):
     x = Vertex(123, "person")
     output = self.graphbinary_reader.readObject(
         self.graphbinary_writer.writeObject(x))
     assert x == output
コード例 #30
0
    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
        # #
        # test binding in P
        results = g.V().has('person', 'age',
                            Bindings.of('x', lt(30))).count().next()
        assert 2 == results
        # #
        # test dict keys which can only work on GraphBinary and GraphSON3 which include specific serialization
        # types for dict
        if not isinstance(remote_connection._client._message_serializer,
                          GraphSONSerializersV2d0):
            results = g.V().has(
                'person', 'name',
                'marko').elementMap("name").groupCount().next()
            assert {
                HashableDict.of({
                    T.id: 1,
                    T.label: 'person',
                    'name': 'marko'
                }): 1
            } == results