testing_profile.h revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
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 "base/timer.h" 14#include "chrome/browser/custom_handlers/protocol_handler_registry.h" 15#include "chrome/browser/profiles/profile.h" 16 17namespace content { 18class MockResourceContext; 19} 20 21namespace extensions { 22class ExtensionPrefs; 23} 24 25namespace history { 26class TopSites; 27} 28 29namespace net { 30class CookieMonster; 31class URLRequestContextGetter; 32} 33 34namespace quota { 35class SpecialStoragePolicy; 36} 37 38class CommandLine; 39class ExtensionSpecialStoragePolicy; 40class HostContentSettingsMap; 41class PrefServiceSyncable; 42class ProfileDependencyManager; 43class ProfileSyncService; 44class TemplateURLService; 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 // Helper class for building an instance of TestingProfile (allows injecting 61 // mocks for various services prior to profile initialization). 62 // TODO(atwilson): Remove non-default constructors and various setters in 63 // favor of using the Builder API. 64 class Builder { 65 public: 66 Builder(); 67 ~Builder(); 68 69 // Sets a Delegate to be called back when the Profile is fully initialized. 70 // This causes the final initialization to be performed via a task so the 71 // caller must run a MessageLoop. Caller maintains ownership of the Delegate 72 // and must manage its lifetime so it continues to exist until profile 73 // initialization is complete. 74 void SetDelegate(Delegate* delegate); 75 76 // Sets the ExtensionSpecialStoragePolicy to be returned by 77 // GetExtensionSpecialStoragePolicy(). 78 void SetExtensionSpecialStoragePolicy( 79 scoped_refptr<ExtensionSpecialStoragePolicy> policy); 80 81 // Sets the path to the directory to be used to hold profile data. 82 void SetPath(const base::FilePath& path); 83 84 // Sets the PrefService to be used by this profile. 85 void SetPrefService(scoped_ptr<PrefServiceSyncable> prefs); 86 87 // Creates the TestingProfile using previously-set settings. 88 scoped_ptr<TestingProfile> Build(); 89 90 private: 91 // If true, Build() has already been called. 92 bool build_called_; 93 94 // Various staging variables where values are held until Build() is invoked. 95 scoped_ptr<PrefServiceSyncable> pref_service_; 96 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy_; 97 base::FilePath path_; 98 Delegate* delegate_; 99 100 DISALLOW_COPY_AND_ASSIGN(Builder); 101 }; 102 103 // Multi-profile aware constructor that takes the path to a directory managed 104 // for this profile. This constructor is meant to be used by 105 // TestingProfileManager::CreateTestingProfile. If you need to create multi- 106 // profile profiles, use that factory method instead of this directly. 107 // Exception: if you need to create multi-profile profiles for testing the 108 // ProfileManager, then use the constructor below instead. 109 explicit TestingProfile(const base::FilePath& path); 110 111 // Multi-profile aware constructor that takes the path to a directory managed 112 // for this profile and a delegate. This constructor is meant to be used 113 // for unittesting the ProfileManager. 114 TestingProfile(const base::FilePath& path, Delegate* delegate); 115 116 // Full constructor allowing the setting of all possible instance data. 117 // Callers should use Builder::Build() instead of invoking this constructor. 118 TestingProfile(const base::FilePath& path, 119 Delegate* delegate, 120 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy, 121 scoped_ptr<PrefServiceSyncable> prefs); 122 123 virtual ~TestingProfile(); 124 125 // Creates the favicon service. Consequent calls would recreate the service. 126 void CreateFaviconService(); 127 128 // Creates the history service. If |delete_file| is true, the history file is 129 // deleted first, then the HistoryService is created. As TestingProfile 130 // deletes the directory containing the files used by HistoryService, this 131 // only matters if you're recreating the HistoryService. If |no_db| is true, 132 // the history backend will fail to initialize its database; this is useful 133 // for testing error conditions. 134 void CreateHistoryService(bool delete_file, bool no_db); 135 136 // Shuts down and nulls out the reference to HistoryService. 137 void DestroyHistoryService(); 138 139 // Creates TopSites. This returns immediately, and top sites may not be 140 // loaded. Use BlockUntilTopSitesLoaded to ensure TopSites has finished 141 // loading. 142 void CreateTopSites(); 143 144 // Shuts down and nulls out the reference to TopSites. 145 void DestroyTopSites(); 146 147 // Creates the BookmkarBarModel. If not invoked the bookmark bar model is 148 // NULL. If |delete_file| is true, the bookmarks file is deleted first, then 149 // the model is created. As TestingProfile deletes the directory containing 150 // the files used by HistoryService, the boolean only matters if you're 151 // recreating the BookmarkModel. 152 // 153 // NOTE: this does not block until the bookmarks are loaded. For that use 154 // ui_test_utils::WaitForBookmarkModelToLoad. 155 void CreateBookmarkModel(bool delete_file); 156 157 // Creates a WebDataService. If not invoked, the web data service is NULL. 158 void CreateWebDataService(); 159 160 // Blocks until the HistoryService finishes restoring its in-memory cache. 161 // This is NOT invoked from CreateHistoryService. 162 void BlockUntilHistoryIndexIsRefreshed(); 163 164 // Blocks until TopSites finishes loading. 165 void BlockUntilTopSitesLoaded(); 166 167 TestingPrefServiceSyncable* GetTestingPrefService(); 168 169 // content::BrowserContext 170 virtual base::FilePath GetPath() OVERRIDE; 171 virtual scoped_refptr<base::SequencedTaskRunner> GetIOTaskRunner() OVERRIDE; 172 virtual bool IsOffTheRecord() const OVERRIDE; 173 virtual content::DownloadManagerDelegate* 174 GetDownloadManagerDelegate() OVERRIDE; 175 // Returns a testing ContextGetter (if one has been created via 176 // CreateRequestContext) or NULL. This is not done on-demand for two reasons: 177 // (1) Some tests depend on GetRequestContext() returning NULL. (2) Because 178 // of the special memory management considerations for the 179 // TestURLRequestContextGetter class, many tests would find themseleves 180 // leaking if they called this method without the necessary IO thread. This 181 // getter is currently only capable of returning a Context that helps test 182 // the CookieMonster. See implementation comments for more details. 183 virtual net::URLRequestContextGetter* GetRequestContext() OVERRIDE; 184 virtual net::URLRequestContextGetter* CreateRequestContext( 185 content::ProtocolHandlerMap* protocol_handlers) OVERRIDE; 186 virtual net::URLRequestContextGetter* GetRequestContextForRenderProcess( 187 int renderer_child_id) OVERRIDE; 188 virtual content::ResourceContext* GetResourceContext() OVERRIDE; 189 virtual content::GeolocationPermissionContext* 190 GetGeolocationPermissionContext() OVERRIDE; 191 virtual content::SpeechRecognitionPreferences* 192 GetSpeechRecognitionPreferences() OVERRIDE; 193 virtual quota::SpecialStoragePolicy* GetSpecialStoragePolicy() OVERRIDE; 194 195 virtual TestingProfile* AsTestingProfile() OVERRIDE; 196 virtual std::string GetProfileName() OVERRIDE; 197 void set_incognito(bool incognito) { incognito_ = incognito; } 198 // Assumes ownership. 199 virtual void SetOffTheRecordProfile(Profile* profile); 200 virtual void SetOriginalProfile(Profile* profile); 201 virtual Profile* GetOffTheRecordProfile() OVERRIDE; 202 virtual void DestroyOffTheRecordProfile() OVERRIDE {} 203 virtual bool HasOffTheRecordProfile() OVERRIDE; 204 virtual Profile* GetOriginalProfile() OVERRIDE; 205 virtual ExtensionService* GetExtensionService() OVERRIDE; 206 void SetExtensionSpecialStoragePolicy( 207 ExtensionSpecialStoragePolicy* extension_special_storage_policy); 208 virtual ExtensionSpecialStoragePolicy* 209 GetExtensionSpecialStoragePolicy() OVERRIDE; 210 // The CookieMonster will only be returned if a Context has been created. Do 211 // this by calling CreateRequestContext(). See the note at GetRequestContext 212 // for more information. 213 net::CookieMonster* GetCookieMonster(); 214 215 virtual policy::ManagedModePolicyProvider* 216 GetManagedModePolicyProvider() OVERRIDE; 217 virtual policy::PolicyService* GetPolicyService() OVERRIDE; 218 219 virtual PrefService* GetPrefs() OVERRIDE; 220 221 virtual history::TopSites* GetTopSites() OVERRIDE; 222 virtual history::TopSites* GetTopSitesWithoutCreating() OVERRIDE; 223 224 void CreateRequestContext(); 225 // Clears out the created request context (which must be done before shutting 226 // down the IO thread to avoid leaks). 227 void ResetRequestContext(); 228 229 virtual net::URLRequestContextGetter* GetMediaRequestContext() OVERRIDE; 230 virtual net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess( 231 int renderer_child_id) OVERRIDE; 232 virtual net::URLRequestContextGetter* 233 GetRequestContextForExtensions() OVERRIDE; 234 virtual net::URLRequestContextGetter* 235 GetMediaRequestContextForStoragePartition( 236 const base::FilePath& partition_path, 237 bool in_memory) OVERRIDE; 238 virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition( 239 const base::FilePath& partition_path, 240 bool in_memory, 241 content::ProtocolHandlerMap* protocol_handlers) OVERRIDE; 242 virtual net::SSLConfigService* GetSSLConfigService() OVERRIDE; 243 virtual HostContentSettingsMap* GetHostContentSettingsMap() OVERRIDE; 244 virtual std::wstring GetName(); 245 virtual void SetName(const std::wstring& name) {} 246 virtual std::wstring GetID(); 247 virtual void SetID(const std::wstring& id); 248 void set_last_session_exited_cleanly(bool value) { 249 last_session_exited_cleanly_ = value; 250 } 251 virtual void MergeResourceString(int message_id, 252 std::wstring* output_string) {} 253 virtual void MergeResourceInteger(int message_id, int* output_value) {} 254 virtual void MergeResourceBoolean(int message_id, bool* output_value) {} 255 virtual bool IsSameProfile(Profile *p) OVERRIDE; 256 virtual base::Time GetStartTime() const OVERRIDE; 257 virtual ProtocolHandlerRegistry* GetProtocolHandlerRegistry() OVERRIDE; 258 259 virtual base::FilePath last_selected_directory() OVERRIDE; 260 virtual void set_last_selected_directory(const base::FilePath& path) OVERRIDE; 261 virtual bool WasCreatedByVersionOrLater(const std::string& version) OVERRIDE; 262 virtual void SetExitType(ExitType exit_type) OVERRIDE {} 263 virtual ExitType GetLastSessionExitType() OVERRIDE; 264#if defined(OS_CHROMEOS) 265 virtual void SetupChromeOSEnterpriseExtensionObserver() OVERRIDE { 266 } 267 virtual void InitChromeOSPreferences() OVERRIDE { 268 } 269 virtual void ChangeAppLocale(const std::string&, 270 AppLocaleChangedVia) OVERRIDE { 271 } 272 virtual void OnLogin() OVERRIDE { 273 } 274#endif // defined(OS_CHROMEOS) 275 276 virtual PrefProxyConfigTracker* GetProxyConfigTracker() OVERRIDE; 277 278 // Schedules a task on the history backend and runs a nested loop until the 279 // task is processed. This has the effect of blocking the caller until the 280 // history service processes all pending requests. 281 void BlockUntilHistoryProcessesPendingRequests(); 282 283 virtual chrome_browser_net::Predictor* GetNetworkPredictor() OVERRIDE; 284 virtual void ClearNetworkingHistorySince( 285 base::Time time, 286 const base::Closure& completion) OVERRIDE; 287 virtual GURL GetHomePage() OVERRIDE; 288 289 virtual PrefService* GetOffTheRecordPrefs() OVERRIDE; 290 291 protected: 292 base::Time start_time_; 293 scoped_ptr<PrefServiceSyncable> prefs_; 294 // ref only for right type, lifecycle is managed by prefs_ 295 TestingPrefServiceSyncable* testing_prefs_; 296 297 private: 298 // Creates a temporary directory for use by this profile. 299 void CreateTempProfileDir(); 300 301 // Common initialization between the two constructors. 302 void Init(); 303 304 // Finishes initialization when a profile is created asynchronously. 305 void FinishInit(); 306 307 // Creates a TestingPrefService and associates it with the TestingProfile. 308 void CreateTestingPrefService(); 309 310 // The policy service. Lazily created as a stub. 311 scoped_ptr<policy::PolicyService> policy_service_; 312 313 // Internally, this is a TestURLRequestContextGetter that creates a dummy 314 // request context. Currently, only the CookieMonster is hooked up. 315 scoped_refptr<net::URLRequestContextGetter> request_context_; 316 scoped_refptr<net::URLRequestContextGetter> extensions_request_context_; 317 318 std::wstring id_; 319 320 bool incognito_; 321 scoped_ptr<Profile> incognito_profile_; 322 Profile* original_profile_; 323 324 // Did the last session exit cleanly? Default is true. 325 bool last_session_exited_cleanly_; 326 327 scoped_refptr<HostContentSettingsMap> host_content_settings_map_; 328 329 base::FilePath last_selected_directory_; 330 scoped_refptr<history::TopSites> top_sites_; // For history and thumbnails. 331 332 scoped_refptr<ExtensionSpecialStoragePolicy> 333 extension_special_storage_policy_; 334 335 // The proxy prefs tracker. 336 scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_; 337 338 // We use a temporary directory to store testing profile data. In a multi- 339 // profile environment, this is invalid and the directory is managed by the 340 // TestingProfileManager. 341 base::ScopedTempDir temp_dir_; 342 // The path to this profile. This will be valid in either of the two above 343 // cases. 344 base::FilePath profile_path_; 345 346 // We keep a weak pointer to the dependency manager we want to notify on our 347 // death. Defaults to the Singleton implementation but overridable for 348 // testing. 349 ProfileDependencyManager* profile_dependency_manager_; 350 351 scoped_ptr<content::MockResourceContext> resource_context_; 352 353 // Weak pointer to a delegate for indicating that a profile was created. 354 Delegate* delegate_; 355}; 356 357#endif // CHROME_TEST_BASE_TESTING_PROFILE_H_ 358