1 /* 	$OpenBSD: test_ptimeout.c,v 1.1 2023/01/06 02:59:50 djm Exp $ */
2 /*
3  * Regress test for misc poll/ppoll timeout helpers.
4  *
5  * Placed in the public domain.
6  */
7 
8 #include "includes.h"
9 
10 #include <sys/types.h>
11 #include <stdio.h>
12 #ifdef HAVE_STDINT_H
13 # include <stdint.h>
14 #endif
15 #include <stdlib.h>
16 #include <string.h>
17 #ifdef HAVE_POLL_H
18 # include <poll.h>
19 #endif
20 #include <time.h>
21 
22 #include "../test_helper/test_helper.h"
23 
24 #include "log.h"
25 #include "misc.h"
26 
27 void test_ptimeout(void);
28 
29 void
30 test_ptimeout(void)
31 {
32 	struct timespec pt, *ts;
33 
34 	TEST_START("ptimeout_init");
35 	ptimeout_init(&pt);
36 	ASSERT_PTR_EQ(ptimeout_get_tsp(&pt), NULL);
37 	ASSERT_INT_EQ(ptimeout_get_ms(&pt), -1);
38 	TEST_DONE();
39 
40 	TEST_START("ptimeout_deadline_sec");
41 	ptimeout_deadline_sec(&pt, 100);
42 	ptimeout_deadline_sec(&pt, 200);
43 	ASSERT_INT_EQ(ptimeout_get_ms(&pt), 100 * 1000);
44 	ts = ptimeout_get_tsp(&pt);
45 	ASSERT_PTR_NE(ts, NULL);
46 	ASSERT_LONG_EQ(ts->tv_nsec, 0);
47 	ASSERT_LONG_EQ(ts->tv_sec, 100);
48 	TEST_DONE();
49 
50 	TEST_START("ptimeout_deadline_ms");
51 	ptimeout_deadline_ms(&pt, 50123);
52 	ptimeout_deadline_ms(&pt, 50500);
53 	ASSERT_INT_EQ(ptimeout_get_ms(&pt), 50123);
54 	ts = ptimeout_get_tsp(&pt);
55 	ASSERT_PTR_NE(ts, NULL);
56 	ASSERT_LONG_EQ(ts->tv_nsec, 123 * 1000000);
57 	ASSERT_LONG_EQ(ts->tv_sec, 50);
58 	TEST_DONE();
59 
60 	TEST_START("ptimeout zero");
61 	ptimeout_init(&pt);
62 	ptimeout_deadline_ms(&pt, 0);
63 	ASSERT_INT_EQ(ptimeout_get_ms(&pt), 0);
64 	ts = ptimeout_get_tsp(&pt);
65 	ASSERT_PTR_NE(ts, NULL);
66 	ASSERT_LONG_EQ(ts->tv_nsec, 0);
67 	ASSERT_LONG_EQ(ts->tv_sec, 0);
68 	TEST_DONE();
69 
70 	TEST_START("ptimeout_deadline_monotime");
71 	ptimeout_init(&pt);
72 	ptimeout_deadline_monotime(&pt, monotime() + 100);
73 	ASSERT_INT_GT(ptimeout_get_ms(&pt), 50000);
74 	ASSERT_INT_LT(ptimeout_get_ms(&pt), 200000);
75 	ts = ptimeout_get_tsp(&pt);
76 	ASSERT_PTR_NE(ts, NULL);
77 	ASSERT_LONG_GT(ts->tv_sec, 50);
78 	ASSERT_LONG_LT(ts->tv_sec, 200);
79 	TEST_DONE();
80 
81 	TEST_START("ptimeout_deadline_monotime past");
82 	ptimeout_init(&pt);
83 	ptimeout_deadline_monotime(&pt, monotime() + 100);
84 	ptimeout_deadline_monotime(&pt, monotime() - 100);
85 	ASSERT_INT_EQ(ptimeout_get_ms(&pt), 0);
86 	ts = ptimeout_get_tsp(&pt);
87 	ASSERT_PTR_NE(ts, NULL);
88 	ASSERT_LONG_EQ(ts->tv_nsec, 0);
89 	ASSERT_LONG_EQ(ts->tv_sec, 0);
90 	TEST_DONE();
91 }
92