You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tinkerpop.apache.org by ok...@apache.org on 2016/10/12 20:53:32 UTC
[05/10] tinkerpop git commit: gremlinpython: refactor GraphsonIO to
use instance type maps
gremlinpython: refactor GraphsonIO to use instance type maps
Project: http://git-wip-us.apache.org/repos/asf/tinkerpop/repo
Commit: http://git-wip-us.apache.org/repos/asf/tinkerpop/commit/d392379e
Tree: http://git-wip-us.apache.org/repos/asf/tinkerpop/tree/d392379e
Diff: http://git-wip-us.apache.org/repos/asf/tinkerpop/diff/d392379e
Branch: refs/heads/master
Commit: d392379e6fc2a7acfc6ed73a8f82ee04cbab2efd
Parents: 6c4bf0b
Author: Adam Holmberg <Ad...@datastax.com>
Authored: Tue Oct 4 13:56:21 2016 -0500
Committer: Adam Holmberg <Ad...@datastax.com>
Committed: Mon Oct 10 16:01:50 2016 -0500
----------------------------------------------------------------------
.../driver/driver_remote_connection.py | 13 +-
.../gremlin_python/structure/io/graphson.py | 372 ++++++++++---------
.../jython/tests/structure/io/test_graphson.py | 87 ++++-
.../python/jsr223/JythonScriptEngineSetup.java | 4 +-
.../jsr223/PythonGraphSONJavaTranslator.java | 2 +-
.../io/graphson/GraphSONReaderTest.java | 68 ++--
.../io/graphson/GraphSONWriterTest.java | 56 +--
7 files changed, 344 insertions(+), 258 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/tinkerpop/blob/d392379e/gremlin-python/src/main/jython/gremlin_python/driver/driver_remote_connection.py
----------------------------------------------------------------------
diff --git a/gremlin-python/src/main/jython/gremlin_python/driver/driver_remote_connection.py b/gremlin-python/src/main/jython/gremlin_python/driver/driver_remote_connection.py
index e47c8e6..b8b3d87 100644
--- a/gremlin-python/src/main/jython/gremlin_python/driver/driver_remote_connection.py
+++ b/gremlin-python/src/main/jython/gremlin_python/driver/driver_remote_connection.py
@@ -23,8 +23,7 @@ from tornado import gen
from tornado import ioloop
from tornado import websocket
-from gremlin_python.structure.io.graphson import GraphSONReader
-from gremlin_python.structure.io.graphson import GraphSONWriter
+from gremlin_python.structure.io.graphson import GraphSONIO
from .remote_connection import RemoteConnection
from .remote_connection import RemoteTraversal
from .remote_connection import RemoteTraversalSideEffects
@@ -42,6 +41,7 @@ class DriverRemoteConnection(RemoteConnection):
self._password = password
if loop is None: self._loop = ioloop.IOLoop.current()
self._websocket = self._loop.run_sync(lambda: websocket.websocket_connect(self.url))
+ self._graphson_io = GraphSONIO()
def submit(self, bytecode):
'''
@@ -65,7 +65,7 @@ class DriverRemoteConnection(RemoteConnection):
"op": "bytecode",
"processor": "traversal",
"args": {
- "gremlin": GraphSONWriter.writeObject(bytecode),
+ "gremlin": self._graphson_io.writeObject(bytecode),
"aliases": {"g": self.traversal_source}
}
}
@@ -142,7 +142,7 @@ class DriverRemoteConnection(RemoteConnection):
if self._websocket.protocol is None:
self._websocket = yield websocket.websocket_connect(self.url)
self._websocket.write_message(send_message, binary=True)
- response = Response(self._websocket, self._username, self._password)
+ response = Response(self._websocket, self._username, self._password, self._graphson_io)
results = None
while True:
recv_message = yield response.receive()
@@ -183,11 +183,12 @@ class DriverRemoteConnection(RemoteConnection):
class Response:
- def __init__(self, websocket, username, password):
+ def __init__(self, websocket, username, password, graphson_io):
self._websocket = websocket
self._username = username
self._password = password
self._closed = False
+ self._graphson_io = graphson_io
@gen.coroutine
def receive(self):
@@ -224,7 +225,7 @@ class Response:
elif status_code in [200, 206]:
results = []
for item in recv_message["result"]["data"]:
- results.append(GraphSONReader._objectify(item))
+ results.append(self._graphson_io.toObject(item))
if status_code == 200:
self._closed = True
raise gen.Return((aggregateTo, results))
http://git-wip-us.apache.org/repos/asf/tinkerpop/blob/d392379e/gremlin-python/src/main/jython/gremlin_python/structure/io/graphson.py
----------------------------------------------------------------------
diff --git a/gremlin-python/src/main/jython/gremlin_python/structure/io/graphson.py b/gremlin-python/src/main/jython/gremlin_python/structure/io/graphson.py
index b44897a..50db7cb 100644
--- a/gremlin-python/src/main/jython/gremlin_python/structure/io/graphson.py
+++ b/gremlin-python/src/main/jython/gremlin_python/structure/io/graphson.py
@@ -17,14 +17,12 @@ specific language governing permissions and limitations
under the License.
'''
import json
-from abc import abstractmethod
from aenum import Enum
import six
from gremlin_python import statics
-from gremlin_python.statics import (
- FloatType, FunctionType, IntType, LongType, long, TypeType)
+from gremlin_python.statics import FloatType, FunctionType, IntType, LongType, TypeType
from gremlin_python.process.traversal import Binding
from gremlin_python.process.traversal import Bytecode
from gremlin_python.process.traversal import P
@@ -38,113 +36,194 @@ from gremlin_python.structure.graph import VertexProperty
from gremlin_python.structure.graph import Path
-__author__ = 'Marko A. Rodriguez (http://markorodriguez.com)'
+_serializers = {}
+_deserializers = {}
-class GraphSONWriter(object):
- @staticmethod
- def _dictify(obj):
- for key, serializer in serializers.items():
+class GraphSONTypeType(type):
+ def __new__(mcs, name, bases, dct):
+ cls = super(GraphSONTypeType, mcs).__new__(mcs, name, bases, dct)
+ if not name.startswith('_'):
+ if cls.python_type:
+ _serializers[cls.python_type] = cls
+ if cls.graphson_type:
+ _deserializers[cls.graphson_type] = cls
+ return cls
+
+
+class GraphSONIO(object):
+
+ _TYPE_KEY = "@type"
+ _VALUE_KEY = "@value"
+
+ def __init__(self, serializer_map=None, deserializer_map=None):
+ """
+ :param serializer_map: map from Python type to serializer instance implementing `dictify`
+ :param deserializer_map: map from GraphSON type tag to deserializer instance implementing `objectify`
+ """
+ self.serializers = _serializers.copy()
+ if serializer_map:
+ self.serializers.update(serializer_map)
+
+ self.deserializers = _deserializers.copy()
+ if deserializer_map:
+ self.deserializers.update(deserializer_map)
+
+ def writeObject(self, objectData):
+ # to JSON
+ return json.dumps(self.toDict(objectData), separators=(',', ':'))
+
+ def readObject(self, jsonData):
+ # from JSON
+ return self.toObject(json.loads(jsonData))
+
+ def toDict(self, obj):
+ """
+ Encodes python objects in GraphSON type-tagged dict values
+ """
+ for key, serializer in self.serializers.items():
if isinstance(obj, key):
- return serializer._dictify(obj)
+ return serializer.dictify(obj, self)
# list and map are treated as normal json objs (could be isolated serializers)
if isinstance(obj, (list, set)):
- return [GraphSONWriter._dictify(o) for o in obj]
+ return [self.toDict(o) for o in obj]
elif isinstance(obj, dict):
- return dict((GraphSONWriter._dictify(k), GraphSONWriter._dictify(v)) for k, v in obj.items())
+ return dict((self.toDict(k), self.toDict(v)) for k, v in obj.items())
else:
return obj
- @staticmethod
- def writeObject(objectData):
- return json.dumps(GraphSONWriter._dictify(objectData), separators=(',', ':'))
-
-
-class GraphSONReader(object):
- @staticmethod
- def _objectify(obj):
+ def toObject(self, obj):
+ """
+ Unpacks GraphSON type-tagged dict values into objects mapped in self.deserializers
+ """
if isinstance(obj, dict):
try:
- return deserializers[obj[_SymbolHelper._TYPE]]._objectify(obj)
+ return self.deserializers[obj[self._TYPE_KEY]].objectify(obj[self._VALUE_KEY], self)
except KeyError:
pass
# list and map are treated as normal json objs (could be isolated deserializers)
- return dict((GraphSONReader._objectify(k), GraphSONReader._objectify(v)) for k, v in obj.items())
+ return dict((self.toObject(k), self.toObject(v)) for k, v in obj.items())
elif isinstance(obj, list):
- return [GraphSONReader._objectify(o) for o in obj]
+ return [self.toObject(o) for o in obj]
else:
return obj
- @staticmethod
- def readObject(jsonData):
- return GraphSONReader._objectify(json.loads(jsonData))
+ def typedValue(self, type_name, value, prefix="g"):
+ out = {self._TYPE_KEY: prefix + ":" + type_name}
+ if value is not None:
+ out[self._VALUE_KEY] = value
+ return out
+
+@six.add_metaclass(GraphSONTypeType)
+class _GraphSONTypeIO(object):
+ python_type = None
+ graphson_type = None
-'''
-SERIALIZERS
-'''
+ symbolMap = {"global_": "global", "as_": "as", "in_": "in", "and_": "and",
+ "or_": "or", "is_": "is", "not_": "not", "from_": "from",
+ "set_": "set", "list_": "list", "all_": "all"}
+
+ @classmethod
+ def unmangleKeyword(cls, symbol):
+ return cls.symbolMap.get(symbol, symbol)
+
+ def dictify(self, obj, graphson_io):
+ raise NotImplementedError()
+ def objectify(self, d, graphson_io):
+ raise NotImplementedError()
-class GraphSONSerializer(object):
- @abstractmethod
- def _dictify(self, obj):
- return obj
+class _BytecodeSerializer(_GraphSONTypeIO):
-class BytecodeSerializer(GraphSONSerializer):
- def _dictify_instructions(self, instructions):
+ @classmethod
+ def _dictify_instructions(cls, instructions, graphson_io):
out = []
for instruction in instructions:
inst = [instruction[0]]
- inst.extend(GraphSONWriter._dictify(arg) for arg in instruction[1:])
+ inst.extend(graphson_io.toDict(arg) for arg in instruction[1:])
out.append(inst)
return out
- def _dictify(self, bytecode):
+ @classmethod
+ def dictify(cls, bytecode, graphson_io):
if isinstance(bytecode, Traversal):
bytecode = bytecode.bytecode
out = {}
if bytecode.source_instructions:
- out["source"] = self._dictify_instructions(bytecode.source_instructions)
+ out["source"] = cls._dictify_instructions(bytecode.source_instructions, graphson_io)
if bytecode.step_instructions:
- out["step"] = self._dictify_instructions(bytecode.step_instructions)
- return _SymbolHelper.objectify("Bytecode", out)
+ out["step"] = cls._dictify_instructions(bytecode.step_instructions, graphson_io)
+ return graphson_io.typedValue("Bytecode", out)
+
+
+class TraversalSerializer(_BytecodeSerializer):
+ python_type = Traversal
-class TraversalStrategySerializer(GraphSONSerializer):
- def _dictify(self, strategy):
- return _SymbolHelper.objectify(strategy.strategy_name, GraphSONWriter._dictify(strategy.configuration))
+class BytecodeSerializer(_BytecodeSerializer):
+ python_type = Bytecode
-class TraverserSerializer(GraphSONSerializer):
- def _dictify(self, traverser):
- return _SymbolHelper.objectify("Traverser", {"value": GraphSONWriter._dictify(traverser.object),
- "bulk": GraphSONWriter._dictify(traverser.bulk)})
+class TraversalStrategySerializer(_GraphSONTypeIO):
+ python_type = TraversalStrategy
+ @classmethod
+ def dictify(cls, strategy, graphson_io):
+ return graphson_io.typedValue(strategy.strategy_name, graphson_io.toDict(strategy.configuration))
-class EnumSerializer(GraphSONSerializer):
- def _dictify(self, enum):
- return _SymbolHelper.objectify(_SymbolHelper.toGremlin(type(enum).__name__),
- _SymbolHelper.toGremlin(str(enum.name)))
+class TraverserIO(_GraphSONTypeIO):
+ python_type = Traverser
+ graphson_type = "g:Traverser"
-class PSerializer(GraphSONSerializer):
- def _dictify(self, p):
+ @classmethod
+ def dictify(cls, traverser, graphson_io):
+ return graphson_io.typedValue("Traverser", {"value": graphson_io.toDict(traverser.object),
+ "bulk": graphson_io.toDict(traverser.bulk)})
+
+ @classmethod
+ def objectify(cls, d, graphson_io):
+ return Traverser(graphson_io.toObject(d["value"]),
+ graphson_io.toObject(d["bulk"]))
+
+
+class EnumSerializer(_GraphSONTypeIO):
+ python_type = Enum
+
+ @classmethod
+ def dictify(cls, enum, graphson_io):
+ return graphson_io.typedValue(cls.unmangleKeyword(type(enum).__name__),
+ cls.unmangleKeyword(str(enum.name)))
+
+
+class PSerializer(_GraphSONTypeIO):
+ python_type = P
+
+ @classmethod
+ def dictify(cls, p, graphson_io):
out = {"predicate": p.operator,
- "value": [GraphSONWriter._dictify(p.value), GraphSONWriter._dictify(p.other)] if p.other is not None else
- GraphSONWriter._dictify(p.value)}
- return _SymbolHelper.objectify("P", out)
+ "value": [graphson_io.toDict(p.value), graphson_io.toDict(p.other)] if p.other is not None else
+ graphson_io.toDict(p.value)}
+ return graphson_io.typedValue("P", out)
+
+class BindingSerializer(_GraphSONTypeIO):
+ python_type = Binding
-class BindingSerializer(GraphSONSerializer):
- def _dictify(self, binding):
+ @classmethod
+ def dictify(cls, binding, graphson_io):
out = {"key": binding.key,
- "value": GraphSONWriter._dictify(binding.value)}
- return _SymbolHelper.objectify("Binding", out)
+ "value": graphson_io.toDict(binding.value)}
+ return graphson_io.typedValue("Binding", out)
+
+class LambdaSerializer(_GraphSONTypeIO):
+ python_type = FunctionType
-class LambdaSerializer(GraphSONSerializer):
- def _dictify(self, lambda_object):
+ @classmethod
+ def dictify(cls, lambda_object, graphson_io):
lambda_result = lambda_object()
script = lambda_result if isinstance(lambda_result, str) else lambda_result[0]
language = statics.default_lambda_language if isinstance(lambda_result, str) else lambda_result[1]
@@ -157,137 +236,94 @@ class LambdaSerializer(GraphSONSerializer):
out["arguments"] = six.get_function_code(eval(out["script"])).co_argcount
else:
out["arguments"] = -1
- return _SymbolHelper.objectify("Lambda", out)
+ return graphson_io.typedValue("Lambda", out)
-class TypeSerializer(GraphSONSerializer):
- def _dictify(self, clazz):
- return GraphSONWriter._dictify(clazz())
+class TypeSerializer(_GraphSONTypeIO):
+ python_type = TypeType
+ @classmethod
+ def dictify(cls, typ, graphson_io):
+ return graphson_io.toDict(typ())
-class NumberSerializer(GraphSONSerializer):
- def _dictify(self, number):
- if isinstance(number, bool): # python thinks that 0/1 integers are booleans
- return number
- elif isinstance(number, long) or (
- abs(number) > 2147483647): # in python all numbers are int unless specified otherwise
- return _SymbolHelper.objectify("Int64", number)
- elif isinstance(number, int):
- return _SymbolHelper.objectify("Int32", number)
- elif isinstance(number, float):
- return _SymbolHelper.objectify("Float", number)
- else:
- return number
+class _NumberIO(_GraphSONTypeIO):
-'''
-DESERIALIZERS
-'''
+ @classmethod
+ def dictify(cls, n, graphson_io):
+ if isinstance(n, bool): # because isinstance(False, int) and isinstance(True, int)
+ return n
+ return graphson_io.typedValue(cls.graphson_base_type, n)
+ @classmethod
+ def objectify(cls, v, _):
+ return cls.python_type(v)
-class GraphSONDeserializer(object):
- @abstractmethod
- def _objectify(self, d):
- return d
+class FloatIO(_NumberIO):
+ python_type = FloatType
+ graphson_type = "g:Float"
+ graphson_base_type = "Float"
-class TraverserDeserializer(GraphSONDeserializer):
- def _objectify(self, d):
- return Traverser(GraphSONReader._objectify(d[_SymbolHelper._VALUE]["value"]),
- GraphSONReader._objectify(d[_SymbolHelper._VALUE]["bulk"]))
+class DoubleIO(FloatIO):
+ graphson_type = "g:Double"
+ graphson_base_type = "Double"
-class NumberDeserializer(GraphSONDeserializer):
- def _objectify(self, d):
- type = d[_SymbolHelper._TYPE]
- value = d[_SymbolHelper._VALUE]
- if type == "g:Int32":
- return int(value)
- elif type == "g:Int64":
- return long(value)
- else:
- return float(value)
+class Int64IO(_NumberIO):
+ python_type = LongType
+ graphson_type = "g:Int64"
+ graphson_base_type = "Int64"
-class VertexDeserializer(GraphSONDeserializer):
- def _objectify(self, d):
- value = d[_SymbolHelper._VALUE]
- return Vertex(GraphSONReader._objectify(value["id"]), value.get("label", ""))
+class Int32IO(_NumberIO):
+ python_type = IntType
+ graphson_type = "g:Int32"
+ graphson_base_type = "Int32"
-class EdgeDeserializer(GraphSONDeserializer):
- def _objectify(self, d):
- value = d[_SymbolHelper._VALUE]
- return Edge(GraphSONReader._objectify(value["id"]),
- Vertex(GraphSONReader._objectify(value["outV"]), ""),
- value.get("label", "vertex"),
- Vertex(GraphSONReader._objectify(value["inV"]), ""))
+class VertexDeserializer(_GraphSONTypeIO):
+ graphson_type = "g:Vertex"
-class VertexPropertyDeserializer(GraphSONDeserializer):
- def _objectify(self, d):
- value = d[_SymbolHelper._VALUE]
- return VertexProperty(GraphSONReader._objectify(value["id"]), value["label"],
- GraphSONReader._objectify(value["value"]))
+ @classmethod
+ def objectify(cls, d, graphson_io):
+ return Vertex(graphson_io.toObject(d["id"]), d.get("label", ""))
-class PropertyDeserializer(GraphSONDeserializer):
- def _objectify(self, d):
- value = d[_SymbolHelper._VALUE]
- return Property(value["key"], GraphSONReader._objectify(value["value"]))
+class EdgeDeserializer(_GraphSONTypeIO):
+ graphson_type = "g:Edge"
+ @classmethod
+ def objectify(cls, d, graphson_io):
+ return Edge(graphson_io.toObject(d["id"]),
+ Vertex(graphson_io.toObject(d["outV"]), ""),
+ d.get("label", "vertex"),
+ Vertex(graphson_io.toObject(d["inV"]), ""))
-class PathDeserializer(GraphSONDeserializer):
- def _objectify(self, d):
- value = d[_SymbolHelper._VALUE]
- labels = [set(label) for label in value["labels"]]
- objects = [GraphSONReader._objectify(o) for o in value["objects"]]
- return Path(labels, objects)
+class VertexPropertyDeserializer(_GraphSONTypeIO):
+ graphson_type = "g:VertexProperty"
-class _SymbolHelper(object):
- symbolMap = {"global_": "global", "as_": "as", "in_": "in", "and_": "and",
- "or_": "or", "is_": "is", "not_": "not", "from_": "from",
- "set_": "set", "list_": "list", "all_": "all"}
+ @classmethod
+ def objectify(cls, d, graphson_io):
+ return VertexProperty(graphson_io.toObject(d["id"]), d["label"],
+ graphson_io.toObject(d["value"]))
- _TYPE = "@type"
- _VALUE = "@value"
- @staticmethod
- def toGremlin(symbol):
- return _SymbolHelper.symbolMap.get(symbol, symbol)
+class PropertyDeserializer(_GraphSONTypeIO):
+ graphson_type = "g:Property"
- @staticmethod
- def objectify(type, value=None, prefix="g"):
- object = {_SymbolHelper._TYPE: prefix + ":" + type}
- if value is not None:
- object[_SymbolHelper._VALUE] = value
- return object
-
-serializers = {
- Traversal: BytecodeSerializer(),
- Traverser: TraverserSerializer(),
- Bytecode: BytecodeSerializer(),
- Binding: BindingSerializer(),
- P: PSerializer(),
- Enum: EnumSerializer(),
- FunctionType: LambdaSerializer(),
- LongType: NumberSerializer(),
- IntType: NumberSerializer(),
- FloatType: NumberSerializer(),
- TypeType: TypeSerializer(),
- TraversalStrategy: TraversalStrategySerializer(),
-}
-
-deserializers = {
- "g:Traverser": TraverserDeserializer(),
- "g:Int32": NumberDeserializer(),
- "g:Int64": NumberDeserializer(),
- "g:Float": NumberDeserializer(),
- "g:Double": NumberDeserializer(),
- "g:Vertex": VertexDeserializer(),
- "g:Edge": EdgeDeserializer(),
- "g:VertexProperty": VertexPropertyDeserializer(),
- "g:Property": PropertyDeserializer(),
- "g:Path": PathDeserializer()
-}
+ @classmethod
+ def objectify(cls, d, graphson_io):
+ return Property(d["key"], graphson_io.toObject(d["value"]))
+
+
+class PathDeserializer(_GraphSONTypeIO):
+ graphson_type = "g:Path"
+
+ @classmethod
+ def objectify(cls, d, graphson_io):
+ labels = [set(label) for label in d["labels"]]
+ objects = [graphson_io.toObject(o) for o in d["objects"]]
+ return Path(labels, objects)
http://git-wip-us.apache.org/repos/asf/tinkerpop/blob/d392379e/gremlin-python/src/main/jython/tests/structure/io/test_graphson.py
----------------------------------------------------------------------
diff --git a/gremlin-python/src/main/jython/tests/structure/io/test_graphson.py b/gremlin-python/src/main/jython/tests/structure/io/test_graphson.py
index 313f406..90866aa 100644
--- a/gremlin-python/src/main/jython/tests/structure/io/test_graphson.py
+++ b/gremlin-python/src/main/jython/tests/structure/io/test_graphson.py
@@ -20,6 +20,7 @@ under the License.
__author__ = 'Marko A. Rodriguez (http://markorodriguez.com)'
import json
+from mock import Mock
import unittest
from unittest import TestCase
@@ -28,37 +29,39 @@ import six
from gremlin_python.statics import *
from gremlin_python.structure.graph import Vertex
from gremlin_python.structure.graph import Path
-from gremlin_python.structure.io.graphson import GraphSONReader
-from gremlin_python.structure.io.graphson import GraphSONWriter
+from gremlin_python.structure.io.graphson import GraphSONIO
+import gremlin_python.structure.io.graphson
from gremlin_python.process.traversal import P
from gremlin_python.process.strategies import SubgraphStrategy
from gremlin_python.process.graph_traversal import __
+graphson_io = GraphSONIO()
-class TestGraphSONReader(TestCase):
- def test_numbers(self):
- x = GraphSONReader.readObject(json.dumps({
+
+class TestGraphSONIO(TestCase):
+ def test_number_input(self):
+ x = graphson_io.readObject(json.dumps({
"@type": "g:Int32",
"@value": 31
}))
assert isinstance(x, int)
assert 31 == x
##
- x = GraphSONReader.readObject(json.dumps({
+ x = graphson_io.readObject(json.dumps({
"@type": "g:Int64",
"@value": 31
}))
assert isinstance(x, long)
assert long(31) == x
##
- x = GraphSONReader.readObject(json.dumps({
+ x = graphson_io.readObject(json.dumps({
"@type": "g:Float",
"@value": 31.3
}))
assert isinstance(x, float)
assert 31.3 == x
##
- x = GraphSONReader.readObject(json.dumps({
+ x = graphson_io.readObject(json.dumps({
"@type": "g:Double",
"@value": 31.2
}))
@@ -66,7 +69,7 @@ class TestGraphSONReader(TestCase):
assert 31.2 == x
def test_graph(self):
- vertex = GraphSONReader.readObject(
+ vertex = graphson_io.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
@@ -75,7 +78,7 @@ class TestGraphSONReader(TestCase):
assert vertex == Vertex(1)
def test_path(self):
- path = GraphSONReader.readObject(
+ path = graphson_io.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)
@@ -88,25 +91,71 @@ class TestGraphSONReader(TestCase):
assert "lop" == path[2]
assert 3 == len(path)
+ def test_number_output(self):
+ assert {"@type":"g:Int64","@value":2} == json.loads(graphson_io.writeObject(long(2)))
+ assert {"@type":"g:Int32","@value":1} == json.loads(graphson_io.writeObject(1))
+ assert {"@type":"g:Double","@value":3.2} == json.loads(graphson_io.writeObject(3.2))
+ assert """true""" == graphson_io.writeObject(True)
-class TestGraphSONWriter(TestCase):
def test_numbers(self):
- assert {"@type": "g:Int64", "@value": 2} == json.loads(GraphSONWriter.writeObject(long(2)))
- assert {"@type": "g:Int32", "@value": 1} == json.loads(GraphSONWriter.writeObject(1))
- assert {"@type": "g:Float", "@value": 3.2} == json.loads(GraphSONWriter.writeObject(3.2))
- assert """true""" == GraphSONWriter.writeObject(True)
+ assert {"@type": "g:Int64", "@value": 2} == json.loads(graphson_io.writeObject(long(2)))
+ assert {"@type": "g:Int32", "@value": 1} == json.loads(graphson_io.writeObject(1))
+ assert {"@type": "g:Double", "@value": 3.2} == json.loads(graphson_io.writeObject(3.2))
+ assert """true""" == graphson_io.writeObject(True)
def test_P(self):
- assert """{"@type":"g:P","@value":{"predicate":"and","value":[{"@type":"g:P","@value":{"predicate":"or","value":[{"@type":"g:P","@value":{"predicate":"lt","value":"b"}},{"@type":"g:P","@value":{"predicate":"gt","value":"c"}}]}},{"@type":"g:P","@value":{"predicate":"neq","value":"d"}}]}}""" == GraphSONWriter.writeObject(
+ assert """{"@type":"g:P","@value":{"predicate":"and","value":[{"@type":"g:P","@value":{"predicate":"or","value":[{"@type":"g:P","@value":{"predicate":"lt","value":"b"}},{"@type":"g:P","@value":{"predicate":"gt","value":"c"}}]}},{"@type":"g:P","@value":{"predicate":"neq","value":"d"}}]}}""" == graphson_io.writeObject(
P.lt("b").or_(P.gt("c")).and_(P.neq("d")))
def test_strategies(self):
# we have a proxy model for now given that we don't want to have to have g:XXX all registered on the Gremlin traversal machine (yet)
- assert {"@type": "g:SubgraphStrategy", "@value": {}} == json.loads(GraphSONWriter.writeObject(SubgraphStrategy))
+ assert {"@type": "g:SubgraphStrategy", "@value": {}} == json.loads(graphson_io.writeObject(SubgraphStrategy))
assert {"@type": "g:SubgraphStrategy", "@value": {
"vertices": {"@type": "g:Bytecode", "@value": {"step": [["has", "name", "marko"]]}}}} == json.loads(
- GraphSONWriter.writeObject(SubgraphStrategy(vertices=__.has("name", "marko"))))
-
+ graphson_io.writeObject(SubgraphStrategy(vertices=__.has("name", "marko"))))
+
+ def test_custom_mapping(self):
+
+ # extended mapping
+ class X(object):
+ pass
+
+ type_string = "test:Xtype"
+ override_string = "g:Int64"
+ serdes = Mock()
+
+ gio = GraphSONIO(serializer_map={X: serdes}, deserializer_map={type_string: serdes, })
+ self.assertIn(X, gio.serializers)
+ self.assertIn(type_string, gio.deserializers)
+
+ # base dicts are not modified
+ self.assertNotIn(X, gremlin_python.structure.io.graphson._serializers)
+ self.assertNotIn(type_string, gremlin_python.structure.io.graphson._deserializers)
+
+ obj = X()
+ d = gio.toDict(obj)
+ serdes.dictify.assert_called_once_with(obj, gio)
+ self.assertIs(d, serdes.dictify())
+
+ o = gio.toObject({GraphSONIO._TYPE_KEY: type_string, GraphSONIO._VALUE_KEY: obj})
+ serdes.objectify.assert_called_once_with(obj, gio)
+ self.assertIs(o, serdes.objectify())
+
+ # overridden mapping
+ type_string = "g:Int64"
+ serdes = Mock()
+ gio = GraphSONIO(serializer_map={int: serdes}, deserializer_map={type_string: serdes, override_string: serdes})
+ self.assertIsNot(gremlin_python.structure.io.graphson._serializers[int], gio.serializers[int])
+ self.assertIsNot(gremlin_python.structure.io.graphson._deserializers[type_string], gio.deserializers[type_string])
+
+ value = 3
+ d = gio.toDict(value)
+ serdes.dictify.assert_called_once_with(value, gio)
+ self.assertIs(d, serdes.dictify())
+
+ o = gio.toObject({GraphSONIO._TYPE_KEY: type_string, GraphSONIO._VALUE_KEY: value})
+ serdes.objectify.assert_called_once_with(value, gio)
+ self.assertIs(o, serdes.objectify())
if __name__ == '__main__':
unittest.main()
http://git-wip-us.apache.org/repos/asf/tinkerpop/blob/d392379e/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/jsr223/JythonScriptEngineSetup.java
----------------------------------------------------------------------
diff --git a/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/jsr223/JythonScriptEngineSetup.java b/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/jsr223/JythonScriptEngineSetup.java
index e71d3e6..d5305dc 100644
--- a/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/jsr223/JythonScriptEngineSetup.java
+++ b/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/jsr223/JythonScriptEngineSetup.java
@@ -49,8 +49,8 @@ public class JythonScriptEngineSetup {
jythonEngine.eval("from gremlin_python.structure.graph import Edge");
jythonEngine.eval("from gremlin_python.structure.graph import VertexProperty");
jythonEngine.eval("from gremlin_python.structure.graph import Property");
- jythonEngine.eval("from gremlin_python.structure.io.graphson import GraphSONWriter");
- jythonEngine.eval("from gremlin_python.structure.io.graphson import GraphSONReader");
+ jythonEngine.eval("from gremlin_python.structure.io.graphson import GraphSONIO");
+ jythonEngine.eval("graphson_io = GraphSONIO()");
return jythonEngine;
} catch (final ScriptException e) {
throw new IllegalStateException(e.getMessage(), e);
http://git-wip-us.apache.org/repos/asf/tinkerpop/blob/d392379e/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/jsr223/PythonGraphSONJavaTranslator.java
----------------------------------------------------------------------
diff --git a/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/jsr223/PythonGraphSONJavaTranslator.java b/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/jsr223/PythonGraphSONJavaTranslator.java
index 8bb5330..e57afd2 100644
--- a/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/jsr223/PythonGraphSONJavaTranslator.java
+++ b/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/jsr223/PythonGraphSONJavaTranslator.java
@@ -69,7 +69,7 @@ final class PythonGraphSONJavaTranslator<S extends TraversalSource, T extends Tr
bindings.putAll(jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE));
bindings.put(this.pythonTranslator.getTraversalSource(), jythonEngine.eval("Graph().traversal()"));
bindings.putAll(bytecode.getBindings());
- final String graphsonBytecode = jythonEngine.eval("GraphSONWriter.writeObject(" + this.pythonTranslator.translate(bytecode) + ")", bindings).toString();
+ final String graphsonBytecode = jythonEngine.eval("graphson_io.writeObject(" + this.pythonTranslator.translate(bytecode) + ")", bindings).toString();
// System.out.println(graphsonBytecode);
return this.javaTranslator.translate(this.reader.readObject(new ByteArrayInputStream(graphsonBytecode.getBytes()), Bytecode.class));
} catch (final Exception e) {
http://git-wip-us.apache.org/repos/asf/tinkerpop/blob/d392379e/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/structure/io/graphson/GraphSONReaderTest.java
----------------------------------------------------------------------
diff --git a/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/structure/io/graphson/GraphSONReaderTest.java b/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/structure/io/graphson/GraphSONReaderTest.java
index 171fd04..7bbf364 100644
--- a/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/structure/io/graphson/GraphSONReaderTest.java
+++ b/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/structure/io/graphson/GraphSONReaderTest.java
@@ -60,49 +60,49 @@ public class GraphSONReaderTest {
public void shouldDeserializeGraphObjects() throws Exception {
final Vertex vertex = g.V(1).next();
jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE).put("x", mapper.writeValueAsString(vertex));
- assertEquals(vertex.toString(), jythonEngine.eval("str(GraphSONReader.readObject(x))"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x),Vertex)"));
+ assertEquals(vertex.toString(), jythonEngine.eval("str(graphson_io.readObject(x))"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x),Vertex)"));
//
final Edge edge = g.V(1).outE("created").next();
jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE).put("x", mapper.writeValueAsString(edge));
- assertEquals(edge.toString(), jythonEngine.eval("str(GraphSONReader.readObject(x))"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x),Edge)"));
+ assertEquals(edge.toString(), jythonEngine.eval("str(graphson_io.readObject(x))"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x),Edge)"));
//
final VertexProperty vertexProperty = (VertexProperty) g.V(1).properties("name").next();
jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE).put("x", mapper.writeValueAsString(vertexProperty));
- assertEquals(vertexProperty.toString(), jythonEngine.eval("str(GraphSONReader.readObject(x))"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x),VertexProperty)"));
+ assertEquals(vertexProperty.toString(), jythonEngine.eval("str(graphson_io.readObject(x))"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x),VertexProperty)"));
//
final Property property = g.V(1).outE("created").properties("weight").next();
jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE).put("x", mapper.writeValueAsString(property));
- assertEquals(property.toString(), jythonEngine.eval("str(GraphSONReader.readObject(x))"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x),Property)"));
+ assertEquals(property.toString(), jythonEngine.eval("str(graphson_io.readObject(x))"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x),Property)"));
//
final Traverser<Vertex> traverser = new DefaultRemoteTraverser<>(vertex, 3L);
jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE).put("x", mapper.writeValueAsString(traverser));
- assertEquals(traverser.toString(), jythonEngine.eval("str(GraphSONReader.readObject(x))"));
- assertEquals(BigInteger.valueOf(3L), jythonEngine.eval("GraphSONReader.readObject(x).bulk")); // jython uses big integer in Java
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x).object,Vertex)"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x),Traverser)"));
+ assertEquals(traverser.toString(), jythonEngine.eval("str(graphson_io.readObject(x))"));
+ assertEquals(BigInteger.valueOf(3L), jythonEngine.eval("graphson_io.readObject(x).bulk")); // jython uses big integer in Java
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x).object,Vertex)"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x),Traverser)"));
}
@Test
public void shouldDeserializeNumbers() throws Exception {
jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE).put("x", mapper.writeValueAsString(1));
- assertEquals("1", jythonEngine.eval("str(GraphSONReader.readObject(x))"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x),int)"));
+ assertEquals("1", jythonEngine.eval("str(graphson_io.readObject(x))"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x),int)"));
//
jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE).put("x", mapper.writeValueAsString(1L));
- assertEquals("1", jythonEngine.eval("str(GraphSONReader.readObject(x))"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x),long)"));
+ assertEquals("1", jythonEngine.eval("str(graphson_io.readObject(x))"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x),long)"));
//
jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE).put("x", mapper.writeValueAsString(1.2f));
- assertEquals("1.2", jythonEngine.eval("str(GraphSONReader.readObject(x))"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x),float)"));
+ assertEquals("1.2", jythonEngine.eval("str(graphson_io.readObject(x))"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x),float)"));
//
jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE).put("x", mapper.writeValueAsString(1.3d));
- assertEquals("1.3", jythonEngine.eval("str(GraphSONReader.readObject(x))"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x),float)"));
+ assertEquals("1.3", jythonEngine.eval("str(graphson_io.readObject(x))"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x),float)"));
}
@Test
@@ -111,23 +111,23 @@ public class GraphSONReaderTest {
map.put("a", 2);
map.put("b", 2.3d);
jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE).put("x", mapper.writeValueAsString(map));
- assertEquals("{u'a': 2, u'b': 2.3}", jythonEngine.eval("str(GraphSONReader.readObject(x))"));
- assertEquals(2, jythonEngine.eval("GraphSONReader.readObject(x)['a']"));
- assertEquals(2.3d, jythonEngine.eval("GraphSONReader.readObject(x)['b']")); // jython is smart about double
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x)['a'],int)"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x)['b'],float)"));
+ assertEquals("{u'a': 2, u'b': 2.3}", jythonEngine.eval("str(graphson_io.readObject(x))"));
+ assertEquals(2, jythonEngine.eval("graphson_io.readObject(x)['a']"));
+ assertEquals(2.3d, jythonEngine.eval("graphson_io.readObject(x)['b']")); // jython is smart about double
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x)['a'],int)"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x)['b'],float)"));
//
final List<Object> list = Arrays.asList(g.V(1).next(), "hello", map, true);
jythonEngine.getBindings(ScriptContext.ENGINE_SCOPE).put("x", mapper.writeValueAsString(list));
- assertEquals("[v[1], u'hello', {u'a': 2, u'b': 2.3}, True]", jythonEngine.eval("str(GraphSONReader.readObject(x))"));
- assertEquals(g.V(1).next().toString(), jythonEngine.eval("str(GraphSONReader.readObject(x)[0])"));
- assertEquals("hello", jythonEngine.eval("GraphSONReader.readObject(x)[1]"));
- assertEquals("{u'a': 2, u'b': 2.3}", jythonEngine.eval("str(GraphSONReader.readObject(x)[2])"));
- assertTrue((Boolean) jythonEngine.eval("GraphSONReader.readObject(x)[3]"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x)[0],Vertex)"));
- // assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x)[1],str)")); // its python unicode jython object
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x)[2],dict)"));
- assertTrue((Boolean) jythonEngine.eval("isinstance(GraphSONReader.readObject(x)[3],bool)"));
+ assertEquals("[v[1], u'hello', {u'a': 2, u'b': 2.3}, True]", jythonEngine.eval("str(graphson_io.readObject(x))"));
+ assertEquals(g.V(1).next().toString(), jythonEngine.eval("str(graphson_io.readObject(x)[0])"));
+ assertEquals("hello", jythonEngine.eval("graphson_io.readObject(x)[1]"));
+ assertEquals("{u'a': 2, u'b': 2.3}", jythonEngine.eval("str(graphson_io.readObject(x)[2])"));
+ assertTrue((Boolean) jythonEngine.eval("graphson_io.readObject(x)[3]"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x)[0],Vertex)"));
+ // assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x)[1],str)")); // its python unicode jython object
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x)[2],dict)"));
+ assertTrue((Boolean) jythonEngine.eval("isinstance(graphson_io.readObject(x)[3],bool)"));
}
}
http://git-wip-us.apache.org/repos/asf/tinkerpop/blob/d392379e/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/structure/io/graphson/GraphSONWriterTest.java
----------------------------------------------------------------------
diff --git a/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/structure/io/graphson/GraphSONWriterTest.java b/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/structure/io/graphson/GraphSONWriterTest.java
index 0ef3158..01e8c23 100644
--- a/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/structure/io/graphson/GraphSONWriterTest.java
+++ b/gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/structure/io/graphson/GraphSONWriterTest.java
@@ -56,75 +56,75 @@ public class GraphSONWriterTest {
@Test
public void shouldSerializeNumbers() throws Exception {
- assertEquals(1, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(1)").toString(), Object.class));
- assertEquals(mapper.writeValueAsString(1), jythonEngine.eval("GraphSONWriter.writeObject(1)").toString().replace(" ", ""));
+ assertEquals(1, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(1)").toString(), Object.class));
+ assertEquals(mapper.writeValueAsString(1), jythonEngine.eval("graphson_io.writeObject(1)").toString().replace(" ", ""));
//
- assertEquals(2L, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(2L)").toString(), Object.class));
- assertEquals(mapper.writeValueAsString(2L), jythonEngine.eval("GraphSONWriter.writeObject(2L)").toString().replace(" ", ""));
+ assertEquals(2L, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(2L)").toString(), Object.class));
+ assertEquals(mapper.writeValueAsString(2L), jythonEngine.eval("graphson_io.writeObject(2L)").toString().replace(" ", ""));
//
- assertEquals(3.4f, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(3.4)").toString(), Object.class));
- assertEquals(mapper.writeValueAsString(3.4f), jythonEngine.eval("GraphSONWriter.writeObject(3.4)").toString().replace(" ", ""));
+ assertEquals(3.4, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(3.4)").toString(), Object.class));
+ assertEquals(mapper.writeValueAsString(3.4), jythonEngine.eval("graphson_io.writeObject(3.4)").toString().replace(" ", ""));
}
@Test
public void shouldSerializeCollections() throws Exception {
final Map<String, Number> map = new LinkedHashMap<>();
map.put("a", 2);
- map.put("b", 2.3f);
- assertEquals(map, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject({'a':2,'b':2.3})").toString(), Object.class));
+ map.put("b", 2.3);
+ assertEquals(map, mapper.readValue(jythonEngine.eval("graphson_io.writeObject({'a':2,'b':2.3})").toString(), Object.class));
//
final List<Object> list = Arrays.asList(new DefaultRemoteTraverser<>("hello", 3L), "hello", map, true);
assertTrue((Boolean) jythonEngine.eval("isinstance([Traverser('hello',3L),'hello',{'a':2,'b':2.3},True],list)"));
- assertEquals(list, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject([Traverser('hello',3L),'hello',{'a':2,'b':2.3},True])").toString(), Object.class));
+ assertEquals(list, mapper.readValue(jythonEngine.eval("graphson_io.writeObject([Traverser('hello',3L),'hello',{'a':2,'b':2.3},True])").toString(), Object.class));
}
@Test
public void shouldSerializeTraverser() throws Exception {
assertEquals(
new DefaultRemoteTraverser<>("hello", 3L),
- mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(Traverser('hello',3L))").toString(), Object.class));
- assertEquals(3L, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(Traverser('hello',3L))").toString(), Traverser.class).bulk());
- assertEquals("hello", mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(Traverser('hello',3L))").toString(), Traverser.class).get());
+ mapper.readValue(jythonEngine.eval("graphson_io.writeObject(Traverser('hello',3L))").toString(), Object.class));
+ assertEquals(3L, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(Traverser('hello',3L))").toString(), Traverser.class).bulk());
+ assertEquals("hello", mapper.readValue(jythonEngine.eval("graphson_io.writeObject(Traverser('hello',3L))").toString(), Traverser.class).get());
}
@Test
public void shouldSerializeBytecode() throws Exception {
- assertEquals(P.eq(7L), mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(P.eq(7L))").toString(), Object.class));
- // TODO: assertEquals(mapper.writeValueAsString(P.between(1, 2).and(P.eq(7L))), jythonEngine.eval("GraphSONWriter.writeObject(P.eq(7L)._and(P.between(1,2)))").toString().replace(" ",""));
- assertEquals(AndP.class, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(P.eq(7L).and_(P.between(1,2)))").toString(), Object.class).getClass());
+ assertEquals(P.eq(7L), mapper.readValue(jythonEngine.eval("graphson_io.writeObject(P.eq(7L))").toString(), Object.class));
+ // TODO: assertEquals(mapper.writeValueAsString(P.between(1, 2).and(P.eq(7L))), jythonEngine.eval("graphson_io.writeObject(P.eq(7L)._and(P.between(1,2)))").toString().replace(" ",""));
+ assertEquals(AndP.class, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(P.eq(7L).and_(P.between(1,2)))").toString(), Object.class).getClass());
//
- assertEquals(new Bytecode.Binding<>("a", 5L), mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(Binding('a',5L))").toString(), Object.class));
+ assertEquals(new Bytecode.Binding<>("a", 5L), mapper.readValue(jythonEngine.eval("graphson_io.writeObject(Binding('a',5L))").toString(), Object.class));
//
for (final Column t : Column.values()) {
- assertEquals(t, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(Column." + t.name() + ")").toString(), Object.class));
+ assertEquals(t, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(Column." + t.name() + ")").toString(), Object.class));
}
for (final T t : T.values()) {
- assertEquals(t, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(T." + t.name() + ")").toString(), Object.class));
+ assertEquals(t, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(T." + t.name() + ")").toString(), Object.class));
}
- assertEquals(Pop.first, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(Pop.first)").toString(), Object.class));
- assertEquals(Pop.last, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(Pop.last)").toString(), Object.class));
- assertEquals(Pop.all, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(Pop.all_)").toString(), Object.class));
- assertEquals(Scope.global, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(Scope.global_)").toString(), Object.class));
- assertEquals(Scope.local, mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(Scope.local)").toString(), Object.class));
+ assertEquals(Pop.first, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(Pop.first)").toString(), Object.class));
+ assertEquals(Pop.last, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(Pop.last)").toString(), Object.class));
+ assertEquals(Pop.all, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(Pop.all_)").toString(), Object.class));
+ assertEquals(Scope.global, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(Scope.global_)").toString(), Object.class));
+ assertEquals(Scope.local, mapper.readValue(jythonEngine.eval("graphson_io.writeObject(Scope.local)").toString(), Object.class));
}
@Test
public void shouldSerializeLambda() throws Exception {
assertEquals(
Lambda.function("lambda z : 1+2", "gremlin-python"),
- mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(lambda : 'z : 1+2')").toString(), Object.class));
+ mapper.readValue(jythonEngine.eval("graphson_io.writeObject(lambda : 'z : 1+2')").toString(), Object.class));
assertEquals(
Lambda.function("lambda z : z+ 7", "gremlin-python"),
- mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(lambda : 'lambda z : z+ 7')").toString(), Object.class));
+ mapper.readValue(jythonEngine.eval("graphson_io.writeObject(lambda : 'lambda z : z+ 7')").toString(), Object.class));
assertEquals(
Lambda.supplier("lambda : 23", "gremlin-python"),
- mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(lambda : 'lambda : 23')").toString(), Object.class));
+ mapper.readValue(jythonEngine.eval("graphson_io.writeObject(lambda : 'lambda : 23')").toString(), Object.class));
assertEquals(
Lambda.consumer("lambda z : z + 23", "gremlin-python"),
- mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(lambda : 'lambda z : z + 23')").toString(), Object.class));
+ mapper.readValue(jythonEngine.eval("graphson_io.writeObject(lambda : 'lambda z : z + 23')").toString(), Object.class));
assertEquals(
Lambda.biFunction("lambda z,y : z - y + 2", "gremlin-python"),
- mapper.readValue(jythonEngine.eval("GraphSONWriter.writeObject(lambda : 'lambda z,y : z - y + 2')").toString(), Object.class));
+ mapper.readValue(jythonEngine.eval("graphson_io.writeObject(lambda : 'lambda z,y : z - y + 2')").toString(), Object.class));
}
}