summaryrefslogtreecommitdiffstats
path: root/src/test/test-format-table.c
diff options
context:
space:
mode:
authorAdrian Vovk <adrianvovk@gmail.com>2024-07-03 23:57:42 +0200
committerAdrian Vovk <adrianvovk@gmail.com>2024-07-17 20:15:43 +0200
commitc4cb49eb342bb347fb974eb55236d2eb3e565086 (patch)
tree63280961c328ad348c129f8d516b4c66c7a3ba82 /src/test/test-format-table.c
parenttable: Add TABLE_SET_JSON_FIELD_NAME (diff)
downloadsystemd-c4cb49eb342bb347fb974eb55236d2eb3e565086.tar.xz
systemd-c4cb49eb342bb347fb974eb55236d2eb3e565086.zip
table: Improve mangling of JSON field names
First, when displaying JSON we convert dashes into underscores. We want to avoid using dashes in JSON field names in new code, because some JSON parsers don't support dashes very well. Second, we make the first character of every word lower-case. This better matches our JSON field name style, and makes the automatic JSON name mangling a lot more useful for vertical tables, where fields are given a display name. For example, "Foo Bar" would be converted into "foo_bar" instead of "Foo_Bar", which much better matches our style. We don't make the whole string lowercase to support cases like: "fooBar" should stay as "fooBar". Some situations don't behave quite perfectly, such as "Foo BarBaz" gets converted into "foo_barBaz", or all-caps headings get mangled incorrectly. In these situations, the JSON field should be overridden manually. In most cases, or at least more cases than before, this heuristic does good enough.
Diffstat (limited to '')
-rw-r--r--src/test/test-format-table.c32
1 files changed, 32 insertions, 0 deletions
diff --git a/src/test/test-format-table.c b/src/test/test-format-table.c
index fa34c29b02..41621dbb5b 100644
--- a/src/test/test-format-table.c
+++ b/src/test/test-format-table.c
@@ -404,6 +404,38 @@ TEST(json) {
assert_se(sd_json_variant_equal(v, w));
}
+TEST(json_mangling) {
+ static const struct {
+ const char *arg;
+ const char *exp;
+ } cases[] = {
+ /* Not Mangled */
+ { "foo", "foo" },
+ { "foo_bar", "foo_bar" },
+ { "fooBar", "fooBar" },
+ { "fooBar123", "fooBar123" },
+ { "foo_bar123", "foo_bar123" },
+ { ALPHANUMERICAL, ALPHANUMERICAL },
+ { "_123", "_123" },
+
+ /* Mangled */
+ { "Foo Bar", "foo_bar" },
+ { "Foo-Bar", "foo_bar" },
+ { "Foo@Bar", "foo_bar" },
+ { "Foo (Bar)", "foo__bar_"},
+ { "MixedCase ALLCAPS", "mixedCase_ALLCAPS" },
+ { "_X", "_x" },
+ { "_Foo", "_foo" },
+ };
+
+ FOREACH_ELEMENT(i, cases) {
+ _cleanup_free_ char *ret = NULL;
+ assert_se(ret = table_mangle_to_json_field_name(i->arg));
+ printf("\"%s\" -> \"%s\"\n", i->arg, ret);
+ assert_se(streq(ret, i->exp));
+ }
+}
+
TEST(table) {
_cleanup_(table_unrefp) Table *t = NULL;
_cleanup_free_ char *formatted = NULL;