Unregister from GCM when the only GCM app is removed
[chromium-blink-merge.git] / chrome / test / base / testing_profile.h
blob9b6faacad189d02e9484876cc3d88bd9ae66509f
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 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 base::FilePath GetPath() const override;
220 scoped_ptr<content::ZoomLevelDelegate> CreateZoomLevelDelegate(
221 const base::FilePath& partition_path) override;
222 scoped_refptr<base::SequencedTaskRunner> GetIOTaskRunner() override;
223 bool IsOffTheRecord() const override;
224 content::DownloadManagerDelegate* GetDownloadManagerDelegate() override;
225 net::URLRequestContextGetter* GetRequestContext() override;
226 net::URLRequestContextGetter* CreateRequestContext(
227 content::ProtocolHandlerMap* protocol_handlers,
228 content::URLRequestInterceptorScopedVector request_interceptors) override;
229 net::URLRequestContextGetter* GetRequestContextForRenderProcess(
230 int renderer_child_id) override;
231 content::ResourceContext* GetResourceContext() override;
232 content::BrowserPluginGuestManager* GetGuestManager() override;
233 storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override;
234 content::PushMessagingService* GetPushMessagingService() override;
235 content::SSLHostStateDelegate* GetSSLHostStateDelegate() override;
237 TestingProfile* AsTestingProfile() override;
239 // Profile
240 std::string GetProfileUserName() override;
241 ProfileType GetProfileType() const override;
243 // DEPRECATED, because it's fragile to change a profile from non-incognito
244 // to incognito after the ProfileKeyedServices have been created (some
245 // ProfileKeyedServices either should not exist in incognito mode, or will
246 // crash when they try to get references to other services they depend on,
247 // but do not exist in incognito mode).
248 // TODO(atwilson): Remove this API (http://crbug.com/277296).
250 // Changes a profile's to/from incognito mode temporarily - profile will be
251 // returned to non-incognito before destruction to allow services to
252 // properly shutdown. This is only supported for legacy tests - new tests
253 // should create a true incognito profile using Builder::SetIncognito() or
254 // by using the TestingProfile constructor that allows setting the incognito
255 // flag.
256 void ForceIncognito(bool force_incognito) {
257 force_incognito_ = force_incognito;
260 Profile* GetOffTheRecordProfile() override;
261 void DestroyOffTheRecordProfile() override {}
262 bool HasOffTheRecordProfile() override;
263 Profile* GetOriginalProfile() override;
264 bool IsSupervised() override;
265 bool IsChild() override;
266 bool IsLegacySupervised() override;
267 #if defined(ENABLE_EXTENSIONS)
268 void SetExtensionSpecialStoragePolicy(
269 ExtensionSpecialStoragePolicy* extension_special_storage_policy);
270 #endif
271 ExtensionSpecialStoragePolicy* GetExtensionSpecialStoragePolicy() override;
272 // TODO(ajwong): Remove this API in favor of directly retrieving the
273 // CookieStore from the StoragePartition after ExtensionURLRequestContext
274 // has been removed.
275 net::CookieMonster* GetCookieMonster();
277 PrefService* GetPrefs() override;
279 net::URLRequestContextGetter* GetMediaRequestContext() override;
280 net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess(
281 int renderer_child_id) override;
282 net::URLRequestContextGetter* GetRequestContextForExtensions() override;
283 net::URLRequestContextGetter* GetMediaRequestContextForStoragePartition(
284 const base::FilePath& partition_path,
285 bool in_memory) override;
286 net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
287 const base::FilePath& partition_path,
288 bool in_memory,
289 content::ProtocolHandlerMap* protocol_handlers,
290 content::URLRequestInterceptorScopedVector request_interceptors) override;
291 net::SSLConfigService* GetSSLConfigService() override;
292 HostContentSettingsMap* GetHostContentSettingsMap() override;
293 void set_last_session_exited_cleanly(bool value) {
294 last_session_exited_cleanly_ = value;
296 bool IsSameProfile(Profile* p) override;
297 base::Time GetStartTime() const override;
298 base::FilePath last_selected_directory() override;
299 void set_last_selected_directory(const base::FilePath& path) override;
300 bool WasCreatedByVersionOrLater(const std::string& version) override;
301 bool IsGuestSession() const override;
302 void SetExitType(ExitType exit_type) override {}
303 ExitType GetLastSessionExitType() override;
304 #if defined(OS_CHROMEOS)
305 void ChangeAppLocale(const std::string&, AppLocaleChangedVia) override {}
306 void OnLogin() override {}
307 void InitChromeOSPreferences() override {}
308 #endif // defined(OS_CHROMEOS)
310 PrefProxyConfigTracker* GetProxyConfigTracker() override;
312 // Schedules a task on the history backend and runs a nested loop until the
313 // task is processed. This has the effect of blocking the caller until the
314 // history service processes all pending requests.
315 void BlockUntilHistoryProcessesPendingRequests();
317 chrome_browser_net::Predictor* GetNetworkPredictor() override;
318 DevToolsNetworkController* GetDevToolsNetworkController() override;
319 void ClearNetworkingHistorySince(base::Time time,
320 const base::Closure& completion) override;
321 GURL GetHomePage() override;
323 PrefService* GetOffTheRecordPrefs() override;
325 void set_profile_name(const std::string& profile_name) {
326 profile_name_ = profile_name;
329 protected:
330 base::Time start_time_;
331 scoped_ptr<PrefServiceSyncable> prefs_;
332 // ref only for right type, lifecycle is managed by prefs_
333 TestingPrefServiceSyncable* testing_prefs_;
335 private:
336 // Creates a temporary directory for use by this profile.
337 void CreateTempProfileDir();
339 // Common initialization between the two constructors.
340 void Init();
342 // Finishes initialization when a profile is created asynchronously.
343 void FinishInit();
345 // Creates a TestingPrefService and associates it with the TestingProfile.
346 void CreateTestingPrefService();
348 // Initializes |prefs_| for an incognito profile, derived from
349 // |original_profile_|.
350 void CreateIncognitoPrefService();
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_;
360 bool force_incognito_;
361 scoped_ptr<Profile> incognito_profile_;
362 TestingProfile* original_profile_;
364 bool guest_session_;
366 std::string supervised_user_id_;
368 // Did the last session exit cleanly? Default is true.
369 bool last_session_exited_cleanly_;
371 scoped_refptr<HostContentSettingsMap> host_content_settings_map_;
373 base::FilePath last_selected_directory_;
375 #if defined(ENABLE_EXTENSIONS)
376 scoped_refptr<ExtensionSpecialStoragePolicy>
377 extension_special_storage_policy_;
378 #endif
380 // The proxy prefs tracker.
381 scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_;
383 // We use a temporary directory to store testing profile data. In a multi-
384 // profile environment, this is invalid and the directory is managed by the
385 // TestingProfileManager.
386 base::ScopedTempDir temp_dir_;
387 // The path to this profile. This will be valid in either of the two above
388 // cases.
389 base::FilePath profile_path_;
391 // We keep a weak pointer to the dependency manager we want to notify on our
392 // death. Defaults to the Singleton implementation but overridable for
393 // testing.
394 BrowserContextDependencyManager* browser_context_dependency_manager_;
396 // Owned, but must be deleted on the IO thread so not placing in a
397 // scoped_ptr<>.
398 content::MockResourceContext* resource_context_;
400 #if defined(ENABLE_CONFIGURATION_POLICY)
401 scoped_ptr<policy::SchemaRegistryService> schema_registry_service_;
402 #endif
403 scoped_ptr<policy::ProfilePolicyConnector> profile_policy_connector_;
405 // Weak pointer to a delegate for indicating that a profile was created.
406 Delegate* delegate_;
408 std::string profile_name_;
410 scoped_ptr<policy::PolicyService> policy_service_;
413 #endif // CHROME_TEST_BASE_TESTING_PROFILE_H_