summaryrefslogtreecommitdiffstats
path: root/webkit/browser/fileapi/timed_task_helper_unittest.cc
blob: 5621135253d7e08d172d7443feb11d33ce536db4 (plain)
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
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/browser/fileapi/timed_task_helper.h"

namespace fileapi {

namespace {

class Embedder {
 public:
  Embedder()
      : timer_(base::MessageLoopProxy::current().get()), timer_fired_(false) {}

  void OnTimerFired() {
    timer_fired_ = true;
  }

  TimedTaskHelper* timer() { return &timer_; }
  bool timer_fired() const { return timer_fired_; }

 private:
  TimedTaskHelper timer_;
  bool timer_fired_;
};

}  // namespace

TEST(TimedTaskHelper, FireTimerWhenAlive) {
  base::MessageLoop message_loop;
  Embedder embedder;

  ASSERT_FALSE(embedder.timer_fired());
  ASSERT_FALSE(embedder.timer()->IsRunning());

  embedder.timer()->Start(
      FROM_HERE,
      base::TimeDelta::FromSeconds(0),
      base::Bind(&Embedder::OnTimerFired, base::Unretained(&embedder)));

  ASSERT_TRUE(embedder.timer()->IsRunning());
  embedder.timer()->Reset();
  ASSERT_TRUE(embedder.timer()->IsRunning());

  base::MessageLoop::current()->RunUntilIdle();

  ASSERT_TRUE(embedder.timer_fired());
}

TEST(TimedTaskHelper, FireTimerWhenAlreadyDeleted) {
  base::MessageLoop message_loop;

  // Run message loop after embedder is already deleted to make sure callback
  // doesn't cause a crash for use after free.
  {
    Embedder embedder;

    ASSERT_FALSE(embedder.timer_fired());
    ASSERT_FALSE(embedder.timer()->IsRunning());

    embedder.timer()->Start(
        FROM_HERE,
        base::TimeDelta::FromSeconds(0),
        base::Bind(&Embedder::OnTimerFired, base::Unretained(&embedder)));

    ASSERT_TRUE(embedder.timer()->IsRunning());
  }

  // At this point the callback is still in the message queue but
  // embedder is gone.
  base::MessageLoop::current()->RunUntilIdle();
}

}  // namespace fileapi