add test for parsing json with multiple incomplete tokens

Sun, 20 Oct 2024 11:39:54 +0200

author
Olaf Wintermann <olaf.wintermann@gmail.com>
date
Sun, 20 Oct 2024 11:39:54 +0200
changeset 939
0bb7258366a0
parent 938
9d02bb5dcc3c
child 940
bbf41b9c2658

add test for parsing json with multiple incomplete tokens

tests/test_json.c file | annotate | diff | comparison | revisions
--- a/tests/test_json.c	Sun Oct 20 10:49:38 2024 +0200
+++ b/tests/test_json.c	Sun Oct 20 11:39:54 2024 +0200
@@ -95,10 +95,64 @@
     }
 }
 
+CX_TEST(test_json_object_incomplete_token) {
+    cxstring text = cx_str(
+            "{\"message\":\"success\"  ,     \"__timestamp\":1729348561}");
+    cxstring parts[16];
+    size_t nparts = 0; // split the json text into mulple parts
+    for(size_t i=0;i<text.length;i+=4) {
+        parts[nparts++] = cx_strsubsl(text, i, 4);
+    }
+    
+    CX_TEST_DO {
+        int result;
+
+        CxJson json;
+        cxJsonInit(&json);
+        CxJsonValue *obj;
+        
+        size_t part = 0;
+        while(part < nparts) {
+            cxJsonFill(&json, parts[part].ptr, parts[part].length);
+            part++;
+            result = cxJsonNext(&json, &obj);
+            
+            if(result != 0) {
+                break;
+            }
+        }
+        
+        CX_TEST_ASSERT(result == 1);
+        CX_TEST_ASSERT(part == nparts);
+        CX_TEST_ASSERT(obj);
+        
+        CxJsonValue *message = cxJsonObjGet(obj, "message");
+        CX_TEST_ASSERT(cxJsonIsString(message));
+        CX_TEST_ASSERT(0 == cx_strcmp(
+                cx_strcast(cxJsonAsString(message)),
+                cx_str("success"))
+        );
+        CxJsonValue *timestamp = cxJsonObjGet(obj, "__timestamp");
+        CX_TEST_ASSERT(message->type == CX_JSON_STRING);
+        CX_TEST_ASSERT(cxJsonIsInteger(timestamp));
+        CX_TEST_ASSERT(cxJsonAsInteger(timestamp) == 1729348561);
+        
+        // this recursively frees everything else
+        cxJsonValueFree(obj);
+
+        // we only have one object that already contained all the data
+        result = cxJsonNext(&json, &obj);
+        CX_TEST_ASSERT(result == 0);
+
+        cxJsonDestroy(&json);
+    }
+}
+
 CxTestSuite *cx_test_suite_json(void) {
     CxTestSuite *suite = cx_test_suite_new("json");
 
     cx_test_register(suite, test_json_simple_object);
+    cx_test_register(suite, test_json_object_incomplete_token);
 
     return suite;
 }

mercurial