tests/test_json.c

changeset 1119
ff4d7e76f85a
parent 1117
54df904472b0
--- a/tests/test_json.c	Fri Jan 10 15:03:58 2025 +0100
+++ b/tests/test_json.c	Fri Jan 10 23:11:08 2025 +0100
@@ -894,7 +894,7 @@
     cxBufferInit(&buf, NULL, 32, NULL, 0);
     CX_TEST_DO {
         // test default settings (6 digits)
-        cxJsonWrite(&buf,num, cxBufferWriteFunc, &writer);
+        cxJsonWrite(&buf, num, cxBufferWriteFunc, &writer);
         CX_TEST_ASSERT(0 == cx_strcmp(cx_strn(buf.space, buf.size), CX_STR("3.141592")));
 
         // test too many digits
@@ -939,6 +939,50 @@
     cxJsonValueFree(num);
 }
 
+CX_TEST(test_json_write_string_escape) {
+    /**
+     * According to RFC-8259 we have to test the following characters:
+     *    "    quotation mark
+     *    \    reverse solidus
+     *    /    solidus
+     *    b    backspace
+     *    f    form feed
+     *    n    line feed
+     *    r    carriage return
+     *    t    tab
+     * And all other control characters must be encoded uXXXX - in our example the bell character.
+     * Also, all unicode characters are encoded that way - in our example the 'ö'.
+     */
+    CxJsonValue* str = cxJsonCreateString(NULL,
+        "hello\twörld\r\nthis/is\\a \"string\"\b in \a string\f");
+    CxJsonWriter writer = cxJsonWriterCompact();
+    CxBuffer buf;
+    cxBufferInit(&buf, NULL, 128, NULL, 0);
+    CX_TEST_DO {
+        cxJsonWrite(&buf, str, cxBufferWriteFunc, &writer);
+        CX_TEST_ASSERT(0 == cx_strcmp(cx_strn(buf.space, buf.size),
+            CX_STR("\"hello\\tw\\u00c3\\u00b6rld\\r\\nthis\\/is\\\\a \\\"string\\\"\\b in \\u0007 string\\f\"")));
+    }
+    cxBufferDestroy(&buf);
+    cxJsonValueFree(str);
+}
+
+CX_TEST(test_json_write_name_escape) {
+    CxJsonValue* obj = cxJsonCreateObj(NULL);
+    cxJsonObjPutLiteral(obj,
+        CX_STR("hello\twörld\r\nthis/is\\a \"string\"\b in \a string\f"), CX_JSON_TRUE);
+    CxJsonWriter writer = cxJsonWriterCompact();
+    CxBuffer buf;
+    cxBufferInit(&buf, NULL, 128, NULL, 0);
+    CX_TEST_DO {
+        cxJsonWrite(&buf, obj, cxBufferWriteFunc, &writer);
+        CX_TEST_ASSERT(0 == cx_strcmp(cx_strn(buf.space, buf.size),
+            CX_STR("{\"hello\\tw\\u00c3\\u00b6rld\\r\\nthis\\/is\\\\a \\\"string\\\"\\b in \\u0007 string\\f\":true}")));
+    }
+    cxBufferDestroy(&buf);
+    cxJsonValueFree(obj);
+}
+
 CxTestSuite *cx_test_suite_json(void) {
     CxTestSuite *suite = cx_test_suite_new("json");
 
@@ -962,6 +1006,8 @@
     cx_test_register(suite, test_json_write_pretty_default_tabs);
     cx_test_register(suite, test_json_write_pretty_preserve_order);
     cx_test_register(suite, test_json_write_frac_max_digits);
+    cx_test_register(suite, test_json_write_string_escape);
+    cx_test_register(suite, test_json_write_name_escape);
     
     return suite;
 }

mercurial