testing_profile.h revision bbcdd45c55eb7c4641ab97aef9889b0fc828e7d3
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 ExtensionService* GetExtensionService() OVERRIDE;
198  void SetExtensionSpecialStoragePolicy(
199      ExtensionSpecialStoragePolicy* extension_special_storage_policy);
200  virtual ExtensionSpecialStoragePolicy*
201      GetExtensionSpecialStoragePolicy() OVERRIDE;
202  // TODO(ajwong): Remove this API in favor of directly retrieving the
203  // CookieStore from the StoragePartition after ExtensionURLRequestContext
204  // has been removed.
205  net::CookieMonster* GetCookieMonster();
206
207  virtual PrefService* GetPrefs() OVERRIDE;
208
209  virtual history::TopSites* GetTopSites() OVERRIDE;
210  virtual history::TopSites* GetTopSitesWithoutCreating() OVERRIDE;
211
212  virtual net::URLRequestContextGetter* GetMediaRequestContext() OVERRIDE;
213  virtual net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess(
214      int renderer_child_id) OVERRIDE;
215  virtual net::URLRequestContextGetter*
216      GetRequestContextForExtensions() OVERRIDE;
217  virtual net::URLRequestContextGetter*
218      GetMediaRequestContextForStoragePartition(
219          const base::FilePath& partition_path,
220          bool in_memory) OVERRIDE;
221  virtual void RequestMIDISysExPermission(
222      int render_process_id,
223      int render_view_id,
224      const GURL& requesting_frame,
225      const MIDISysExPermissionCallback& callback) OVERRIDE;
226  virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
227      const base::FilePath& partition_path,
228      bool in_memory,
229      content::ProtocolHandlerMap* protocol_handlers) OVERRIDE;
230  virtual net::SSLConfigService* GetSSLConfigService() OVERRIDE;
231  virtual HostContentSettingsMap* GetHostContentSettingsMap() OVERRIDE;
232  virtual std::wstring GetName();
233  virtual void SetName(const std::wstring& name) {}
234  virtual std::wstring GetID();
235  virtual void SetID(const std::wstring& id);
236  void set_last_session_exited_cleanly(bool value) {
237    last_session_exited_cleanly_ = value;
238  }
239  virtual void MergeResourceString(int message_id,
240                                   std::wstring* output_string) {}
241  virtual void MergeResourceInteger(int message_id, int* output_value) {}
242  virtual void MergeResourceBoolean(int message_id, bool* output_value) {}
243  virtual bool IsSameProfile(Profile *p) OVERRIDE;
244  virtual base::Time GetStartTime() const OVERRIDE;
245  virtual base::FilePath last_selected_directory() OVERRIDE;
246  virtual void set_last_selected_directory(const base::FilePath& path) OVERRIDE;
247  virtual bool WasCreatedByVersionOrLater(const std::string& version) OVERRIDE;
248  virtual bool IsGuestSession() const OVERRIDE;
249  virtual void SetExitType(ExitType exit_type) OVERRIDE {}
250  virtual ExitType GetLastSessionExitType() OVERRIDE;
251#if defined(OS_CHROMEOS)
252  virtual void SetupChromeOSEnterpriseExtensionObserver() OVERRIDE {
253  }
254  virtual void InitChromeOSPreferences() OVERRIDE {
255  }
256  virtual void ChangeAppLocale(const std::string&,
257                               AppLocaleChangedVia) OVERRIDE {
258  }
259  virtual void OnLogin() OVERRIDE {
260  }
261#endif  // defined(OS_CHROMEOS)
262
263  virtual PrefProxyConfigTracker* GetProxyConfigTracker() OVERRIDE;
264
265  // Schedules a task on the history backend and runs a nested loop until the
266  // task is processed.  This has the effect of blocking the caller until the
267  // history service processes all pending requests.
268  void BlockUntilHistoryProcessesPendingRequests();
269
270  virtual chrome_browser_net::Predictor* GetNetworkPredictor() OVERRIDE;
271  virtual void ClearNetworkingHistorySince(
272      base::Time time,
273      const base::Closure& completion) OVERRIDE;
274  virtual GURL GetHomePage() OVERRIDE;
275
276  virtual PrefService* GetOffTheRecordPrefs() OVERRIDE;
277
278 protected:
279  base::Time start_time_;
280  scoped_ptr<PrefServiceSyncable> prefs_;
281  // ref only for right type, lifecycle is managed by prefs_
282  TestingPrefServiceSyncable* testing_prefs_;
283
284 private:
285  // Creates a temporary directory for use by this profile.
286  void CreateTempProfileDir();
287
288  // Common initialization between the two constructors.
289  void Init();
290
291  // Finishes initialization when a profile is created asynchronously.
292  void FinishInit();
293
294  // Creates a TestingPrefService and associates it with the TestingProfile.
295  void CreateTestingPrefService();
296
297  // Creates a ProfilePolicyConnector that the ProfilePolicyConnectorFactory
298  // maps to this profile.
299  void CreateProfilePolicyConnector();
300
301  // Internally, this is a TestURLRequestContextGetter that creates a dummy
302  // request context. Currently, only the CookieMonster is hooked up.
303  scoped_refptr<net::URLRequestContextGetter> extensions_request_context_;
304
305  std::wstring id_;
306
307  bool incognito_;
308  scoped_ptr<Profile> incognito_profile_;
309  Profile* original_profile_;
310
311  // Did the last session exit cleanly? Default is true.
312  bool last_session_exited_cleanly_;
313
314  scoped_refptr<HostContentSettingsMap> host_content_settings_map_;
315
316  base::FilePath last_selected_directory_;
317  scoped_refptr<history::TopSites> top_sites_;  // For history and thumbnails.
318
319  scoped_refptr<ExtensionSpecialStoragePolicy>
320      extension_special_storage_policy_;
321
322  // The proxy prefs tracker.
323  scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_;
324
325  // We use a temporary directory to store testing profile data. In a multi-
326  // profile environment, this is invalid and the directory is managed by the
327  // TestingProfileManager.
328  base::ScopedTempDir temp_dir_;
329  // The path to this profile. This will be valid in either of the two above
330  // cases.
331  base::FilePath profile_path_;
332
333  // We keep a weak pointer to the dependency manager we want to notify on our
334  // death. Defaults to the Singleton implementation but overridable for
335  // testing.
336  BrowserContextDependencyManager* browser_context_dependency_manager_;
337
338  // Owned, but must be deleted on the IO thread so not placing in a
339  // scoped_ptr<>.
340  content::MockResourceContext* resource_context_;
341
342  scoped_ptr<policy::ProfilePolicyConnector> profile_policy_connector_;
343
344  // Weak pointer to a delegate for indicating that a profile was created.
345  Delegate* delegate_;
346};
347
348#endif  // CHROME_TEST_BASE_TESTING_PROFILE_H_
349