testing_profile.h revision 010d83a9304c5a91596085d917d248abff47903a
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 content::BrowserPluginGuestManagerDelegate* 226 GetGuestManagerDelegate() OVERRIDE; 227 virtual quota::SpecialStoragePolicy* GetSpecialStoragePolicy() OVERRIDE; 228 229 virtual TestingProfile* AsTestingProfile() OVERRIDE; 230 231 // Profile 232 virtual std::string GetProfileName() OVERRIDE; 233 virtual ProfileType GetProfileType() const OVERRIDE; 234 235 // DEPRECATED, because it's fragile to change a profile from non-incognito 236 // to incognito after the ProfileKeyedServices have been created (some 237 // ProfileKeyedServices either should not exist in incognito mode, or will 238 // crash when they try to get references to other services they depend on, 239 // but do not exist in incognito mode). 240 // TODO(atwilson): Remove this API (http://crbug.com/277296). 241 // 242 // Changes a profile's to/from incognito mode temporarily - profile will be 243 // returned to non-incognito before destruction to allow services to 244 // properly shutdown. This is only supported for legacy tests - new tests 245 // should create a true incognito profile using Builder::SetIncognito() or 246 // by using the TestingProfile constructor that allows setting the incognito 247 // flag. 248 void ForceIncognito(bool force_incognito) { 249 force_incognito_ = force_incognito; 250 } 251 252 // Assumes ownership. 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 IsManaged() OVERRIDE; 260 virtual ExtensionService* GetExtensionService() OVERRIDE; 261 void SetExtensionSpecialStoragePolicy( 262 ExtensionSpecialStoragePolicy* extension_special_storage_policy); 263 virtual ExtensionSpecialStoragePolicy* 264 GetExtensionSpecialStoragePolicy() OVERRIDE; 265 // TODO(ajwong): Remove this API in favor of directly retrieving the 266 // CookieStore from the StoragePartition after ExtensionURLRequestContext 267 // has been removed. 268 net::CookieMonster* GetCookieMonster(); 269 270 virtual PrefService* GetPrefs() OVERRIDE; 271 272 virtual history::TopSites* GetTopSites() OVERRIDE; 273 virtual history::TopSites* GetTopSitesWithoutCreating() OVERRIDE; 274 275 virtual net::URLRequestContextGetter* GetMediaRequestContext() OVERRIDE; 276 virtual net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess( 277 int renderer_child_id) OVERRIDE; 278 virtual net::URLRequestContextGetter* 279 GetRequestContextForExtensions() OVERRIDE; 280 virtual net::URLRequestContextGetter* 281 GetMediaRequestContextForStoragePartition( 282 const base::FilePath& partition_path, 283 bool in_memory) OVERRIDE; 284 virtual void RequestMidiSysExPermission( 285 int render_process_id, 286 int render_view_id, 287 int bridge_id, 288 const GURL& requesting_frame, 289 bool user_gesture, 290 const MidiSysExPermissionCallback& callback) OVERRIDE; 291 virtual void CancelMidiSysExPermissionRequest( 292 int render_process_id, 293 int render_view_id, 294 int bridge_id, 295 const GURL& requesting_frame) OVERRIDE; 296 virtual void RequestProtectedMediaIdentifierPermission( 297 int render_process_id, 298 int render_view_id, 299 int bridge_id, 300 int group_id, 301 const GURL& requesting_frame, 302 const ProtectedMediaIdentifierPermissionCallback& callback) OVERRIDE; 303 virtual void CancelProtectedMediaIdentifierPermissionRequests( 304 int group_id) OVERRIDE; 305 virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition( 306 const base::FilePath& partition_path, 307 bool in_memory, 308 content::ProtocolHandlerMap* protocol_handlers, 309 content::ProtocolHandlerScopedVector protocol_interceptors) OVERRIDE; 310 virtual net::SSLConfigService* GetSSLConfigService() OVERRIDE; 311 virtual HostContentSettingsMap* GetHostContentSettingsMap() OVERRIDE; 312 virtual std::wstring GetName(); 313 virtual void SetName(const std::wstring& name) {} 314 virtual std::wstring GetID(); 315 virtual void SetID(const std::wstring& id); 316 void set_last_session_exited_cleanly(bool value) { 317 last_session_exited_cleanly_ = value; 318 } 319 virtual void MergeResourceString(int message_id, 320 std::wstring* output_string) {} 321 virtual void MergeResourceInteger(int message_id, int* output_value) {} 322 virtual void MergeResourceBoolean(int message_id, bool* output_value) {} 323 virtual bool IsSameProfile(Profile *p) OVERRIDE; 324 virtual base::Time GetStartTime() const OVERRIDE; 325 virtual base::FilePath last_selected_directory() OVERRIDE; 326 virtual void set_last_selected_directory(const base::FilePath& path) OVERRIDE; 327 virtual bool WasCreatedByVersionOrLater(const std::string& version) OVERRIDE; 328 virtual bool IsGuestSession() const OVERRIDE; 329 virtual void SetExitType(ExitType exit_type) OVERRIDE {} 330 virtual ExitType GetLastSessionExitType() OVERRIDE; 331#if defined(OS_CHROMEOS) 332 virtual void ChangeAppLocale(const std::string&, 333 AppLocaleChangedVia) OVERRIDE { 334 } 335 virtual void OnLogin() OVERRIDE { 336 } 337 virtual void InitChromeOSPreferences() OVERRIDE { 338 } 339#endif // defined(OS_CHROMEOS) 340 341 virtual PrefProxyConfigTracker* GetProxyConfigTracker() OVERRIDE; 342 343 // Schedules a task on the history backend and runs a nested loop until the 344 // task is processed. This has the effect of blocking the caller until the 345 // history service processes all pending requests. 346 void BlockUntilHistoryProcessesPendingRequests(); 347 348 virtual chrome_browser_net::Predictor* GetNetworkPredictor() OVERRIDE; 349 virtual void ClearNetworkingHistorySince( 350 base::Time time, 351 const base::Closure& completion) OVERRIDE; 352 virtual GURL GetHomePage() OVERRIDE; 353 354 virtual PrefService* GetOffTheRecordPrefs() OVERRIDE; 355 356 void set_profile_name(const std::string& profile_name) { 357 profile_name_ = profile_name; 358 } 359 360 protected: 361 base::Time start_time_; 362 scoped_ptr<PrefServiceSyncable> prefs_; 363 // ref only for right type, lifecycle is managed by prefs_ 364 TestingPrefServiceSyncable* testing_prefs_; 365 366 private: 367 // Creates a temporary directory for use by this profile. 368 void CreateTempProfileDir(); 369 370 // Common initialization between the two constructors. 371 void Init(); 372 373 // Finishes initialization when a profile is created asynchronously. 374 void FinishInit(); 375 376 // Creates a TestingPrefService and associates it with the TestingProfile. 377 void CreateTestingPrefService(); 378 379 // Creates a ProfilePolicyConnector that the ProfilePolicyConnectorFactory 380 // maps to this profile. 381 void CreateProfilePolicyConnector(); 382 383 // Internally, this is a TestURLRequestContextGetter that creates a dummy 384 // request context. Currently, only the CookieMonster is hooked up. 385 scoped_refptr<net::URLRequestContextGetter> extensions_request_context_; 386 387 std::wstring id_; 388 389 bool incognito_; 390 bool force_incognito_; 391 scoped_ptr<Profile> incognito_profile_; 392 Profile* original_profile_; 393 394 bool guest_session_; 395 396 std::string managed_user_id_; 397 398 // Did the last session exit cleanly? Default is true. 399 bool last_session_exited_cleanly_; 400 401 scoped_refptr<HostContentSettingsMap> host_content_settings_map_; 402 403 base::FilePath last_selected_directory_; 404 scoped_refptr<history::TopSites> top_sites_; // For history and thumbnails. 405 406 scoped_refptr<ExtensionSpecialStoragePolicy> 407 extension_special_storage_policy_; 408 409 // The proxy prefs tracker. 410 scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_; 411 412 // We use a temporary directory to store testing profile data. In a multi- 413 // profile environment, this is invalid and the directory is managed by the 414 // TestingProfileManager. 415 base::ScopedTempDir temp_dir_; 416 // The path to this profile. This will be valid in either of the two above 417 // cases. 418 base::FilePath profile_path_; 419 420 // We keep a weak pointer to the dependency manager we want to notify on our 421 // death. Defaults to the Singleton implementation but overridable for 422 // testing. 423 BrowserContextDependencyManager* browser_context_dependency_manager_; 424 425 // Owned, but must be deleted on the IO thread so not placing in a 426 // scoped_ptr<>. 427 content::MockResourceContext* resource_context_; 428 429#if defined(ENABLE_CONFIGURATION_POLICY) 430 scoped_ptr<policy::SchemaRegistryService> schema_registry_service_; 431#endif 432 scoped_ptr<policy::ProfilePolicyConnector> profile_policy_connector_; 433 434 // Weak pointer to a delegate for indicating that a profile was created. 435 Delegate* delegate_; 436 437 std::string profile_name_; 438 439 scoped_ptr<policy::PolicyService> policy_service_; 440}; 441 442#endif // CHROME_TEST_BASE_TESTING_PROFILE_H_ 443