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 a guest profile.
101 void SetGuestSession();
103 // Sets the supervised user ID (which is empty by default). If it is set to
104 // a non-empty string, the profile is supervised.
105 void SetSupervisedUserId(const std::string
& supervised_user_id
);
107 // Sets the PolicyService to be used by this profile.
108 void SetPolicyService(scoped_ptr
<policy::PolicyService
> policy_service
);
110 // Creates the TestingProfile using previously-set settings.
111 scoped_ptr
<TestingProfile
> Build();
113 // Build an incognito profile, owned by |original_profile|. Note: unless you
114 // need to customize the Builder, or access TestingProfile member functions,
115 // you can use original_profile->GetOffTheRecordProfile().
116 TestingProfile
* BuildIncognito(TestingProfile
* original_profile
);
119 // If true, Build() has already been called.
122 // Various staging variables where values are held until Build() is invoked.
123 scoped_ptr
<PrefServiceSyncable
> pref_service_
;
124 #if defined(ENABLE_EXTENSIONS)
125 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy_
;
127 base::FilePath path_
;
130 std::string supervised_user_id_
;
131 scoped_ptr
<policy::PolicyService
> policy_service_
;
132 TestingFactories testing_factories_
;
134 DISALLOW_COPY_AND_ASSIGN(Builder
);
137 // Multi-profile aware constructor that takes the path to a directory managed
138 // for this profile. This constructor is meant to be used by
139 // TestingProfileManager::CreateTestingProfile. If you need to create multi-
140 // profile profiles, use that factory method instead of this directly.
141 // Exception: if you need to create multi-profile profiles for testing the
142 // ProfileManager, then use the constructor below instead.
143 explicit TestingProfile(const base::FilePath
& path
);
145 // Multi-profile aware constructor that takes the path to a directory managed
146 // for this profile and a delegate. This constructor is meant to be used
147 // for unittesting the ProfileManager.
148 TestingProfile(const base::FilePath
& path
, Delegate
* delegate
);
150 // Full constructor allowing the setting of all possible instance data.
151 // Callers should use Builder::Build() instead of invoking this constructor.
152 TestingProfile(const base::FilePath
& path
,
154 #if defined(ENABLE_EXTENSIONS)
155 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy
,
157 scoped_ptr
<PrefServiceSyncable
> prefs
,
158 TestingProfile
* parent
,
160 const std::string
& supervised_user_id
,
161 scoped_ptr
<policy::PolicyService
> policy_service
,
162 const TestingFactories
& factories
);
164 virtual ~TestingProfile();
166 // Creates the favicon service. Consequent calls would recreate the service.
167 void CreateFaviconService();
169 // Creates the history service. If |delete_file| is true, the history file is
170 // deleted first, then the HistoryService is created. As TestingProfile
171 // deletes the directory containing the files used by HistoryService, this
172 // only matters if you're recreating the HistoryService. If |no_db| is true,
173 // the history backend will fail to initialize its database; this is useful
174 // for testing error conditions. Returns true on success.
175 bool CreateHistoryService(bool delete_file
, bool no_db
) WARN_UNUSED_RESULT
;
177 // Shuts down and nulls out the reference to HistoryService.
178 void DestroyHistoryService();
180 // Creates TopSites. This returns immediately, and top sites may not be
181 // loaded. Use BlockUntilTopSitesLoaded to ensure TopSites has finished
183 void CreateTopSites();
185 // Shuts down and nulls out the reference to TopSites.
186 void DestroyTopSites();
188 // Creates the BookmarkBarModel. If not invoked the bookmark bar model is
189 // NULL. If |delete_file| is true, the bookmarks file is deleted first, then
190 // the model is created. As TestingProfile deletes the directory containing
191 // the files used by HistoryService, the boolean only matters if you're
192 // recreating the BookmarkModel.
194 // NOTE: this does not block until the bookmarks are loaded. For that use
195 // WaitForBookmarkModelToLoad().
196 void CreateBookmarkModel(bool delete_file
);
198 // Creates a WebDataService. If not invoked, the web data service is NULL.
199 void CreateWebDataService();
201 // Blocks until the HistoryService finishes restoring its in-memory cache.
202 // This is NOT invoked from CreateHistoryService.
203 void BlockUntilHistoryIndexIsRefreshed();
205 // Blocks until TopSites finishes loading.
206 void BlockUntilTopSitesLoaded();
208 // Allow setting a profile as Guest after-the-fact to simplify some tests.
209 void SetGuestSession(bool guest
);
211 TestingPrefServiceSyncable
* GetTestingPrefService();
213 // Called on the parent of an incognito |profile|. Usually called from the
214 // constructor of an incognito TestingProfile, but can also be used by tests
215 // to provide an OffTheRecordProfileImpl instance.
216 void SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
);
218 // content::BrowserContext
219 virtual base::FilePath
GetPath() const OVERRIDE
;
220 virtual scoped_refptr
<base::SequencedTaskRunner
> GetIOTaskRunner() OVERRIDE
;
221 virtual bool IsOffTheRecord() const OVERRIDE
;
222 virtual content::DownloadManagerDelegate
*
223 GetDownloadManagerDelegate() OVERRIDE
;
224 virtual net::URLRequestContextGetter
* GetRequestContext() OVERRIDE
;
225 virtual net::URLRequestContextGetter
* CreateRequestContext(
226 content::ProtocolHandlerMap
* protocol_handlers
,
227 content::URLRequestInterceptorScopedVector request_interceptors
) OVERRIDE
;
228 virtual net::URLRequestContextGetter
* GetRequestContextForRenderProcess(
229 int renderer_child_id
) OVERRIDE
;
230 virtual content::ResourceContext
* GetResourceContext() OVERRIDE
;
231 virtual content::BrowserPluginGuestManager
* GetGuestManager() OVERRIDE
;
232 virtual storage::SpecialStoragePolicy
* GetSpecialStoragePolicy() OVERRIDE
;
233 virtual content::PushMessagingService
* GetPushMessagingService() OVERRIDE
;
234 virtual content::SSLHostStateDelegate
* GetSSLHostStateDelegate() OVERRIDE
;
236 virtual TestingProfile
* AsTestingProfile() OVERRIDE
;
239 virtual std::string
GetProfileName() OVERRIDE
;
240 virtual ProfileType
GetProfileType() const OVERRIDE
;
242 // DEPRECATED, because it's fragile to change a profile from non-incognito
243 // to incognito after the ProfileKeyedServices have been created (some
244 // ProfileKeyedServices either should not exist in incognito mode, or will
245 // crash when they try to get references to other services they depend on,
246 // but do not exist in incognito mode).
247 // TODO(atwilson): Remove this API (http://crbug.com/277296).
249 // Changes a profile's to/from incognito mode temporarily - profile will be
250 // returned to non-incognito before destruction to allow services to
251 // properly shutdown. This is only supported for legacy tests - new tests
252 // should create a true incognito profile using Builder::SetIncognito() or
253 // by using the TestingProfile constructor that allows setting the incognito
255 void ForceIncognito(bool force_incognito
) {
256 force_incognito_
= force_incognito
;
259 virtual Profile
* GetOffTheRecordProfile() OVERRIDE
;
260 virtual void DestroyOffTheRecordProfile() OVERRIDE
{}
261 virtual bool HasOffTheRecordProfile() OVERRIDE
;
262 virtual Profile
* GetOriginalProfile() OVERRIDE
;
263 virtual bool IsSupervised() OVERRIDE
;
264 #if defined(ENABLE_EXTENSIONS)
265 void SetExtensionSpecialStoragePolicy(
266 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
);
268 virtual ExtensionSpecialStoragePolicy
*
269 GetExtensionSpecialStoragePolicy() OVERRIDE
;
270 // TODO(ajwong): Remove this API in favor of directly retrieving the
271 // CookieStore from the StoragePartition after ExtensionURLRequestContext
273 net::CookieMonster
* GetCookieMonster();
275 virtual PrefService
* GetPrefs() OVERRIDE
;
277 virtual history::TopSites
* GetTopSites() OVERRIDE
;
278 virtual history::TopSites
* GetTopSitesWithoutCreating() OVERRIDE
;
280 virtual net::URLRequestContextGetter
* GetMediaRequestContext() OVERRIDE
;
281 virtual net::URLRequestContextGetter
* GetMediaRequestContextForRenderProcess(
282 int renderer_child_id
) OVERRIDE
;
283 virtual net::URLRequestContextGetter
*
284 GetRequestContextForExtensions() OVERRIDE
;
285 virtual net::URLRequestContextGetter
*
286 GetMediaRequestContextForStoragePartition(
287 const base::FilePath
& partition_path
,
288 bool in_memory
) OVERRIDE
;
289 virtual net::URLRequestContextGetter
* CreateRequestContextForStoragePartition(
290 const base::FilePath
& partition_path
,
292 content::ProtocolHandlerMap
* protocol_handlers
,
293 content::URLRequestInterceptorScopedVector request_interceptors
) OVERRIDE
;
294 virtual net::SSLConfigService
* GetSSLConfigService() OVERRIDE
;
295 virtual HostContentSettingsMap
* GetHostContentSettingsMap() OVERRIDE
;
296 void set_last_session_exited_cleanly(bool value
) {
297 last_session_exited_cleanly_
= value
;
299 virtual bool IsSameProfile(Profile
*p
) OVERRIDE
;
300 virtual base::Time
GetStartTime() const OVERRIDE
;
301 virtual base::FilePath
last_selected_directory() OVERRIDE
;
302 virtual void set_last_selected_directory(const base::FilePath
& path
) OVERRIDE
;
303 virtual bool WasCreatedByVersionOrLater(const std::string
& version
) OVERRIDE
;
304 virtual bool IsGuestSession() const OVERRIDE
;
305 virtual void SetExitType(ExitType exit_type
) OVERRIDE
{}
306 virtual ExitType
GetLastSessionExitType() OVERRIDE
;
307 #if defined(OS_CHROMEOS)
308 virtual void ChangeAppLocale(const std::string
&,
309 AppLocaleChangedVia
) OVERRIDE
{
311 virtual void OnLogin() OVERRIDE
{
313 virtual void InitChromeOSPreferences() OVERRIDE
{
315 #endif // defined(OS_CHROMEOS)
317 virtual PrefProxyConfigTracker
* GetProxyConfigTracker() OVERRIDE
;
319 // Schedules a task on the history backend and runs a nested loop until the
320 // task is processed. This has the effect of blocking the caller until the
321 // history service processes all pending requests.
322 void BlockUntilHistoryProcessesPendingRequests();
324 virtual chrome_browser_net::Predictor
* GetNetworkPredictor() OVERRIDE
;
325 virtual DevToolsNetworkController
* GetDevToolsNetworkController() OVERRIDE
;
326 virtual void ClearNetworkingHistorySince(
328 const base::Closure
& completion
) OVERRIDE
;
329 virtual GURL
GetHomePage() OVERRIDE
;
331 virtual PrefService
* GetOffTheRecordPrefs() OVERRIDE
;
333 void set_profile_name(const std::string
& profile_name
) {
334 profile_name_
= profile_name
;
338 base::Time start_time_
;
339 scoped_ptr
<PrefServiceSyncable
> prefs_
;
340 // ref only for right type, lifecycle is managed by prefs_
341 TestingPrefServiceSyncable
* testing_prefs_
;
344 // Creates a temporary directory for use by this profile.
345 void CreateTempProfileDir();
347 // Common initialization between the two constructors.
350 // Finishes initialization when a profile is created asynchronously.
353 // Creates a TestingPrefService and associates it with the TestingProfile.
354 void CreateTestingPrefService();
356 // Initializes |prefs_| for an incognito profile, derived from
357 // |original_profile_|.
358 void CreateIncognitoPrefService();
360 // Creates a ProfilePolicyConnector that the ProfilePolicyConnectorFactory
361 // maps to this profile.
362 void CreateProfilePolicyConnector();
364 // Internally, this is a TestURLRequestContextGetter that creates a dummy
365 // request context. Currently, only the CookieMonster is hooked up.
366 scoped_refptr
<net::URLRequestContextGetter
> extensions_request_context_
;
368 bool force_incognito_
;
369 scoped_ptr
<Profile
> incognito_profile_
;
370 TestingProfile
* original_profile_
;
374 std::string supervised_user_id_
;
376 // Did the last session exit cleanly? Default is true.
377 bool last_session_exited_cleanly_
;
379 scoped_refptr
<HostContentSettingsMap
> host_content_settings_map_
;
381 base::FilePath last_selected_directory_
;
382 scoped_refptr
<history::TopSites
> top_sites_
; // For history and thumbnails.
384 #if defined(ENABLE_EXTENSIONS)
385 scoped_refptr
<ExtensionSpecialStoragePolicy
>
386 extension_special_storage_policy_
;
389 // The proxy prefs tracker.
390 scoped_ptr
<PrefProxyConfigTracker
> pref_proxy_config_tracker_
;
392 // We use a temporary directory to store testing profile data. In a multi-
393 // profile environment, this is invalid and the directory is managed by the
394 // TestingProfileManager.
395 base::ScopedTempDir temp_dir_
;
396 // The path to this profile. This will be valid in either of the two above
398 base::FilePath profile_path_
;
400 // We keep a weak pointer to the dependency manager we want to notify on our
401 // death. Defaults to the Singleton implementation but overridable for
403 BrowserContextDependencyManager
* browser_context_dependency_manager_
;
405 // Owned, but must be deleted on the IO thread so not placing in a
407 content::MockResourceContext
* resource_context_
;
409 #if defined(ENABLE_CONFIGURATION_POLICY)
410 scoped_ptr
<policy::SchemaRegistryService
> schema_registry_service_
;
412 scoped_ptr
<policy::ProfilePolicyConnector
> profile_policy_connector_
;
414 // Weak pointer to a delegate for indicating that a profile was created.
417 std::string profile_name_
;
419 scoped_ptr
<policy::PolicyService
> policy_service_
;
422 #endif // CHROME_TEST_BASE_TESTING_PROFILE_H_