summaryrefslogtreecommitdiffstats
path: root/chrome/test/base/thread_observer_helper.h
blob: bbfc40f9e1d29ca269aa45725c7206193ecc75bc (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
// Copyright (c) 2011 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.

#ifndef CHROME_TEST_BASE_THREAD_OBSERVER_HELPER_H_
#define CHROME_TEST_BASE_THREAD_OBSERVER_HELPER_H_
#pragma once

#include "base/memory/ref_counted.h"
#include "base/synchronization/waitable_event.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_registrar.h"
#include "content/test/notification_observer_mock.h"

// Helper class to add and remove observers on a non-UI thread from
// the UI thread.
template <class T, typename Traits>
class ThreadObserverHelper : public base::RefCountedThreadSafe<T, Traits> {
 public:
  explicit ThreadObserverHelper(content::BrowserThread::ID id)
      : id_(id), done_event_(false, false) {}

  void Init() {
    using content::BrowserThread;
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    BrowserThread::PostTask(
        id_,
        FROM_HERE,
        NewRunnableMethod(this, &ThreadObserverHelper::RegisterObserversTask));
    done_event_.Wait();
  }

  virtual ~ThreadObserverHelper() {
    DCHECK(content::BrowserThread::CurrentlyOn(id_));
    registrar_.RemoveAll();
  }

  content::NotificationObserverMock* observer() {
    return &observer_;
  }

 protected:
  friend class base::RefCountedThreadSafe<T>;

  virtual void RegisterObservers() = 0;

  content::NotificationRegistrar registrar_;
  content::NotificationObserverMock observer_;

 private:
  void RegisterObserversTask() {
    DCHECK(content::BrowserThread::CurrentlyOn(id_));
    RegisterObservers();
    done_event_.Signal();
  }

  content::BrowserThread::ID id_;
  base::WaitableEvent done_event_;
};

class DBThreadObserverHelper;
typedef ThreadObserverHelper<
    DBThreadObserverHelper,
    content::BrowserThread::DeleteOnDBThread> DBThreadObserverHelperBase;

class DBThreadObserverHelper : public DBThreadObserverHelperBase {
 public:
  DBThreadObserverHelper() :
      DBThreadObserverHelperBase(content::BrowserThread::DB) {}
};

#endif  // CHROME_TEST_BASE_THREAD_OBSERVER_HELPER_H_