Unregister from GCM when the only GCM app is removed
[chromium-blink-merge.git] / chrome / test / base / testing_profile.cc
blobe2870aa1c0a23964ec95bf4248c4182f1eceb261
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, GetPrefs()->GetString(prefs::kAcceptLanguages),
572 history::HistoryDatabaseParamsForPath(GetPath()))) {
573 HistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
574 return false;
576 // Disable WebHistoryService by default, since it makes network requests.
577 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
578 return true;
581 void TestingProfile::DestroyHistoryService() {
582 HistoryService* history_service =
583 HistoryServiceFactory::GetForProfileWithoutCreating(this);
584 if (!history_service)
585 return;
587 history_service->ClearCachedDataForContextID(0);
588 history_service->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
589 history_service->Cleanup();
590 HistoryServiceFactory::ShutdownForProfile(this);
592 // Wait for the backend class to terminate before deleting the files and
593 // moving to the next test. Note: if this never terminates, somebody is
594 // probably leaking a reference to the history backend, so it never calls
595 // our destroy task.
596 base::MessageLoop::current()->Run();
598 // Make sure we don't have any event pending that could disrupt the next
599 // test.
600 base::MessageLoop::current()->PostTask(FROM_HERE,
601 base::MessageLoop::QuitClosure());
602 base::MessageLoop::current()->Run();
605 void TestingProfile::CreateTopSites() {
606 DestroyTopSites();
607 TopSitesFactory::GetInstance()->SetTestingFactoryAndUse(this, BuildTopSites);
610 void TestingProfile::DestroyTopSites() {
611 TopSitesFactory* top_sites_factory = TopSitesFactory::GetInstance();
612 if (top_sites_factory->GetForProfileIfExists(this)) {
613 // BrowserContextKeyedServiceFactory will destroy the previous service when
614 // registering a new testing factory so use this to ensure that destroy the
615 // old service.
616 top_sites_factory->SetTestingFactory(this, nullptr);
617 CleanupAfterTopSitesDestroyed();
621 void TestingProfile::CreateBookmarkModel(bool delete_file) {
622 if (delete_file) {
623 base::FilePath path = GetPath().Append(bookmarks::kBookmarksFileName);
624 base::DeleteFile(path, false);
626 ChromeHistoryClientFactory::GetInstance()->SetTestingFactory(
627 this, BuildChromeHistoryClient);
628 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
629 this, BuildChromeBookmarkClient);
630 // This creates the BookmarkModel.
631 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
632 this, BuildBookmarkModel));
635 void TestingProfile::CreateWebDataService() {
636 WebDataServiceFactory::GetInstance()->SetTestingFactory(
637 this, BuildWebDataService);
640 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
641 // Only get the history service if it actually exists since the caller of the
642 // test should explicitly call CreateHistoryService to build it.
643 HistoryService* history_service =
644 HistoryServiceFactory::GetForProfileWithoutCreating(this);
645 DCHECK(history_service);
646 history::InMemoryURLIndex* index = history_service->InMemoryIndex();
647 if (!index || index->restored())
648 return;
649 base::RunLoop run_loop;
650 HistoryIndexRestoreObserver observer(
651 content::GetQuitTaskForRunLoop(&run_loop));
652 index->set_restore_cache_observer(&observer);
653 run_loop.Run();
654 index->set_restore_cache_observer(NULL);
655 DCHECK(index->restored());
658 // TODO(phajdan.jr): Doesn't this hang if Top Sites are already loaded?
659 void TestingProfile::BlockUntilTopSitesLoaded() {
660 scoped_refptr<content::MessageLoopRunner> runner =
661 new content::MessageLoopRunner;
662 WaitTopSitesLoadedObserver observer(runner.get());
663 scoped_refptr<history::TopSites> top_sites =
664 TopSitesFactory::GetForProfile(this);
665 top_sites->AddObserver(&observer);
666 runner->Run();
667 top_sites->RemoveObserver(&observer);
670 void TestingProfile::SetGuestSession(bool guest) {
671 guest_session_ = guest;
674 base::FilePath TestingProfile::GetPath() const {
675 return profile_path_;
678 scoped_ptr<content::ZoomLevelDelegate> TestingProfile::CreateZoomLevelDelegate(
679 const base::FilePath& partition_path) {
680 return nullptr;
683 scoped_refptr<base::SequencedTaskRunner> TestingProfile::GetIOTaskRunner() {
684 return base::MessageLoop::current()->message_loop_proxy();
687 TestingPrefServiceSyncable* TestingProfile::GetTestingPrefService() {
688 DCHECK(prefs_);
689 DCHECK(testing_prefs_);
690 return testing_prefs_;
693 TestingProfile* TestingProfile::AsTestingProfile() {
694 return this;
697 std::string TestingProfile::GetProfileUserName() {
698 return profile_name_;
701 Profile::ProfileType TestingProfile::GetProfileType() const {
702 if (guest_session_)
703 return GUEST_PROFILE;
704 if (force_incognito_ || original_profile_)
705 return INCOGNITO_PROFILE;
706 return REGULAR_PROFILE;
709 bool TestingProfile::IsOffTheRecord() const {
710 return force_incognito_ || original_profile_;
713 void TestingProfile::SetOffTheRecordProfile(scoped_ptr<Profile> profile) {
714 DCHECK(!IsOffTheRecord());
715 DCHECK_EQ(this, profile->GetOriginalProfile());
716 incognito_profile_ = profile.Pass();
719 Profile* TestingProfile::GetOffTheRecordProfile() {
720 if (IsOffTheRecord())
721 return this;
722 if (!incognito_profile_)
723 TestingProfile::Builder().BuildIncognito(this);
724 return incognito_profile_.get();
727 bool TestingProfile::HasOffTheRecordProfile() {
728 return incognito_profile_.get() != NULL;
731 Profile* TestingProfile::GetOriginalProfile() {
732 if (original_profile_)
733 return original_profile_;
734 return this;
737 bool TestingProfile::IsSupervised() {
738 return !supervised_user_id_.empty();
741 bool TestingProfile::IsChild() {
742 #if defined(ENABLE_SUPERVISED_USERS)
743 return supervised_user_id_ == supervised_users::kChildAccountSUID;
744 #else
745 return false;
746 #endif
749 bool TestingProfile::IsLegacySupervised() {
750 return IsSupervised() && !IsChild();
753 #if defined(ENABLE_EXTENSIONS)
754 void TestingProfile::SetExtensionSpecialStoragePolicy(
755 ExtensionSpecialStoragePolicy* extension_special_storage_policy) {
756 extension_special_storage_policy_ = extension_special_storage_policy;
758 #endif
760 ExtensionSpecialStoragePolicy*
761 TestingProfile::GetExtensionSpecialStoragePolicy() {
762 #if defined(ENABLE_EXTENSIONS)
763 if (!extension_special_storage_policy_.get())
764 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(NULL);
765 return extension_special_storage_policy_.get();
766 #else
767 return NULL;
768 #endif
771 net::CookieMonster* TestingProfile::GetCookieMonster() {
772 if (!GetRequestContext())
773 return NULL;
774 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
775 GetCookieMonster();
778 void TestingProfile::CreateTestingPrefService() {
779 DCHECK(!prefs_.get());
780 testing_prefs_ = new TestingPrefServiceSyncable();
781 prefs_.reset(testing_prefs_);
782 user_prefs::UserPrefs::Set(this, prefs_.get());
783 chrome::RegisterUserProfilePrefs(testing_prefs_->registry());
786 void TestingProfile::CreateIncognitoPrefService() {
787 DCHECK(original_profile_);
788 DCHECK(!testing_prefs_);
789 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
790 // leaves testing_prefs_ unset.
791 prefs_.reset(original_profile_->prefs_->CreateIncognitoPrefService(NULL));
792 user_prefs::UserPrefs::Set(this, prefs_.get());
795 void TestingProfile::CreateProfilePolicyConnector() {
796 #if defined(ENABLE_CONFIGURATION_POLICY)
797 schema_registry_service_ =
798 policy::SchemaRegistryServiceFactory::CreateForContext(
799 this, policy::Schema(), NULL);
800 CHECK_EQ(schema_registry_service_.get(),
801 policy::SchemaRegistryServiceFactory::GetForContext(this));
802 #endif // defined(ENABLE_CONFIGURATION_POLICY)
804 if (!policy_service_) {
805 #if defined(ENABLE_CONFIGURATION_POLICY)
806 std::vector<policy::ConfigurationPolicyProvider*> providers;
807 policy_service_.reset(new policy::PolicyServiceImpl(providers));
808 #else
809 policy_service_.reset(new policy::PolicyServiceStub());
810 #endif
812 profile_policy_connector_.reset(new policy::ProfilePolicyConnector());
813 profile_policy_connector_->InitForTesting(policy_service_.Pass());
814 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
815 this, profile_policy_connector_.get());
816 CHECK_EQ(profile_policy_connector_.get(),
817 policy::ProfilePolicyConnectorFactory::GetForProfile(this));
820 PrefService* TestingProfile::GetPrefs() {
821 DCHECK(prefs_);
822 return prefs_.get();
825 DownloadManagerDelegate* TestingProfile::GetDownloadManagerDelegate() {
826 return NULL;
829 net::URLRequestContextGetter* TestingProfile::GetRequestContext() {
830 return GetDefaultStoragePartition(this)->GetURLRequestContext();
833 net::URLRequestContextGetter* TestingProfile::CreateRequestContext(
834 content::ProtocolHandlerMap* protocol_handlers,
835 content::URLRequestInterceptorScopedVector request_interceptors) {
836 return new net::TestURLRequestContextGetter(
837 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
840 net::URLRequestContextGetter* TestingProfile::GetRequestContextForRenderProcess(
841 int renderer_child_id) {
842 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
843 renderer_child_id);
844 return rph->GetStoragePartition()->GetURLRequestContext();
847 net::URLRequestContextGetter* TestingProfile::GetMediaRequestContext() {
848 return NULL;
851 net::URLRequestContextGetter*
852 TestingProfile::GetMediaRequestContextForRenderProcess(
853 int renderer_child_id) {
854 return NULL;
857 net::URLRequestContextGetter*
858 TestingProfile::GetMediaRequestContextForStoragePartition(
859 const base::FilePath& partition_path,
860 bool in_memory) {
861 return NULL;
864 net::URLRequestContextGetter* TestingProfile::GetRequestContextForExtensions() {
865 if (!extensions_request_context_.get())
866 extensions_request_context_ = new TestExtensionURLRequestContextGetter();
867 return extensions_request_context_.get();
870 net::SSLConfigService* TestingProfile::GetSSLConfigService() {
871 if (!GetRequestContext())
872 return NULL;
873 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
876 net::URLRequestContextGetter*
877 TestingProfile::CreateRequestContextForStoragePartition(
878 const base::FilePath& partition_path,
879 bool in_memory,
880 content::ProtocolHandlerMap* protocol_handlers,
881 content::URLRequestInterceptorScopedVector request_interceptors) {
882 // We don't test storage partitions here yet, so returning the same dummy
883 // context is sufficient for now.
884 return GetRequestContext();
887 content::ResourceContext* TestingProfile::GetResourceContext() {
888 if (!resource_context_)
889 resource_context_ = new content::MockResourceContext();
890 return resource_context_;
893 HostContentSettingsMap* TestingProfile::GetHostContentSettingsMap() {
894 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
895 if (!host_content_settings_map_.get()) {
896 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
897 #if defined(ENABLE_EXTENSIONS)
898 ExtensionService* extension_service =
899 extensions::ExtensionSystem::Get(this)->extension_service();
900 if (extension_service) {
901 extension_service->RegisterContentSettings(
902 host_content_settings_map_.get());
904 #endif
906 return host_content_settings_map_.get();
909 content::BrowserPluginGuestManager* TestingProfile::GetGuestManager() {
910 #if defined(ENABLE_EXTENSIONS)
911 return extensions::GuestViewManager::FromBrowserContext(this);
912 #else
913 return NULL;
914 #endif
917 content::PushMessagingService* TestingProfile::GetPushMessagingService() {
918 return NULL;
921 bool TestingProfile::IsSameProfile(Profile *p) {
922 return this == p;
925 base::Time TestingProfile::GetStartTime() const {
926 return start_time_;
929 base::FilePath TestingProfile::last_selected_directory() {
930 return last_selected_directory_;
933 void TestingProfile::set_last_selected_directory(const base::FilePath& path) {
934 last_selected_directory_ = path;
937 PrefProxyConfigTracker* TestingProfile::GetProxyConfigTracker() {
938 if (!pref_proxy_config_tracker_.get()) {
939 // TestingProfile is used in unit tests, where local state is not available.
940 pref_proxy_config_tracker_.reset(
941 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
942 NULL));
944 return pref_proxy_config_tracker_.get();
947 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
948 HistoryService* history_service = HistoryServiceFactory::GetForProfile(
949 this, ServiceAccessType::EXPLICIT_ACCESS);
950 DCHECK(history_service);
951 DCHECK(base::MessageLoop::current());
953 base::CancelableTaskTracker tracker;
954 history_service->ScheduleDBTask(
955 scoped_ptr<history::HistoryDBTask>(
956 new QuittingHistoryDBTask()),
957 &tracker);
958 base::MessageLoop::current()->Run();
961 chrome_browser_net::Predictor* TestingProfile::GetNetworkPredictor() {
962 return NULL;
965 DevToolsNetworkController* TestingProfile::GetDevToolsNetworkController() {
966 return NULL;
969 void TestingProfile::ClearNetworkingHistorySince(
970 base::Time time,
971 const base::Closure& completion) {
972 if (!completion.is_null()) {
973 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, completion);
977 GURL TestingProfile::GetHomePage() {
978 return GURL(chrome::kChromeUINewTabURL);
981 PrefService* TestingProfile::GetOffTheRecordPrefs() {
982 return NULL;
985 storage::SpecialStoragePolicy* TestingProfile::GetSpecialStoragePolicy() {
986 #if defined(ENABLE_EXTENSIONS)
987 return GetExtensionSpecialStoragePolicy();
988 #else
989 return NULL;
990 #endif
993 content::SSLHostStateDelegate* TestingProfile::GetSSLHostStateDelegate() {
994 return NULL;
997 bool TestingProfile::WasCreatedByVersionOrLater(const std::string& version) {
998 return true;
1001 bool TestingProfile::IsGuestSession() const {
1002 return guest_session_;
1005 Profile::ExitType TestingProfile::GetLastSessionExitType() {
1006 return last_session_exited_cleanly_ ? EXIT_NORMAL : EXIT_CRASHED;
1009 TestingProfile::Builder::Builder()
1010 : build_called_(false),
1011 delegate_(NULL),
1012 guest_session_(false) {
1015 TestingProfile::Builder::~Builder() {
1018 void TestingProfile::Builder::SetPath(const base::FilePath& path) {
1019 path_ = path;
1022 void TestingProfile::Builder::SetDelegate(Delegate* delegate) {
1023 delegate_ = delegate;
1026 #if defined(ENABLE_EXTENSIONS)
1027 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
1028 scoped_refptr<ExtensionSpecialStoragePolicy> policy) {
1029 extension_policy_ = policy;
1031 #endif
1033 void TestingProfile::Builder::SetPrefService(
1034 scoped_ptr<PrefServiceSyncable> prefs) {
1035 pref_service_ = prefs.Pass();
1038 void TestingProfile::Builder::SetGuestSession() {
1039 guest_session_ = true;
1042 void TestingProfile::Builder::SetSupervisedUserId(
1043 const std::string& supervised_user_id) {
1044 supervised_user_id_ = supervised_user_id;
1047 void TestingProfile::Builder::SetPolicyService(
1048 scoped_ptr<policy::PolicyService> policy_service) {
1049 policy_service_ = policy_service.Pass();
1052 void TestingProfile::Builder::AddTestingFactory(
1053 BrowserContextKeyedServiceFactory* service_factory,
1054 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback) {
1055 testing_factories_.push_back(std::make_pair(service_factory, callback));
1058 scoped_ptr<TestingProfile> TestingProfile::Builder::Build() {
1059 DCHECK(!build_called_);
1060 build_called_ = true;
1062 return scoped_ptr<TestingProfile>(new TestingProfile(path_,
1063 delegate_,
1064 #if defined(ENABLE_EXTENSIONS)
1065 extension_policy_,
1066 #endif
1067 pref_service_.Pass(),
1068 NULL,
1069 guest_session_,
1070 supervised_user_id_,
1071 policy_service_.Pass(),
1072 testing_factories_));
1075 TestingProfile* TestingProfile::Builder::BuildIncognito(
1076 TestingProfile* original_profile) {
1077 DCHECK(!build_called_);
1078 DCHECK(original_profile);
1079 build_called_ = true;
1081 // Note: Owned by |original_profile|.
1082 return new TestingProfile(path_,
1083 delegate_,
1084 #if defined(ENABLE_EXTENSIONS)
1085 extension_policy_,
1086 #endif
1087 pref_service_.Pass(),
1088 original_profile,
1089 guest_session_,
1090 supervised_user_id_,
1091 policy_service_.Pass(),
1092 testing_factories_);