tests/test_json.c

changeset 1556
afdaa70034f8
parent 1548
12315ee158ad
--- a/tests/test_json.c	Sun Dec 07 15:34:46 2025 +0100
+++ b/tests/test_json.c	Sun Dec 07 19:36:51 2025 +0100
@@ -143,6 +143,62 @@
     cxJsonValueFree(obj);
 }
 
+CX_TEST(test_json_from_string) {
+    cxstring text = cx_str(
+            "{\n"
+            "\t\"message\":\"success\",\n"
+            "\t\"position\":{\n"
+            "\t\t\"longitude\":-94.7099,\n"
+            "\t\t\"latitude\":51.5539\n"
+            "\t},\n"
+            "\t\"timestamp\":1729348561,\n"
+            "\t\"alive\":true\n"
+            "}"
+    );
+
+    CX_TEST_DO {
+        CxJsonValue *obj;
+        CX_TEST_ASSERT(cxJsonFromString(NULL, text, &obj) == CX_JSON_NO_ERROR);
+
+        // check the contents
+        CX_TEST_ASSERT(cxJsonIsObject(obj));
+
+        CxJsonValue *message = cxJsonObjGet(obj, "message");
+        CX_TEST_ASSERT(cxJsonIsString(message));
+        CX_TEST_ASSERT(0 == cx_strcmp(
+                cxJsonAsCxString(message),
+                "success")
+        );
+
+        CxJsonValue *position = cxJsonObjGet(obj, "position");
+        CX_TEST_ASSERT(cxJsonIsObject(position));
+        CxJsonValue *longitude = cxJsonObjGet(position, "longitude");
+        CX_TEST_ASSERT(cxJsonIsNumber(longitude));
+        CX_TEST_ASSERT(!cxJsonIsInteger(longitude));
+        CX_TEST_ASSERT(0 == cx_vcmp_double(cxJsonAsDouble(longitude), -94.7099));
+        CX_TEST_ASSERT(cxJsonAsInteger(longitude) == -94);
+        CxJsonValue *latitude = cxJsonObjGet(position, "latitude");
+        CX_TEST_ASSERT(cxJsonIsNumber(latitude));
+        CX_TEST_ASSERT(!cxJsonIsInteger(latitude));
+        CX_TEST_ASSERT(0 == cx_vcmp_double(cxJsonAsDouble(latitude), 51.5539));
+        CX_TEST_ASSERT(cxJsonAsInteger(latitude) == 51);
+
+        CxJsonValue *timestamp = cxJsonObjGet(obj, "timestamp");
+        CX_TEST_ASSERT(cxJsonIsInteger(timestamp));
+        CX_TEST_ASSERT(cxJsonIsNumber(timestamp));
+        CX_TEST_ASSERT(cxJsonAsInteger(timestamp) == 1729348561);
+        CX_TEST_ASSERT(cxJsonAsDouble(timestamp) == 1729348561.0);
+
+        CxJsonValue *alive = cxJsonObjGet(obj, "alive");
+        CX_TEST_ASSERT(cxJsonIsBool(alive));
+        CX_TEST_ASSERT(cxJsonIsTrue(alive));
+        CX_TEST_ASSERT(!cxJsonIsFalse(alive));
+        CX_TEST_ASSERT(cxJsonAsBool(alive));
+
+        cxJsonValueFree(obj);
+    }
+}
+
 CX_TEST(test_json_escaped_strings) {
     cxstring text = cx_str(
             "{\n"
@@ -1462,6 +1518,7 @@
     cx_test_register(suite, test_json_init_default);
     cx_test_register(suite, test_json_simple_object);
     cx_test_register(suite, test_json_large_object);
+    cx_test_register(suite, test_json_from_string);
     cx_test_register(suite, test_json_escaped_strings);
     cx_test_register(suite, test_json_escaped_unicode_strings);
     cx_test_register(suite, test_json_escaped_unicode_malformed);

mercurial