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