Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / test / base / testing_profile.cc
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 #include "chrome/test/base/testing_profile.h"
6
7 #include "build/build_config.h"
8
9 #include "base/base_paths.h"
10 #include "base/command_line.h"
11 #include "base/file_util.h"
12 #include "base/message_loop/message_loop_proxy.h"
13 #include "base/path_service.h"
14 #include "base/prefs/testing_pref_store.h"
15 #include "base/run_loop.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
18 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
19 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/chrome_notification_types.h"
22 #include "chrome/browser/content_settings/host_content_settings_map.h"
23 #include "chrome/browser/extensions/extension_service.h"
24 #include "chrome/browser/extensions/extension_special_storage_policy.h"
25 #include "chrome/browser/extensions/extension_system_factory.h"
26 #include "chrome/browser/extensions/test_extension_system.h"
27 #include "chrome/browser/favicon/favicon_service.h"
28 #include "chrome/browser/favicon/favicon_service_factory.h"
29 #include "chrome/browser/geolocation/chrome_geolocation_permission_context.h"
30 #include "chrome/browser/geolocation/chrome_geolocation_permission_context_factory.h"
31 #include "chrome/browser/guest_view/guest_view_manager.h"
32 #include "chrome/browser/history/history_backend.h"
33 #include "chrome/browser/history/history_db_task.h"
34 #include "chrome/browser/history/history_service.h"
35 #include "chrome/browser/history/history_service_factory.h"
36 #include "chrome/browser/history/top_sites.h"
37 #include "chrome/browser/history/web_history_service_factory.h"
38 #include "chrome/browser/net/pref_proxy_config_tracker.h"
39 #include "chrome/browser/net/proxy_service_factory.h"
40 #include "chrome/browser/notifications/desktop_notification_service.h"
41 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
42 #include "chrome/browser/policy/profile_policy_connector.h"
43 #include "chrome/browser/policy/profile_policy_connector_factory.h"
44 #include "chrome/browser/prefs/browser_prefs.h"
45 #include "chrome/browser/prefs/pref_service_syncable.h"
46 #include "chrome/browser/prerender/prerender_manager.h"
47 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
48 #include "chrome/browser/profiles/profile_manager.h"
49 #include "chrome/browser/profiles/storage_partition_descriptor.h"
50 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
51 #include "chrome/browser/webdata/web_data_service.h"
52 #include "chrome/browser/webdata/web_data_service_factory.h"
53 #include "chrome/common/chrome_constants.h"
54 #include "chrome/common/chrome_switches.h"
55 #include "chrome/common/pref_names.h"
56 #include "chrome/common/url_constants.h"
57 #include "chrome/test/base/history_index_restore_observer.h"
58 #include "chrome/test/base/testing_pref_service_syncable.h"
59 #include "chrome/test/base/ui_test_utils.h"
60 #include "components/bookmarks/core/browser/bookmark_model.h"
61 #include "components/bookmarks/core/common/bookmark_constants.h"
62 #include "components/keyed_service/content/browser_context_dependency_manager.h"
63 #include "components/policy/core/common/policy_service.h"
64 #include "components/user_prefs/user_prefs.h"
65 #include "content/public/browser/browser_thread.h"
66 #include "content/public/browser/cookie_store_factory.h"
67 #include "content/public/browser/notification_service.h"
68 #include "content/public/browser/render_process_host.h"
69 #include "content/public/browser/storage_partition.h"
70 #include "content/public/test/mock_resource_context.h"
71 #include "content/public/test/test_utils.h"
72 #include "extensions/browser/extension_system.h"
73 #include "extensions/common/constants.h"
74 #include "net/cookies/cookie_monster.h"
75 #include "net/url_request/url_request_context.h"
76 #include "net/url_request/url_request_context_getter.h"
77 #include "net/url_request/url_request_test_util.h"
78 #include "testing/gmock/include/gmock/gmock.h"
79
80 #if defined(ENABLE_CONFIGURATION_POLICY)
81 #include "chrome/browser/policy/schema_registry_service.h"
82 #include "chrome/browser/policy/schema_registry_service_factory.h"
83 #include "components/policy/core/common/configuration_policy_provider.h"
84 #include "components/policy/core/common/policy_service_impl.h"
85 #include "components/policy/core/common/schema.h"
86 #else
87 #include "components/policy/core/common/policy_service_stub.h"
88 #endif  // defined(ENABLE_CONFIGURATION_POLICY)
89
90 #if defined(ENABLE_MANAGED_USERS)
91 #include "chrome/browser/managed_mode/managed_user_settings_service.h"
92 #include "chrome/browser/managed_mode/managed_user_settings_service_factory.h"
93 #endif
94
95 using base::Time;
96 using content::BrowserThread;
97 using content::DownloadManagerDelegate;
98 using testing::NiceMock;
99 using testing::Return;
100
101 namespace {
102
103 // Task used to make sure history has finished processing a request. Intended
104 // for use with BlockUntilHistoryProcessesPendingRequests.
105
106 class QuittingHistoryDBTask : public history::HistoryDBTask {
107  public:
108   QuittingHistoryDBTask() {}
109
110   virtual bool RunOnDBThread(history::HistoryBackend* backend,
111                              history::HistoryDatabase* db) OVERRIDE {
112     return true;
113   }
114
115   virtual void DoneRunOnMainThread() OVERRIDE {
116     base::MessageLoop::current()->Quit();
117   }
118
119  private:
120   virtual ~QuittingHistoryDBTask() {}
121
122   DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
123 };
124
125 class TestExtensionURLRequestContext : public net::URLRequestContext {
126  public:
127   TestExtensionURLRequestContext() {
128     net::CookieMonster* cookie_monster =
129         content::CreateCookieStore(content::CookieStoreConfig())->
130             GetCookieMonster();
131     const char* schemes[] = {extensions::kExtensionScheme};
132     cookie_monster->SetCookieableSchemes(schemes, 1);
133     set_cookie_store(cookie_monster);
134   }
135
136   virtual ~TestExtensionURLRequestContext() {}
137 };
138
139 class TestExtensionURLRequestContextGetter
140     : public net::URLRequestContextGetter {
141  public:
142   virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE {
143     if (!context_.get())
144       context_.reset(new TestExtensionURLRequestContext());
145     return context_.get();
146   }
147   virtual scoped_refptr<base::SingleThreadTaskRunner>
148       GetNetworkTaskRunner() const OVERRIDE {
149     return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
150   }
151
152  protected:
153   virtual ~TestExtensionURLRequestContextGetter() {}
154
155  private:
156   scoped_ptr<net::URLRequestContext> context_;
157 };
158
159 #if defined(ENABLE_NOTIFICATIONS)
160 KeyedService* CreateTestDesktopNotificationService(
161     content::BrowserContext* profile) {
162   return new DesktopNotificationService(static_cast<Profile*>(profile), NULL);
163 }
164 #endif
165
166 }  // namespace
167
168 // static
169 #if defined(OS_CHROMEOS)
170 // Must be kept in sync with
171 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
172 const char TestingProfile::kTestUserProfileDir[] = "test-user";
173 #else
174 const char TestingProfile::kTestUserProfileDir[] = "Default";
175 #endif
176
177 TestingProfile::TestingProfile()
178     : start_time_(Time::Now()),
179       testing_prefs_(NULL),
180       incognito_(false),
181       force_incognito_(false),
182       original_profile_(NULL),
183       guest_session_(false),
184       last_session_exited_cleanly_(true),
185       browser_context_dependency_manager_(
186           BrowserContextDependencyManager::GetInstance()),
187       resource_context_(NULL),
188       delegate_(NULL) {
189   CreateTempProfileDir();
190   profile_path_ = temp_dir_.path();
191
192   Init();
193   FinishInit();
194 }
195
196 TestingProfile::TestingProfile(const base::FilePath& path)
197     : start_time_(Time::Now()),
198       testing_prefs_(NULL),
199       incognito_(false),
200       force_incognito_(false),
201       original_profile_(NULL),
202       guest_session_(false),
203       last_session_exited_cleanly_(true),
204       profile_path_(path),
205       browser_context_dependency_manager_(
206           BrowserContextDependencyManager::GetInstance()),
207       resource_context_(NULL),
208       delegate_(NULL) {
209   Init();
210   FinishInit();
211 }
212
213 TestingProfile::TestingProfile(const base::FilePath& path,
214                                Delegate* delegate)
215     : start_time_(Time::Now()),
216       testing_prefs_(NULL),
217       incognito_(false),
218       force_incognito_(false),
219       original_profile_(NULL),
220       guest_session_(false),
221       last_session_exited_cleanly_(true),
222       profile_path_(path),
223       browser_context_dependency_manager_(
224           BrowserContextDependencyManager::GetInstance()),
225       resource_context_(NULL),
226       delegate_(delegate) {
227   Init();
228   if (delegate_) {
229     base::MessageLoop::current()->PostTask(
230         FROM_HERE,
231         base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
232   } else {
233     FinishInit();
234   }
235 }
236
237 TestingProfile::TestingProfile(
238     const base::FilePath& path,
239     Delegate* delegate,
240     scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
241     scoped_ptr<PrefServiceSyncable> prefs,
242     bool incognito,
243     bool guest_session,
244     const std::string& managed_user_id,
245     scoped_ptr<policy::PolicyService> policy_service,
246     const TestingFactories& factories)
247     : start_time_(Time::Now()),
248       prefs_(prefs.release()),
249       testing_prefs_(NULL),
250       incognito_(incognito),
251       force_incognito_(false),
252       original_profile_(NULL),
253       guest_session_(guest_session),
254       managed_user_id_(managed_user_id),
255       last_session_exited_cleanly_(true),
256       extension_special_storage_policy_(extension_policy),
257       profile_path_(path),
258       browser_context_dependency_manager_(
259           BrowserContextDependencyManager::GetInstance()),
260       resource_context_(NULL),
261       delegate_(delegate),
262       policy_service_(policy_service.release()) {
263
264   // If no profile path was supplied, create one.
265   if (profile_path_.empty()) {
266     CreateTempProfileDir();
267     profile_path_ = temp_dir_.path();
268   }
269
270   // Set any testing factories prior to initializing the services.
271   for (TestingFactories::const_iterator it = factories.begin();
272        it != factories.end(); ++it) {
273     it->first->SetTestingFactory(this, it->second);
274   }
275
276   Init();
277   // If caller supplied a delegate, delay the FinishInit invocation until other
278   // tasks have run.
279   // TODO(atwilson): See if this is still required once we convert the current
280   // users of the constructor that takes a Delegate* param.
281   if (delegate_) {
282     base::MessageLoop::current()->PostTask(
283         FROM_HERE,
284         base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
285   } else {
286     FinishInit();
287   }
288 }
289
290 void TestingProfile::CreateTempProfileDir() {
291   if (!temp_dir_.CreateUniqueTempDir()) {
292     LOG(ERROR) << "Failed to create unique temporary directory.";
293
294     // Fallback logic in case we fail to create unique temporary directory.
295     base::FilePath system_tmp_dir;
296     bool success = PathService::Get(base::DIR_TEMP, &system_tmp_dir);
297
298     // We're severly screwed if we can't get the system temporary
299     // directory. Die now to avoid writing to the filesystem root
300     // or other bad places.
301     CHECK(success);
302
303     base::FilePath fallback_dir(
304         system_tmp_dir.AppendASCII("TestingProfilePath"));
305     base::DeleteFile(fallback_dir, true);
306     base::CreateDirectory(fallback_dir);
307     if (!temp_dir_.Set(fallback_dir)) {
308       // That shouldn't happen, but if it does, try to recover.
309       LOG(ERROR) << "Failed to use a fallback temporary directory.";
310
311       // We're screwed if this fails, see CHECK above.
312       CHECK(temp_dir_.Set(system_tmp_dir));
313     }
314   }
315 }
316
317 void TestingProfile::Init() {
318   // If threads have been initialized, we should be on the UI thread.
319   DCHECK(!content::BrowserThread::IsThreadInitialized(
320              content::BrowserThread::UI) ||
321          content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
322
323   // Normally this would happen during browser startup, but for tests
324   // we need to trigger creation of Profile-related services.
325   ChromeBrowserMainExtraPartsProfiles::
326       EnsureBrowserContextKeyedServiceFactoriesBuilt();
327
328   if (prefs_.get())
329     user_prefs::UserPrefs::Set(this, prefs_.get());
330   else
331     CreateTestingPrefService();
332
333   if (!base::PathExists(profile_path_))
334     base::CreateDirectory(profile_path_);
335
336   // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
337   // anymore, after converting the PrefService to a PKS. Until then it must
338   // be associated with a TestingProfile too.
339   if (!IsOffTheRecord())
340     CreateProfilePolicyConnector();
341
342   extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
343       this, extensions::TestExtensionSystem::Build);
344
345   // If no original profile was specified for this profile: register preferences
346   // even if this is an incognito profile - this allows tests to create a
347   // standalone incognito profile while still having prefs registered.
348   if (!IsOffTheRecord() || !original_profile_) {
349     user_prefs::PrefRegistrySyncable* pref_registry =
350         static_cast<user_prefs::PrefRegistrySyncable*>(
351             prefs_->DeprecatedGetPrefRegistry());
352     browser_context_dependency_manager_->
353         RegisterProfilePrefsForServices(this, pref_registry);
354   }
355
356   browser_context_dependency_manager_->CreateBrowserContextServicesForTest(
357       this);
358
359 #if defined(ENABLE_NOTIFICATIONS)
360   // Install profile keyed service factory hooks for dummy/test services
361   DesktopNotificationServiceFactory::GetInstance()->SetTestingFactory(
362       this, CreateTestDesktopNotificationService);
363 #endif
364
365 #if defined(ENABLE_MANAGED_USERS)
366   ManagedUserSettingsService* settings_service =
367       ManagedUserSettingsServiceFactory::GetForProfile(this);
368   TestingPrefStore* store = new TestingPrefStore();
369   settings_service->Init(store);
370   store->SetInitializationCompleted();
371 #endif
372
373   profile_name_ = "testing_profile";
374 }
375
376 void TestingProfile::FinishInit() {
377   DCHECK(content::NotificationService::current());
378   content::NotificationService::current()->Notify(
379       chrome::NOTIFICATION_PROFILE_CREATED,
380       content::Source<Profile>(static_cast<Profile*>(this)),
381       content::NotificationService::NoDetails());
382
383   ProfileManager* profile_manager = g_browser_process->profile_manager();
384   if (profile_manager)
385     profile_manager->InitProfileUserPrefs(this);
386
387   if (delegate_)
388     delegate_->OnProfileCreated(this, true, false);
389 }
390
391 TestingProfile::~TestingProfile() {
392   // Revert to non-incognito mode before shutdown.
393   force_incognito_ = false;
394
395   // Any objects holding live URLFetchers should be deleted before teardown.
396   TemplateURLFetcherFactory::ShutdownForProfile(this);
397
398   MaybeSendDestroyedNotification();
399
400   browser_context_dependency_manager_->DestroyBrowserContextServices(this);
401
402   if (host_content_settings_map_.get())
403     host_content_settings_map_->ShutdownOnUIThread();
404
405   DestroyTopSites();
406
407   if (pref_proxy_config_tracker_.get())
408     pref_proxy_config_tracker_->DetachFromPrefService();
409   // Failing a post == leaks == heapcheck failure. Make that an immediate test
410   // failure.
411   if (resource_context_) {
412     CHECK(BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
413                                     resource_context_));
414     resource_context_ = NULL;
415     content::RunAllPendingInMessageLoop(BrowserThread::IO);
416   }
417 }
418
419 static KeyedService* BuildFaviconService(content::BrowserContext* profile) {
420   return new FaviconService(static_cast<Profile*>(profile));
421 }
422
423 void TestingProfile::CreateFaviconService() {
424   // It is up to the caller to create the history service if one is needed.
425   FaviconServiceFactory::GetInstance()->SetTestingFactory(
426       this, BuildFaviconService);
427 }
428
429 static KeyedService* BuildHistoryService(content::BrowserContext* profile) {
430   return new HistoryService(static_cast<Profile*>(profile));
431 }
432
433 bool TestingProfile::CreateHistoryService(bool delete_file, bool no_db) {
434   DestroyHistoryService();
435   if (delete_file) {
436     base::FilePath path = GetPath();
437     path = path.Append(chrome::kHistoryFilename);
438     if (!base::DeleteFile(path, false) || base::PathExists(path))
439       return false;
440   }
441   // This will create and init the history service.
442   HistoryService* history_service = static_cast<HistoryService*>(
443       HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
444           this, BuildHistoryService));
445   if (!history_service->Init(this->GetPath(),
446                              BookmarkModelFactory::GetForProfile(this),
447                              no_db)) {
448     HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(this, NULL);
449   }
450   // Disable WebHistoryService by default, since it makes network requests.
451   WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, NULL);
452   return true;
453 }
454
455 void TestingProfile::DestroyHistoryService() {
456   HistoryService* history_service =
457       HistoryServiceFactory::GetForProfileWithoutCreating(this);
458   if (!history_service)
459     return;
460
461   history_service->NotifyRenderProcessHostDestruction(0);
462   history_service->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
463   history_service->Cleanup();
464   HistoryServiceFactory::ShutdownForProfile(this);
465
466   // Wait for the backend class to terminate before deleting the files and
467   // moving to the next test. Note: if this never terminates, somebody is
468   // probably leaking a reference to the history backend, so it never calls
469   // our destroy task.
470   base::MessageLoop::current()->Run();
471
472   // Make sure we don't have any event pending that could disrupt the next
473   // test.
474   base::MessageLoop::current()->PostTask(FROM_HERE,
475                                          base::MessageLoop::QuitClosure());
476   base::MessageLoop::current()->Run();
477 }
478
479 void TestingProfile::CreateTopSites() {
480   DestroyTopSites();
481   top_sites_ = history::TopSites::Create(
482       this, GetPath().Append(chrome::kTopSitesFilename));
483 }
484
485 void TestingProfile::DestroyTopSites() {
486   if (top_sites_.get()) {
487     top_sites_->Shutdown();
488     top_sites_ = NULL;
489     // TopSitesImpl::Shutdown schedules some tasks (from TopSitesBackend) that
490     // need to be run to properly shutdown. Run all pending tasks now. This is
491     // normally handled by browser_process shutdown.
492     if (base::MessageLoop::current())
493       base::MessageLoop::current()->RunUntilIdle();
494   }
495 }
496
497 static KeyedService* BuildBookmarkModel(content::BrowserContext* context) {
498   Profile* profile = static_cast<Profile*>(context);
499   ChromeBookmarkClient* bookmark_client =
500       new ChromeBookmarkClient(profile, false);
501   bookmark_client->model()->Load(
502       profile->GetPrefs(),
503       profile->GetPrefs()->GetString(prefs::kAcceptLanguages),
504       profile->GetPath(),
505       profile->GetIOTaskRunner(),
506       content::BrowserThread::GetMessageLoopProxyForThread(
507           content::BrowserThread::UI));
508   return bookmark_client;
509 }
510
511 void TestingProfile::CreateBookmarkModel(bool delete_file) {
512   if (delete_file) {
513     base::FilePath path = GetPath().Append(bookmarks::kBookmarksFileName);
514     base::DeleteFile(path, false);
515   }
516   // This will create a bookmark model.
517   BookmarkModel* bookmark_service =
518       static_cast<ChromeBookmarkClient*>(
519           BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
520               this, BuildBookmarkModel))->model();
521
522   HistoryService* history_service =
523       HistoryServiceFactory::GetForProfileWithoutCreating(this);
524   if (history_service) {
525     history_service->history_backend_->bookmark_service_ = bookmark_service;
526     history_service->history_backend_->expirer_.bookmark_service_ =
527         bookmark_service;
528   }
529 }
530
531 static KeyedService* BuildWebDataService(content::BrowserContext* profile) {
532   return new WebDataServiceWrapper(static_cast<Profile*>(profile));
533 }
534
535 void TestingProfile::CreateWebDataService() {
536   WebDataServiceFactory::GetInstance()->SetTestingFactory(
537       this, BuildWebDataService);
538 }
539
540 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
541   // Only get the history service if it actually exists since the caller of the
542   // test should explicitly call CreateHistoryService to build it.
543   HistoryService* history_service =
544       HistoryServiceFactory::GetForProfileWithoutCreating(this);
545   DCHECK(history_service);
546   history::InMemoryURLIndex* index = history_service->InMemoryIndex();
547   if (!index || index->restored())
548     return;
549   base::RunLoop run_loop;
550   HistoryIndexRestoreObserver observer(
551       content::GetQuitTaskForRunLoop(&run_loop));
552   index->set_restore_cache_observer(&observer);
553   run_loop.Run();
554   index->set_restore_cache_observer(NULL);
555   DCHECK(index->restored());
556 }
557
558 // TODO(phajdan.jr): Doesn't this hang if Top Sites are already loaded?
559 void TestingProfile::BlockUntilTopSitesLoaded() {
560   content::WindowedNotificationObserver top_sites_loaded_observer(
561       chrome::NOTIFICATION_TOP_SITES_LOADED,
562       content::NotificationService::AllSources());
563   top_sites_loaded_observer.Wait();
564 }
565
566 void TestingProfile::SetGuestSession(bool guest) {
567   guest_session_ = guest;
568 }
569
570 base::FilePath TestingProfile::GetPath() const {
571   return profile_path_;
572 }
573
574 scoped_refptr<base::SequencedTaskRunner> TestingProfile::GetIOTaskRunner() {
575   return base::MessageLoop::current()->message_loop_proxy();
576 }
577
578 TestingPrefServiceSyncable* TestingProfile::GetTestingPrefService() {
579   if (!prefs_.get())
580     CreateTestingPrefService();
581   DCHECK(testing_prefs_);
582   return testing_prefs_;
583 }
584
585 TestingProfile* TestingProfile::AsTestingProfile() {
586   return this;
587 }
588
589 std::string TestingProfile::GetProfileName() {
590   return profile_name_;
591 }
592
593 Profile::ProfileType TestingProfile::GetProfileType() const {
594   if (guest_session_)
595     return GUEST_PROFILE;
596   if (force_incognito_ || incognito_)
597     return INCOGNITO_PROFILE;
598   return REGULAR_PROFILE;
599 }
600
601 bool TestingProfile::IsOffTheRecord() const {
602   return force_incognito_ || incognito_;
603 }
604
605 void TestingProfile::SetOffTheRecordProfile(scoped_ptr<Profile> profile) {
606   DCHECK(!IsOffTheRecord());
607   incognito_profile_ = profile.Pass();
608 }
609
610 void TestingProfile::SetOriginalProfile(Profile* profile) {
611   DCHECK(IsOffTheRecord());
612   original_profile_ = profile;
613 }
614
615 Profile* TestingProfile::GetOffTheRecordProfile() {
616   if (IsOffTheRecord())
617     return this;
618   if (!incognito_profile_) {
619     TestingProfile::Builder builder;
620     builder.SetIncognito();
621     scoped_ptr<TestingProfile> incognito_test_profile(builder.Build());
622     incognito_test_profile->SetOriginalProfile(this);
623     SetOffTheRecordProfile(incognito_test_profile.PassAs<Profile>());
624   }
625   return incognito_profile_.get();
626 }
627
628 bool TestingProfile::HasOffTheRecordProfile() {
629   return incognito_profile_.get() != NULL;
630 }
631
632 Profile* TestingProfile::GetOriginalProfile() {
633   if (original_profile_)
634     return original_profile_;
635   return this;
636 }
637
638 bool TestingProfile::IsManaged() {
639   return !managed_user_id_.empty();
640 }
641
642 ExtensionService* TestingProfile::GetExtensionService() {
643   return extensions::ExtensionSystem::Get(this)->extension_service();
644 }
645
646 void TestingProfile::SetExtensionSpecialStoragePolicy(
647     ExtensionSpecialStoragePolicy* extension_special_storage_policy) {
648   extension_special_storage_policy_ = extension_special_storage_policy;
649 }
650
651 ExtensionSpecialStoragePolicy*
652 TestingProfile::GetExtensionSpecialStoragePolicy() {
653   if (!extension_special_storage_policy_.get())
654     extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(NULL);
655   return extension_special_storage_policy_.get();
656 }
657
658 net::CookieMonster* TestingProfile::GetCookieMonster() {
659   if (!GetRequestContext())
660     return NULL;
661   return GetRequestContext()->GetURLRequestContext()->cookie_store()->
662       GetCookieMonster();
663 }
664
665 void TestingProfile::CreateTestingPrefService() {
666   DCHECK(!prefs_.get());
667   testing_prefs_ = new TestingPrefServiceSyncable();
668   prefs_.reset(testing_prefs_);
669   user_prefs::UserPrefs::Set(this, prefs_.get());
670   chrome::RegisterUserProfilePrefs(testing_prefs_->registry());
671 }
672
673 void TestingProfile::CreateProfilePolicyConnector() {
674 #if defined(ENABLE_CONFIGURATION_POLICY)
675   schema_registry_service_ =
676       policy::SchemaRegistryServiceFactory::CreateForContext(
677           this, policy::Schema(), NULL);
678   CHECK_EQ(schema_registry_service_.get(),
679            policy::SchemaRegistryServiceFactory::GetForContext(this));
680 #endif  // defined(ENABLE_CONFIGURATION_POLICY)
681
682 if (!policy_service_) {
683 #if defined(ENABLE_CONFIGURATION_POLICY)
684     std::vector<policy::ConfigurationPolicyProvider*> providers;
685     policy_service_.reset(new policy::PolicyServiceImpl(providers));
686 #else
687     policy_service_.reset(new policy::PolicyServiceStub());
688 #endif
689   }
690   profile_policy_connector_.reset(new policy::ProfilePolicyConnector());
691   profile_policy_connector_->InitForTesting(policy_service_.Pass());
692   policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
693       this, profile_policy_connector_.get());
694   CHECK_EQ(profile_policy_connector_.get(),
695            policy::ProfilePolicyConnectorFactory::GetForProfile(this));
696 }
697
698 PrefService* TestingProfile::GetPrefs() {
699   if (!prefs_.get()) {
700     CreateTestingPrefService();
701   }
702   return prefs_.get();
703 }
704
705 history::TopSites* TestingProfile::GetTopSites() {
706   return top_sites_.get();
707 }
708
709 history::TopSites* TestingProfile::GetTopSitesWithoutCreating() {
710   return top_sites_.get();
711 }
712
713 DownloadManagerDelegate* TestingProfile::GetDownloadManagerDelegate() {
714   return NULL;
715 }
716
717 net::URLRequestContextGetter* TestingProfile::GetRequestContext() {
718   return GetDefaultStoragePartition(this)->GetURLRequestContext();
719 }
720
721 net::URLRequestContextGetter* TestingProfile::CreateRequestContext(
722     content::ProtocolHandlerMap* protocol_handlers,
723     content::ProtocolHandlerScopedVector protocol_interceptors) {
724   return new net::TestURLRequestContextGetter(
725             BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
726 }
727
728 net::URLRequestContextGetter* TestingProfile::GetRequestContextForRenderProcess(
729     int renderer_child_id) {
730   content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
731       renderer_child_id);
732   return rph->GetStoragePartition()->GetURLRequestContext();
733 }
734
735 net::URLRequestContextGetter* TestingProfile::GetMediaRequestContext() {
736   return NULL;
737 }
738
739 net::URLRequestContextGetter*
740 TestingProfile::GetMediaRequestContextForRenderProcess(
741     int renderer_child_id) {
742   return NULL;
743 }
744
745 net::URLRequestContextGetter*
746 TestingProfile::GetMediaRequestContextForStoragePartition(
747     const base::FilePath& partition_path,
748     bool in_memory) {
749   return NULL;
750 }
751
752 void TestingProfile::RequestMidiSysExPermission(
753       int render_process_id,
754       int render_view_id,
755       int bridge_id,
756       const GURL& requesting_frame,
757       bool user_gesture,
758       const MidiSysExPermissionCallback& callback) {
759   // Always reject requests for testing.
760   callback.Run(false);
761 }
762
763 void TestingProfile::CancelMidiSysExPermissionRequest(
764     int render_process_id,
765     int render_view_id,
766     int bridge_id,
767     const GURL& requesting_frame) {
768 }
769
770 void TestingProfile::RequestProtectedMediaIdentifierPermission(
771     int render_process_id,
772     int render_view_id,
773     int bridge_id,
774     int group_id,
775     const GURL& requesting_frame,
776     const ProtectedMediaIdentifierPermissionCallback& callback) {
777   // Always reject requests for testing.
778   callback.Run(false);
779 }
780
781 void TestingProfile::CancelProtectedMediaIdentifierPermissionRequests(
782     int group_id) {
783 }
784
785 net::URLRequestContextGetter* TestingProfile::GetRequestContextForExtensions() {
786   if (!extensions_request_context_.get())
787     extensions_request_context_ = new TestExtensionURLRequestContextGetter();
788   return extensions_request_context_.get();
789 }
790
791 net::SSLConfigService* TestingProfile::GetSSLConfigService() {
792   if (!GetRequestContext())
793     return NULL;
794   return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
795 }
796
797 net::URLRequestContextGetter*
798 TestingProfile::CreateRequestContextForStoragePartition(
799     const base::FilePath& partition_path,
800     bool in_memory,
801     content::ProtocolHandlerMap* protocol_handlers,
802     content::ProtocolHandlerScopedVector protocol_interceptors) {
803   // We don't test storage partitions here yet, so returning the same dummy
804   // context is sufficient for now.
805   return GetRequestContext();
806 }
807
808 content::ResourceContext* TestingProfile::GetResourceContext() {
809   if (!resource_context_)
810     resource_context_ = new content::MockResourceContext();
811   return resource_context_;
812 }
813
814 HostContentSettingsMap* TestingProfile::GetHostContentSettingsMap() {
815   if (!host_content_settings_map_.get()) {
816     host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
817 #if defined(ENABLE_EXTENSIONS)
818     ExtensionService* extension_service = GetExtensionService();
819     if (extension_service)
820       host_content_settings_map_->RegisterExtensionService(extension_service);
821 #endif
822   }
823   return host_content_settings_map_.get();
824 }
825
826 content::GeolocationPermissionContext*
827 TestingProfile::GetGeolocationPermissionContext() {
828   return ChromeGeolocationPermissionContextFactory::GetForProfile(this);
829 }
830
831 content::BrowserPluginGuestManagerDelegate*
832     TestingProfile::GetGuestManagerDelegate() {
833   return GuestViewManager::FromBrowserContext(this);
834 }
835
836 std::wstring TestingProfile::GetName() {
837   return std::wstring();
838 }
839
840 std::wstring TestingProfile::GetID() {
841   return id_;
842 }
843
844 void TestingProfile::SetID(const std::wstring& id) {
845   id_ = id;
846 }
847
848 bool TestingProfile::IsSameProfile(Profile *p) {
849   return this == p;
850 }
851
852 base::Time TestingProfile::GetStartTime() const {
853   return start_time_;
854 }
855
856 base::FilePath TestingProfile::last_selected_directory() {
857   return last_selected_directory_;
858 }
859
860 void TestingProfile::set_last_selected_directory(const base::FilePath& path) {
861   last_selected_directory_ = path;
862 }
863
864 PrefProxyConfigTracker* TestingProfile::GetProxyConfigTracker() {
865   if (!pref_proxy_config_tracker_.get()) {
866     // TestingProfile is used in unit tests, where local state is not available.
867     pref_proxy_config_tracker_.reset(
868         ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
869                                                                    NULL));
870   }
871   return pref_proxy_config_tracker_.get();
872 }
873
874 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
875   HistoryService* history_service =
876       HistoryServiceFactory::GetForProfile(this, Profile::EXPLICIT_ACCESS);
877   DCHECK(history_service);
878   DCHECK(base::MessageLoop::current());
879
880   CancelableRequestConsumer consumer;
881   history_service->ScheduleDBTask(new QuittingHistoryDBTask(), &consumer);
882   base::MessageLoop::current()->Run();
883 }
884
885 chrome_browser_net::Predictor* TestingProfile::GetNetworkPredictor() {
886   return NULL;
887 }
888
889 void TestingProfile::ClearNetworkingHistorySince(
890     base::Time time,
891     const base::Closure& completion) {
892   if (!completion.is_null()) {
893     BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, completion);
894   }
895 }
896
897 GURL TestingProfile::GetHomePage() {
898   return GURL(chrome::kChromeUINewTabURL);
899 }
900
901 PrefService* TestingProfile::GetOffTheRecordPrefs() {
902   return NULL;
903 }
904
905 quota::SpecialStoragePolicy* TestingProfile::GetSpecialStoragePolicy() {
906   return GetExtensionSpecialStoragePolicy();
907 }
908
909 bool TestingProfile::WasCreatedByVersionOrLater(const std::string& version) {
910   return true;
911 }
912
913 bool TestingProfile::IsGuestSession() const {
914   return guest_session_;
915 }
916
917 Profile::ExitType TestingProfile::GetLastSessionExitType() {
918   return last_session_exited_cleanly_ ? EXIT_NORMAL : EXIT_CRASHED;
919 }
920
921 TestingProfile::Builder::Builder()
922     : build_called_(false),
923       delegate_(NULL),
924       incognito_(false),
925       guest_session_(false) {
926 }
927
928 TestingProfile::Builder::~Builder() {
929 }
930
931 void TestingProfile::Builder::SetPath(const base::FilePath& path) {
932   path_ = path;
933 }
934
935 void TestingProfile::Builder::SetDelegate(Delegate* delegate) {
936   delegate_ = delegate;
937 }
938
939 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
940     scoped_refptr<ExtensionSpecialStoragePolicy> policy) {
941   extension_policy_ = policy;
942 }
943
944 void TestingProfile::Builder::SetPrefService(
945     scoped_ptr<PrefServiceSyncable> prefs) {
946   pref_service_ = prefs.Pass();
947 }
948
949 void TestingProfile::Builder::SetIncognito() {
950   incognito_ = true;
951 }
952
953 void TestingProfile::Builder::SetGuestSession() {
954   guest_session_ = true;
955 }
956
957 void TestingProfile::Builder::SetManagedUserId(
958     const std::string& managed_user_id) {
959   managed_user_id_ = managed_user_id;
960 }
961
962 void TestingProfile::Builder::SetPolicyService(
963     scoped_ptr<policy::PolicyService> policy_service) {
964   policy_service_ = policy_service.Pass();
965 }
966
967 void TestingProfile::Builder::AddTestingFactory(
968     BrowserContextKeyedServiceFactory* service_factory,
969     BrowserContextKeyedServiceFactory::TestingFactoryFunction callback) {
970   testing_factories_.push_back(std::make_pair(service_factory, callback));
971 }
972
973 scoped_ptr<TestingProfile> TestingProfile::Builder::Build() {
974   DCHECK(!build_called_);
975   build_called_ = true;
976
977   return scoped_ptr<TestingProfile>(new TestingProfile(
978       path_,
979       delegate_,
980       extension_policy_,
981       pref_service_.Pass(),
982       incognito_,
983       guest_session_,
984       managed_user_id_,
985       policy_service_.Pass(),
986       testing_factories_));
987 }