1 #include <assert.h>
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <stdio.h>
5
6 #ifndef SYSCONFDIR
7 // Bypass compilation error due to -DSYSCONFDIR not provided
8 #define SYSCONFDIR
9 #endif
10
11 #include "config.c"
12
13 struct test_parse_size_unit {
14 const char *test_str;
15 size_t expected_size;
16 int expected_rc;
17 };
18
test_config_parse_bytesize(void)19 void test_config_parse_bytesize(void)
20 {
21 const struct test_parse_size_unit test_data[] = {
22 { NULL, 0, -1 },
23 { "", 0, -1 },
24 { "0", 0, -1 },
25 { "1", 1, 0 },
26 { "4k", 4ul * 1024ul, 0 },
27 { "6M", (6ul << 20), 0 },
28 { "4095M", (4095ul << 20), 0 },
29 { "2G", (2ul << 30), 0 },
30 { "8M\n", (8ul << 20), 0 }, /* Suffix ignored */
31 { " 10k", 10ul * 1024ul, 0 }, /* Leading spaces trimmed */
32 { "10k ", 10ul * 1024ul, 0 }, /* Trailing spaces trimmed */
33 { "\r\t10k \r\t", 10ul * 1024ul, 0 }, /* Spaces trimmed */
34 { " 10 kB ", 10ul * 1024ul, 0 }, /* Spaces trimmed */
35 { "11G", 0, -1 }, /* Overflow */
36 { "4294967296", 0, -1 }, /* Overflow */
37 { "4096M", 0, -1 }, /* Overflow */
38 { "65535G", 0, -1 }, /* Overflow */
39 { "xyz", 0, -1 }, /* Invalid */
40 { "000", 0, -1 }, /* Invalid */
41 { "0.1", 0, -1 }, /* Invalid */
42 { "9T", 0, -1 }, /* Invalid suffix */
43 };
44 const size_t num_tests =
45 sizeof(test_data) / sizeof(struct test_parse_size_unit);
46 size_t size;
47 size_t i;
48 int rc;
49
50 for (i = 0; i < num_tests; i++) {
51 rc = config_parse_bytesize(test_data[i].test_str, &size);
52
53 if (rc == -1 && rc != test_data[i].expected_rc) {
54 warn("[%zu] Str %s expected rc %d, got rc %d\n", i,
55 test_data[i].test_str, test_data[i].expected_rc,
56 rc);
57 } else if (rc == 0 && test_data[i].expected_size != size) {
58 warn("[%zu] Str %s expected size %zu, got size %zu\n",
59 i, test_data[i].test_str,
60 test_data[i].expected_size, size);
61 }
62 assert(rc == test_data[i].expected_rc);
63 if (rc == 0) {
64 assert(size == test_data[i].expected_size);
65 }
66 }
67 }
68
main(void)69 int main(void)
70 {
71 test_config_parse_bytesize();
72 return EXIT_SUCCESS;
73 }
74