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