1 // Copyright 2014 The Chromium 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 "base/timer/mock_timer.h"
6
7 #include "base/macros.h"
8 #include "testing/gtest/include/gtest/gtest.h"
9
10 namespace {
11
CallMeMaybe(int * number)12 void CallMeMaybe(int *number) {
13 (*number)++;
14 }
15
TEST(MockTimerTest,FiresOnce)16 TEST(MockTimerTest, FiresOnce) {
17 int calls = 0;
18 base::MockOneShotTimer timer;
19 base::TimeDelta delay = base::TimeDelta::FromSeconds(2);
20 timer.Start(FROM_HERE, delay,
21 base::Bind(&CallMeMaybe,
22 base::Unretained(&calls)));
23 EXPECT_EQ(delay, timer.GetCurrentDelay());
24 EXPECT_TRUE(timer.IsRunning());
25 timer.Fire();
26 EXPECT_FALSE(timer.IsRunning());
27 EXPECT_EQ(1, calls);
28 }
29
TEST(MockTimerTest,FiresRepeatedly)30 TEST(MockTimerTest, FiresRepeatedly) {
31 int calls = 0;
32 base::MockRepeatingTimer timer;
33 base::TimeDelta delay = base::TimeDelta::FromSeconds(2);
34 timer.Start(FROM_HERE, delay,
35 base::Bind(&CallMeMaybe,
36 base::Unretained(&calls)));
37 timer.Fire();
38 EXPECT_TRUE(timer.IsRunning());
39 timer.Fire();
40 timer.Fire();
41 EXPECT_TRUE(timer.IsRunning());
42 EXPECT_EQ(3, calls);
43 }
44
TEST(MockTimerTest,Stops)45 TEST(MockTimerTest, Stops) {
46 int calls = 0;
47 base::MockRepeatingTimer timer;
48 base::TimeDelta delay = base::TimeDelta::FromSeconds(2);
49 timer.Start(FROM_HERE, delay,
50 base::Bind(&CallMeMaybe,
51 base::Unretained(&calls)));
52 EXPECT_TRUE(timer.IsRunning());
53 timer.Stop();
54 EXPECT_FALSE(timer.IsRunning());
55 }
56
57 class HasWeakPtr : public base::SupportsWeakPtr<HasWeakPtr> {
58 public:
59 HasWeakPtr() = default;
60 virtual ~HasWeakPtr() = default;
61
62 private:
63 DISALLOW_COPY_AND_ASSIGN(HasWeakPtr);
64 };
65
TEST(MockTimerTest,DoesNotRetainClosure)66 TEST(MockTimerTest, DoesNotRetainClosure) {
67 HasWeakPtr *has_weak_ptr = new HasWeakPtr();
68 base::WeakPtr<HasWeakPtr> weak_ptr(has_weak_ptr->AsWeakPtr());
69 base::MockOneShotTimer timer;
70 base::TimeDelta delay = base::TimeDelta::FromSeconds(2);
71 ASSERT_TRUE(weak_ptr.get());
72 timer.Start(FROM_HERE, delay,
73 base::Bind(base::DoNothing::Repeatedly<HasWeakPtr*>(),
74 base::Owned(has_weak_ptr)));
75 ASSERT_TRUE(weak_ptr.get());
76 timer.Fire();
77 ASSERT_FALSE(weak_ptr.get());
78 }
79
80 } // namespace
81