testing_profile.h revision a36e5920737c6adbddd3e43b760e5de8431db6e0
1// Copyright (c) 2012 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#ifndef CHROME_TEST_BASE_TESTING_PROFILE_H_
6#define CHROME_TEST_BASE_TESTING_PROFILE_H_
7
8#include <string>
9
10#include "base/files/scoped_temp_dir.h"
11#include "base/memory/ref_counted.h"
12#include "base/memory/scoped_ptr.h"
13#include "chrome/browser/profiles/profile.h"
14
15namespace content {
16class MockResourceContext;
17}
18
19namespace extensions {
20class ExtensionPrefs;
21}
22
23namespace history {
24class TopSites;
25}
26
27namespace net {
28class CookieMonster;
29class URLRequestContextGetter;
30}
31
32namespace policy {
33class ProfilePolicyConnector;
34}
35
36namespace quota {
37class SpecialStoragePolicy;
38}
39
40class BrowserContextDependencyManager;
41class CommandLine;
42class ExtensionSpecialStoragePolicy;
43class HostContentSettingsMap;
44class PrefServiceSyncable;
45class ProfileSyncService;
46class TemplateURLService;
47class TestingPrefServiceSyncable;
48
49class TestingProfile : public Profile {
50 public:
51  // Profile directory name for the test user. This is "Default" on most
52  // platforms but must be different on ChromeOS because a logged-in user cannot
53  // use "Default" as profile directory.
54  // Browser- and UI tests should always use this to get to the user's profile
55  // directory. Unit-tests, though, should use |kInitialProfile|, which is
56  // always "Default", because they are runnining without logged-in user.
57  static const char kTestUserProfileDir[];
58
59  // Default constructor that cannot be used with multi-profiles.
60  TestingProfile();
61
62  // Helper class for building an instance of TestingProfile (allows injecting
63  // mocks for various services prior to profile initialization).
64  // TODO(atwilson): Remove non-default constructors and various setters in
65  // favor of using the Builder API.
66  class Builder {
67   public:
68    Builder();
69    ~Builder();
70
71    // Sets a Delegate to be called back when the Profile is fully initialized.
72    // This causes the final initialization to be performed via a task so the
73    // caller must run a MessageLoop. Caller maintains ownership of the Delegate
74    // and must manage its lifetime so it continues to exist until profile
75    // initialization is complete.
76    void SetDelegate(Delegate* delegate);
77
78    // Sets the ExtensionSpecialStoragePolicy to be returned by
79    // GetExtensionSpecialStoragePolicy().
80    void SetExtensionSpecialStoragePolicy(
81        scoped_refptr<ExtensionSpecialStoragePolicy> policy);
82
83    // Sets the path to the directory to be used to hold profile data.
84    void SetPath(const base::FilePath& path);
85
86    // Sets the PrefService to be used by this profile.
87    void SetPrefService(scoped_ptr<PrefServiceSyncable> prefs);
88
89    // Creates the TestingProfile using previously-set settings.
90    scoped_ptr<TestingProfile> Build();
91
92   private:
93    // If true, Build() has already been called.
94    bool build_called_;
95
96    // Various staging variables where values are held until Build() is invoked.
97    scoped_ptr<PrefServiceSyncable> pref_service_;
98    scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy_;
99    base::FilePath path_;
100    Delegate* delegate_;
101
102    DISALLOW_COPY_AND_ASSIGN(Builder);
103  };
104
105  // Multi-profile aware constructor that takes the path to a directory managed
106  // for this profile. This constructor is meant to be used by
107  // TestingProfileManager::CreateTestingProfile. If you need to create multi-
108  // profile profiles, use that factory method instead of this directly.
109  // Exception: if you need to create multi-profile profiles for testing the
110  // ProfileManager, then use the constructor below instead.
111  explicit TestingProfile(const base::FilePath& path);
112
113  // Multi-profile aware constructor that takes the path to a directory managed
114  // for this profile and a delegate. This constructor is meant to be used
115  // for unittesting the ProfileManager.
116  TestingProfile(const base::FilePath& path, Delegate* delegate);
117
118  // Full constructor allowing the setting of all possible instance data.
119  // Callers should use Builder::Build() instead of invoking this constructor.
120  TestingProfile(const base::FilePath& path,
121                 Delegate* delegate,
122                 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
123                 scoped_ptr<PrefServiceSyncable> prefs);
124
125  virtual ~TestingProfile();
126
127  // Creates the favicon service. Consequent calls would recreate the service.
128  void CreateFaviconService();
129
130  // Creates the history service. If |delete_file| is true, the history file is
131  // deleted first, then the HistoryService is created. As TestingProfile
132  // deletes the directory containing the files used by HistoryService, this
133  // only matters if you're recreating the HistoryService.  If |no_db| is true,
134  // the history backend will fail to initialize its database; this is useful
135  // for testing error conditions. Returns true on success.
136  bool CreateHistoryService(bool delete_file, bool no_db) WARN_UNUSED_RESULT;
137
138  // Shuts down and nulls out the reference to HistoryService.
139  void DestroyHistoryService();
140
141  // Creates TopSites. This returns immediately, and top sites may not be
142  // loaded. Use BlockUntilTopSitesLoaded to ensure TopSites has finished
143  // loading.
144  void CreateTopSites();
145
146  // Shuts down and nulls out the reference to TopSites.
147  void DestroyTopSites();
148
149  // Creates the BookmkarBarModel. If not invoked the bookmark bar model is
150  // NULL. If |delete_file| is true, the bookmarks file is deleted first, then
151  // the model is created. As TestingProfile deletes the directory containing
152  // the files used by HistoryService, the boolean only matters if you're
153  // recreating the BookmarkModel.
154  //
155  // NOTE: this does not block until the bookmarks are loaded. For that use
156  // ui_test_utils::WaitForBookmarkModelToLoad.
157  void CreateBookmarkModel(bool delete_file);
158
159  // Creates a WebDataService. If not invoked, the web data service is NULL.
160  void CreateWebDataService();
161
162  // Blocks until the HistoryService finishes restoring its in-memory cache.
163  // This is NOT invoked from CreateHistoryService.
164  void BlockUntilHistoryIndexIsRefreshed();
165
166  // Blocks until TopSites finishes loading.
167  void BlockUntilTopSitesLoaded();
168
169  TestingPrefServiceSyncable* GetTestingPrefService();
170
171  // content::BrowserContext
172  virtual base::FilePath GetPath() const OVERRIDE;
173  virtual scoped_refptr<base::SequencedTaskRunner> GetIOTaskRunner() OVERRIDE;
174  virtual bool IsOffTheRecord() const OVERRIDE;
175  virtual content::DownloadManagerDelegate*
176      GetDownloadManagerDelegate() OVERRIDE;
177  virtual net::URLRequestContextGetter* GetRequestContext() OVERRIDE;
178  virtual net::URLRequestContextGetter* CreateRequestContext(
179      content::ProtocolHandlerMap* protocol_handlers) OVERRIDE;
180  virtual net::URLRequestContextGetter* GetRequestContextForRenderProcess(
181      int renderer_child_id) OVERRIDE;
182  virtual content::ResourceContext* GetResourceContext() OVERRIDE;
183  virtual content::GeolocationPermissionContext*
184      GetGeolocationPermissionContext() OVERRIDE;
185  virtual quota::SpecialStoragePolicy* GetSpecialStoragePolicy() OVERRIDE;
186
187  virtual TestingProfile* AsTestingProfile() OVERRIDE;
188  virtual std::string GetProfileName() OVERRIDE;
189  void set_incognito(bool incognito) { incognito_ = incognito; }
190  // Assumes ownership.
191  virtual void SetOffTheRecordProfile(Profile* profile);
192  virtual void SetOriginalProfile(Profile* profile);
193  virtual Profile* GetOffTheRecordProfile() OVERRIDE;
194  virtual void DestroyOffTheRecordProfile() OVERRIDE {}
195  virtual bool HasOffTheRecordProfile() OVERRIDE;
196  virtual Profile* GetOriginalProfile() OVERRIDE;
197  virtual bool IsManaged() OVERRIDE;
198  virtual ExtensionService* GetExtensionService() OVERRIDE;
199  void SetExtensionSpecialStoragePolicy(
200      ExtensionSpecialStoragePolicy* extension_special_storage_policy);
201  virtual ExtensionSpecialStoragePolicy*
202      GetExtensionSpecialStoragePolicy() OVERRIDE;
203  // TODO(ajwong): Remove this API in favor of directly retrieving the
204  // CookieStore from the StoragePartition after ExtensionURLRequestContext
205  // has been removed.
206  net::CookieMonster* GetCookieMonster();
207
208  virtual PrefService* GetPrefs() OVERRIDE;
209
210  virtual history::TopSites* GetTopSites() OVERRIDE;
211  virtual history::TopSites* GetTopSitesWithoutCreating() OVERRIDE;
212
213  virtual net::URLRequestContextGetter* GetMediaRequestContext() OVERRIDE;
214  virtual net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess(
215      int renderer_child_id) OVERRIDE;
216  virtual net::URLRequestContextGetter*
217      GetRequestContextForExtensions() OVERRIDE;
218  virtual net::URLRequestContextGetter*
219      GetMediaRequestContextForStoragePartition(
220          const base::FilePath& partition_path,
221          bool in_memory) OVERRIDE;
222  virtual void RequestMIDISysExPermission(
223      int render_process_id,
224      int render_view_id,
225      const GURL& requesting_frame,
226      const MIDISysExPermissionCallback& callback) OVERRIDE;
227  virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
228      const base::FilePath& partition_path,
229      bool in_memory,
230      content::ProtocolHandlerMap* protocol_handlers) OVERRIDE;
231  virtual net::SSLConfigService* GetSSLConfigService() OVERRIDE;
232  virtual HostContentSettingsMap* GetHostContentSettingsMap() OVERRIDE;
233  virtual std::wstring GetName();
234  virtual void SetName(const std::wstring& name) {}
235  virtual std::wstring GetID();
236  virtual void SetID(const std::wstring& id);
237  void set_last_session_exited_cleanly(bool value) {
238    last_session_exited_cleanly_ = value;
239  }
240  virtual void MergeResourceString(int message_id,
241                                   std::wstring* output_string) {}
242  virtual void MergeResourceInteger(int message_id, int* output_value) {}
243  virtual void MergeResourceBoolean(int message_id, bool* output_value) {}
244  virtual bool IsSameProfile(Profile *p) OVERRIDE;
245  virtual base::Time GetStartTime() const OVERRIDE;
246  virtual base::FilePath last_selected_directory() OVERRIDE;
247  virtual void set_last_selected_directory(const base::FilePath& path) OVERRIDE;
248  virtual bool WasCreatedByVersionOrLater(const std::string& version) OVERRIDE;
249  virtual bool IsGuestSession() const OVERRIDE;
250  virtual void SetExitType(ExitType exit_type) OVERRIDE {}
251  virtual ExitType GetLastSessionExitType() OVERRIDE;
252#if defined(OS_CHROMEOS)
253  virtual void SetupChromeOSEnterpriseExtensionObserver() OVERRIDE {
254  }
255  virtual void InitChromeOSPreferences() OVERRIDE {
256  }
257  virtual void ChangeAppLocale(const std::string&,
258                               AppLocaleChangedVia) OVERRIDE {
259  }
260  virtual void OnLogin() OVERRIDE {
261  }
262#endif  // defined(OS_CHROMEOS)
263
264  virtual PrefProxyConfigTracker* GetProxyConfigTracker() OVERRIDE;
265
266  // Schedules a task on the history backend and runs a nested loop until the
267  // task is processed.  This has the effect of blocking the caller until the
268  // history service processes all pending requests.
269  void BlockUntilHistoryProcessesPendingRequests();
270
271  virtual chrome_browser_net::Predictor* GetNetworkPredictor() OVERRIDE;
272  virtual void ClearNetworkingHistorySince(
273      base::Time time,
274      const base::Closure& completion) OVERRIDE;
275  virtual GURL GetHomePage() OVERRIDE;
276
277  virtual PrefService* GetOffTheRecordPrefs() OVERRIDE;
278
279 protected:
280  base::Time start_time_;
281  scoped_ptr<PrefServiceSyncable> prefs_;
282  // ref only for right type, lifecycle is managed by prefs_
283  TestingPrefServiceSyncable* testing_prefs_;
284
285 private:
286  // Creates a temporary directory for use by this profile.
287  void CreateTempProfileDir();
288
289  // Common initialization between the two constructors.
290  void Init();
291
292  // Finishes initialization when a profile is created asynchronously.
293  void FinishInit();
294
295  // Creates a TestingPrefService and associates it with the TestingProfile.
296  void CreateTestingPrefService();
297
298  // Creates a ProfilePolicyConnector that the ProfilePolicyConnectorFactory
299  // maps to this profile.
300  void CreateProfilePolicyConnector();
301
302  // Internally, this is a TestURLRequestContextGetter that creates a dummy
303  // request context. Currently, only the CookieMonster is hooked up.
304  scoped_refptr<net::URLRequestContextGetter> extensions_request_context_;
305
306  std::wstring id_;
307
308  bool incognito_;
309  scoped_ptr<Profile> incognito_profile_;
310  Profile* original_profile_;
311
312  // Did the last session exit cleanly? Default is true.
313  bool last_session_exited_cleanly_;
314
315  scoped_refptr<HostContentSettingsMap> host_content_settings_map_;
316
317  base::FilePath last_selected_directory_;
318  scoped_refptr<history::TopSites> top_sites_;  // For history and thumbnails.
319
320  scoped_refptr<ExtensionSpecialStoragePolicy>
321      extension_special_storage_policy_;
322
323  // The proxy prefs tracker.
324  scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_;
325
326  // We use a temporary directory to store testing profile data. In a multi-
327  // profile environment, this is invalid and the directory is managed by the
328  // TestingProfileManager.
329  base::ScopedTempDir temp_dir_;
330  // The path to this profile. This will be valid in either of the two above
331  // cases.
332  base::FilePath profile_path_;
333
334  // We keep a weak pointer to the dependency manager we want to notify on our
335  // death. Defaults to the Singleton implementation but overridable for
336  // testing.
337  BrowserContextDependencyManager* browser_context_dependency_manager_;
338
339  // Owned, but must be deleted on the IO thread so not placing in a
340  // scoped_ptr<>.
341  content::MockResourceContext* resource_context_;
342
343  scoped_ptr<policy::ProfilePolicyConnector> profile_policy_connector_;
344
345  // Weak pointer to a delegate for indicating that a profile was created.
346  Delegate* delegate_;
347};
348
349#endif  // CHROME_TEST_BASE_TESTING_PROFILE_H_
350