add cram based unit tests
[project/libubox.git] / tests / test-list.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 #include "list.h"
6 #include "utils.h"
7
8 struct item {
9 const char *name;
10 struct list_head list;
11 };
12
13 #define OUT(fmt, ...) do { \
14 fprintf(stdout, "%s: " fmt, __func__, ## __VA_ARGS__); \
15 } while (0);
16
17 static void test_basics()
18 {
19 size_t i;
20 struct item *tmp;
21 struct item *item;
22 struct item *last;
23 struct item *first;
24 static struct list_head test_list = LIST_HEAD_INIT(test_list);
25
26 const char *vals[] = {
27 "zero", "one", "two", "three", "four", "five", "six",
28 "seven", "eight", "nine", "ten", "eleven", "twelve"
29 };
30
31 OUT("list_empty: %s\n", list_empty(&test_list) ? "yes" : "no");
32 OUT("list_add_tail: ");
33 for (i=0; i<ARRAY_SIZE(vals); i++) {
34 struct item *e = malloc(sizeof(struct item));
35 e->name = vals[i];
36 list_add_tail(&e->list, &test_list);
37 fprintf(stdout, "%s ", vals[i]);
38 }
39 fprintf(stdout, "\n");
40 OUT("list_empty: %s\n", list_empty(&test_list) ? "yes" : "no");
41
42 first = list_first_entry(&test_list, struct item, list);
43 last = list_last_entry(&test_list, struct item, list);
44 OUT("first=%s last=%s\n", first->name, last->name);
45 OUT("'zero' is first, %s\n", list_is_first(&first->list, &test_list) ? "yes" : "no");
46 OUT("'twelve' is last, %s\n", list_is_last(&last->list, &test_list) ? "yes" : "no");
47
48 OUT("removing 'twelve' and 'zero'\n");
49 list_del(&first->list);
50 list_del(&last->list);
51 free(first);
52 free(last);
53 first = list_first_entry(&test_list, struct item, list);
54 last = list_last_entry(&test_list, struct item, list);
55 OUT("first=%s last=%s\n", first->name, last->name);
56 OUT("'one' is first, %s\n", list_is_first(&first->list, &test_list) ? "yes" : "no");
57 OUT("'eleven' is last, %s\n", list_is_last(&last->list, &test_list) ? "yes" : "no");
58
59 OUT("moving 'one' to the tail\n");
60 list_move_tail(&first->list, &test_list);
61 first = list_first_entry(&test_list, struct item, list);
62 last = list_last_entry(&test_list, struct item, list);
63 OUT("first=%s last=%s\n", first->name, last->name);
64 OUT("'two' is first, %s\n", list_is_first(&first->list, &test_list) ? "yes" : "no");
65 OUT("'one' is last, %s\n", list_is_last(&last->list, &test_list) ? "yes" : "no");
66
67 OUT("list_for_each_entry: ");
68 list_for_each_entry(item, &test_list, list) {
69 fprintf(stdout, "%s ", item->name);
70 }
71 fprintf(stdout, "\n");
72
73 OUT("list_for_each_entry_reverse: ");
74 list_for_each_entry_reverse(item, &test_list, list) {
75 fprintf(stdout, "%s ", item->name);
76 }
77 fprintf(stdout, "\n");
78
79 OUT("delete all entries\n");
80 list_for_each_entry_safe(item, tmp, &test_list, list) {
81 list_del(&item->list);
82 free(item);
83 }
84 OUT("list_empty: %s\n", list_empty(&test_list) ? "yes" : "no");
85 }
86
87 int main()
88 {
89 test_basics();
90 return 0;
91 }