]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
json: don't assert() if we add a NULL element via json_variant_set_field()
authorLennart Poettering <lennart@poettering.net>
Thu, 25 Nov 2021 09:30:45 +0000 (10:30 +0100)
committerLennart Poettering <lennart@poettering.net>
Thu, 25 Nov 2021 13:21:54 +0000 (14:21 +0100)
The rest of our JSON code tries hard to magically convert NULL inputs
into "null" JSON objects, let's make sure this also works with
json_variant_set_field().

src/shared/json.c
src/test/test-json.c

index 5e162ec0fffd08e28776460a62c3810e2cf2f81f..58d6117ac903d686f1cd6fc71e0fc16997f8c637 100644 (file)
@@ -515,7 +515,6 @@ static void json_variant_set(JsonVariant *a, JsonVariant *b) {
 
 static void json_variant_copy_source(JsonVariant *v, JsonVariant *from) {
         assert(v);
-        assert(from);
 
         if (!json_variant_is_regular(from))
                 return;
index d0bc810c7f36582d41c16b1318030a4e1b1f02f9..d1d551e7463f1431eb441b23a983ad06bcb54b72 100644 (file)
@@ -569,6 +569,29 @@ static void test_float(void) {
         test_float_match(w);
 }
 
+static void test_equal_text(JsonVariant *v, const char *text) {
+        _cleanup_(json_variant_unrefp) JsonVariant *w = NULL;
+
+        assert_se(json_parse(text, 0, &w, NULL, NULL) >= 0);
+        assert_se(json_variant_equal(v, w) || (!v && json_variant_is_null(w)));
+}
+
+static void test_set_field(void) {
+        _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
+
+        log_info("/* %s */", __func__);
+
+        test_equal_text(v, "null");
+        assert_se(json_variant_set_field(&v, "foo", NULL) >= 0);
+        test_equal_text(v, "{\"foo\" : null}");
+        assert_se(json_variant_set_field(&v, "bar", JSON_VARIANT_STRING_CONST("quux")) >= 0);
+        test_equal_text(v, "{\"foo\" : null, \"bar\" : \"quux\"}");
+        assert_se(json_variant_set_field(&v, "foo", JSON_VARIANT_STRING_CONST("quux2")) >= 0);
+        test_equal_text(v, "{\"foo\" : \"quux2\", \"bar\" : \"quux\"}");
+        assert_se(json_variant_set_field(&v, "bar", NULL) >= 0);
+        test_equal_text(v, "{\"foo\" : \"quux2\", \"bar\" : null}");
+}
+
 int main(int argc, char *argv[]) {
         test_setup_logging(LOG_DEBUG);
 
@@ -622,6 +645,7 @@ int main(int argc, char *argv[]) {
         test_normalize();
         test_bisect();
         test_float();
+        test_set_field();
 
         return 0;
 }