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