task_scheduler_ut.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <algorithm>
  2. #include <library/cpp/testing/unittest/registar.h>
  3. #include <util/stream/output.h>
  4. #include <library/cpp/deprecated/atomic/atomic.h>
  5. #include <util/generic/vector.h>
  6. #include "task_scheduler.h"
  7. class TTaskSchedulerTest: public TTestBase {
  8. UNIT_TEST_SUITE(TTaskSchedulerTest);
  9. UNIT_TEST(Test);
  10. UNIT_TEST_SUITE_END();
  11. class TCheckTask: public TTaskScheduler::IRepeatedTask {
  12. public:
  13. TCheckTask(const TDuration& delay)
  14. : Start_(Now())
  15. , Delay_(delay)
  16. {
  17. AtomicIncrement(ScheduledTaskCounter_);
  18. }
  19. ~TCheckTask() override {
  20. }
  21. bool Process() override {
  22. const TDuration delay = Now() - Start_;
  23. if (delay < Delay_) {
  24. AtomicIncrement(BadTimeoutCounter_);
  25. }
  26. AtomicIncrement(ExecutedTaskCounter_);
  27. return false;
  28. }
  29. static bool AllTaskExecuted() {
  30. return AtomicGet(ScheduledTaskCounter_) == AtomicGet(ExecutedTaskCounter_);
  31. }
  32. static size_t BadTimeoutCount() {
  33. return AtomicGet(BadTimeoutCounter_);
  34. }
  35. private:
  36. TInstant Start_;
  37. TDuration Delay_;
  38. static TAtomic BadTimeoutCounter_;
  39. static TAtomic ScheduledTaskCounter_;
  40. static TAtomic ExecutedTaskCounter_;
  41. };
  42. public:
  43. inline void Test() {
  44. ScheduleCheckTask(200);
  45. ScheduleCheckTask(100);
  46. ScheduleCheckTask(1000);
  47. ScheduleCheckTask(10000);
  48. ScheduleCheckTask(5000);
  49. Scheduler_.Start();
  50. usleep(1000000);
  51. UNIT_ASSERT_EQUAL(TCheckTask::BadTimeoutCount(), 0);
  52. UNIT_ASSERT(TCheckTask::AllTaskExecuted());
  53. }
  54. private:
  55. void ScheduleCheckTask(size_t delay) {
  56. TDuration d = TDuration::MicroSeconds(delay);
  57. Scheduler_.Add(new TCheckTask(d), d);
  58. }
  59. private:
  60. TTaskScheduler Scheduler_;
  61. };
  62. TAtomic TTaskSchedulerTest::TCheckTask::BadTimeoutCounter_ = 0;
  63. TAtomic TTaskSchedulerTest::TCheckTask::ScheduledTaskCounter_ = 0;
  64. TAtomic TTaskSchedulerTest::TCheckTask::ExecutedTaskCounter_ = 0;
  65. UNIT_TEST_SUITE_REGISTRATION(TTaskSchedulerTest);