forked from IronsDu/brynet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_timer.cpp
More file actions
84 lines (75 loc) · 2.01 KB
/
Copy pathtest_timer.cpp
File metadata and controls
84 lines (75 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#define CATCH_CONFIG_MAIN// This tells Catch to provide a main() - only do this in one cpp file
#include <brynet/base/Timer.hpp>
#include <brynet/base/WaitGroup.hpp>
#include <chrono>
#include <memory>
#include <thread>
#include "catch.hpp"
TEST_CASE("Timer are computed", "[timer]")
{
auto timerMgr = std::make_shared<brynet::base::TimerMgr>();
int upvalue = 0;
auto timer = timerMgr->addTimer(std::chrono::seconds(1), [&upvalue]() {
upvalue++;
});
std::function<void(void)> fuck;
bool testCancelFlag = false;
timer = timerMgr->addTimer(std::chrono::seconds(1), [&upvalue, &fuck]() {
fuck();
upvalue++;
});
fuck = [&]() {
auto t = timer.lock();
if (t != nullptr)
{
t->cancel();
testCancelFlag = true;
}
};
auto leftTime = timerMgr->nearLeftTime();
REQUIRE_FALSE(leftTime > std::chrono::seconds(1));
REQUIRE(timerMgr->isEmpty() == false);
while (!timerMgr->isEmpty())
{
timerMgr->schedule();
}
REQUIRE(upvalue == 2);
REQUIRE(testCancelFlag);
timer = timerMgr->addTimer(std::chrono::seconds(1), [&upvalue]() {
upvalue++;
});
timer.lock()->cancel();
REQUIRE(timerMgr->isEmpty() == false);
while (!timerMgr->isEmpty())
{
timerMgr->schedule();
}
REQUIRE(upvalue == 2);
}
TEST_CASE("repeat timer are computed", "[repeat timer]")
{
auto timerMgr = std::make_shared<brynet::base::TimerMgr>();
auto wg = brynet::base::WaitGroup::Create();
wg->add(1);
std::atomic_int value = ATOMIC_VAR_INIT(0);
auto timer = timerMgr->addIntervalTimer(std::chrono::milliseconds(100), [&]() {
if (value.load() < 10)
{
value.fetch_add(1);
}
else
{
wg->done();
}
});
std::thread t([&]() {
wg->wait();
timer->cancel();
});
while (!timerMgr->isEmpty())
{
timerMgr->schedule();
}
t.join();
REQUIRE(value.load() == 10);
}