strmap: set errno on strmap_add() failures.
[ccan] / ccan / strmap / test / run.c
1 #include <ccan/strmap/strmap.h>
2 #include <ccan/strmap/strmap.c>
3 #include <ccan/tap/tap.h>
4
5 int main(void)
6 {
7         struct strmap_charp {
8                 STRMAP_MEMBERS(char *);
9         } map;
10         const char str[] = "hello";
11         const char val[] = "there";
12         const char none[] = "";
13         char *dup = strdup(str);
14         char *v;
15
16         /* This is how many tests you plan to run */
17         plan_tests(32);
18
19         strmap_init(&map);
20
21         ok1(!strmap_get(&map, str));
22         ok1(!strmap_get(&map, none));
23         ok1(!strmap_del(&map, str, NULL));
24         ok1(!strmap_del(&map, none, NULL));
25
26         ok1(strmap_add(&map, str, val));
27         ok1(strmap_get(&map, str) == val);
28         /* We compare the string, not the pointer. */
29         ok1(strmap_get(&map, dup) == val);
30         ok1(!strmap_get(&map, none));
31
32         /* Add a duplicate should fail. */
33         ok1(!strmap_add(&map, dup, val));
34         ok1(errno == EEXIST);
35         ok1(strmap_get(&map, dup) == val);
36
37         /* Delete should return original string. */
38         ok1(strmap_del(&map, dup, &v) == str);
39         ok1(v == val);
40         ok1(!strmap_get(&map, str));
41         ok1(!strmap_get(&map, none));
42
43         /* Try insert and delete of empty string. */
44         ok1(strmap_add(&map, none, none));
45         ok1(strmap_get(&map, none) == none);
46         ok1(!strmap_get(&map, str));
47
48         /* Delete should return original string. */
49         ok1(strmap_del(&map, "", &v) == none);
50         ok1(v == none);
51         ok1(!strmap_get(&map, str));
52         ok1(!strmap_get(&map, none));
53
54         /* Both at once... */
55         ok1(strmap_add(&map, none, none));
56         ok1(strmap_add(&map, str, val));
57         ok1(strmap_get(&map, str) == val);
58         ok1(strmap_get(&map, none) == none);
59         ok1(strmap_del(&map, "does not exist", NULL) == NULL);
60         ok1(strmap_del(&map, "", NULL) == none);
61         ok1(strmap_get(&map, str) == val);
62         ok1(strmap_del(&map, dup, &v) == str);
63         ok1(v == val);
64
65         ok1(strmap_empty(&map));
66         free(dup);
67
68         /* This exits depending on whether all tests passed */
69         return exit_status();
70 }