summaryrefslogtreecommitdiff
path: root/test/test-observers.cc
blob: be1418dd9a27ae2c51144905fe475204f497f852 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// -*- mode: c++; c-basic-offset: 2; -*-

#include "common.hh"
#include "test.hh"

#include "observers.hh"

namespace {

bool test_sanity() {
  Observers<int> obs;
  ASSERT_EQ(false, obs.notify().has_next());
  obs.insert(1);
  auto it = obs.notify();
  ASSERT_EQ(true, it.has_next());
  ASSERT_EQ(1, it.next());
  ASSERT_EQ(false, it.has_next());
  obs.erase(2);
  it = obs.notify();
  ASSERT_EQ(true, it.has_next());
  ASSERT_EQ(1, it.next());
  obs.erase(1);
  ASSERT_EQ(false, obs.notify().has_next());
  return true;
}

bool test_insert() {
  Observers<int> obs;
  auto it = obs.notify();
  ASSERT_EQ(false, it.has_next());
  obs.insert(1);
  ASSERT_EQ(true, it.has_next());
  ASSERT_EQ(1, it.next());
  obs.insert(2);
  ASSERT_EQ(false, it.has_next());
  it = obs.notify();
  ASSERT_EQ(true, it.has_next());
  int other;
  switch (it.next()) {
  case 1:
    other = 2;
    break;
  case 2:
    other = 1;
    break;
  default:
    ASSERT_TRUE(false);
  }
  ASSERT_EQ(true, it.has_next());
  ASSERT_EQ(other, it.next());
  return true;
}

bool test_erase() {
  Observers<int> obs;
  auto it = obs.notify();
  ASSERT_EQ(false, it.has_next());
  obs.insert(1);
  ASSERT_EQ(true, it.has_next());
  ASSERT_EQ(1, it.next());
  ASSERT_EQ(false, it.has_next());
  obs.erase(1);
  auto it2 = obs.notify();
  ASSERT_EQ(false, it2.has_next());
  it = it2;

  obs.insert(4);
  obs.insert(3);
  obs.insert(2);
  it = obs.notify();
  ASSERT_EQ(true, it.has_next());
  ASSERT_EQ(2, it.next());
  obs.erase(2);
  it2 = obs.notify();
  ASSERT_EQ(true, it2.has_next());
  ASSERT_EQ(3, it2.next());
  obs.erase(3);
  ASSERT_EQ(true, it.has_next());
  ASSERT_EQ(4, it.next());
  ASSERT_EQ(true, it2.has_next());
  ASSERT_EQ(4, it2.next());

  return true;
}

}  // namespace

int main(void) {
  BEFORE;
  RUN(test_sanity());
  RUN(test_insert());
  RUN(test_erase());
  AFTER;
}