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