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"
20 class MockResourceContext
;
21 class SSLHostStateDelegate
;
22 class ZoomLevelDelegate
;
27 class URLRequestContextGetter
;
32 class ProfilePolicyConnector
;
33 class SchemaRegistryService
;
37 class SpecialStoragePolicy
;
40 class BrowserContextDependencyManager
;
41 class ExtensionSpecialStoragePolicy
;
42 class HostContentSettingsMap
;
43 class PrefServiceSyncable
;
44 class TestingPrefServiceSyncable
;
46 class TestingProfile
: public Profile
{
48 // Profile directory name for the test user. This is "Default" on most
49 // platforms but must be different on ChromeOS because a logged-in user cannot
50 // use "Default" as profile directory.
51 // Browser- and UI tests should always use this to get to the user's profile
52 // directory. Unit-tests, though, should use |kInitialProfile|, which is
53 // always "Default", because they are runnining without logged-in user.
54 static const char kTestUserProfileDir
[];
56 // Default constructor that cannot be used with multi-profiles.
59 typedef std::vector
<std::pair
<
60 BrowserContextKeyedServiceFactory
*,
61 BrowserContextKeyedServiceFactory::TestingFactoryFunction
> >
64 // Helper class for building an instance of TestingProfile (allows injecting
65 // mocks for various services prior to profile initialization).
66 // TODO(atwilson): Remove non-default constructors and various setters in
67 // favor of using the Builder API.
73 // Sets a Delegate to be called back during profile init. This causes the
74 // final initialization to be performed via a task so the caller must run
75 // a MessageLoop. Caller maintains ownership of the Delegate
76 // and must manage its lifetime so it continues to exist until profile
77 // initialization is complete.
78 void SetDelegate(Delegate
* delegate
);
80 // Adds a testing factory to the TestingProfile. These testing factories
81 // are applied before the ProfileKeyedServices are created.
82 void AddTestingFactory(
83 BrowserContextKeyedServiceFactory
* service_factory
,
84 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback
);
86 #if defined(ENABLE_EXTENSIONS)
87 // Sets the ExtensionSpecialStoragePolicy to be returned by
88 // GetExtensionSpecialStoragePolicy().
89 void SetExtensionSpecialStoragePolicy(
90 scoped_refptr
<ExtensionSpecialStoragePolicy
> policy
);
93 // Sets the path to the directory to be used to hold profile data.
94 void SetPath(const base::FilePath
& path
);
96 // Sets the PrefService to be used by this profile.
97 void SetPrefService(scoped_ptr
<PrefServiceSyncable
> prefs
);
99 // Makes the Profile being built a guest profile.
100 void SetGuestSession();
102 // Sets the supervised user ID (which is empty by default). If it is set to
103 // a non-empty string, the profile is supervised.
104 void SetSupervisedUserId(const std::string
& supervised_user_id
);
106 // Sets the PolicyService to be used by this profile.
107 void SetPolicyService(scoped_ptr
<policy::PolicyService
> policy_service
);
109 // Creates the TestingProfile using previously-set settings.
110 scoped_ptr
<TestingProfile
> Build();
112 // Build an incognito profile, owned by |original_profile|. Note: unless you
113 // need to customize the Builder, or access TestingProfile member functions,
114 // you can use original_profile->GetOffTheRecordProfile().
115 TestingProfile
* BuildIncognito(TestingProfile
* original_profile
);
118 // If true, Build() has already been called.
121 // Various staging variables where values are held until Build() is invoked.
122 scoped_ptr
<PrefServiceSyncable
> pref_service_
;
123 #if defined(ENABLE_EXTENSIONS)
124 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy_
;
126 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
,
157 TestingProfile
* parent
,
159 const std::string
& supervised_user_id
,
160 scoped_ptr
<policy::PolicyService
> policy_service
,
161 const TestingFactories
& factories
);
163 ~TestingProfile() override
;
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 the BookmarkBarModel. If not invoked the bookmark bar model is
180 // NULL. If |delete_file| is true, the bookmarks file is deleted first, then
181 // the model is created. As TestingProfile deletes the directory containing
182 // the files used by HistoryService, the boolean only matters if you're
183 // recreating the BookmarkModel.
185 // NOTE: this does not block until the bookmarks are loaded. For that use
186 // WaitForBookmarkModelToLoad().
187 void CreateBookmarkModel(bool delete_file
);
189 // Creates a WebDataService. If not invoked, the web data service is NULL.
190 void CreateWebDataService();
192 // Blocks until the HistoryService finishes restoring its in-memory cache.
193 // This is NOT invoked from CreateHistoryService.
194 void BlockUntilHistoryIndexIsRefreshed();
196 // Allow setting a profile as Guest after-the-fact to simplify some tests.
197 void SetGuestSession(bool guest
);
199 TestingPrefServiceSyncable
* GetTestingPrefService();
201 // Called on the parent of an incognito |profile|. Usually called from the
202 // constructor of an incognito TestingProfile, but can also be used by tests
203 // to provide an OffTheRecordProfileImpl instance.
204 void SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
);
206 void SetSupervisedUserId(const std::string
& id
);
208 // content::BrowserContext
209 base::FilePath
GetPath() const override
;
210 scoped_ptr
<content::ZoomLevelDelegate
> CreateZoomLevelDelegate(
211 const base::FilePath
& partition_path
) override
;
212 scoped_refptr
<base::SequencedTaskRunner
> GetIOTaskRunner() override
;
213 bool IsOffTheRecord() const override
;
214 content::DownloadManagerDelegate
* GetDownloadManagerDelegate() override
;
215 net::URLRequestContextGetter
* GetRequestContext() override
;
216 net::URLRequestContextGetter
* CreateRequestContext(
217 content::ProtocolHandlerMap
* protocol_handlers
,
218 content::URLRequestInterceptorScopedVector request_interceptors
) override
;
219 net::URLRequestContextGetter
* GetRequestContextForRenderProcess(
220 int renderer_child_id
) override
;
221 content::ResourceContext
* GetResourceContext() override
;
222 content::BrowserPluginGuestManager
* GetGuestManager() override
;
223 storage::SpecialStoragePolicy
* GetSpecialStoragePolicy() override
;
224 content::PushMessagingService
* GetPushMessagingService() override
;
225 content::SSLHostStateDelegate
* GetSSLHostStateDelegate() override
;
226 content::PermissionManager
* GetPermissionManager() override
;
228 TestingProfile
* AsTestingProfile() override
;
231 std::string
GetProfileUserName() const override
;
232 ProfileType
GetProfileType() const override
;
234 // DEPRECATED, because it's fragile to change a profile from non-incognito
235 // to incognito after the ProfileKeyedServices have been created (some
236 // ProfileKeyedServices either should not exist in incognito mode, or will
237 // crash when they try to get references to other services they depend on,
238 // but do not exist in incognito mode).
239 // TODO(atwilson): Remove this API (http://crbug.com/277296).
241 // Changes a profile's to/from incognito mode temporarily - profile will be
242 // returned to non-incognito before destruction to allow services to
243 // properly shutdown. This is only supported for legacy tests - new tests
244 // should create a true incognito profile using Builder::SetIncognito() or
245 // by using the TestingProfile constructor that allows setting the incognito
247 void ForceIncognito(bool force_incognito
) {
248 force_incognito_
= force_incognito
;
251 Profile
* GetOffTheRecordProfile() override
;
252 void DestroyOffTheRecordProfile() override
{}
253 bool HasOffTheRecordProfile() override
;
254 Profile
* GetOriginalProfile() override
;
255 bool IsSupervised() override
;
256 bool IsChild() override
;
257 bool IsLegacySupervised() override
;
258 #if defined(ENABLE_EXTENSIONS)
259 void SetExtensionSpecialStoragePolicy(
260 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
);
262 ExtensionSpecialStoragePolicy
* GetExtensionSpecialStoragePolicy() override
;
263 // TODO(ajwong): Remove this API in favor of directly retrieving the
264 // CookieStore from the StoragePartition after ExtensionURLRequestContext
266 net::CookieMonster
* GetCookieMonster();
268 PrefService
* GetPrefs() override
;
269 const PrefService
* GetPrefs() const override
;
270 chrome::ChromeZoomLevelPrefs
* GetZoomLevelPrefs() override
;
272 net::URLRequestContextGetter
* GetMediaRequestContext() override
;
273 net::URLRequestContextGetter
* GetMediaRequestContextForRenderProcess(
274 int renderer_child_id
) override
;
275 net::URLRequestContextGetter
* GetRequestContextForExtensions() override
;
276 net::URLRequestContextGetter
* GetMediaRequestContextForStoragePartition(
277 const base::FilePath
& partition_path
,
278 bool in_memory
) override
;
279 net::URLRequestContextGetter
* CreateRequestContextForStoragePartition(
280 const base::FilePath
& partition_path
,
282 content::ProtocolHandlerMap
* protocol_handlers
,
283 content::URLRequestInterceptorScopedVector request_interceptors
) override
;
284 net::SSLConfigService
* GetSSLConfigService() override
;
285 HostContentSettingsMap
* GetHostContentSettingsMap() override
;
286 void set_last_session_exited_cleanly(bool value
) {
287 last_session_exited_cleanly_
= value
;
289 bool IsSameProfile(Profile
* p
) override
;
290 base::Time
GetStartTime() const override
;
291 base::FilePath
last_selected_directory() override
;
292 void set_last_selected_directory(const base::FilePath
& path
) override
;
293 bool WasCreatedByVersionOrLater(const std::string
& version
) override
;
294 bool IsGuestSession() const override
;
295 void SetExitType(ExitType exit_type
) override
{}
296 ExitType
GetLastSessionExitType() override
;
297 #if defined(OS_CHROMEOS)
298 void ChangeAppLocale(const std::string
&, AppLocaleChangedVia
) override
{}
299 void OnLogin() override
{}
300 void InitChromeOSPreferences() override
{}
301 #endif // defined(OS_CHROMEOS)
303 PrefProxyConfigTracker
* GetProxyConfigTracker() override
;
305 // Schedules a task on the history backend and runs a nested loop until the
306 // task is processed. This has the effect of blocking the caller until the
307 // history service processes all pending requests.
308 void BlockUntilHistoryProcessesPendingRequests();
310 chrome_browser_net::Predictor
* GetNetworkPredictor() override
;
311 DevToolsNetworkController
* GetDevToolsNetworkController() override
;
312 void ClearNetworkingHistorySince(base::Time time
,
313 const base::Closure
& completion
) override
;
314 GURL
GetHomePage() override
;
316 PrefService
* GetOffTheRecordPrefs() override
;
318 void set_profile_name(const std::string
& profile_name
) {
319 profile_name_
= profile_name
;
323 base::Time start_time_
;
324 scoped_ptr
<PrefServiceSyncable
> prefs_
;
325 // ref only for right type, lifecycle is managed by prefs_
326 TestingPrefServiceSyncable
* testing_prefs_
;
329 // Creates a temporary directory for use by this profile.
330 void CreateTempProfileDir();
332 // Common initialization between the two constructors.
335 // Finishes initialization when a profile is created asynchronously.
338 // Creates a TestingPrefService and associates it with the TestingProfile.
339 void CreateTestingPrefService();
341 // Initializes |prefs_| for an incognito profile, derived from
342 // |original_profile_|.
343 void CreateIncognitoPrefService();
345 // Creates a ProfilePolicyConnector that the ProfilePolicyConnectorFactory
346 // maps to this profile.
347 void CreateProfilePolicyConnector();
349 // Internally, this is a TestURLRequestContextGetter that creates a dummy
350 // request context. Currently, only the CookieMonster is hooked up.
351 scoped_refptr
<net::URLRequestContextGetter
> extensions_request_context_
;
353 bool force_incognito_
;
354 scoped_ptr
<Profile
> incognito_profile_
;
355 TestingProfile
* original_profile_
;
359 std::string supervised_user_id_
;
361 // Did the last session exit cleanly? Default is true.
362 bool last_session_exited_cleanly_
;
364 scoped_refptr
<HostContentSettingsMap
> host_content_settings_map_
;
366 base::FilePath last_selected_directory_
;
368 #if defined(ENABLE_EXTENSIONS)
369 scoped_refptr
<ExtensionSpecialStoragePolicy
>
370 extension_special_storage_policy_
;
373 // The proxy prefs tracker.
374 scoped_ptr
<PrefProxyConfigTracker
> pref_proxy_config_tracker_
;
376 // We use a temporary directory to store testing profile data. In a multi-
377 // profile environment, this is invalid and the directory is managed by the
378 // TestingProfileManager.
379 base::ScopedTempDir temp_dir_
;
380 // The path to this profile. This will be valid in either of the two above
382 base::FilePath profile_path_
;
384 base::FilePath extensions_path_
;
386 // We keep a weak pointer to the dependency manager we want to notify on our
387 // death. Defaults to the Singleton implementation but overridable for
389 BrowserContextDependencyManager
* browser_context_dependency_manager_
;
391 // Owned, but must be deleted on the IO thread so not placing in a
393 content::MockResourceContext
* resource_context_
;
395 #if defined(ENABLE_CONFIGURATION_POLICY)
396 scoped_ptr
<policy::SchemaRegistryService
> schema_registry_service_
;
398 scoped_ptr
<policy::ProfilePolicyConnector
> profile_policy_connector_
;
400 // Weak pointer to a delegate for indicating that a profile was created.
403 std::string profile_name_
;
405 scoped_ptr
<policy::PolicyService
> policy_service_
;
408 #endif // CHROME_TEST_BASE_TESTING_PROFILE_H_