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