Home | History | Annotate | Download | only in base
      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 
     17 namespace content {
     18 class MockResourceContext;
     19 }
     20 
     21 namespace history {
     22 class TopSites;
     23 }
     24 
     25 namespace net {
     26 class CookieMonster;
     27 class URLRequestContextGetter;
     28 }
     29 
     30 namespace policy {
     31 class PolicyService;
     32 class ProfilePolicyConnector;
     33 class SchemaRegistryService;
     34 }
     35 
     36 namespace quota {
     37 class SpecialStoragePolicy;
     38 }
     39 
     40 class BrowserContextDependencyManager;
     41 class ExtensionSpecialStoragePolicy;
     42 class HostContentSettingsMap;
     43 class PrefServiceSyncable;
     44 class TestingPrefServiceSyncable;
     45 
     46 class 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 supervised user ID (which is empty by default). If it is set to
    104     // a non-empty string, the profile is supervised.
    105     void SetSupervisedUserId(const std::string& supervised_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 supervised_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& supervised_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::BrowserPluginGuestManager* GetGuestManager() OVERRIDE;
    219   virtual quota::SpecialStoragePolicy* GetSpecialStoragePolicy() OVERRIDE;
    220   virtual content::PushMessagingService* GetPushMessagingService() OVERRIDE;
    221 
    222   virtual TestingProfile* AsTestingProfile() OVERRIDE;
    223 
    224   // Profile
    225   virtual std::string GetProfileName() OVERRIDE;
    226   virtual ProfileType GetProfileType() const OVERRIDE;
    227 
    228   // DEPRECATED, because it's fragile to change a profile from non-incognito
    229   // to incognito after the ProfileKeyedServices have been created (some
    230   // ProfileKeyedServices either should not exist in incognito mode, or will
    231   // crash when they try to get references to other services they depend on,
    232   // but do not exist in incognito mode).
    233   // TODO(atwilson): Remove this API (http://crbug.com/277296).
    234   //
    235   // Changes a profile's to/from incognito mode temporarily - profile will be
    236   // returned to non-incognito before destruction to allow services to
    237   // properly shutdown. This is only supported for legacy tests - new tests
    238   // should create a true incognito profile using Builder::SetIncognito() or
    239   // by using the TestingProfile constructor that allows setting the incognito
    240   // flag.
    241   void ForceIncognito(bool force_incognito) {
    242     force_incognito_ = force_incognito;
    243   }
    244 
    245   // Assumes ownership.
    246   virtual void SetOffTheRecordProfile(scoped_ptr<Profile> profile);
    247   virtual void SetOriginalProfile(Profile* profile);
    248   virtual Profile* GetOffTheRecordProfile() OVERRIDE;
    249   virtual void DestroyOffTheRecordProfile() OVERRIDE {}
    250   virtual bool HasOffTheRecordProfile() OVERRIDE;
    251   virtual Profile* GetOriginalProfile() OVERRIDE;
    252   virtual bool IsSupervised() OVERRIDE;
    253   virtual ExtensionService* GetExtensionService() OVERRIDE;
    254   void SetExtensionSpecialStoragePolicy(
    255       ExtensionSpecialStoragePolicy* extension_special_storage_policy);
    256   virtual ExtensionSpecialStoragePolicy*
    257       GetExtensionSpecialStoragePolicy() OVERRIDE;
    258   // TODO(ajwong): Remove this API in favor of directly retrieving the
    259   // CookieStore from the StoragePartition after ExtensionURLRequestContext
    260   // has been removed.
    261   net::CookieMonster* GetCookieMonster();
    262 
    263   virtual PrefService* GetPrefs() OVERRIDE;
    264 
    265   virtual history::TopSites* GetTopSites() OVERRIDE;
    266   virtual history::TopSites* GetTopSitesWithoutCreating() OVERRIDE;
    267 
    268   virtual net::URLRequestContextGetter* GetMediaRequestContext() OVERRIDE;
    269   virtual net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess(
    270       int renderer_child_id) OVERRIDE;
    271   virtual net::URLRequestContextGetter*
    272       GetRequestContextForExtensions() OVERRIDE;
    273   virtual net::URLRequestContextGetter*
    274       GetMediaRequestContextForStoragePartition(
    275           const base::FilePath& partition_path,
    276           bool in_memory) OVERRIDE;
    277   virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
    278       const base::FilePath& partition_path,
    279       bool in_memory,
    280       content::ProtocolHandlerMap* protocol_handlers,
    281       content::URLRequestInterceptorScopedVector request_interceptors) OVERRIDE;
    282   virtual net::SSLConfigService* GetSSLConfigService() OVERRIDE;
    283   virtual HostContentSettingsMap* GetHostContentSettingsMap() OVERRIDE;
    284   void set_last_session_exited_cleanly(bool value) {
    285     last_session_exited_cleanly_ = value;
    286   }
    287   virtual bool IsSameProfile(Profile *p) OVERRIDE;
    288   virtual base::Time GetStartTime() const OVERRIDE;
    289   virtual base::FilePath last_selected_directory() OVERRIDE;
    290   virtual void set_last_selected_directory(const base::FilePath& path) OVERRIDE;
    291   virtual bool WasCreatedByVersionOrLater(const std::string& version) OVERRIDE;
    292   virtual bool IsGuestSession() const OVERRIDE;
    293   virtual void SetExitType(ExitType exit_type) OVERRIDE {}
    294   virtual ExitType GetLastSessionExitType() OVERRIDE;
    295 #if defined(OS_CHROMEOS)
    296   virtual void ChangeAppLocale(const std::string&,
    297                                AppLocaleChangedVia) OVERRIDE {
    298   }
    299   virtual void OnLogin() OVERRIDE {
    300   }
    301   virtual void InitChromeOSPreferences() OVERRIDE {
    302   }
    303 #endif  // defined(OS_CHROMEOS)
    304 
    305   virtual PrefProxyConfigTracker* GetProxyConfigTracker() OVERRIDE;
    306 
    307   // Schedules a task on the history backend and runs a nested loop until the
    308   // task is processed.  This has the effect of blocking the caller until the
    309   // history service processes all pending requests.
    310   void BlockUntilHistoryProcessesPendingRequests();
    311 
    312   virtual chrome_browser_net::Predictor* GetNetworkPredictor() OVERRIDE;
    313   virtual DevToolsNetworkController* GetDevToolsNetworkController() OVERRIDE;
    314   virtual void ClearNetworkingHistorySince(
    315       base::Time time,
    316       const base::Closure& completion) OVERRIDE;
    317   virtual void ClearDomainReliabilityMonitor(
    318       domain_reliability::DomainReliabilityClearMode mode,
    319       const base::Closure& completion) OVERRIDE;
    320   virtual GURL GetHomePage() OVERRIDE;
    321 
    322   virtual PrefService* GetOffTheRecordPrefs() OVERRIDE;
    323 
    324   void set_profile_name(const std::string& profile_name) {
    325     profile_name_ = profile_name;
    326   }
    327 
    328  protected:
    329   base::Time start_time_;
    330   scoped_ptr<PrefServiceSyncable> prefs_;
    331   // ref only for right type, lifecycle is managed by prefs_
    332   TestingPrefServiceSyncable* testing_prefs_;
    333 
    334  private:
    335   // Creates a temporary directory for use by this profile.
    336   void CreateTempProfileDir();
    337 
    338   // Common initialization between the two constructors.
    339   void Init();
    340 
    341   // Finishes initialization when a profile is created asynchronously.
    342   void FinishInit();
    343 
    344   // Creates a TestingPrefService and associates it with the TestingProfile.
    345   void CreateTestingPrefService();
    346 
    347   // Creates a ProfilePolicyConnector that the ProfilePolicyConnectorFactory
    348   // maps to this profile.
    349   void CreateProfilePolicyConnector();
    350 
    351   // Internally, this is a TestURLRequestContextGetter that creates a dummy
    352   // request context. Currently, only the CookieMonster is hooked up.
    353   scoped_refptr<net::URLRequestContextGetter> extensions_request_context_;
    354 
    355   bool incognito_;
    356   bool force_incognito_;
    357   scoped_ptr<Profile> incognito_profile_;
    358   Profile* original_profile_;
    359 
    360   bool guest_session_;
    361 
    362   std::string supervised_user_id_;
    363 
    364   // Did the last session exit cleanly? Default is true.
    365   bool last_session_exited_cleanly_;
    366 
    367   scoped_refptr<HostContentSettingsMap> host_content_settings_map_;
    368 
    369   base::FilePath last_selected_directory_;
    370   scoped_refptr<history::TopSites> top_sites_;  // For history and thumbnails.
    371 
    372   scoped_refptr<ExtensionSpecialStoragePolicy>
    373       extension_special_storage_policy_;
    374 
    375   // The proxy prefs tracker.
    376   scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_;
    377 
    378   // We use a temporary directory to store testing profile data. In a multi-
    379   // profile environment, this is invalid and the directory is managed by the
    380   // TestingProfileManager.
    381   base::ScopedTempDir temp_dir_;
    382   // The path to this profile. This will be valid in either of the two above
    383   // cases.
    384   base::FilePath profile_path_;
    385 
    386   // We keep a weak pointer to the dependency manager we want to notify on our
    387   // death. Defaults to the Singleton implementation but overridable for
    388   // testing.
    389   BrowserContextDependencyManager* browser_context_dependency_manager_;
    390 
    391   // Owned, but must be deleted on the IO thread so not placing in a
    392   // scoped_ptr<>.
    393   content::MockResourceContext* resource_context_;
    394 
    395 #if defined(ENABLE_CONFIGURATION_POLICY)
    396   scoped_ptr<policy::SchemaRegistryService> schema_registry_service_;
    397 #endif
    398   scoped_ptr<policy::ProfilePolicyConnector> profile_policy_connector_;
    399 
    400   // Weak pointer to a delegate for indicating that a profile was created.
    401   Delegate* delegate_;
    402 
    403   std::string profile_name_;
    404 
    405   scoped_ptr<policy::PolicyService> policy_service_;
    406 };
    407 
    408 #endif  // CHROME_TEST_BASE_TESTING_PROFILE_H_
    409