aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/threading/task_scheduler/task_scheduler_ut.cpp
blob: 2223dce65074cbb0ce6cb065def3581c3dfe5588 (plain) (blame)
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
85
86
#include <algorithm>
#include <library/cpp/testing/unittest/registar.h>

#include <util/stream/output.h>
#include <util/system/atomic.h>
#include <util/generic/vector.h>

#include "task_scheduler.h"

class TTaskSchedulerTest: public TTestBase {
        UNIT_TEST_SUITE(TTaskSchedulerTest);
            UNIT_TEST(Test);
        UNIT_TEST_SUITE_END();

        class TCheckTask: public TTaskScheduler::IRepeatedTask {
            public:
                TCheckTask(const TDuration& delay) 
                    : Start_(Now()) 
                    , Delay_(delay) 
                {
                    AtomicIncrement(ScheduledTaskCounter_);
                }

                ~TCheckTask() override {
                }

                bool Process() override {
                    const TDuration delay = Now() - Start_; 

                    if (delay < Delay_) { 
                        AtomicIncrement(BadTimeoutCounter_);
                    }

                    AtomicIncrement(ExecutedTaskCounter_);
 
                    return false; 
                }

                static bool AllTaskExecuted() {
                    return AtomicGet(ScheduledTaskCounter_) == AtomicGet(ExecutedTaskCounter_);
                }

                static size_t BadTimeoutCount() {
                    return AtomicGet(BadTimeoutCounter_);
                }

            private:
                TInstant Start_; 
                TDuration Delay_; 
                static TAtomic BadTimeoutCounter_;
                static TAtomic ScheduledTaskCounter_;
                static TAtomic ExecutedTaskCounter_;
        };

    public:
        inline void Test() {
            ScheduleCheckTask(200);
            ScheduleCheckTask(100);
            ScheduleCheckTask(1000);
            ScheduleCheckTask(10000);
            ScheduleCheckTask(5000);

            Scheduler_.Start(); 

            usleep(1000000);

            UNIT_ASSERT_EQUAL(TCheckTask::BadTimeoutCount(), 0);
            UNIT_ASSERT(TCheckTask::AllTaskExecuted());
        }

    private:
        void ScheduleCheckTask(size_t delay) {
            TDuration d = TDuration::MicroSeconds(delay); 
 
            Scheduler_.Add(new TCheckTask(d), d);
        }

    private:
        TTaskScheduler Scheduler_;
};

TAtomic TTaskSchedulerTest::TCheckTask::BadTimeoutCounter_ = 0;
TAtomic TTaskSchedulerTest::TCheckTask::ScheduledTaskCounter_ = 0;
TAtomic TTaskSchedulerTest::TCheckTask::ExecutedTaskCounter_ = 0;

UNIT_TEST_SUITE_REGISTRATION(TTaskSchedulerTest);