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_
12 #include "base/files/scoped_temp_dir.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "chrome/browser/profiles/profile.h"
16 #include "components/domain_reliability/clear_mode.h"
17 #include "components/keyed_service/content/browser_context_keyed_service_factory.h"
19 class BrowserContextDependencyManager
;
20 class ExtensionSpecialStoragePolicy
;
21 class HostContentSettingsMap
;
24 class MockResourceContext
;
25 class SSLHostStateDelegate
;
26 class ZoomLevelDelegate
;
31 class URLRequestContextGetter
;
36 class ProfilePolicyConnector
;
37 class SchemaRegistryService
;
41 class SpecialStoragePolicy
;
44 namespace syncable_prefs
{
45 class PrefServiceSyncable
;
46 class TestingPrefServiceSyncable
;
49 class TestingProfile
: public Profile
{
51 // Profile directory name for the test user. This is "Default" on most
52 // platforms but must be different on ChromeOS because a logged-in user cannot
53 // use "Default" as profile directory.
54 // Browser- and UI tests should always use this to get to the user's profile
55 // directory. Unit-tests, though, should use |kInitialProfile|, which is
56 // always "Default", because they are runnining without logged-in user.
57 static const char kTestUserProfileDir
[];
59 // Default constructor that cannot be used with multi-profiles.
62 typedef std::vector
<std::pair
<
63 BrowserContextKeyedServiceFactory
*,
64 BrowserContextKeyedServiceFactory::TestingFactoryFunction
> >
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.
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
);
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::TestingFactoryFunction callback
);
89 #if defined(ENABLE_EXTENSIONS)
90 // Sets the ExtensionSpecialStoragePolicy to be returned by
91 // GetExtensionSpecialStoragePolicy().
92 void SetExtensionSpecialStoragePolicy(
93 scoped_refptr
<ExtensionSpecialStoragePolicy
> policy
);
96 // Sets the path to the directory to be used to hold profile data.
97 void SetPath(const base::FilePath
& path
);
99 // Sets the PrefService to be used by this profile.
100 void SetPrefService(scoped_ptr
<syncable_prefs::PrefServiceSyncable
> prefs
);
102 // Makes the Profile being built a guest profile.
103 void SetGuestSession();
105 // Sets the supervised user ID (which is empty by default). If it is set to
106 // a non-empty string, the profile is supervised.
107 void SetSupervisedUserId(const std::string
& supervised_user_id
);
109 // Sets the PolicyService to be used by this profile.
110 void SetPolicyService(scoped_ptr
<policy::PolicyService
> policy_service
);
112 // Creates the TestingProfile using previously-set settings.
113 scoped_ptr
<TestingProfile
> Build();
115 // Build an incognito profile, owned by |original_profile|. Note: unless you
116 // need to customize the Builder, or access TestingProfile member functions,
117 // you can use original_profile->GetOffTheRecordProfile().
118 TestingProfile
* BuildIncognito(TestingProfile
* original_profile
);
121 // If true, Build() has already been called.
124 // Various staging variables where values are held until Build() is invoked.
125 scoped_ptr
<syncable_prefs::PrefServiceSyncable
> pref_service_
;
126 #if defined(ENABLE_EXTENSIONS)
127 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy_
;
129 base::FilePath path_
;
132 std::string supervised_user_id_
;
133 scoped_ptr
<policy::PolicyService
> policy_service_
;
134 TestingFactories testing_factories_
;
136 DISALLOW_COPY_AND_ASSIGN(Builder
);
139 // Multi-profile aware constructor that takes the path to a directory managed
140 // for this profile. This constructor is meant to be used by
141 // TestingProfileManager::CreateTestingProfile. If you need to create multi-
142 // profile profiles, use that factory method instead of this directly.
143 // Exception: if you need to create multi-profile profiles for testing the
144 // ProfileManager, then use the constructor below instead.
145 explicit TestingProfile(const base::FilePath
& path
);
147 // Multi-profile aware constructor that takes the path to a directory managed
148 // for this profile and a delegate. This constructor is meant to be used
149 // for unittesting the ProfileManager.
150 TestingProfile(const base::FilePath
& path
, Delegate
* delegate
);
152 // Full constructor allowing the setting of all possible instance data.
153 // Callers should use Builder::Build() instead of invoking this constructor.
154 TestingProfile(const base::FilePath
& path
,
156 #if defined(ENABLE_EXTENSIONS)
157 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy
,
159 scoped_ptr
<syncable_prefs::PrefServiceSyncable
> prefs
,
160 TestingProfile
* parent
,
162 const std::string
& supervised_user_id
,
163 scoped_ptr
<policy::PolicyService
> policy_service
,
164 const TestingFactories
& factories
);
166 ~TestingProfile() override
;
168 // Creates the favicon service. Consequent calls would recreate the service.
169 void CreateFaviconService();
171 // Creates the history service. If |delete_file| is true, the history file is
172 // deleted first, then the HistoryService is created. As TestingProfile
173 // deletes the directory containing the files used by HistoryService, this
174 // only matters if you're recreating the HistoryService. If |no_db| is true,
175 // the history backend will fail to initialize its database; this is useful
176 // for testing error conditions. Returns true on success.
177 bool CreateHistoryService(bool delete_file
, bool no_db
) WARN_UNUSED_RESULT
;
179 // Shuts down and nulls out the reference to HistoryService.
180 void DestroyHistoryService();
182 // Creates the BookmarkBarModel. If not invoked the bookmark bar model is
183 // NULL. If |delete_file| is true, the bookmarks file is deleted first, then
184 // the model is created. As TestingProfile deletes the directory containing
185 // the files used by HistoryService, the boolean only matters if you're
186 // recreating the BookmarkModel.
188 // NOTE: this does not block until the bookmarks are loaded. For that use
189 // WaitForBookmarkModelToLoad().
190 void CreateBookmarkModel(bool delete_file
);
192 // Creates a WebDataService. If not invoked, the web data service is NULL.
193 void CreateWebDataService();
195 // Blocks until the HistoryService finishes restoring its in-memory cache.
196 // This is NOT invoked from CreateHistoryService.
197 void BlockUntilHistoryIndexIsRefreshed();
199 // Allow setting a profile as Guest after-the-fact to simplify some tests.
200 void SetGuestSession(bool guest
);
202 syncable_prefs::TestingPrefServiceSyncable
* GetTestingPrefService();
204 // Called on the parent of an incognito |profile|. Usually called from the
205 // constructor of an incognito TestingProfile, but can also be used by tests
206 // to provide an OffTheRecordProfileImpl instance.
207 void SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
);
209 void SetSupervisedUserId(const std::string
& id
);
211 // content::BrowserContext
212 base::FilePath
GetPath() const override
;
213 scoped_ptr
<content::ZoomLevelDelegate
> CreateZoomLevelDelegate(
214 const base::FilePath
& partition_path
) override
;
215 scoped_refptr
<base::SequencedTaskRunner
> GetIOTaskRunner() override
;
216 bool IsOffTheRecord() const override
;
217 content::DownloadManagerDelegate
* GetDownloadManagerDelegate() override
;
218 net::URLRequestContextGetter
* GetRequestContext() override
;
219 net::URLRequestContextGetter
* CreateRequestContext(
220 content::ProtocolHandlerMap
* protocol_handlers
,
221 content::URLRequestInterceptorScopedVector request_interceptors
) override
;
222 net::URLRequestContextGetter
* GetRequestContextForRenderProcess(
223 int renderer_child_id
) override
;
224 content::ResourceContext
* GetResourceContext() override
;
225 content::BrowserPluginGuestManager
* GetGuestManager() override
;
226 storage::SpecialStoragePolicy
* GetSpecialStoragePolicy() override
;
227 content::PushMessagingService
* GetPushMessagingService() override
;
228 content::SSLHostStateDelegate
* GetSSLHostStateDelegate() override
;
229 content::PermissionManager
* GetPermissionManager() override
;
231 TestingProfile
* AsTestingProfile() override
;
234 std::string
GetProfileUserName() const override
;
235 ProfileType
GetProfileType() const override
;
237 // DEPRECATED, because it's fragile to change a profile from non-incognito
238 // to incognito after the ProfileKeyedServices have been created (some
239 // ProfileKeyedServices either should not exist in incognito mode, or will
240 // crash when they try to get references to other services they depend on,
241 // but do not exist in incognito mode).
242 // TODO(atwilson): Remove this API (http://crbug.com/277296).
244 // Changes a profile's to/from incognito mode temporarily - profile will be
245 // returned to non-incognito before destruction to allow services to
246 // properly shutdown. This is only supported for legacy tests - new tests
247 // should create a true incognito profile using Builder::SetIncognito() or
248 // by using the TestingProfile constructor that allows setting the incognito
250 void ForceIncognito(bool force_incognito
) {
251 force_incognito_
= force_incognito
;
254 Profile
* GetOffTheRecordProfile() override
;
255 void DestroyOffTheRecordProfile() override
{}
256 bool HasOffTheRecordProfile() override
;
257 Profile
* GetOriginalProfile() override
;
258 bool IsSupervised() const override
;
259 bool IsChild() const override
;
260 bool IsLegacySupervised() const override
;
261 #if defined(ENABLE_EXTENSIONS)
262 void SetExtensionSpecialStoragePolicy(
263 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
);
265 ExtensionSpecialStoragePolicy
* 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 PrefService
* GetPrefs() override
;
272 const PrefService
* GetPrefs() const override
;
273 ChromeZoomLevelPrefs
* GetZoomLevelPrefs() override
;
275 net::URLRequestContextGetter
* GetMediaRequestContext() override
;
276 net::URLRequestContextGetter
* GetMediaRequestContextForRenderProcess(
277 int renderer_child_id
) override
;
278 net::URLRequestContextGetter
* GetRequestContextForExtensions() override
;
279 net::URLRequestContextGetter
* GetMediaRequestContextForStoragePartition(
280 const base::FilePath
& partition_path
,
281 bool in_memory
) override
;
282 net::URLRequestContextGetter
* CreateRequestContextForStoragePartition(
283 const base::FilePath
& partition_path
,
285 content::ProtocolHandlerMap
* protocol_handlers
,
286 content::URLRequestInterceptorScopedVector request_interceptors
) override
;
287 net::SSLConfigService
* GetSSLConfigService() override
;
288 void set_last_session_exited_cleanly(bool value
) {
289 last_session_exited_cleanly_
= value
;
291 bool IsSameProfile(Profile
* p
) override
;
292 base::Time
GetStartTime() const override
;
293 base::FilePath
last_selected_directory() override
;
294 void set_last_selected_directory(const base::FilePath
& path
) override
;
295 bool WasCreatedByVersionOrLater(const std::string
& version
) override
;
296 bool IsGuestSession() const override
;
297 void SetExitType(ExitType exit_type
) override
{}
298 ExitType
GetLastSessionExitType() override
;
299 #if defined(OS_CHROMEOS)
300 void ChangeAppLocale(const std::string
&, AppLocaleChangedVia
) override
{}
301 void OnLogin() override
{}
302 void InitChromeOSPreferences() override
{}
303 #endif // defined(OS_CHROMEOS)
305 PrefProxyConfigTracker
* GetProxyConfigTracker() override
;
307 // Schedules a task on the history backend and runs a nested loop until the
308 // task is processed. This has the effect of blocking the caller until the
309 // history service processes all pending requests.
310 void BlockUntilHistoryProcessesPendingRequests();
312 chrome_browser_net::Predictor
* GetNetworkPredictor() override
;
313 DevToolsNetworkControllerHandle
* GetDevToolsNetworkControllerHandle()
315 void ClearNetworkingHistorySince(base::Time time
,
316 const base::Closure
& completion
) override
;
317 GURL
GetHomePage() override
;
319 PrefService
* GetOffTheRecordPrefs() override
;
321 void set_profile_name(const std::string
& profile_name
) {
322 profile_name_
= profile_name
;
326 base::Time start_time_
;
327 scoped_ptr
<syncable_prefs::PrefServiceSyncable
> prefs_
;
328 // ref only for right type, lifecycle is managed by prefs_
329 syncable_prefs::TestingPrefServiceSyncable
* testing_prefs_
;
332 // Creates a temporary directory for use by this profile.
333 void CreateTempProfileDir();
335 // Common initialization between the two constructors.
338 // Finishes initialization when a profile is created asynchronously.
341 // Creates a TestingPrefService and associates it with the TestingProfile.
342 void CreateTestingPrefService();
344 // Initializes |prefs_| for an incognito profile, derived from
345 // |original_profile_|.
346 void CreateIncognitoPrefService();
348 // Creates a ProfilePolicyConnector that the ProfilePolicyConnectorFactory
349 // maps to this profile.
350 void CreateProfilePolicyConnector();
352 // Internally, this is a TestURLRequestContextGetter that creates a dummy
353 // request context. Currently, only the CookieMonster is hooked up.
354 scoped_refptr
<net::URLRequestContextGetter
> extensions_request_context_
;
356 bool force_incognito_
;
357 scoped_ptr
<Profile
> incognito_profile_
;
358 TestingProfile
* original_profile_
;
362 std::string supervised_user_id_
;
364 // Did the last session exit cleanly? Default is true.
365 bool last_session_exited_cleanly_
;
367 scoped_refptr
<HostContentSettingsMap
> host_content_settings_map_
;
369 base::FilePath last_selected_directory_
;
371 #if defined(ENABLE_EXTENSIONS)
372 scoped_refptr
<ExtensionSpecialStoragePolicy
>
373 extension_special_storage_policy_
;
376 // The proxy prefs tracker.
377 scoped_ptr
<PrefProxyConfigTracker
> pref_proxy_config_tracker_
;
379 // We use a temporary directory to store testing profile data. In a multi-
380 // profile environment, this is invalid and the directory is managed by the
381 // TestingProfileManager.
382 base::ScopedTempDir temp_dir_
;
383 // The path to this profile. This will be valid in either of the two above
385 base::FilePath profile_path_
;
387 base::FilePath extensions_path_
;
389 // We keep a weak pointer to the dependency manager we want to notify on our
390 // death. Defaults to the Singleton implementation but overridable for
392 BrowserContextDependencyManager
* browser_context_dependency_manager_
;
394 // Owned, but must be deleted on the IO thread so not placing in a
396 content::MockResourceContext
* resource_context_
;
398 #if defined(ENABLE_CONFIGURATION_POLICY)
399 scoped_ptr
<policy::SchemaRegistryService
> schema_registry_service_
;
401 scoped_ptr
<policy::ProfilePolicyConnector
> profile_policy_connector_
;
403 // Weak pointer to a delegate for indicating that a profile was created.
406 std::string profile_name_
;
408 scoped_ptr
<policy::PolicyService
> policy_service_
;
411 #endif // CHROME_TEST_BASE_TESTING_PROFILE_H_