Toolbox snapshot
The Reactive C++ Toolbox
Loading...
Searching...
No Matches
RateLimit.ut.cpp
Go to the documentation of this file.
1// The Reactive C++ Toolbox.
2// Copyright (C) 2021 Reactive Markets Limited
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#include "RateLimit.hpp"
17
19
20#include <boost/test/unit_test.hpp>
21
22using namespace std;
23using namespace toolbox;
24
26
28{
30 const auto rl = from_string<RateLimit>("3/5");
31 BOOST_CHECK_EQUAL(rl.limit(), 3);
32 BOOST_CHECK_EQUAL(rl.interval().count(), 50);
33}
34
36{
37 const auto t = MonoClock::now();
38
39 RateWindow rw{1s};
40 BOOST_CHECK_EQUAL(rw.count(), 0);
41
42 rw.add(t + 0s, 1);
43 BOOST_CHECK_EQUAL(rw.count(), 1);
44 rw.add(t + 100ms, 2);
45 BOOST_CHECK_EQUAL(rw.count(), 3);
46 // The first bucket is cleaned.
47 rw.add(t + 1s, 1);
48 BOOST_CHECK_EQUAL(rw.count(), 3);
49 rw.add(t + 1100ms, 1);
50 BOOST_CHECK_EQUAL(rw.count(), 2);
51 rw.add(t + 2s, 2);
52 BOOST_CHECK_EQUAL(rw.count(), 3);
53 rw.add(t + 3s, 3);
54 BOOST_CHECK_EQUAL(rw.count(), 3);
55
56 rw = RateWindow{5s};
57 BOOST_CHECK_EQUAL(rw.count(), 0);
58
59 rw.add(t + 0s, 1);
60 BOOST_CHECK_EQUAL(rw.count(), 1);
61 rw.add(t + 1s, 2);
62 BOOST_CHECK_EQUAL(rw.count(), 3);
63 rw.add(t + 2s, 3);
64 BOOST_CHECK_EQUAL(rw.count(), 6);
65 rw.add(t + 3s, 4);
66 BOOST_CHECK_EQUAL(rw.count(), 10);
67 rw.add(t + 4s, 5);
68 BOOST_CHECK_EQUAL(rw.count(), 15);
69
70 // Circular buffer wraps and replaces first entry.
71 rw.add(t + 5s, 6);
72 BOOST_CHECK_EQUAL(rw.count(), 20);
73
74 // Skip two entries entirely.
75 rw.add(t + 8s, 7);
76 BOOST_CHECK_EQUAL(rw.count(), 18);
77
78 // Skip every entry in the buffer.
79 rw.add(t + 13s, 8);
80 BOOST_CHECK_EQUAL(rw.count(), 8);
81}
82
BOOST_CHECK_EQUAL(v.size(), 10U)
BOOST_AUTO_TEST_CASE(RateLimitCase)
RateWindow maintains a sliding window of second time buckets for the specified interval.
Definition RateLimit.hpp:60
STL namespace.
std::string to_string(ValueT &&val)
Definition String.hpp:54
constexpr auto bind() noexcept
Definition Slot.hpp:92