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