summaryrefslogtreecommitdiff
path: root/ccan/strmap/test/run.c
blob: aaa8618125c14d228a0a08da695aff8bd4c7e708 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <ccan/strmap/strmap.h>
#include <ccan/strmap/strmap.c>
#include <ccan/tap/tap.h>

int main(void)
{
	struct strmap_charp {
		STRMAP_MEMBERS(char *);
	} map;
	const char str[] = "hello";
	const char val[] = "there";
	const char none[] = "";
	char *dup = strdup(str);
	char *v;

	/* This is how many tests you plan to run */
	plan_tests(42);

	strmap_init(&map);

	ok1(!strmap_get(&map, str));
	ok1(errno == ENOENT);
	ok1(!strmap_get(&map, none));
	ok1(errno == ENOENT);
	ok1(!strmap_del(&map, str, NULL));
	ok1(errno == ENOENT);
	ok1(!strmap_del(&map, none, NULL));
	ok1(errno == ENOENT);

	ok1(strmap_add(&map, str, val));
	ok1(strmap_get(&map, str) == val);
	/* We compare the string, not the pointer. */
	ok1(strmap_get(&map, dup) == val);
	ok1(!strmap_get(&map, none));
	ok1(errno == ENOENT);

	/* Add a duplicate should fail. */
	ok1(!strmap_add(&map, dup, val));
	ok1(errno == EEXIST);
	ok1(strmap_get(&map, dup) == val);

	/* Delete should return original string. */
	ok1(strmap_del(&map, dup, &v) == str);
	ok1(v == val);
	ok1(!strmap_get(&map, str));
	ok1(errno == ENOENT);
	ok1(!strmap_get(&map, none));
	ok1(errno == ENOENT);

	/* Try insert and delete of empty string. */
	ok1(strmap_add(&map, none, none));
	ok1(strmap_get(&map, none) == none);
	ok1(!strmap_get(&map, str));
	ok1(errno == ENOENT);

	/* Delete should return original string. */
	ok1(strmap_del(&map, "", &v) == none);
	ok1(v == none);
	ok1(!strmap_get(&map, str));
	ok1(errno == ENOENT);
	ok1(!strmap_get(&map, none));
	ok1(errno == ENOENT);

	/* Both at once... */
	ok1(strmap_add(&map, none, none));
	ok1(strmap_add(&map, str, val));
	ok1(strmap_get(&map, str) == val);
	ok1(strmap_get(&map, none) == none);
	ok1(strmap_del(&map, "does not exist", NULL) == NULL);
	ok1(strmap_del(&map, "", NULL) == none);
	ok1(strmap_get(&map, str) == val);
	ok1(strmap_del(&map, dup, &v) == str);
	ok1(v == val);

	ok1(strmap_empty(&map));
	free(dup);

	/* This exits depending on whether all tests passed */
	return exit_status();
}