]> git.ozlabs.org Git - ccan/blob - ccan/io/test/run-20-io_time_override.c
c0b607a74cfdf09cb6a6c703da40b0ae794fc3bd
[ccan] / ccan / io / test / run-20-io_time_override.c
1 #include <ccan/io/io.h>
2 /* Include the C files directly. */
3 #include <ccan/io/poll.c>
4 #include <ccan/io/io.c>
5 #include <ccan/tap/tap.h>
6 #include <sys/wait.h>
7 #include <stdio.h>
8
9 #define PORT "65020"
10
11 static struct io_plan *init_conn(struct io_conn *conn, void *unused)
12 {
13         return io_close(conn);
14 }
15
16 static int make_listen_fd(const char *port, struct addrinfo **info)
17 {
18         int fd, on = 1;
19         struct addrinfo *addrinfo, hints;
20
21         memset(&hints, 0, sizeof(hints));
22         hints.ai_family = AF_UNSPEC;
23         hints.ai_socktype = SOCK_STREAM;
24         hints.ai_flags = AI_PASSIVE;
25         hints.ai_protocol = 0;
26
27         if (getaddrinfo(NULL, port, &hints, &addrinfo) != 0)
28                 return -1;
29
30         fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
31                     addrinfo->ai_protocol);
32         if (fd < 0)
33                 return -1;
34
35         setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
36         if (bind(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0) {
37                 close(fd);
38                 return -1;
39         }
40         if (listen(fd, 1) != 0) {
41                 close(fd);
42                 return -1;
43         }
44         *info = addrinfo;
45         return fd;
46 }
47
48 static struct timemono fake_time;
49
50 static struct timemono get_fake_time(void)
51 {
52         return fake_time;
53 }
54
55 int main(void)
56 {
57         struct io_listener *l;
58         int fd;
59         struct timers timers;
60         struct timer timer, *expired;
61         struct addrinfo *addrinfo;
62
63         /* This is how many tests you plan to run */
64         plan_tests(7);
65
66         fake_time = time_mono();
67
68         timers_init(&timers, fake_time);
69         timer_init(&timer);
70         timer_addmono(&timers, &timer,
71                       timemono_add(fake_time, time_from_sec(1000)));
72
73         fd = make_listen_fd(PORT, &addrinfo);
74         freeaddrinfo(addrinfo);
75         ok1(fd >= 0);
76         l = io_new_listener(NULL, fd, init_conn, NULL);
77         ok1(l);
78
79         fake_time.ts.tv_sec += 1000;
80         ok1(io_time_override(get_fake_time) == time_mono);
81         ok1(io_loop(&timers, &expired) == NULL);
82
83         ok1(expired == &timer);
84         ok1(!timers_expire(&timers, fake_time));
85         ok1(io_time_override(time_mono) == get_fake_time);
86         io_close_listener(l);
87
88         timers_cleanup(&timers);
89
90         /* This exits depending on whether all tests passed */
91         return exit_status();
92 }