From 8618ff1368844936eccdfc58afeed0f29f863551 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Fri, 5 Jan 2024 12:00:35 +0100 Subject: [PATCH] test: add unit test for JSON_DISPATCH_ENUM_DEFINE() --- src/test/test-json.c | 51 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/test/test-json.c b/src/test/test-json.c index 4ceb084c0c8..42e85324170 100644 --- a/src/test/test-json.c +++ b/src/test/test-json.c @@ -9,6 +9,7 @@ #include "json-internal.h" #include "json.h" #include "math-util.h" +#include "string-table.h" #include "string-util.h" #include "strv.h" #include "tests.h" @@ -824,6 +825,56 @@ TEST(json_dispatch) { assert_se(foobar.l == INT16_MIN); } +typedef enum mytestenum { + myfoo, mybar, mybaz, _mymax, _myinvalid = -EINVAL, +} mytestenum; + +static const char *mytestenum_table[_mymax] = { + [myfoo] = "myfoo", + [mybar] = "mybar", + [mybaz] = "mybaz", +}; + +DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(mytestenum, mytestenum); + +static JSON_DISPATCH_ENUM_DEFINE(dispatch_mytestenum, mytestenum, mytestenum_from_string); + +TEST(json_dispatch_enum_define) { + + struct data { + mytestenum a, b, c, d; + } data = { + .a = _myinvalid, + .b = _myinvalid, + .c = _myinvalid, + .d = mybar, + }; + + _cleanup_(json_variant_unrefp) JsonVariant *j = NULL; + + assert_se(json_build(&j, JSON_BUILD_OBJECT( + JSON_BUILD_PAIR("a", JSON_BUILD_STRING("mybaz")), + JSON_BUILD_PAIR("b", JSON_BUILD_STRING("mybar")), + JSON_BUILD_PAIR("c", JSON_BUILD_STRING("myfoo")), + JSON_BUILD_PAIR("d", JSON_BUILD_NULL))) >= 0); + + assert_se(json_dispatch(j, + (const JsonDispatch[]) { + { "a", _JSON_VARIANT_TYPE_INVALID, dispatch_mytestenum, offsetof(struct data, a), 0 }, + { "b", _JSON_VARIANT_TYPE_INVALID, dispatch_mytestenum, offsetof(struct data, b), 0 }, + { "c", _JSON_VARIANT_TYPE_INVALID, dispatch_mytestenum, offsetof(struct data, c), 0 }, + { "d", _JSON_VARIANT_TYPE_INVALID, dispatch_mytestenum, offsetof(struct data, d), 0 }, + {}, + }, + /* flags= */ 0, + &data) >= 0); + + assert(data.a == mybaz); + assert(data.b == mybar); + assert(data.c == myfoo); + assert(data.d < 0); +} + TEST(json_sensitive) { _cleanup_(json_variant_unrefp) JsonVariant *a = NULL, *b = NULL, *v = NULL; _cleanup_free_ char *s = NULL;