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