tests/test_json.c

changeset 1117
54df904472b0
parent 1112
22dc2163fffd
--- a/tests/test_json.c	Thu Jan 09 21:19:52 2025 +0100
+++ b/tests/test_json.c	Thu Jan 09 22:37:10 2025 +0100
@@ -887,6 +887,58 @@
     cx_testing_allocator_destroy(&talloc);
 }
 
+CX_TEST(test_json_write_frac_max_digits) {
+    CxJsonValue* num = cxJsonCreateNumber(NULL, 3.141592653589793);
+    CxJsonWriter writer = cxJsonWriterCompact();
+    CxBuffer buf;
+    cxBufferInit(&buf, NULL, 32, NULL, 0);
+    CX_TEST_DO {
+        // test default settings (6 digits)
+        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
+        cxBufferReset(&buf);
+        writer.frac_max_digits = 200;
+        cxJsonWrite(&buf, num, cxBufferWriteFunc, &writer);
+        CX_TEST_ASSERT(0 == cx_strcmp(cx_strn(buf.space, buf.size), CX_STR("3.141592653589793")));
+        
+        // test 0 digits
+        cxBufferReset(&buf);
+        writer.frac_max_digits = 0;
+        cxJsonWrite(&buf, num, cxBufferWriteFunc, &writer);
+        CX_TEST_ASSERT(0 == cx_strcmp(cx_strn(buf.space, buf.size), CX_STR("3")));
+
+        // test 2 digits
+        cxBufferReset(&buf);
+        writer.frac_max_digits = 2;
+        cxJsonWrite(&buf, num, cxBufferWriteFunc, &writer);
+        CX_TEST_ASSERT(0 == cx_strcmp(cx_strn(buf.space, buf.size), CX_STR("3.14")));
+
+        // test 3 digits
+        cxBufferReset(&buf);
+        writer.frac_max_digits = 3;
+        cxJsonWrite(&buf, num, cxBufferWriteFunc, &writer);
+        CX_TEST_ASSERT(0 == cx_strcmp(cx_strn(buf.space, buf.size), CX_STR("3.141")));
+
+        // test 6 digits, but two are left of the decimal point
+        num->value.number = 47.110815;
+        cxBufferReset(&buf);
+        writer.frac_max_digits = 6;
+        cxJsonWrite(&buf, num, cxBufferWriteFunc, &writer);
+        CX_TEST_ASSERT(0 == cx_strcmp(cx_strn(buf.space, buf.size), CX_STR("47.110815")));
+
+        // test 4 digits with exponent
+        num->value.number = 5.11223344e23;
+        cxBufferReset(&buf);
+        writer.frac_max_digits = 4;
+        cxJsonWrite(&buf, num, cxBufferWriteFunc, &writer);
+        CX_TEST_ASSERT(0 == cx_strcmp(cx_strn(buf.space, buf.size), CX_STR("5.1122e+23")));
+    }
+    cxBufferDestroy(&buf);
+    cxJsonValueFree(num);
+}
+
 CxTestSuite *cx_test_suite_json(void) {
     CxTestSuite *suite = cx_test_suite_new("json");
 
@@ -909,6 +961,7 @@
     cx_test_register(suite, test_json_write_pretty_default_spaces);
     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);
     
     return suite;
 }

mercurial