1
2 #include <assert.h>
3 #include <stdlib.h>
4 #include <stdint.h>
5 #include <stdio.h>
6
7 #ifndef SYSCONFDIR
8 // Bypass compilation error due to -DSYSCONFDIR not provided
9 #define SYSCONFDIR
10 #endif
11
12 #include "config.c"
13
mock_config_from_buffer(const char * input)14 static struct config *mock_config_from_buffer(const char *input)
15 {
16 struct config *ctx;
17 ssize_t rc;
18
19 int fd = memfd_create("test-parse-ini", 0);
20 assert(fd != -1);
21
22 const size_t len = strlen(input);
23 rc = write(fd, input, len);
24
25 assert(rc >= 0);
26 assert((size_t)rc == len);
27
28 rc = lseek(fd, 0, SEEK_SET);
29 assert(rc == 0);
30
31 FILE *f = fdopen(fd, "r");
32 assert(f != NULL);
33
34 dictionary *dict = iniparser_load_file(f, "");
35
36 fclose(f);
37
38 if (dict == NULL) {
39 return NULL;
40 }
41
42 ctx = calloc(1, sizeof(*ctx));
43
44 if (ctx) {
45 ctx->dict = dict;
46 }
47
48 return ctx;
49 }
50
execute_test(const char * input,const char * key,const char * expected)51 static void execute_test(const char *input, const char *key,
52 const char *expected)
53 {
54 struct config *ctx = mock_config_from_buffer(input);
55 const char *found;
56
57 if (!expected) {
58 if (ctx == NULL) {
59 return;
60 }
61
62 found = config_get_value(ctx, key);
63 assert(!found);
64
65 goto cleanup;
66 }
67
68 assert(ctx->dict != NULL);
69 found = config_get_value(ctx, key);
70
71 assert(found);
72 assert(!strcmp(expected, found));
73 cleanup:
74 config_fini(ctx);
75 }
76
test_config_parse_basic(void)77 static void test_config_parse_basic(void)
78 {
79 execute_test("tty = ttyS0", "tty", "ttyS0");
80 }
81
test_config_parse_no_key(void)82 static void test_config_parse_no_key(void)
83 {
84 execute_test("= ttyS0", "tty", NULL);
85 }
86
test_config_parse_no_value(void)87 static void test_config_parse_no_value(void)
88 {
89 execute_test("tty =", "tty", NULL);
90 }
91
test_config_parse_no_operator(void)92 static void test_config_parse_no_operator(void)
93 {
94 execute_test("tty ttyS0", "tty", NULL);
95 }
96
test_config_parse_no_spaces(void)97 static void test_config_parse_no_spaces(void)
98 {
99 execute_test("tty=ttyS0", "tty", "ttyS0");
100 }
101
test_config_parse_empty(void)102 static void test_config_parse_empty(void)
103 {
104 execute_test("", "tty", NULL);
105 }
106
main(void)107 int main(void)
108 {
109 test_config_parse_basic();
110 test_config_parse_no_key();
111 test_config_parse_no_value();
112 test_config_parse_no_operator();
113 test_config_parse_no_spaces();
114 test_config_parse_empty();
115
116 return EXIT_SUCCESS;
117 }
118