1 /*
2 * nghttp2 - HTTP/2 C Library
3 *
4 * Copyright (c) 2023 nghttp2 contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25 #include "nghttp2_ratelim_test.h"
26
27 #include <stdio.h>
28
29 #include <CUnit/CUnit.h>
30
31 #include "nghttp2_ratelim.h"
32
test_nghttp2_ratelim_update(void)33 void test_nghttp2_ratelim_update(void) {
34 nghttp2_ratelim rl;
35
36 nghttp2_ratelim_init(&rl, 1000, 21);
37
38 CU_ASSERT(1000 == rl.val);
39 CU_ASSERT(1000 == rl.burst);
40 CU_ASSERT(21 == rl.rate);
41 CU_ASSERT(0 == rl.tstamp);
42
43 nghttp2_ratelim_update(&rl, 999);
44
45 CU_ASSERT(1000 == rl.val);
46 CU_ASSERT(999 == rl.tstamp);
47
48 nghttp2_ratelim_drain(&rl, 100);
49
50 CU_ASSERT(900 == rl.val);
51
52 nghttp2_ratelim_update(&rl, 1000);
53
54 CU_ASSERT(921 == rl.val);
55
56 nghttp2_ratelim_update(&rl, 1002);
57
58 CU_ASSERT(963 == rl.val);
59
60 nghttp2_ratelim_update(&rl, 1004);
61
62 CU_ASSERT(1000 == rl.val);
63 CU_ASSERT(1004 == rl.tstamp);
64
65 /* timer skew */
66 nghttp2_ratelim_init(&rl, 1000, 21);
67 nghttp2_ratelim_update(&rl, 1);
68
69 CU_ASSERT(1000 == rl.val);
70
71 nghttp2_ratelim_update(&rl, 0);
72
73 CU_ASSERT(1000 == rl.val);
74
75 /* rate * duration overflow */
76 nghttp2_ratelim_init(&rl, 1000, 100);
77 nghttp2_ratelim_drain(&rl, 999);
78
79 CU_ASSERT(1 == rl.val);
80
81 nghttp2_ratelim_update(&rl, UINT64_MAX);
82
83 CU_ASSERT(1000 == rl.val);
84
85 /* val + rate * duration overflow */
86 nghttp2_ratelim_init(&rl, UINT64_MAX - 1, 2);
87 nghttp2_ratelim_update(&rl, 1);
88
89 CU_ASSERT(UINT64_MAX - 1 == rl.val);
90 }
91
test_nghttp2_ratelim_drain(void)92 void test_nghttp2_ratelim_drain(void) {
93 nghttp2_ratelim rl;
94
95 nghttp2_ratelim_init(&rl, 100, 7);
96
97 CU_ASSERT(-1 == nghttp2_ratelim_drain(&rl, 101));
98 CU_ASSERT(0 == nghttp2_ratelim_drain(&rl, 51));
99 CU_ASSERT(0 == nghttp2_ratelim_drain(&rl, 49));
100 CU_ASSERT(-1 == nghttp2_ratelim_drain(&rl, 1));
101 }
102