Do not announce robot account token before account ID is available
[chromium-blink-merge.git] / chrome / test / base / testing_profile.cc
blob7f49296f44b09f6d60f80d22b7e869255934cb0e
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.
5 #include "chrome/test/base/testing_profile.h"
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_service.h"
28 #include "chrome/browser/history/history_service_factory.h"
29 #include "chrome/browser/history/top_sites_factory.h"
30 #include "chrome/browser/history/top_sites_impl.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/sync/glue/sync_start_util.h"
46 #include "chrome/browser/webdata/web_data_service_factory.h"
47 #include "chrome/common/chrome_constants.h"
48 #include "chrome/common/chrome_switches.h"
49 #include "chrome/common/pref_names.h"
50 #include "chrome/common/url_constants.h"
51 #include "chrome/test/base/history_index_restore_observer.h"
52 #include "chrome/test/base/testing_pref_service_syncable.h"
53 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
54 #include "components/bookmarks/browser/bookmark_model.h"
55 #include "components/bookmarks/common/bookmark_constants.h"
56 #include "components/content_settings/core/browser/host_content_settings_map.h"
57 #include "components/history/content/browser/history_database_helper.h"
58 #include "components/history/core/browser/history_constants.h"
59 #include "components/history/core/browser/history_database_params.h"
60 #include "components/history/core/browser/history_db_task.h"
61 #include "components/history/core/browser/top_sites.h"
62 #include "components/history/core/browser/top_sites_observer.h"
63 #include "components/keyed_service/content/browser_context_dependency_manager.h"
64 #include "components/keyed_service/core/refcounted_keyed_service.h"
65 #include "components/policy/core/common/policy_service.h"
66 #include "components/user_prefs/user_prefs.h"
67 #include "components/webdata_services/web_data_service_wrapper.h"
68 #include "content/public/browser/browser_thread.h"
69 #include "content/public/browser/cookie_store_factory.h"
70 #include "content/public/browser/notification_service.h"
71 #include "content/public/browser/render_process_host.h"
72 #include "content/public/browser/storage_partition.h"
73 #include "content/public/test/mock_resource_context.h"
74 #include "content/public/test/test_utils.h"
75 #include "extensions/common/constants.h"
76 #include "net/cookies/cookie_monster.h"
77 #include "net/url_request/url_request_context.h"
78 #include "net/url_request/url_request_context_getter.h"
79 #include "net/url_request/url_request_test_util.h"
80 #include "testing/gmock/include/gmock/gmock.h"
82 #if defined(ENABLE_CONFIGURATION_POLICY)
83 #include "chrome/browser/policy/schema_registry_service.h"
84 #include "chrome/browser/policy/schema_registry_service_factory.h"
85 #include "components/policy/core/common/configuration_policy_provider.h"
86 #include "components/policy/core/common/policy_service_impl.h"
87 #include "components/policy/core/common/schema.h"
88 #else
89 #include "components/policy/core/common/policy_service_stub.h"
90 #endif // defined(ENABLE_CONFIGURATION_POLICY)
92 #if defined(ENABLE_EXTENSIONS)
93 #include "chrome/browser/extensions/extension_service.h"
94 #include "chrome/browser/extensions/extension_special_storage_policy.h"
95 #include "chrome/browser/extensions/extension_system_factory.h"
96 #include "chrome/browser/extensions/test_extension_system.h"
97 #include "extensions/browser/extension_system.h"
98 #include "extensions/browser/guest_view/guest_view_manager.h"
99 #endif
101 #if defined(OS_ANDROID)
102 #include "chrome/browser/signin/android_profile_oauth2_token_service.h"
103 #endif
105 #if defined(ENABLE_SUPERVISED_USERS)
106 #include "chrome/browser/supervised_user/supervised_user_constants.h"
107 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
108 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
109 #endif
111 using base::Time;
112 using bookmarks::BookmarkModel;
113 using content::BrowserThread;
114 using content::DownloadManagerDelegate;
115 using testing::NiceMock;
116 using testing::Return;
118 namespace {
120 // TopSitesImpl::Shutdown schedules some tasks (from TopSitesBackend) that
121 // need to be run to properly shutdown. Run all pending tasks now. This is
122 // normally handled by browser_process shutdown.
124 void CleanupAfterTopSitesDestroyed() {
125 if (base::MessageLoop::current())
126 base::MessageLoop::current()->RunUntilIdle();
129 // Returns true if a TopSites service has been registered for |profile|.
130 bool HasTopSites(Profile* profile) {
131 return !!TopSitesFactory::GetInstance()->GetForProfileIfExists(profile);
134 // Used to make sure TopSites has finished loading
135 class WaitTopSitesLoadedObserver : public history::TopSitesObserver {
136 public:
137 explicit WaitTopSitesLoadedObserver(content::MessageLoopRunner* runner)
138 : runner_(runner) {}
139 void TopSitesLoaded(history::TopSites* top_sites) override {
140 runner_->Quit();
142 void TopSitesChanged(history::TopSites* top_sites) override {}
144 private:
145 // weak
146 content::MessageLoopRunner* runner_;
149 // Task used to make sure history has finished processing a request. Intended
150 // for use with BlockUntilHistoryProcessesPendingRequests.
152 class QuittingHistoryDBTask : public history::HistoryDBTask {
153 public:
154 QuittingHistoryDBTask() {}
156 bool RunOnDBThread(history::HistoryBackend* backend,
157 history::HistoryDatabase* db) override {
158 return true;
161 void DoneRunOnMainThread() override { base::MessageLoop::current()->Quit(); }
163 private:
164 ~QuittingHistoryDBTask() override {}
166 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
169 class TestExtensionURLRequestContext : public net::URLRequestContext {
170 public:
171 TestExtensionURLRequestContext() {
172 net::CookieMonster* cookie_monster =
173 content::CreateCookieStore(content::CookieStoreConfig())->
174 GetCookieMonster();
175 const char* const schemes[] = {extensions::kExtensionScheme};
176 cookie_monster->SetCookieableSchemes(schemes, arraysize(schemes));
177 set_cookie_store(cookie_monster);
180 ~TestExtensionURLRequestContext() override { AssertNoURLRequests(); }
183 class TestExtensionURLRequestContextGetter
184 : public net::URLRequestContextGetter {
185 public:
186 net::URLRequestContext* GetURLRequestContext() override {
187 if (!context_.get())
188 context_.reset(new TestExtensionURLRequestContext());
189 return context_.get();
191 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
192 const override {
193 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
196 protected:
197 ~TestExtensionURLRequestContextGetter() override {}
199 private:
200 scoped_ptr<net::URLRequestContext> context_;
203 #if defined(ENABLE_NOTIFICATIONS)
204 KeyedService* CreateTestDesktopNotificationService(
205 content::BrowserContext* profile) {
206 return new DesktopNotificationService(static_cast<Profile*>(profile));
208 #endif
210 KeyedService* BuildFaviconService(content::BrowserContext* profile) {
211 FaviconClient* favicon_client =
212 ChromeFaviconClientFactory::GetForProfile(static_cast<Profile*>(profile));
213 return new FaviconService(static_cast<Profile*>(profile), favicon_client);
216 KeyedService* BuildHistoryService(content::BrowserContext* context) {
217 Profile* profile = static_cast<Profile*>(context);
218 HistoryService* history_service = new HistoryService(
219 ChromeHistoryClientFactory::GetForProfile(profile), profile);
220 return history_service;
223 KeyedService* BuildBookmarkModel(content::BrowserContext* context) {
224 Profile* profile = static_cast<Profile*>(context);
225 ChromeBookmarkClient* bookmark_client =
226 ChromeBookmarkClientFactory::GetForProfile(profile);
227 BookmarkModel* bookmark_model = new BookmarkModel(bookmark_client);
228 bookmark_client->Init(bookmark_model);
229 bookmark_model->Load(profile->GetPrefs(),
230 profile->GetPrefs()->GetString(prefs::kAcceptLanguages),
231 profile->GetPath(),
232 profile->GetIOTaskRunner(),
233 content::BrowserThread::GetMessageLoopProxyForThread(
234 content::BrowserThread::UI));
235 return bookmark_model;
238 KeyedService* BuildChromeBookmarkClient(
239 content::BrowserContext* context) {
240 return new ChromeBookmarkClient(static_cast<Profile*>(context));
243 KeyedService* BuildChromeHistoryClient(
244 content::BrowserContext* context) {
245 Profile* profile = static_cast<Profile*>(context);
246 return new ChromeHistoryClient(BookmarkModelFactory::GetForProfile(profile));
249 void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type,
250 sql::InitStatus status) {
251 NOTREACHED();
254 KeyedService* BuildWebDataService(content::BrowserContext* context) {
255 const base::FilePath& context_path = context->GetPath();
256 return new WebDataServiceWrapper(
257 context_path, g_browser_process->GetApplicationLocale(),
258 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
259 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB),
260 sync_start_util::GetFlareForSyncableService(context_path),
261 &TestProfileErrorCallback);
264 scoped_refptr<RefcountedKeyedService> BuildTopSites(
265 content::BrowserContext* profile) {
266 history::TopSitesImpl* top_sites = new history::TopSitesImpl(
267 static_cast<Profile*>(profile), history::PrepopulatedPageList());
268 top_sites->Init(
269 profile->GetPath().Append(chrome::kTopSitesFilename),
270 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB));
271 return make_scoped_refptr(top_sites);
274 } // namespace
276 // static
277 #if defined(OS_CHROMEOS)
278 // Must be kept in sync with
279 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
280 const char TestingProfile::kTestUserProfileDir[] = "test-user";
281 #else
282 const char TestingProfile::kTestUserProfileDir[] = "Default";
283 #endif
285 TestingProfile::TestingProfile()
286 : start_time_(Time::Now()),
287 testing_prefs_(NULL),
288 force_incognito_(false),
289 original_profile_(NULL),
290 guest_session_(false),
291 last_session_exited_cleanly_(true),
292 browser_context_dependency_manager_(
293 BrowserContextDependencyManager::GetInstance()),
294 resource_context_(NULL),
295 delegate_(NULL) {
296 CreateTempProfileDir();
297 profile_path_ = temp_dir_.path();
299 Init();
300 FinishInit();
303 TestingProfile::TestingProfile(const base::FilePath& path)
304 : start_time_(Time::Now()),
305 testing_prefs_(NULL),
306 force_incognito_(false),
307 original_profile_(NULL),
308 guest_session_(false),
309 last_session_exited_cleanly_(true),
310 profile_path_(path),
311 browser_context_dependency_manager_(
312 BrowserContextDependencyManager::GetInstance()),
313 resource_context_(NULL),
314 delegate_(NULL) {
315 Init();
316 FinishInit();
319 TestingProfile::TestingProfile(const base::FilePath& path,
320 Delegate* delegate)
321 : start_time_(Time::Now()),
322 testing_prefs_(NULL),
323 force_incognito_(false),
324 original_profile_(NULL),
325 guest_session_(false),
326 last_session_exited_cleanly_(true),
327 profile_path_(path),
328 browser_context_dependency_manager_(
329 BrowserContextDependencyManager::GetInstance()),
330 resource_context_(NULL),
331 delegate_(delegate) {
332 Init();
333 if (delegate_) {
334 base::MessageLoop::current()->PostTask(
335 FROM_HERE,
336 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
337 } else {
338 FinishInit();
342 TestingProfile::TestingProfile(
343 const base::FilePath& path,
344 Delegate* delegate,
345 #if defined(ENABLE_EXTENSIONS)
346 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
347 #endif
348 scoped_ptr<PrefServiceSyncable> prefs,
349 TestingProfile* parent,
350 bool guest_session,
351 const std::string& supervised_user_id,
352 scoped_ptr<policy::PolicyService> policy_service,
353 const TestingFactories& factories)
354 : start_time_(Time::Now()),
355 prefs_(prefs.release()),
356 testing_prefs_(NULL),
357 force_incognito_(false),
358 original_profile_(parent),
359 guest_session_(guest_session),
360 supervised_user_id_(supervised_user_id),
361 last_session_exited_cleanly_(true),
362 #if defined(ENABLE_EXTENSIONS)
363 extension_special_storage_policy_(extension_policy),
364 #endif
365 profile_path_(path),
366 browser_context_dependency_manager_(
367 BrowserContextDependencyManager::GetInstance()),
368 resource_context_(NULL),
369 delegate_(delegate),
370 policy_service_(policy_service.release()) {
371 if (parent)
372 parent->SetOffTheRecordProfile(scoped_ptr<Profile>(this));
374 // If no profile path was supplied, create one.
375 if (profile_path_.empty()) {
376 CreateTempProfileDir();
377 profile_path_ = temp_dir_.path();
380 // Set any testing factories prior to initializing the services.
381 for (TestingFactories::const_iterator it = factories.begin();
382 it != factories.end(); ++it) {
383 it->first->SetTestingFactory(this, it->second);
386 Init();
387 // If caller supplied a delegate, delay the FinishInit invocation until other
388 // tasks have run.
389 // TODO(atwilson): See if this is still required once we convert the current
390 // users of the constructor that takes a Delegate* param.
391 if (delegate_) {
392 base::MessageLoop::current()->PostTask(
393 FROM_HERE,
394 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
395 } else {
396 FinishInit();
400 void TestingProfile::CreateTempProfileDir() {
401 if (!temp_dir_.CreateUniqueTempDir()) {
402 LOG(ERROR) << "Failed to create unique temporary directory.";
404 // Fallback logic in case we fail to create unique temporary directory.
405 base::FilePath system_tmp_dir;
406 bool success = PathService::Get(base::DIR_TEMP, &system_tmp_dir);
408 // We're severly screwed if we can't get the system temporary
409 // directory. Die now to avoid writing to the filesystem root
410 // or other bad places.
411 CHECK(success);
413 base::FilePath fallback_dir(
414 system_tmp_dir.AppendASCII("TestingProfilePath"));
415 base::DeleteFile(fallback_dir, true);
416 base::CreateDirectory(fallback_dir);
417 if (!temp_dir_.Set(fallback_dir)) {
418 // That shouldn't happen, but if it does, try to recover.
419 LOG(ERROR) << "Failed to use a fallback temporary directory.";
421 // We're screwed if this fails, see CHECK above.
422 CHECK(temp_dir_.Set(system_tmp_dir));
427 void TestingProfile::Init() {
428 // If threads have been initialized, we should be on the UI thread.
429 DCHECK(!content::BrowserThread::IsThreadInitialized(
430 content::BrowserThread::UI) ||
431 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
433 set_is_guest_profile(guest_session_);
435 #if defined(OS_ANDROID)
436 // Make sure token service knows its running in tests.
437 AndroidProfileOAuth2TokenService::set_is_testing_profile();
438 #endif
440 // Normally this would happen during browser startup, but for tests
441 // we need to trigger creation of Profile-related services.
442 ChromeBrowserMainExtraPartsProfiles::
443 EnsureBrowserContextKeyedServiceFactoriesBuilt();
445 if (prefs_.get())
446 user_prefs::UserPrefs::Set(this, prefs_.get());
447 else if (IsOffTheRecord())
448 CreateIncognitoPrefService();
449 else
450 CreateTestingPrefService();
452 if (!base::PathExists(profile_path_))
453 base::CreateDirectory(profile_path_);
455 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
456 // anymore, after converting the PrefService to a PKS. Until then it must
457 // be associated with a TestingProfile too.
458 if (!IsOffTheRecord())
459 CreateProfilePolicyConnector();
461 #if defined(ENABLE_EXTENSIONS)
462 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
463 this, extensions::TestExtensionSystem::Build);
464 #endif
466 // Prefs for incognito profiles are set in CreateIncognitoPrefService() by
467 // simulating ProfileImpl::GetOffTheRecordPrefs().
468 if (!IsOffTheRecord()) {
469 DCHECK(!original_profile_);
470 user_prefs::PrefRegistrySyncable* pref_registry =
471 static_cast<user_prefs::PrefRegistrySyncable*>(
472 prefs_->DeprecatedGetPrefRegistry());
473 browser_context_dependency_manager_->
474 RegisterProfilePrefsForServices(this, pref_registry);
477 browser_context_dependency_manager_->CreateBrowserContextServicesForTest(
478 this);
480 #if defined(ENABLE_NOTIFICATIONS)
481 // Install profile keyed service factory hooks for dummy/test services
482 DesktopNotificationServiceFactory::GetInstance()->SetTestingFactory(
483 this, CreateTestDesktopNotificationService);
484 #endif
486 #if defined(ENABLE_SUPERVISED_USERS)
487 if (!IsOffTheRecord()) {
488 SupervisedUserSettingsService* settings_service =
489 SupervisedUserSettingsServiceFactory::GetForProfile(this);
490 TestingPrefStore* store = new TestingPrefStore();
491 settings_service->Init(store);
492 store->SetInitializationCompleted();
494 #endif
496 profile_name_ = "testing_profile";
499 void TestingProfile::FinishInit() {
500 DCHECK(content::NotificationService::current());
501 content::NotificationService::current()->Notify(
502 chrome::NOTIFICATION_PROFILE_CREATED,
503 content::Source<Profile>(static_cast<Profile*>(this)),
504 content::NotificationService::NoDetails());
506 ProfileManager* profile_manager = g_browser_process->profile_manager();
507 if (profile_manager)
508 profile_manager->InitProfileUserPrefs(this);
510 if (delegate_)
511 delegate_->OnProfileCreated(this, true, false);
514 TestingProfile::~TestingProfile() {
515 // Revert to non-incognito mode before shutdown.
516 force_incognito_ = false;
518 // If this profile owns an incognito profile, tear it down first.
519 incognito_profile_.reset();
521 // Any objects holding live URLFetchers should be deleted before teardown.
522 TemplateURLFetcherFactory::ShutdownForProfile(this);
524 MaybeSendDestroyedNotification();
526 // Remember whether a TopSites has been created for the current profile,
527 // so that we can run cleanup after destroying all services.
528 bool had_top_sites = HasTopSites(this);
530 browser_context_dependency_manager_->DestroyBrowserContextServices(this);
532 if (host_content_settings_map_.get())
533 host_content_settings_map_->ShutdownOnUIThread();
535 // Wait until TopSites shutdown tasks have completed if a TopSites has
536 // been created for the current profile.
537 if (had_top_sites)
538 CleanupAfterTopSitesDestroyed();
540 if (pref_proxy_config_tracker_.get())
541 pref_proxy_config_tracker_->DetachFromPrefService();
542 // Failing a post == leaks == heapcheck failure. Make that an immediate test
543 // failure.
544 if (resource_context_) {
545 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
546 resource_context_));
547 resource_context_ = NULL;
548 content::RunAllPendingInMessageLoop(BrowserThread::IO);
552 void TestingProfile::CreateFaviconService() {
553 // It is up to the caller to create the history service if one is needed.
554 FaviconServiceFactory::GetInstance()->SetTestingFactory(
555 this, BuildFaviconService);
558 bool TestingProfile::CreateHistoryService(bool delete_file, bool no_db) {
559 DestroyHistoryService();
560 if (delete_file) {
561 base::FilePath path = GetPath();
562 path = path.Append(history::kHistoryFilename);
563 if (!base::DeleteFile(path, false) || base::PathExists(path))
564 return false;
566 // This will create and init the history service.
567 HistoryService* history_service = static_cast<HistoryService*>(
568 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
569 this, BuildHistoryService));
570 if (!history_service->Init(
571 no_db, history::HistoryDatabaseParamsForPath(this->GetPath()))) {
572 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(this, NULL);
574 // Disable WebHistoryService by default, since it makes network requests.
575 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, NULL);
576 return true;
579 void TestingProfile::DestroyHistoryService() {
580 // TODO(sdefresne): remove this once ChromeHistoryClient is no longer an
581 // HistoryServiceObserver, http://crbug.com/373326
582 ChromeHistoryClient* history_client =
583 ChromeHistoryClientFactory::GetForProfileWithoutCreating(this);
584 if (history_client)
585 history_client->Shutdown();
587 HistoryService* history_service =
588 HistoryServiceFactory::GetForProfileWithoutCreating(this);
589 if (!history_service)
590 return;
592 history_service->ClearCachedDataForContextID(0);
593 history_service->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
594 history_service->Cleanup();
595 HistoryServiceFactory::ShutdownForProfile(this);
597 // Wait for the backend class to terminate before deleting the files and
598 // moving to the next test. Note: if this never terminates, somebody is
599 // probably leaking a reference to the history backend, so it never calls
600 // our destroy task.
601 base::MessageLoop::current()->Run();
603 // Make sure we don't have any event pending that could disrupt the next
604 // test.
605 base::MessageLoop::current()->PostTask(FROM_HERE,
606 base::MessageLoop::QuitClosure());
607 base::MessageLoop::current()->Run();
610 void TestingProfile::CreateTopSites() {
611 DestroyTopSites();
612 TopSitesFactory::GetInstance()->SetTestingFactoryAndUse(this, BuildTopSites);
615 void TestingProfile::DestroyTopSites() {
616 TopSitesFactory* top_sites_factory = TopSitesFactory::GetInstance();
617 if (top_sites_factory->GetForProfileIfExists(this)) {
618 // BrowserContextKeyedServiceFactory will destroy the previous service when
619 // registering a new testing factory so use this to ensure that destroy the
620 // old service.
621 top_sites_factory->SetTestingFactory(this, nullptr);
622 CleanupAfterTopSitesDestroyed();
626 void TestingProfile::CreateBookmarkModel(bool delete_file) {
627 if (delete_file) {
628 base::FilePath path = GetPath().Append(bookmarks::kBookmarksFileName);
629 base::DeleteFile(path, false);
631 ChromeHistoryClientFactory::GetInstance()->SetTestingFactory(
632 this, BuildChromeHistoryClient);
633 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
634 this, BuildChromeBookmarkClient);
635 // This creates the BookmarkModel.
636 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
637 this, BuildBookmarkModel));
640 void TestingProfile::CreateWebDataService() {
641 WebDataServiceFactory::GetInstance()->SetTestingFactory(
642 this, BuildWebDataService);
645 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
646 // Only get the history service if it actually exists since the caller of the
647 // test should explicitly call CreateHistoryService to build it.
648 HistoryService* history_service =
649 HistoryServiceFactory::GetForProfileWithoutCreating(this);
650 DCHECK(history_service);
651 history::InMemoryURLIndex* index = history_service->InMemoryIndex();
652 if (!index || index->restored())
653 return;
654 base::RunLoop run_loop;
655 HistoryIndexRestoreObserver observer(
656 content::GetQuitTaskForRunLoop(&run_loop));
657 index->set_restore_cache_observer(&observer);
658 run_loop.Run();
659 index->set_restore_cache_observer(NULL);
660 DCHECK(index->restored());
663 // TODO(phajdan.jr): Doesn't this hang if Top Sites are already loaded?
664 void TestingProfile::BlockUntilTopSitesLoaded() {
665 scoped_refptr<content::MessageLoopRunner> runner =
666 new content::MessageLoopRunner;
667 WaitTopSitesLoadedObserver observer(runner.get());
668 scoped_refptr<history::TopSites> top_sites =
669 TopSitesFactory::GetForProfile(this);
670 top_sites->AddObserver(&observer);
671 runner->Run();
672 top_sites->RemoveObserver(&observer);
675 void TestingProfile::SetGuestSession(bool guest) {
676 guest_session_ = guest;
679 base::FilePath TestingProfile::GetPath() const {
680 return profile_path_;
683 scoped_ptr<content::ZoomLevelDelegate> TestingProfile::CreateZoomLevelDelegate(
684 const base::FilePath& partition_path) {
685 return nullptr;
688 scoped_refptr<base::SequencedTaskRunner> TestingProfile::GetIOTaskRunner() {
689 return base::MessageLoop::current()->message_loop_proxy();
692 TestingPrefServiceSyncable* TestingProfile::GetTestingPrefService() {
693 DCHECK(prefs_);
694 DCHECK(testing_prefs_);
695 return testing_prefs_;
698 TestingProfile* TestingProfile::AsTestingProfile() {
699 return this;
702 std::string TestingProfile::GetProfileName() {
703 return profile_name_;
706 Profile::ProfileType TestingProfile::GetProfileType() const {
707 if (guest_session_)
708 return GUEST_PROFILE;
709 if (force_incognito_ || original_profile_)
710 return INCOGNITO_PROFILE;
711 return REGULAR_PROFILE;
714 bool TestingProfile::IsOffTheRecord() const {
715 return force_incognito_ || original_profile_;
718 void TestingProfile::SetOffTheRecordProfile(scoped_ptr<Profile> profile) {
719 DCHECK(!IsOffTheRecord());
720 DCHECK_EQ(this, profile->GetOriginalProfile());
721 incognito_profile_ = profile.Pass();
724 Profile* TestingProfile::GetOffTheRecordProfile() {
725 if (IsOffTheRecord())
726 return this;
727 if (!incognito_profile_)
728 TestingProfile::Builder().BuildIncognito(this);
729 return incognito_profile_.get();
732 bool TestingProfile::HasOffTheRecordProfile() {
733 return incognito_profile_.get() != NULL;
736 Profile* TestingProfile::GetOriginalProfile() {
737 if (original_profile_)
738 return original_profile_;
739 return this;
742 bool TestingProfile::IsSupervised() {
743 return !supervised_user_id_.empty();
746 bool TestingProfile::IsChild() {
747 #if defined(ENABLE_SUPERVISED_USERS)
748 return supervised_user_id_ == supervised_users::kChildAccountSUID;
749 #else
750 return false;
751 #endif
754 bool TestingProfile::IsLegacySupervised() {
755 return IsSupervised() && !IsChild();
758 #if defined(ENABLE_EXTENSIONS)
759 void TestingProfile::SetExtensionSpecialStoragePolicy(
760 ExtensionSpecialStoragePolicy* extension_special_storage_policy) {
761 extension_special_storage_policy_ = extension_special_storage_policy;
763 #endif
765 ExtensionSpecialStoragePolicy*
766 TestingProfile::GetExtensionSpecialStoragePolicy() {
767 #if defined(ENABLE_EXTENSIONS)
768 if (!extension_special_storage_policy_.get())
769 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(NULL);
770 return extension_special_storage_policy_.get();
771 #else
772 return NULL;
773 #endif
776 net::CookieMonster* TestingProfile::GetCookieMonster() {
777 if (!GetRequestContext())
778 return NULL;
779 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
780 GetCookieMonster();
783 void TestingProfile::CreateTestingPrefService() {
784 DCHECK(!prefs_.get());
785 testing_prefs_ = new TestingPrefServiceSyncable();
786 prefs_.reset(testing_prefs_);
787 user_prefs::UserPrefs::Set(this, prefs_.get());
788 chrome::RegisterUserProfilePrefs(testing_prefs_->registry());
791 void TestingProfile::CreateIncognitoPrefService() {
792 DCHECK(original_profile_);
793 DCHECK(!testing_prefs_);
794 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
795 // leaves testing_prefs_ unset.
796 prefs_.reset(original_profile_->prefs_->CreateIncognitoPrefService(NULL));
797 user_prefs::UserPrefs::Set(this, prefs_.get());
800 void TestingProfile::CreateProfilePolicyConnector() {
801 #if defined(ENABLE_CONFIGURATION_POLICY)
802 schema_registry_service_ =
803 policy::SchemaRegistryServiceFactory::CreateForContext(
804 this, policy::Schema(), NULL);
805 CHECK_EQ(schema_registry_service_.get(),
806 policy::SchemaRegistryServiceFactory::GetForContext(this));
807 #endif // defined(ENABLE_CONFIGURATION_POLICY)
809 if (!policy_service_) {
810 #if defined(ENABLE_CONFIGURATION_POLICY)
811 std::vector<policy::ConfigurationPolicyProvider*> providers;
812 policy_service_.reset(new policy::PolicyServiceImpl(providers));
813 #else
814 policy_service_.reset(new policy::PolicyServiceStub());
815 #endif
817 profile_policy_connector_.reset(new policy::ProfilePolicyConnector());
818 profile_policy_connector_->InitForTesting(policy_service_.Pass());
819 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
820 this, profile_policy_connector_.get());
821 CHECK_EQ(profile_policy_connector_.get(),
822 policy::ProfilePolicyConnectorFactory::GetForProfile(this));
825 PrefService* TestingProfile::GetPrefs() {
826 DCHECK(prefs_);
827 return prefs_.get();
830 DownloadManagerDelegate* TestingProfile::GetDownloadManagerDelegate() {
831 return NULL;
834 net::URLRequestContextGetter* TestingProfile::GetRequestContext() {
835 return GetDefaultStoragePartition(this)->GetURLRequestContext();
838 net::URLRequestContextGetter* TestingProfile::CreateRequestContext(
839 content::ProtocolHandlerMap* protocol_handlers,
840 content::URLRequestInterceptorScopedVector request_interceptors) {
841 return new net::TestURLRequestContextGetter(
842 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
845 net::URLRequestContextGetter* TestingProfile::GetRequestContextForRenderProcess(
846 int renderer_child_id) {
847 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
848 renderer_child_id);
849 return rph->GetStoragePartition()->GetURLRequestContext();
852 net::URLRequestContextGetter* TestingProfile::GetMediaRequestContext() {
853 return NULL;
856 net::URLRequestContextGetter*
857 TestingProfile::GetMediaRequestContextForRenderProcess(
858 int renderer_child_id) {
859 return NULL;
862 net::URLRequestContextGetter*
863 TestingProfile::GetMediaRequestContextForStoragePartition(
864 const base::FilePath& partition_path,
865 bool in_memory) {
866 return NULL;
869 net::URLRequestContextGetter* TestingProfile::GetRequestContextForExtensions() {
870 if (!extensions_request_context_.get())
871 extensions_request_context_ = new TestExtensionURLRequestContextGetter();
872 return extensions_request_context_.get();
875 net::SSLConfigService* TestingProfile::GetSSLConfigService() {
876 if (!GetRequestContext())
877 return NULL;
878 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
881 net::URLRequestContextGetter*
882 TestingProfile::CreateRequestContextForStoragePartition(
883 const base::FilePath& partition_path,
884 bool in_memory,
885 content::ProtocolHandlerMap* protocol_handlers,
886 content::URLRequestInterceptorScopedVector request_interceptors) {
887 // We don't test storage partitions here yet, so returning the same dummy
888 // context is sufficient for now.
889 return GetRequestContext();
892 content::ResourceContext* TestingProfile::GetResourceContext() {
893 if (!resource_context_)
894 resource_context_ = new content::MockResourceContext();
895 return resource_context_;
898 HostContentSettingsMap* TestingProfile::GetHostContentSettingsMap() {
899 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
900 if (!host_content_settings_map_.get()) {
901 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
902 #if defined(ENABLE_EXTENSIONS)
903 ExtensionService* extension_service =
904 extensions::ExtensionSystem::Get(this)->extension_service();
905 if (extension_service) {
906 extension_service->RegisterContentSettings(
907 host_content_settings_map_.get());
909 #endif
911 return host_content_settings_map_.get();
914 content::BrowserPluginGuestManager* TestingProfile::GetGuestManager() {
915 #if defined(ENABLE_EXTENSIONS)
916 return extensions::GuestViewManager::FromBrowserContext(this);
917 #else
918 return NULL;
919 #endif
922 content::PushMessagingService* TestingProfile::GetPushMessagingService() {
923 return NULL;
926 bool TestingProfile::IsSameProfile(Profile *p) {
927 return this == p;
930 base::Time TestingProfile::GetStartTime() const {
931 return start_time_;
934 base::FilePath TestingProfile::last_selected_directory() {
935 return last_selected_directory_;
938 void TestingProfile::set_last_selected_directory(const base::FilePath& path) {
939 last_selected_directory_ = path;
942 PrefProxyConfigTracker* TestingProfile::GetProxyConfigTracker() {
943 if (!pref_proxy_config_tracker_.get()) {
944 // TestingProfile is used in unit tests, where local state is not available.
945 pref_proxy_config_tracker_.reset(
946 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
947 NULL));
949 return pref_proxy_config_tracker_.get();
952 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
953 HistoryService* history_service = HistoryServiceFactory::GetForProfile(
954 this, ServiceAccessType::EXPLICIT_ACCESS);
955 DCHECK(history_service);
956 DCHECK(base::MessageLoop::current());
958 base::CancelableTaskTracker tracker;
959 history_service->ScheduleDBTask(
960 scoped_ptr<history::HistoryDBTask>(
961 new QuittingHistoryDBTask()),
962 &tracker);
963 base::MessageLoop::current()->Run();
966 chrome_browser_net::Predictor* TestingProfile::GetNetworkPredictor() {
967 return NULL;
970 DevToolsNetworkController* TestingProfile::GetDevToolsNetworkController() {
971 return NULL;
974 void TestingProfile::ClearNetworkingHistorySince(
975 base::Time time,
976 const base::Closure& completion) {
977 if (!completion.is_null()) {
978 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, completion);
982 GURL TestingProfile::GetHomePage() {
983 return GURL(chrome::kChromeUINewTabURL);
986 PrefService* TestingProfile::GetOffTheRecordPrefs() {
987 return NULL;
990 storage::SpecialStoragePolicy* TestingProfile::GetSpecialStoragePolicy() {
991 #if defined(ENABLE_EXTENSIONS)
992 return GetExtensionSpecialStoragePolicy();
993 #else
994 return NULL;
995 #endif
998 content::SSLHostStateDelegate* TestingProfile::GetSSLHostStateDelegate() {
999 return NULL;
1002 bool TestingProfile::WasCreatedByVersionOrLater(const std::string& version) {
1003 return true;
1006 bool TestingProfile::IsGuestSession() const {
1007 return guest_session_;
1010 Profile::ExitType TestingProfile::GetLastSessionExitType() {
1011 return last_session_exited_cleanly_ ? EXIT_NORMAL : EXIT_CRASHED;
1014 TestingProfile::Builder::Builder()
1015 : build_called_(false),
1016 delegate_(NULL),
1017 guest_session_(false) {
1020 TestingProfile::Builder::~Builder() {
1023 void TestingProfile::Builder::SetPath(const base::FilePath& path) {
1024 path_ = path;
1027 void TestingProfile::Builder::SetDelegate(Delegate* delegate) {
1028 delegate_ = delegate;
1031 #if defined(ENABLE_EXTENSIONS)
1032 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
1033 scoped_refptr<ExtensionSpecialStoragePolicy> policy) {
1034 extension_policy_ = policy;
1036 #endif
1038 void TestingProfile::Builder::SetPrefService(
1039 scoped_ptr<PrefServiceSyncable> prefs) {
1040 pref_service_ = prefs.Pass();
1043 void TestingProfile::Builder::SetGuestSession() {
1044 guest_session_ = true;
1047 void TestingProfile::Builder::SetSupervisedUserId(
1048 const std::string& supervised_user_id) {
1049 supervised_user_id_ = supervised_user_id;
1052 void TestingProfile::Builder::SetPolicyService(
1053 scoped_ptr<policy::PolicyService> policy_service) {
1054 policy_service_ = policy_service.Pass();
1057 void TestingProfile::Builder::AddTestingFactory(
1058 BrowserContextKeyedServiceFactory* service_factory,
1059 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback) {
1060 testing_factories_.push_back(std::make_pair(service_factory, callback));
1063 scoped_ptr<TestingProfile> TestingProfile::Builder::Build() {
1064 DCHECK(!build_called_);
1065 build_called_ = true;
1067 return scoped_ptr<TestingProfile>(new TestingProfile(path_,
1068 delegate_,
1069 #if defined(ENABLE_EXTENSIONS)
1070 extension_policy_,
1071 #endif
1072 pref_service_.Pass(),
1073 NULL,
1074 guest_session_,
1075 supervised_user_id_,
1076 policy_service_.Pass(),
1077 testing_factories_));
1080 TestingProfile* TestingProfile::Builder::BuildIncognito(
1081 TestingProfile* original_profile) {
1082 DCHECK(!build_called_);
1083 DCHECK(original_profile);
1084 build_called_ = true;
1086 // Note: Owned by |original_profile|.
1087 return new TestingProfile(path_,
1088 delegate_,
1089 #if defined(ENABLE_EXTENSIONS)
1090 extension_policy_,
1091 #endif
1092 pref_service_.Pass(),
1093 original_profile,
1094 guest_session_,
1095 supervised_user_id_,
1096 policy_service_.Pass(),
1097 testing_factories_);