tests/test_json.c

changeset 1072
c89283cd559b
parent 1063
e453e717876e
child 1075
0cc4b63a0ae0
--- a/tests/test_json.c	Wed Jan 01 15:26:50 2025 +0100
+++ b/tests/test_json.c	Wed Jan 01 15:33:41 2025 +0100
@@ -705,6 +705,46 @@
     cx_testing_allocator_destroy(&talloc);
 }
 
+CX_TEST(test_json_write_default_format) {
+    CxTestingAllocator talloc;
+    cx_testing_allocator_init(&talloc);
+    CxAllocator *allocator = &talloc.base;
+    CX_TEST_DO {
+        // expected value
+        cxstring expected = CX_STR("{\"bool\":false,\"nested\":{\"floats\":[3.1415,47.11,8.15],\"ints\":[4,8,15,16,23,42],\"literals\":[true,null,false],\"string\":\"test\"},\"num\":47.11,\"strings\":[\"hello\",\"world\"]}");
+
+        // create the value
+        CxJsonValue *obj = cxJsonCreateObj(allocator);
+        cxJsonObjPutLiteral(obj, CX_STR("bool"), CX_JSON_FALSE);
+        cxJsonObjPutNumber(obj, CX_STR("num"), 47.11);
+        CxJsonValue *strings = cxJsonObjPutArr(obj, CX_STR("strings"));
+        cxJsonArrAddCxStrings(strings, (cxstring[]) {CX_STR("hello"), CX_STR("world")}, 2);
+        CxJsonValue *nested = cxJsonObjPutObj(obj, CX_STR("nested"));
+        cxJsonObjPutString(nested, CX_STR("string"), "test");
+        cxJsonArrAddNumbers(cxJsonObjPutArr(nested, CX_STR("floats")),
+            (double[]){3.1415, 47.11, 8.15}, 3);
+        cxJsonArrAddLiterals(cxJsonObjPutArr(nested, CX_STR("literals")),
+                    (CxJsonLiteral[]){CX_JSON_TRUE, CX_JSON_NULL, CX_JSON_FALSE}, 3);
+        cxJsonArrAddIntegers(cxJsonObjPutArr(nested, CX_STR("ints")),
+            (int64_t[]){4, 8, 15, 16, 23, 42}, 6);
+
+        // write it to a buffer
+        CxBuffer buf;
+        cxBufferInit(&buf, NULL, 256, NULL, CX_BUFFER_DEFAULT);
+        int result = cxJsonWrite(&buf, obj, (cx_write_func) cxBufferWrite, NULL);
+        CX_TEST_ASSERT(result == 0);
+
+        // compare the string
+        CX_TEST_ASSERT(0 == cx_strcmp(cx_strn(buf.space, buf.size), expected));
+
+        // destroy everything
+        cxBufferDestroy(&buf);
+        cxJsonValueFree(obj);
+        CX_TEST_ASSERT(cx_testing_allocator_verify(&talloc));
+    }
+    cx_testing_allocator_destroy(&talloc);
+}
+
 CxTestSuite *cx_test_suite_json(void) {
     CxTestSuite *suite = cx_test_suite_new("json");
 
@@ -723,6 +763,7 @@
     cx_test_register(suite, test_json_allocator);
     cx_test_register(suite, test_json_allocator_parse_error);
     cx_test_register(suite, test_json_create_value);
+    cx_test_register(suite, test_json_write_default_format);
     
     return suite;
 }

mercurial