• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "core/fxcrt/cfx_timer.h"
6 
7 #include <memory>
8 
9 #include "core/fxcrt/timerhandler_iface.h"
10 #include "testing/gmock/include/gmock/gmock.h"
11 #include "testing/gtest/include/gtest/gtest.h"
12 #include "third_party/base/ptr_util.h"
13 
14 using testing::_;
15 using testing::DoAll;
16 using testing::Return;
17 using testing::SaveArg;
18 
19 class MockTimerScheduler : public TimerHandlerIface {
20  public:
21   MOCK_METHOD2(SetTimer, int(int32_t uElapse, TimerCallback lpTimerFunc));
22   MOCK_METHOD1(KillTimer, void(int32_t nID));
23 };
24 
25 class MockTimerCallback : public CFX_Timer::CallbackIface {
26  public:
27   MOCK_METHOD0(OnTimerFired, void());
28 };
29 
TEST(CFX_Timer,ValidTimers)30 TEST(CFX_Timer, ValidTimers) {
31   TimerHandlerIface::TimerCallback fn1 = nullptr;
32   TimerHandlerIface::TimerCallback fn2 = nullptr;
33 
34   MockTimerScheduler scheduler;
35   EXPECT_CALL(scheduler, SetTimer(100, _))
36       .WillOnce(DoAll(SaveArg<1>(&fn1), Return(1001)));
37   EXPECT_CALL(scheduler, SetTimer(200, _))
38       .WillOnce(DoAll(SaveArg<1>(&fn2), Return(1002)));
39   EXPECT_CALL(scheduler, KillTimer(1001));
40   EXPECT_CALL(scheduler, KillTimer(1002));
41 
42   MockTimerCallback cb1;
43   EXPECT_CALL(cb1, OnTimerFired()).Times(1);
44 
45   MockTimerCallback cb2;
46   EXPECT_CALL(cb2, OnTimerFired()).Times(2);
47 
48   auto timer1 = pdfium::MakeUnique<CFX_Timer>(&scheduler, &cb1, 100);
49   auto timer2 = pdfium::MakeUnique<CFX_Timer>(&scheduler, &cb2, 200);
50   EXPECT_TRUE(timer1->HasValidID());
51   EXPECT_TRUE(timer2->HasValidID());
52 
53   // Fire some timers.
54   ASSERT_TRUE(fn1);
55   ASSERT_TRUE(fn2);
56   (*fn1)(1001);
57   (*fn1)(1002);
58   (*fn1)(1002);
59 }
60 
TEST(CFX_Timer,MisbehavingEmbedder)61 TEST(CFX_Timer, MisbehavingEmbedder) {
62   TimerHandlerIface::TimerCallback fn1 = nullptr;
63 
64   MockTimerScheduler scheduler;
65   EXPECT_CALL(scheduler, SetTimer(100, _))
66       .WillOnce(DoAll(SaveArg<1>(&fn1), Return(1001)));
67   EXPECT_CALL(scheduler, KillTimer(1001));
68 
69   MockTimerCallback cb1;
70   EXPECT_CALL(cb1, OnTimerFired()).Times(0);
71 
72   {
73     auto timer1 = pdfium::MakeUnique<CFX_Timer>(&scheduler, &cb1, 100);
74     EXPECT_TRUE(timer1->HasValidID());
75 
76     // Fire callback with bad arguments.
77     ASSERT_TRUE(fn1);
78     (*fn1)(-1);
79     (*fn1)(0);
80     (*fn1)(1002);
81   }
82 
83   // Fire callback against stale timer.
84   (*fn1)(1001);
85 }
86