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