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.
5 #ifndef CHROME_TEST_BASE_TESTING_PROFILE_H_
6 #define CHROME_TEST_BASE_TESTING_PROFILE_H_
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/domain_reliability/clear_mode.h"
15 #include "components/keyed_service/content/browser_context_keyed_service_factory.h"
18 class MockResourceContext;
19 class SSLHostStateDelegate;
28 class URLRequestContextGetter;
33 class ProfilePolicyConnector;
34 class SchemaRegistryService;
38 class SpecialStoragePolicy;
41 class BrowserContextDependencyManager;
42 class ExtensionSpecialStoragePolicy;
43 class HostContentSettingsMap;
44 class PrefServiceSyncable;
45 class TestingPrefServiceSyncable;
47 class TestingProfile : public Profile {
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[];
57 // Default constructor that cannot be used with multi-profiles.
60 typedef std::vector<std::pair<
61 BrowserContextKeyedServiceFactory*,
62 BrowserContextKeyedServiceFactory::TestingFactoryFunction> >
65 // Helper class for building an instance of TestingProfile (allows injecting
66 // mocks for various services prior to profile initialization).
67 // TODO(atwilson): Remove non-default constructors and various setters in
68 // favor of using the Builder API.
74 // Sets a Delegate to be called back during profile init. This causes the
75 // final initialization to be performed via a task so the caller must run
76 // a MessageLoop. Caller maintains ownership of the Delegate
77 // and must manage its lifetime so it continues to exist until profile
78 // initialization is complete.
79 void SetDelegate(Delegate* delegate);
81 // Adds a testing factory to the TestingProfile. These testing factories
82 // are applied before the ProfileKeyedServices are created.
83 void AddTestingFactory(
84 BrowserContextKeyedServiceFactory* service_factory,
85 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback);
87 #if defined(ENABLE_EXTENSIONS)
88 // Sets the ExtensionSpecialStoragePolicy to be returned by
89 // GetExtensionSpecialStoragePolicy().
90 void SetExtensionSpecialStoragePolicy(
91 scoped_refptr<ExtensionSpecialStoragePolicy> policy);
94 // Sets the path to the directory to be used to hold profile data.
95 void SetPath(const base::FilePath& path);
97 // Sets the PrefService to be used by this profile.
98 void SetPrefService(scoped_ptr<PrefServiceSyncable> prefs);
100 // Makes the Profile being built an incognito profile.
103 // Makes the Profile being built a guest profile.
104 void SetGuestSession();
106 // Sets the supervised user ID (which is empty by default). If it is set to
107 // a non-empty string, the profile is supervised.
108 void SetSupervisedUserId(const std::string& supervised_user_id);
110 // Sets the PolicyService to be used by this profile.
111 void SetPolicyService(scoped_ptr<policy::PolicyService> policy_service);
113 // Creates the TestingProfile using previously-set settings.
114 scoped_ptr<TestingProfile> Build();
117 // If true, Build() has already been called.
120 // Various staging variables where values are held until Build() is invoked.
121 scoped_ptr<PrefServiceSyncable> pref_service_;
122 #if defined(ENABLE_EXTENSIONS)
123 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy_;
125 base::FilePath path_;
129 std::string supervised_user_id_;
130 scoped_ptr<policy::PolicyService> policy_service_;
131 TestingFactories testing_factories_;
133 DISALLOW_COPY_AND_ASSIGN(Builder);
136 // Multi-profile aware constructor that takes the path to a directory managed
137 // for this profile. This constructor is meant to be used by
138 // TestingProfileManager::CreateTestingProfile. If you need to create multi-
139 // profile profiles, use that factory method instead of this directly.
140 // Exception: if you need to create multi-profile profiles for testing the
141 // ProfileManager, then use the constructor below instead.
142 explicit TestingProfile(const base::FilePath& path);
144 // Multi-profile aware constructor that takes the path to a directory managed
145 // for this profile and a delegate. This constructor is meant to be used
146 // for unittesting the ProfileManager.
147 TestingProfile(const base::FilePath& path, Delegate* delegate);
149 // Full constructor allowing the setting of all possible instance data.
150 // Callers should use Builder::Build() instead of invoking this constructor.
151 TestingProfile(const base::FilePath& path,
153 #if defined(ENABLE_EXTENSIONS)
154 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
156 scoped_ptr<PrefServiceSyncable> prefs,
159 const std::string& supervised_user_id,
160 scoped_ptr<policy::PolicyService> policy_service,
161 const TestingFactories& factories);
163 virtual ~TestingProfile();
165 // Creates the favicon service. Consequent calls would recreate the service.
166 void CreateFaviconService();
168 // Creates the history service. If |delete_file| is true, the history file is
169 // deleted first, then the HistoryService is created. As TestingProfile
170 // deletes the directory containing the files used by HistoryService, this
171 // only matters if you're recreating the HistoryService. If |no_db| is true,
172 // the history backend will fail to initialize its database; this is useful
173 // for testing error conditions. Returns true on success.
174 bool CreateHistoryService(bool delete_file, bool no_db) WARN_UNUSED_RESULT;
176 // Shuts down and nulls out the reference to HistoryService.
177 void DestroyHistoryService();
179 // Creates TopSites. This returns immediately, and top sites may not be
180 // loaded. Use BlockUntilTopSitesLoaded to ensure TopSites has finished
182 void CreateTopSites();
184 // Shuts down and nulls out the reference to TopSites.
185 void DestroyTopSites();
187 // Creates the BookmarkBarModel. If not invoked the bookmark bar model is
188 // NULL. If |delete_file| is true, the bookmarks file is deleted first, then
189 // the model is created. As TestingProfile deletes the directory containing
190 // the files used by HistoryService, the boolean only matters if you're
191 // recreating the BookmarkModel.
193 // NOTE: this does not block until the bookmarks are loaded. For that use
194 // WaitForBookmarkModelToLoad().
195 void CreateBookmarkModel(bool delete_file);
197 // Creates a WebDataService. If not invoked, the web data service is NULL.
198 void CreateWebDataService();
200 // Blocks until the HistoryService finishes restoring its in-memory cache.
201 // This is NOT invoked from CreateHistoryService.
202 void BlockUntilHistoryIndexIsRefreshed();
204 // Blocks until TopSites finishes loading.
205 void BlockUntilTopSitesLoaded();
207 // Allow setting a profile as Guest after-the-fact to simplify some tests.
208 void SetGuestSession(bool guest);
210 TestingPrefServiceSyncable* GetTestingPrefService();
212 // content::BrowserContext
213 virtual base::FilePath GetPath() const OVERRIDE;
214 virtual scoped_refptr<base::SequencedTaskRunner> GetIOTaskRunner() OVERRIDE;
215 virtual bool IsOffTheRecord() const OVERRIDE;
216 virtual content::DownloadManagerDelegate*
217 GetDownloadManagerDelegate() OVERRIDE;
218 virtual net::URLRequestContextGetter* GetRequestContext() OVERRIDE;
219 virtual net::URLRequestContextGetter* CreateRequestContext(
220 content::ProtocolHandlerMap* protocol_handlers,
221 content::URLRequestInterceptorScopedVector request_interceptors) OVERRIDE;
222 virtual net::URLRequestContextGetter* GetRequestContextForRenderProcess(
223 int renderer_child_id) OVERRIDE;
224 virtual content::ResourceContext* GetResourceContext() OVERRIDE;
225 virtual content::BrowserPluginGuestManager* GetGuestManager() OVERRIDE;
226 virtual quota::SpecialStoragePolicy* GetSpecialStoragePolicy() OVERRIDE;
227 virtual content::PushMessagingService* GetPushMessagingService() OVERRIDE;
228 virtual content::SSLHostStateDelegate* GetSSLHostStateDelegate() OVERRIDE;
230 virtual TestingProfile* AsTestingProfile() OVERRIDE;
233 virtual std::string GetProfileName() OVERRIDE;
234 virtual ProfileType GetProfileType() const OVERRIDE;
236 // DEPRECATED, because it's fragile to change a profile from non-incognito
237 // to incognito after the ProfileKeyedServices have been created (some
238 // ProfileKeyedServices either should not exist in incognito mode, or will
239 // crash when they try to get references to other services they depend on,
240 // but do not exist in incognito mode).
241 // TODO(atwilson): Remove this API (http://crbug.com/277296).
243 // Changes a profile's to/from incognito mode temporarily - profile will be
244 // returned to non-incognito before destruction to allow services to
245 // properly shutdown. This is only supported for legacy tests - new tests
246 // should create a true incognito profile using Builder::SetIncognito() or
247 // by using the TestingProfile constructor that allows setting the incognito
249 void ForceIncognito(bool force_incognito) {
250 force_incognito_ = force_incognito;
253 virtual void SetOffTheRecordProfile(scoped_ptr<Profile> profile);
254 virtual void SetOriginalProfile(Profile* profile);
255 virtual Profile* GetOffTheRecordProfile() OVERRIDE;
256 virtual void DestroyOffTheRecordProfile() OVERRIDE {}
257 virtual bool HasOffTheRecordProfile() OVERRIDE;
258 virtual Profile* GetOriginalProfile() OVERRIDE;
259 virtual bool IsSupervised() OVERRIDE;
260 #if defined(ENABLE_EXTENSIONS)
261 void SetExtensionSpecialStoragePolicy(
262 ExtensionSpecialStoragePolicy* extension_special_storage_policy);
264 virtual ExtensionSpecialStoragePolicy*
265 GetExtensionSpecialStoragePolicy() OVERRIDE;
266 // TODO(ajwong): Remove this API in favor of directly retrieving the
267 // CookieStore from the StoragePartition after ExtensionURLRequestContext
269 net::CookieMonster* GetCookieMonster();
271 virtual PrefService* GetPrefs() OVERRIDE;
273 virtual history::TopSites* GetTopSites() OVERRIDE;
274 virtual history::TopSites* GetTopSitesWithoutCreating() OVERRIDE;
276 virtual net::URLRequestContextGetter* GetMediaRequestContext() OVERRIDE;
277 virtual net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess(
278 int renderer_child_id) OVERRIDE;
279 virtual net::URLRequestContextGetter*
280 GetRequestContextForExtensions() OVERRIDE;
281 virtual net::URLRequestContextGetter*
282 GetMediaRequestContextForStoragePartition(
283 const base::FilePath& partition_path,
284 bool in_memory) OVERRIDE;
285 virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
286 const base::FilePath& partition_path,
288 content::ProtocolHandlerMap* protocol_handlers,
289 content::URLRequestInterceptorScopedVector request_interceptors) OVERRIDE;
290 virtual net::SSLConfigService* GetSSLConfigService() OVERRIDE;
291 virtual HostContentSettingsMap* GetHostContentSettingsMap() OVERRIDE;
292 void set_last_session_exited_cleanly(bool value) {
293 last_session_exited_cleanly_ = value;
295 virtual bool IsSameProfile(Profile *p) OVERRIDE;
296 virtual base::Time GetStartTime() const OVERRIDE;
297 virtual base::FilePath last_selected_directory() OVERRIDE;
298 virtual void set_last_selected_directory(const base::FilePath& path) OVERRIDE;
299 virtual bool WasCreatedByVersionOrLater(const std::string& version) OVERRIDE;
300 virtual bool IsGuestSession() const OVERRIDE;
301 virtual void SetExitType(ExitType exit_type) OVERRIDE {}
302 virtual ExitType GetLastSessionExitType() OVERRIDE;
303 #if defined(OS_CHROMEOS)
304 virtual void ChangeAppLocale(const std::string&,
305 AppLocaleChangedVia) OVERRIDE {
307 virtual void OnLogin() OVERRIDE {
309 virtual void InitChromeOSPreferences() OVERRIDE {
311 #endif // defined(OS_CHROMEOS)
313 virtual PrefProxyConfigTracker* GetProxyConfigTracker() OVERRIDE;
315 // Schedules a task on the history backend and runs a nested loop until the
316 // task is processed. This has the effect of blocking the caller until the
317 // history service processes all pending requests.
318 void BlockUntilHistoryProcessesPendingRequests();
320 virtual chrome_browser_net::Predictor* GetNetworkPredictor() OVERRIDE;
321 virtual DevToolsNetworkController* GetDevToolsNetworkController() OVERRIDE;
322 virtual void ClearNetworkingHistorySince(
324 const base::Closure& completion) OVERRIDE;
325 virtual GURL GetHomePage() OVERRIDE;
327 virtual PrefService* GetOffTheRecordPrefs() OVERRIDE;
329 void set_profile_name(const std::string& profile_name) {
330 profile_name_ = profile_name;
334 base::Time start_time_;
335 scoped_ptr<PrefServiceSyncable> prefs_;
336 // ref only for right type, lifecycle is managed by prefs_
337 TestingPrefServiceSyncable* testing_prefs_;
340 // Creates a temporary directory for use by this profile.
341 void CreateTempProfileDir();
343 // Common initialization between the two constructors.
346 // Finishes initialization when a profile is created asynchronously.
349 // Creates a TestingPrefService and associates it with the TestingProfile.
350 void CreateTestingPrefService();
352 // Creates a ProfilePolicyConnector that the ProfilePolicyConnectorFactory
353 // maps to this profile.
354 void CreateProfilePolicyConnector();
356 // Internally, this is a TestURLRequestContextGetter that creates a dummy
357 // request context. Currently, only the CookieMonster is hooked up.
358 scoped_refptr<net::URLRequestContextGetter> extensions_request_context_;
361 bool force_incognito_;
362 scoped_ptr<Profile> incognito_profile_;
363 Profile* original_profile_;
367 std::string supervised_user_id_;
369 // Did the last session exit cleanly? Default is true.
370 bool last_session_exited_cleanly_;
372 scoped_refptr<HostContentSettingsMap> host_content_settings_map_;
374 base::FilePath last_selected_directory_;
375 scoped_refptr<history::TopSites> top_sites_; // For history and thumbnails.
377 #if defined(ENABLE_EXTENSIONS)
378 scoped_refptr<ExtensionSpecialStoragePolicy>
379 extension_special_storage_policy_;
382 // The proxy prefs tracker.
383 scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_;
385 // We use a temporary directory to store testing profile data. In a multi-
386 // profile environment, this is invalid and the directory is managed by the
387 // TestingProfileManager.
388 base::ScopedTempDir temp_dir_;
389 // The path to this profile. This will be valid in either of the two above
391 base::FilePath profile_path_;
393 // We keep a weak pointer to the dependency manager we want to notify on our
394 // death. Defaults to the Singleton implementation but overridable for
396 BrowserContextDependencyManager* browser_context_dependency_manager_;
398 // Owned, but must be deleted on the IO thread so not placing in a
400 content::MockResourceContext* resource_context_;
402 #if defined(ENABLE_CONFIGURATION_POLICY)
403 scoped_ptr<policy::SchemaRegistryService> schema_registry_service_;
405 scoped_ptr<policy::ProfilePolicyConnector> profile_policy_connector_;
407 // Weak pointer to a delegate for indicating that a profile was created.
410 std::string profile_name_;
412 scoped_ptr<policy::PolicyService> policy_service_;
415 #endif // CHROME_TEST_BASE_TESTING_PROFILE_H_