blob: 8409f246e008df52da2b2f2c8056b3f7c2d5ef20 [file] [log] [blame]
Andrew Jefferyd30d7572023-04-18 14:51:51 +09301
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
Alexander Hansen1e04f442024-06-12 16:35:58 +020014static 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
Andrew Jefferya72711a2023-04-18 18:19:41 +093051static void execute_test(const char *input, const char *key,
52 const char *expected)
Andrew Jefferyd30d7572023-04-18 14:51:51 +093053{
Alexander Hansen1e04f442024-06-12 16:35:58 +020054 struct config *ctx = mock_config_from_buffer(input);
Andrew Jefferyd30d7572023-04-18 14:51:51 +093055 const char *found;
Andrew Jefferyd30d7572023-04-18 14:51:51 +093056
Andrew Jeffery2834c5b2023-04-19 12:47:09 +093057 if (!expected) {
Alexander Hansen1e04f442024-06-12 16:35:58 +020058 if (ctx == NULL) {
59 return;
60 }
61
62 found = config_get_value(ctx, key);
Andrew Jefferyd30d7572023-04-18 14:51:51 +093063 assert(!found);
Alexander Hansen1e04f442024-06-12 16:35:58 +020064
65 goto cleanup;
Andrew Jeffery2834c5b2023-04-19 12:47:09 +093066 }
Alexander Hansen1e04f442024-06-12 16:35:58 +020067
68 assert(ctx->dict != NULL);
69 found = config_get_value(ctx, key);
70
71 assert(found);
72 assert(!strcmp(expected, found));
73cleanup:
Andrew Jefferyd30d7572023-04-18 14:51:51 +093074 config_fini(ctx);
75}
76
77static void test_config_parse_basic(void)
78{
79 execute_test("tty = ttyS0", "tty", "ttyS0");
80}
81
82static void test_config_parse_no_key(void)
83{
84 execute_test("= ttyS0", "tty", NULL);
85}
86
87static void test_config_parse_no_value(void)
88{
89 execute_test("tty =", "tty", NULL);
90}
91
92static void test_config_parse_no_operator(void)
93{
94 execute_test("tty ttyS0", "tty", NULL);
95}
96
97static void test_config_parse_no_spaces(void)
98{
99 execute_test("tty=ttyS0", "tty", "ttyS0");
100}
101
102static void test_config_parse_empty(void)
103{
104 execute_test("", "tty", NULL);
105}
106
107int 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}