aboutsummaryrefslogtreecommitdiff
path: root/list/test/list_test.c
blob: 418e156c1a3e7069a0de2ab985093ae577c2b9a2 (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
#include "list.h"

#include "test.h"

#define TEST_LIST_SIZE 10

DEF_LIST(int, int);

// Iterate over a list.
TEST_CASE(list_traverse) {
  int_list list = make_list(int);
  for (int i = 0; i < TEST_LIST_SIZE; ++i) {
    list_add(list, i + 1);
  }

  int count = 0;
  int sum   = 0;
  list_foreach(list, value, {
    count++;
    sum += value;
  });

  TEST_EQUAL(count, TEST_LIST_SIZE);
  TEST_EQUAL(sum, TEST_LIST_SIZE * (TEST_LIST_SIZE + 1) / 2);

  del_list(list);
}

// Delete by value.
TEST_CASE(list_remove_by_value) {
  int_list list = make_list(int);
  for (int i = 0; i < TEST_LIST_SIZE; ++i) {
    list_add(list, i + 1);
  }

  list_remove(list, 5);

  int count = 0;
  int sum   = 0;
  list_foreach(list, value, {
    count++;
    sum += value;
  });

  TEST_EQUAL(count, TEST_LIST_SIZE - 1);
  TEST_EQUAL(sum, (TEST_LIST_SIZE * (TEST_LIST_SIZE + 1) / 2) - 5);

  del_list(list);
}

// Delete by address.
TEST_CASE(list_remove_by_address) {
  const int N = 3;

  int* ptrs[3] = {0};

  int_list list = make_list(int);
  for (int i = 0; i < N; ++i) {
    list_add(list, i + 1);
    ptrs[i] = &list.head->val;
  }

  list_remove_ptr(list, ptrs[1]); // Value 2.

  int count = 0;
  int sum   = 0;
  list_foreach(list, value, {
    count++;
    sum += value;
  });

  TEST_EQUAL(count, 2);
  TEST_EQUAL(sum, 1 + 3);

  del_list(list);
}

int main() { return 0; }