Merge html-office-public repo into src
[chromium-blink-merge.git] / chrome / test / base / testing_profile.h
blobedb28debda7535d960bc880f40a6c27af1c53f8b
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_
8 #include <string>
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"
17 namespace content {
18 class MockResourceContext;
19 class SSLHostStateDelegate;
20 class ZoomLevelDelegate;
23 namespace history {
24 class TopSites;
27 namespace net {
28 class CookieMonster;
29 class URLRequestContextGetter;
32 namespace policy {
33 class PolicyService;
34 class ProfilePolicyConnector;
35 class SchemaRegistryService;
38 namespace storage {
39 class SpecialStoragePolicy;
42 class BrowserContextDependencyManager;
43 class ExtensionSpecialStoragePolicy;
44 class HostContentSettingsMap;
45 class PrefServiceSyncable;
46 class TestingPrefServiceSyncable;
48 class TestingProfile : public Profile {
49 public:
50 // Profile directory name for the test user. This is "Default" on most
51 // platforms but must be different on ChromeOS because a logged-in user cannot
52 // use "Default" as profile directory.
53 // Browser- and UI tests should always use this to get to the user's profile
54 // directory. Unit-tests, though, should use |kInitialProfile|, which is
55 // always "Default", because they are runnining without logged-in user.
56 static const char kTestUserProfileDir[];
58 // Default constructor that cannot be used with multi-profiles.
59 TestingProfile();
61 typedef std::vector<std::pair<
62 BrowserContextKeyedServiceFactory*,
63 BrowserContextKeyedServiceFactory::TestingFactoryFunction> >
64 TestingFactories;
66 // Helper class for building an instance of TestingProfile (allows injecting
67 // mocks for various services prior to profile initialization).
68 // TODO(atwilson): Remove non-default constructors and various setters in
69 // favor of using the Builder API.
70 class Builder {
71 public:
72 Builder();
73 ~Builder();
75 // Sets a Delegate to be called back during profile init. This causes the
76 // final initialization to be performed via a task so the caller must run
77 // a MessageLoop. Caller maintains ownership of the Delegate
78 // and must manage its lifetime so it continues to exist until profile
79 // initialization is complete.
80 void SetDelegate(Delegate* delegate);
82 // Adds a testing factory to the TestingProfile. These testing factories
83 // are applied before the ProfileKeyedServices are created.
84 void AddTestingFactory(
85 BrowserContextKeyedServiceFactory* service_factory,
86 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback);
88 #if defined(ENABLE_EXTENSIONS)
89 // Sets the ExtensionSpecialStoragePolicy to be returned by
90 // GetExtensionSpecialStoragePolicy().
91 void SetExtensionSpecialStoragePolicy(
92 scoped_refptr<ExtensionSpecialStoragePolicy> policy);
93 #endif
95 // Sets the path to the directory to be used to hold profile data.
96 void SetPath(const base::FilePath& path);
98 // Sets the PrefService to be used by this profile.
99 void SetPrefService(scoped_ptr<PrefServiceSyncable> prefs);
101 // Makes the Profile being built a guest profile.
102 void SetGuestSession();
104 // Sets the supervised user ID (which is empty by default). If it is set to
105 // a non-empty string, the profile is supervised.
106 void SetSupervisedUserId(const std::string& supervised_user_id);
108 // Sets the PolicyService to be used by this profile.
109 void SetPolicyService(scoped_ptr<policy::PolicyService> policy_service);
111 // Creates the TestingProfile using previously-set settings.
112 scoped_ptr<TestingProfile> Build();
114 // Build an incognito profile, owned by |original_profile|. Note: unless you
115 // need to customize the Builder, or access TestingProfile member functions,
116 // you can use original_profile->GetOffTheRecordProfile().
117 TestingProfile* BuildIncognito(TestingProfile* original_profile);
119 private:
120 // If true, Build() has already been called.
121 bool build_called_;
123 // Various staging variables where values are held until Build() is invoked.
124 scoped_ptr<PrefServiceSyncable> pref_service_;
125 #if defined(ENABLE_EXTENSIONS)
126 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy_;
127 #endif
128 base::FilePath path_;
129 Delegate* delegate_;
130 bool guest_session_;
131 std::string supervised_user_id_;
132 scoped_ptr<policy::PolicyService> policy_service_;
133 TestingFactories testing_factories_;
135 DISALLOW_COPY_AND_ASSIGN(Builder);
138 // Multi-profile aware constructor that takes the path to a directory managed
139 // for this profile. This constructor is meant to be used by
140 // TestingProfileManager::CreateTestingProfile. If you need to create multi-
141 // profile profiles, use that factory method instead of this directly.
142 // Exception: if you need to create multi-profile profiles for testing the
143 // ProfileManager, then use the constructor below instead.
144 explicit TestingProfile(const base::FilePath& path);
146 // Multi-profile aware constructor that takes the path to a directory managed
147 // for this profile and a delegate. This constructor is meant to be used
148 // for unittesting the ProfileManager.
149 TestingProfile(const base::FilePath& path, Delegate* delegate);
151 // Full constructor allowing the setting of all possible instance data.
152 // Callers should use Builder::Build() instead of invoking this constructor.
153 TestingProfile(const base::FilePath& path,
154 Delegate* delegate,
155 #if defined(ENABLE_EXTENSIONS)
156 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
157 #endif
158 scoped_ptr<PrefServiceSyncable> prefs,
159 TestingProfile* parent,
160 bool guest_session,
161 const std::string& supervised_user_id,
162 scoped_ptr<policy::PolicyService> policy_service,
163 const TestingFactories& factories);
165 ~TestingProfile() override;
167 // Creates the favicon service. Consequent calls would recreate the service.
168 void CreateFaviconService();
170 // Creates the history service. If |delete_file| is true, the history file is
171 // deleted first, then the HistoryService is created. As TestingProfile
172 // deletes the directory containing the files used by HistoryService, this
173 // only matters if you're recreating the HistoryService. If |no_db| is true,
174 // the history backend will fail to initialize its database; this is useful
175 // for testing error conditions. Returns true on success.
176 bool CreateHistoryService(bool delete_file, bool no_db) WARN_UNUSED_RESULT;
178 // Shuts down and nulls out the reference to HistoryService.
179 void DestroyHistoryService();
181 // Creates TopSites. This returns immediately, and top sites may not be
182 // loaded. Use BlockUntilTopSitesLoaded to ensure TopSites has finished
183 // loading.
184 void CreateTopSites();
186 // Allows to set a test implementation |top_sites|. Testing profile owns
187 // the reference and is responsible for releasing memory.
188 void SetTopSites(history::TopSites* top_sites);
190 // Shuts down and nulls out the reference to TopSites.
191 void DestroyTopSites();
193 // Creates the BookmarkBarModel. If not invoked the bookmark bar model is
194 // NULL. If |delete_file| is true, the bookmarks file is deleted first, then
195 // the model is created. As TestingProfile deletes the directory containing
196 // the files used by HistoryService, the boolean only matters if you're
197 // recreating the BookmarkModel.
199 // NOTE: this does not block until the bookmarks are loaded. For that use
200 // WaitForBookmarkModelToLoad().
201 void CreateBookmarkModel(bool delete_file);
203 // Creates a WebDataService. If not invoked, the web data service is NULL.
204 void CreateWebDataService();
206 // Blocks until the HistoryService finishes restoring its in-memory cache.
207 // This is NOT invoked from CreateHistoryService.
208 void BlockUntilHistoryIndexIsRefreshed();
210 // Blocks until TopSites finishes loading.
211 void BlockUntilTopSitesLoaded();
213 // Allow setting a profile as Guest after-the-fact to simplify some tests.
214 void SetGuestSession(bool guest);
216 TestingPrefServiceSyncable* GetTestingPrefService();
218 // Called on the parent of an incognito |profile|. Usually called from the
219 // constructor of an incognito TestingProfile, but can also be used by tests
220 // to provide an OffTheRecordProfileImpl instance.
221 void SetOffTheRecordProfile(scoped_ptr<Profile> profile);
223 // content::BrowserContext
224 base::FilePath GetPath() const override;
225 scoped_ptr<content::ZoomLevelDelegate> CreateZoomLevelDelegate(
226 const base::FilePath& partition_path) override;
227 scoped_refptr<base::SequencedTaskRunner> GetIOTaskRunner() override;
228 bool IsOffTheRecord() const override;
229 content::DownloadManagerDelegate* GetDownloadManagerDelegate() override;
230 net::URLRequestContextGetter* GetRequestContext() override;
231 net::URLRequestContextGetter* CreateRequestContext(
232 content::ProtocolHandlerMap* protocol_handlers,
233 content::URLRequestInterceptorScopedVector request_interceptors) override;
234 net::URLRequestContextGetter* GetRequestContextForRenderProcess(
235 int renderer_child_id) override;
236 content::ResourceContext* GetResourceContext() override;
237 content::BrowserPluginGuestManager* GetGuestManager() override;
238 storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override;
239 content::PushMessagingService* GetPushMessagingService() override;
240 content::SSLHostStateDelegate* GetSSLHostStateDelegate() override;
242 TestingProfile* AsTestingProfile() override;
244 // Profile
245 std::string GetProfileName() override;
246 ProfileType GetProfileType() const override;
248 // DEPRECATED, because it's fragile to change a profile from non-incognito
249 // to incognito after the ProfileKeyedServices have been created (some
250 // ProfileKeyedServices either should not exist in incognito mode, or will
251 // crash when they try to get references to other services they depend on,
252 // but do not exist in incognito mode).
253 // TODO(atwilson): Remove this API (http://crbug.com/277296).
255 // Changes a profile's to/from incognito mode temporarily - profile will be
256 // returned to non-incognito before destruction to allow services to
257 // properly shutdown. This is only supported for legacy tests - new tests
258 // should create a true incognito profile using Builder::SetIncognito() or
259 // by using the TestingProfile constructor that allows setting the incognito
260 // flag.
261 void ForceIncognito(bool force_incognito) {
262 force_incognito_ = force_incognito;
265 Profile* GetOffTheRecordProfile() override;
266 void DestroyOffTheRecordProfile() override {}
267 bool HasOffTheRecordProfile() override;
268 Profile* GetOriginalProfile() override;
269 bool IsSupervised() override;
270 bool IsChild() override;
271 bool IsLegacySupervised() override;
272 #if defined(ENABLE_EXTENSIONS)
273 void SetExtensionSpecialStoragePolicy(
274 ExtensionSpecialStoragePolicy* extension_special_storage_policy);
275 #endif
276 ExtensionSpecialStoragePolicy* GetExtensionSpecialStoragePolicy() override;
277 // TODO(ajwong): Remove this API in favor of directly retrieving the
278 // CookieStore from the StoragePartition after ExtensionURLRequestContext
279 // has been removed.
280 net::CookieMonster* GetCookieMonster();
282 PrefService* GetPrefs() override;
284 history::TopSites* GetTopSites() override;
285 history::TopSites* GetTopSitesWithoutCreating() override;
287 net::URLRequestContextGetter* GetMediaRequestContext() override;
288 net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess(
289 int renderer_child_id) override;
290 net::URLRequestContextGetter* GetRequestContextForExtensions() override;
291 net::URLRequestContextGetter* GetMediaRequestContextForStoragePartition(
292 const base::FilePath& partition_path,
293 bool in_memory) override;
294 net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
295 const base::FilePath& partition_path,
296 bool in_memory,
297 content::ProtocolHandlerMap* protocol_handlers,
298 content::URLRequestInterceptorScopedVector request_interceptors) override;
299 net::SSLConfigService* GetSSLConfigService() override;
300 HostContentSettingsMap* GetHostContentSettingsMap() override;
301 void set_last_session_exited_cleanly(bool value) {
302 last_session_exited_cleanly_ = value;
304 bool IsSameProfile(Profile* p) override;
305 base::Time GetStartTime() const override;
306 base::FilePath last_selected_directory() override;
307 void set_last_selected_directory(const base::FilePath& path) override;
308 bool WasCreatedByVersionOrLater(const std::string& version) override;
309 bool IsGuestSession() const override;
310 void SetExitType(ExitType exit_type) override {}
311 ExitType GetLastSessionExitType() override;
312 #if defined(OS_CHROMEOS)
313 virtual void ChangeAppLocale(const std::string&,
314 AppLocaleChangedVia) override {
316 virtual void OnLogin() override {
318 virtual void InitChromeOSPreferences() override {
320 #endif // defined(OS_CHROMEOS)
322 PrefProxyConfigTracker* GetProxyConfigTracker() override;
324 // Schedules a task on the history backend and runs a nested loop until the
325 // task is processed. This has the effect of blocking the caller until the
326 // history service processes all pending requests.
327 void BlockUntilHistoryProcessesPendingRequests();
329 chrome_browser_net::Predictor* GetNetworkPredictor() override;
330 DevToolsNetworkController* GetDevToolsNetworkController() override;
331 void ClearNetworkingHistorySince(base::Time time,
332 const base::Closure& completion) override;
333 GURL GetHomePage() override;
335 PrefService* GetOffTheRecordPrefs() override;
337 void set_profile_name(const std::string& profile_name) {
338 profile_name_ = profile_name;
341 protected:
342 base::Time start_time_;
343 scoped_ptr<PrefServiceSyncable> prefs_;
344 // ref only for right type, lifecycle is managed by prefs_
345 TestingPrefServiceSyncable* testing_prefs_;
347 private:
348 // Creates a temporary directory for use by this profile.
349 void CreateTempProfileDir();
351 // Common initialization between the two constructors.
352 void Init();
354 // Finishes initialization when a profile is created asynchronously.
355 void FinishInit();
357 // Creates a TestingPrefService and associates it with the TestingProfile.
358 void CreateTestingPrefService();
360 // Initializes |prefs_| for an incognito profile, derived from
361 // |original_profile_|.
362 void CreateIncognitoPrefService();
364 // Creates a ProfilePolicyConnector that the ProfilePolicyConnectorFactory
365 // maps to this profile.
366 void CreateProfilePolicyConnector();
368 // Internally, this is a TestURLRequestContextGetter that creates a dummy
369 // request context. Currently, only the CookieMonster is hooked up.
370 scoped_refptr<net::URLRequestContextGetter> extensions_request_context_;
372 bool force_incognito_;
373 scoped_ptr<Profile> incognito_profile_;
374 TestingProfile* original_profile_;
376 bool guest_session_;
378 std::string supervised_user_id_;
380 // Did the last session exit cleanly? Default is true.
381 bool last_session_exited_cleanly_;
383 scoped_refptr<HostContentSettingsMap> host_content_settings_map_;
385 base::FilePath last_selected_directory_;
386 scoped_refptr<history::TopSites> top_sites_; // For history and thumbnails.
388 #if defined(ENABLE_EXTENSIONS)
389 scoped_refptr<ExtensionSpecialStoragePolicy>
390 extension_special_storage_policy_;
391 #endif
393 // The proxy prefs tracker.
394 scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_;
396 // We use a temporary directory to store testing profile data. In a multi-
397 // profile environment, this is invalid and the directory is managed by the
398 // TestingProfileManager.
399 base::ScopedTempDir temp_dir_;
400 // The path to this profile. This will be valid in either of the two above
401 // cases.
402 base::FilePath profile_path_;
404 // We keep a weak pointer to the dependency manager we want to notify on our
405 // death. Defaults to the Singleton implementation but overridable for
406 // testing.
407 BrowserContextDependencyManager* browser_context_dependency_manager_;
409 // Owned, but must be deleted on the IO thread so not placing in a
410 // scoped_ptr<>.
411 content::MockResourceContext* resource_context_;
413 #if defined(ENABLE_CONFIGURATION_POLICY)
414 scoped_ptr<policy::SchemaRegistryService> schema_registry_service_;
415 #endif
416 scoped_ptr<policy::ProfilePolicyConnector> profile_policy_connector_;
418 // Weak pointer to a delegate for indicating that a profile was created.
419 Delegate* delegate_;
421 std::string profile_name_;
423 scoped_ptr<policy::PolicyService> policy_service_;
426 #endif // CHROME_TEST_BASE_TESTING_PROFILE_H_