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