1 #include <gtest/gtest.h>
2 #include <pthread.h>
3 #include <sys/time.h>
4 #include <unistd.h>
5
6 extern "C" {
7 #include "reactor.h"
8 }
9
10 static pthread_t thread;
11 static volatile bool thread_running;
12
reactor_thread(void * ptr)13 static void *reactor_thread(void *ptr) {
14 reactor_t *reactor = (reactor_t *)ptr;
15
16 thread_running = true;
17 reactor_start(reactor);
18 thread_running = false;
19
20 return NULL;
21 }
22
spawn_reactor_thread(reactor_t * reactor)23 static void spawn_reactor_thread(reactor_t *reactor) {
24 int ret = pthread_create(&thread, NULL, reactor_thread, reactor);
25 EXPECT_EQ(ret, 0);
26 }
27
join_reactor_thread()28 static void join_reactor_thread() {
29 pthread_join(thread, NULL);
30 }
31
get_timestamp(void)32 static uint64_t get_timestamp(void) {
33 struct timeval tv;
34 gettimeofday(&tv, NULL);
35 return tv.tv_sec * 1000 + tv.tv_usec / 1000;
36 }
37
TEST(ReactorTest,reactor_new)38 TEST(ReactorTest, reactor_new) {
39 reactor_t *reactor = reactor_new();
40 EXPECT_TRUE(reactor != NULL);
41 reactor_free(reactor);
42 }
43
TEST(ReactorTest,reactor_free_null)44 TEST(ReactorTest, reactor_free_null) {
45 reactor_free(NULL);
46 }
47
TEST(ReactorTest,reactor_stop_start)48 TEST(ReactorTest, reactor_stop_start) {
49 reactor_t *reactor = reactor_new();
50 reactor_stop(reactor);
51 reactor_start(reactor);
52 reactor_free(reactor);
53 }
54
TEST(ReactorTest,reactor_repeated_stop_start)55 TEST(ReactorTest, reactor_repeated_stop_start) {
56 reactor_t *reactor = reactor_new();
57 for (int i = 0; i < 10; ++i) {
58 reactor_stop(reactor);
59 reactor_start(reactor);
60 }
61 reactor_free(reactor);
62 }
63
TEST(ReactorTest,reactor_multi_stop_start)64 TEST(ReactorTest, reactor_multi_stop_start) {
65 reactor_t *reactor = reactor_new();
66
67 reactor_stop(reactor);
68 reactor_stop(reactor);
69 reactor_stop(reactor);
70
71 reactor_start(reactor);
72 reactor_start(reactor);
73 reactor_start(reactor);
74
75 reactor_free(reactor);
76 }
77
TEST(ReactorTest,reactor_start_wait_stop)78 TEST(ReactorTest, reactor_start_wait_stop) {
79 reactor_t *reactor = reactor_new();
80
81 spawn_reactor_thread(reactor);
82 usleep(50 * 1000);
83 EXPECT_TRUE(thread_running);
84
85 reactor_stop(reactor);
86 join_reactor_thread();
87 EXPECT_FALSE(thread_running);
88
89 reactor_free(reactor);
90 }
91
TEST(ReactorTest,reactor_run_once_timeout)92 TEST(ReactorTest, reactor_run_once_timeout) {
93 reactor_t *reactor = reactor_new();
94
95 uint64_t start = get_timestamp();
96 reactor_status_t status = reactor_run_once_timeout(reactor, 50);
97 EXPECT_GE(get_timestamp() - start, static_cast<uint64_t>(50));
98 EXPECT_EQ(status, REACTOR_STATUS_TIMEOUT);
99
100 reactor_free(reactor);
101 }
102