testing_profile.h revision 03b57e008b61dfcb1fbad3aea950ae0e001748b0
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. 4 5#ifndef CHROME_TEST_BASE_TESTING_PROFILE_H_ 6#define CHROME_TEST_BASE_TESTING_PROFILE_H_ 7 8#include <string> 9 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" 16 17namespace content { 18class MockResourceContext; 19class SSLHostStateDelegate; 20} 21 22namespace history { 23class TopSites; 24} 25 26namespace net { 27class CookieMonster; 28class URLRequestContextGetter; 29} 30 31namespace policy { 32class PolicyService; 33class ProfilePolicyConnector; 34class SchemaRegistryService; 35} 36 37namespace storage { 38class SpecialStoragePolicy; 39} 40 41class BrowserContextDependencyManager; 42class ExtensionSpecialStoragePolicy; 43class HostContentSettingsMap; 44class PrefServiceSyncable; 45class TestingPrefServiceSyncable; 46 47class TestingProfile : public Profile { 48 public: 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[]; 56 57 // Default constructor that cannot be used with multi-profiles. 58 TestingProfile(); 59 60 typedef std::vector<std::pair< 61 BrowserContextKeyedServiceFactory*, 62 BrowserContextKeyedServiceFactory::TestingFactoryFunction> > 63 TestingFactories; 64 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. 69 class Builder { 70 public: 71 Builder(); 72 ~Builder(); 73 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); 80 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); 86 87#if defined(ENABLE_EXTENSIONS) 88 // Sets the ExtensionSpecialStoragePolicy to be returned by 89 // GetExtensionSpecialStoragePolicy(). 90 void SetExtensionSpecialStoragePolicy( 91 scoped_refptr<ExtensionSpecialStoragePolicy> policy); 92#endif 93 94 // Sets the path to the directory to be used to hold profile data. 95 void SetPath(const base::FilePath& path); 96 97 // Sets the PrefService to be used by this profile. 98 void SetPrefService(scoped_ptr<PrefServiceSyncable> prefs); 99 100 // Makes the Profile being built an incognito profile. 101 void SetIncognito(); 102 103 // Makes the Profile being built a guest profile. 104 void SetGuestSession(); 105 106 // Sets the supervised user ID (which is empty by default). If it is set to 107 // a non-empty string, the profile is supervised. 108 void SetSupervisedUserId(const std::string& supervised_user_id); 109 110 // Sets the PolicyService to be used by this profile. 111 void SetPolicyService(scoped_ptr<policy::PolicyService> policy_service); 112 113 // Creates the TestingProfile using previously-set settings. 114 scoped_ptr<TestingProfile> Build(); 115 116 private: 117 // If true, Build() has already been called. 118 bool build_called_; 119 120 // Various staging variables where values are held until Build() is invoked. 121 scoped_ptr<PrefServiceSyncable> pref_service_; 122#if defined(ENABLE_EXTENSIONS) 123 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy_; 124#endif 125 base::FilePath path_; 126 Delegate* delegate_; 127 bool incognito_; 128 bool guest_session_; 129 std::string supervised_user_id_; 130 scoped_ptr<policy::PolicyService> policy_service_; 131 TestingFactories testing_factories_; 132 133 DISALLOW_COPY_AND_ASSIGN(Builder); 134 }; 135 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); 143 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); 148 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, 152 Delegate* delegate, 153#if defined(ENABLE_EXTENSIONS) 154 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy, 155#endif 156 scoped_ptr<PrefServiceSyncable> prefs, 157 bool incognito, 158 bool guest_session, 159 const std::string& supervised_user_id, 160 scoped_ptr<policy::PolicyService> policy_service, 161 const TestingFactories& factories); 162 163 virtual ~TestingProfile(); 164 165 // Creates the favicon service. Consequent calls would recreate the service. 166 void CreateFaviconService(); 167 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; 175 176 // Shuts down and nulls out the reference to HistoryService. 177 void DestroyHistoryService(); 178 179 // Creates TopSites. This returns immediately, and top sites may not be 180 // loaded. Use BlockUntilTopSitesLoaded to ensure TopSites has finished 181 // loading. 182 void CreateTopSites(); 183 184 // Shuts down and nulls out the reference to TopSites. 185 void DestroyTopSites(); 186 187 // Creates the BookmarkBarModel. If not invoked the bookmark bar model is 188 // NULL. If |delete_file| is true, the bookmarks file is deleted first, then 189 // the model is created. As TestingProfile deletes the directory containing 190 // the files used by HistoryService, the boolean only matters if you're 191 // recreating the BookmarkModel. 192 // 193 // NOTE: this does not block until the bookmarks are loaded. For that use 194 // WaitForBookmarkModelToLoad(). 195 void CreateBookmarkModel(bool delete_file); 196 197 // Creates a WebDataService. If not invoked, the web data service is NULL. 198 void CreateWebDataService(); 199 200 // Blocks until the HistoryService finishes restoring its in-memory cache. 201 // This is NOT invoked from CreateHistoryService. 202 void BlockUntilHistoryIndexIsRefreshed(); 203 204 // Blocks until TopSites finishes loading. 205 void BlockUntilTopSitesLoaded(); 206 207 // Allow setting a profile as Guest after-the-fact to simplify some tests. 208 void SetGuestSession(bool guest); 209 210 TestingPrefServiceSyncable* GetTestingPrefService(); 211 212 // content::BrowserContext 213 virtual base::FilePath GetPath() const OVERRIDE; 214 virtual scoped_refptr<base::SequencedTaskRunner> GetIOTaskRunner() OVERRIDE; 215 virtual bool IsOffTheRecord() const OVERRIDE; 216 virtual content::DownloadManagerDelegate* 217 GetDownloadManagerDelegate() OVERRIDE; 218 virtual net::URLRequestContextGetter* GetRequestContext() OVERRIDE; 219 virtual net::URLRequestContextGetter* CreateRequestContext( 220 content::ProtocolHandlerMap* protocol_handlers, 221 content::URLRequestInterceptorScopedVector request_interceptors) OVERRIDE; 222 virtual net::URLRequestContextGetter* GetRequestContextForRenderProcess( 223 int renderer_child_id) OVERRIDE; 224 virtual content::ResourceContext* GetResourceContext() OVERRIDE; 225 virtual content::BrowserPluginGuestManager* GetGuestManager() OVERRIDE; 226 virtual storage::SpecialStoragePolicy* GetSpecialStoragePolicy() OVERRIDE; 227 virtual content::PushMessagingService* GetPushMessagingService() OVERRIDE; 228 virtual content::SSLHostStateDelegate* GetSSLHostStateDelegate() OVERRIDE; 229 230 virtual TestingProfile* AsTestingProfile() OVERRIDE; 231 232 // Profile 233 virtual std::string GetProfileName() OVERRIDE; 234 virtual ProfileType GetProfileType() const OVERRIDE; 235 236 // DEPRECATED, because it's fragile to change a profile from non-incognito 237 // to incognito after the ProfileKeyedServices have been created (some 238 // ProfileKeyedServices either should not exist in incognito mode, or will 239 // crash when they try to get references to other services they depend on, 240 // but do not exist in incognito mode). 241 // TODO(atwilson): Remove this API (http://crbug.com/277296). 242 // 243 // Changes a profile's to/from incognito mode temporarily - profile will be 244 // returned to non-incognito before destruction to allow services to 245 // properly shutdown. This is only supported for legacy tests - new tests 246 // should create a true incognito profile using Builder::SetIncognito() or 247 // by using the TestingProfile constructor that allows setting the incognito 248 // flag. 249 void ForceIncognito(bool force_incognito) { 250 force_incognito_ = force_incognito; 251 } 252 253 virtual void SetOffTheRecordProfile(scoped_ptr<Profile> profile); 254 virtual void SetOriginalProfile(Profile* profile); 255 virtual Profile* GetOffTheRecordProfile() OVERRIDE; 256 virtual void DestroyOffTheRecordProfile() OVERRIDE {} 257 virtual bool HasOffTheRecordProfile() OVERRIDE; 258 virtual Profile* GetOriginalProfile() OVERRIDE; 259 virtual bool IsSupervised() OVERRIDE; 260#if defined(ENABLE_EXTENSIONS) 261 void SetExtensionSpecialStoragePolicy( 262 ExtensionSpecialStoragePolicy* extension_special_storage_policy); 263#endif 264 virtual ExtensionSpecialStoragePolicy* 265 GetExtensionSpecialStoragePolicy() OVERRIDE; 266 // TODO(ajwong): Remove this API in favor of directly retrieving the 267 // CookieStore from the StoragePartition after ExtensionURLRequestContext 268 // has been removed. 269 net::CookieMonster* GetCookieMonster(); 270 271 virtual PrefService* GetPrefs() OVERRIDE; 272 273 virtual history::TopSites* GetTopSites() OVERRIDE; 274 virtual history::TopSites* GetTopSitesWithoutCreating() OVERRIDE; 275 276 virtual net::URLRequestContextGetter* GetMediaRequestContext() OVERRIDE; 277 virtual net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess( 278 int renderer_child_id) OVERRIDE; 279 virtual net::URLRequestContextGetter* 280 GetRequestContextForExtensions() OVERRIDE; 281 virtual net::URLRequestContextGetter* 282 GetMediaRequestContextForStoragePartition( 283 const base::FilePath& partition_path, 284 bool in_memory) OVERRIDE; 285 virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition( 286 const base::FilePath& partition_path, 287 bool in_memory, 288 content::ProtocolHandlerMap* protocol_handlers, 289 content::URLRequestInterceptorScopedVector request_interceptors) OVERRIDE; 290 virtual net::SSLConfigService* GetSSLConfigService() OVERRIDE; 291 virtual HostContentSettingsMap* GetHostContentSettingsMap() OVERRIDE; 292 void set_last_session_exited_cleanly(bool value) { 293 last_session_exited_cleanly_ = value; 294 } 295 virtual bool IsSameProfile(Profile *p) OVERRIDE; 296 virtual base::Time GetStartTime() const OVERRIDE; 297 virtual base::FilePath last_selected_directory() OVERRIDE; 298 virtual void set_last_selected_directory(const base::FilePath& path) OVERRIDE; 299 virtual bool WasCreatedByVersionOrLater(const std::string& version) OVERRIDE; 300 virtual bool IsGuestSession() const OVERRIDE; 301 virtual void SetExitType(ExitType exit_type) OVERRIDE {} 302 virtual ExitType GetLastSessionExitType() OVERRIDE; 303#if defined(OS_CHROMEOS) 304 virtual void ChangeAppLocale(const std::string&, 305 AppLocaleChangedVia) OVERRIDE { 306 } 307 virtual void OnLogin() OVERRIDE { 308 } 309 virtual void InitChromeOSPreferences() OVERRIDE { 310 } 311#endif // defined(OS_CHROMEOS) 312 313 virtual PrefProxyConfigTracker* GetProxyConfigTracker() OVERRIDE; 314 315 // Schedules a task on the history backend and runs a nested loop until the 316 // task is processed. This has the effect of blocking the caller until the 317 // history service processes all pending requests. 318 void BlockUntilHistoryProcessesPendingRequests(); 319 320 virtual chrome_browser_net::Predictor* GetNetworkPredictor() OVERRIDE; 321 virtual DevToolsNetworkController* GetDevToolsNetworkController() OVERRIDE; 322 virtual void ClearNetworkingHistorySince( 323 base::Time time, 324 const base::Closure& completion) OVERRIDE; 325 virtual GURL GetHomePage() OVERRIDE; 326 327 virtual PrefService* GetOffTheRecordPrefs() OVERRIDE; 328 329 void set_profile_name(const std::string& profile_name) { 330 profile_name_ = profile_name; 331 } 332 333 protected: 334 base::Time start_time_; 335 scoped_ptr<PrefServiceSyncable> prefs_; 336 // ref only for right type, lifecycle is managed by prefs_ 337 TestingPrefServiceSyncable* testing_prefs_; 338 339 private: 340 // Creates a temporary directory for use by this profile. 341 void CreateTempProfileDir(); 342 343 // Common initialization between the two constructors. 344 void Init(); 345 346 // Finishes initialization when a profile is created asynchronously. 347 void FinishInit(); 348 349 // Creates a TestingPrefService and associates it with the TestingProfile. 350 void CreateTestingPrefService(); 351 352 // Creates a ProfilePolicyConnector that the ProfilePolicyConnectorFactory 353 // maps to this profile. 354 void CreateProfilePolicyConnector(); 355 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_; 359 360 bool incognito_; 361 bool force_incognito_; 362 scoped_ptr<Profile> incognito_profile_; 363 Profile* original_profile_; 364 365 bool guest_session_; 366 367 std::string supervised_user_id_; 368 369 // Did the last session exit cleanly? Default is true. 370 bool last_session_exited_cleanly_; 371 372 scoped_refptr<HostContentSettingsMap> host_content_settings_map_; 373 374 base::FilePath last_selected_directory_; 375 scoped_refptr<history::TopSites> top_sites_; // For history and thumbnails. 376 377#if defined(ENABLE_EXTENSIONS) 378 scoped_refptr<ExtensionSpecialStoragePolicy> 379 extension_special_storage_policy_; 380#endif 381 382 // The proxy prefs tracker. 383 scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_; 384 385 // We use a temporary directory to store testing profile data. In a multi- 386 // profile environment, this is invalid and the directory is managed by the 387 // TestingProfileManager. 388 base::ScopedTempDir temp_dir_; 389 // The path to this profile. This will be valid in either of the two above 390 // cases. 391 base::FilePath profile_path_; 392 393 // We keep a weak pointer to the dependency manager we want to notify on our 394 // death. Defaults to the Singleton implementation but overridable for 395 // testing. 396 BrowserContextDependencyManager* browser_context_dependency_manager_; 397 398 // Owned, but must be deleted on the IO thread so not placing in a 399 // scoped_ptr<>. 400 content::MockResourceContext* resource_context_; 401 402#if defined(ENABLE_CONFIGURATION_POLICY) 403 scoped_ptr<policy::SchemaRegistryService> schema_registry_service_; 404#endif 405 scoped_ptr<policy::ProfilePolicyConnector> profile_policy_connector_; 406 407 // Weak pointer to a delegate for indicating that a profile was created. 408 Delegate* delegate_; 409 410 std::string profile_name_; 411 412 scoped_ptr<policy::PolicyService> policy_service_; 413}; 414 415#endif // CHROME_TEST_BASE_TESTING_PROFILE_H_ 416