This is an automated email from the ASF dual-hosted git repository.

mtaha pushed a commit to branch PG15
in repository https://gitbox.apache.org/repos/asf/age.git


The following commit(s) were added to refs/heads/PG15 by this push:
     new 4cdaa93d Fix json serialization error in Python Driver (#1228) (#1593)
4cdaa93d is described below

commit 4cdaa93d123b3f3fb1fb919171eb6e08a4d316ce
Author: John Gemignani <[email protected]>
AuthorDate: Wed Feb 14 11:04:23 2024 -0800

    Fix json serialization error in Python Driver (#1228) (#1593)
    
    * * Added test to catch the error in toJson()
    * removed the trailing comma in _nodeToJson() node.properties part
    * removed the trailing comma in _nodeToString() node.properties part
    
    * * Added missing ", ".join() _nodeToString() in node.properties part
    
    ---------
    
    Co-authored-by: omaurel-socha 
<[email protected]>
    Co-authored-by: Olivier <[email protected]>
---
 drivers/python/age/models.py  | 24 ++++++++++++----------
 drivers/python/test_age_py.py | 48 +++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 61 insertions(+), 11 deletions(-)

diff --git a/drivers/python/age/models.py b/drivers/python/age/models.py
index 838110a1..aee1b759 100644
--- a/drivers/python/age/models.py
+++ b/drivers/python/age/models.py
@@ -238,11 +238,12 @@ def _nodeToString(node, buf, extraFormatter=None):
         
     if node.properties != None:
         buf.write(", properties:{")
-        for k,v in node.properties.items():
-            buf.write(k)
-            buf.write(": ")
-            buf.write(str(v))
-            buf.write(", ")
+        prop_list = []
+        for k, v in node.properties.items():
+            prop_list.append(f"{k}: {str(v)}")
+
+        # Join properties with comma and write to buffer
+        buf.write(", ".join(prop_list))
         buf.write("}")
 
     if extraFormatter != None:
@@ -281,12 +282,13 @@ def _nodeToJson(node, buf, extraFormatter=None):
         
     if node.properties != None:
         buf.write(", \"properties\":{")
-        for k,v in node.properties.items():
-            buf.write("\"")
-            buf.write(k)
-            buf.write("\": \"")
-            buf.write(str(v))
-            buf.write("\", ")
+
+        prop_list = []
+        for k, v in node.properties.items():
+            prop_list.append(f"\"{k}\": \"{str(v)}\"")
+
+        # Join properties with comma and write to buffer
+        buf.write(", ".join(prop_list))
         buf.write("}")
     buf.write("}")
     
\ No newline at end of file
diff --git a/drivers/python/test_age_py.py b/drivers/python/test_age_py.py
index e62aeeac..1161fda8 100644
--- a/drivers/python/test_age_py.py
+++ b/drivers/python/test_age_py.py
@@ -12,6 +12,7 @@
 # KIND, either express or implied.  See the License for the
 # specific language governing permissions and limitations
 # under the License.
+import json
 
 from age.models import Vertex
 import unittest
@@ -328,6 +329,52 @@ class TestAgeBasic(unittest.TestCase):
             self.assertEqual(3,len(collected))
         print("\nTest 6 Successful...")
 
+    def testSerialization(self):
+
+        print("\n---------------------------------------")
+        print("Test 6: Testing Vertex Serialization.....")
+        print("-----------------------------------------\n")
+
+        ag = self.ag
+
+        with ag.connection.cursor() as cursor:
+            try:
+                ag.cypher(cursor, "CREATE (n:Person {name: %s}) ", 
params=('Joe',))
+                ag.cypher(cursor, "CREATE (n:Person {name: %s}) ", 
params=('Jack',))
+                ag.cypher(cursor, "CREATE (n:Person {name: %s}) ", 
params=('Andy',))
+                ag.cypher(cursor, "CREATE (n:Person {name: %s}) ", 
params=('Smith',))
+                ag.cypher(cursor, "CREATE (n:Person {name: %s}) ", 
params=('Tom',))
+
+                # You must commit explicitly
+                ag.commit()
+            except Exception as ex:
+                print(ex)
+                ag.rollback()
+
+        print(" -------- TESTING Output #1 --------")
+        cursor = ag.execCypher("MATCH (n) RETURN n")
+
+        for row in cursor:
+            vertex = row[0]
+            try:
+                # json.loads will fail if the json str is not properly 
formatted
+                as_dict = json.loads(vertex.toJson())
+                print("Vertex.toJson() returns a correct json string.")
+                assert True
+            except:
+                assert False
+
+        print(" -------- TESTING Output #2 --------")
+        cursor = ag.execCypher("MATCH (n) RETURN n")
+
+        for row in cursor:
+            vertex = row[0]
+            as_str = vertex.toString()
+            # Checking if the trailing comma appears in .toString() output
+            self.assertFalse(as_str.endswith(", }}::VERTEX"))
+        print("Vertex.toString() 'properties' field is formatted properly.")
+
+
 if __name__ == '__main__':
     parser = argparse.ArgumentParser()
 
@@ -364,5 +411,6 @@ if __name__ == '__main__':
     suite.addTest(TestAgeBasic('testCypher'))
     suite.addTest(TestAgeBasic('testMultipleEdges'))
     suite.addTest(TestAgeBasic('testCollect'))
+    suite.addTest(TestAgeBasic('testSerialization'))
     TestAgeBasic.args = args
     unittest.TextTestRunner().run(suite)

Reply via email to