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/autocomplete/in_memory_url_index.h"
17 #include "chrome/browser/autocomplete/in_memory_url_index_factory.h"
18 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
19 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
20 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
21 #include "chrome/browser/browser_process.h"
22 #include "chrome/browser/chrome_notification_types.h"
23 #include "chrome/browser/favicon/chrome_fallback_icon_client_factory.h"
24 #include "chrome/browser/favicon/chrome_favicon_client_factory.h"
25 #include "chrome/browser/favicon/fallback_icon_service_factory.h"
26 #include "chrome/browser/favicon/favicon_service_factory.h"
27 #include "chrome/browser/history/chrome_history_client.h"
28 #include "chrome/browser/history/chrome_history_client_factory.h"
29 #include "chrome/browser/history/history_service_factory.h"
30 #include "chrome/browser/history/top_sites_factory.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/ui/zoom/chrome_zoom_level_prefs.h"
47 #include "chrome/browser/webdata/web_data_service_factory.h"
48 #include "chrome/common/chrome_constants.h"
49 #include "chrome/common/chrome_switches.h"
50 #include "chrome/common/pref_names.h"
51 #include "chrome/common/url_constants.h"
52 #include "chrome/test/base/history_index_restore_observer.h"
53 #include "chrome/test/base/testing_pref_service_syncable.h"
54 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
55 #include "components/bookmarks/browser/bookmark_model.h"
56 #include "components/bookmarks/common/bookmark_constants.h"
57 #include "components/content_settings/core/browser/host_content_settings_map.h"
58 #include "components/favicon/core/fallback_icon_service.h"
59 #include "components/favicon/core/favicon_service.h"
60 #include "components/history/content/browser/content_visit_delegate.h"
61 #include "components/history/content/browser/history_database_helper.h"
62 #include "components/history/core/browser/history_backend.h"
63 #include "components/history/core/browser/history_constants.h"
64 #include "components/history/core/browser/history_database_params.h"
65 #include "components/history/core/browser/history_db_task.h"
66 #include "components/history/core/browser/history_service.h"
67 #include "components/history/core/browser/top_sites.h"
68 #include "components/history/core/browser/top_sites_impl.h"
69 #include "components/history/core/browser/top_sites_observer.h"
70 #include "components/keyed_service/content/browser_context_dependency_manager.h"
71 #include "components/keyed_service/core/refcounted_keyed_service.h"
72 #include "components/policy/core/common/policy_service.h"
73 #include "components/ui/zoom/zoom_event_manager.h"
74 #include "components/user_prefs/user_prefs.h"
75 #include "components/webdata_services/web_data_service_wrapper.h"
76 #include "content/public/browser/browser_thread.h"
77 #include "content/public/browser/cookie_store_factory.h"
78 #include "content/public/browser/notification_service.h"
79 #include "content/public/browser/render_process_host.h"
80 #include "content/public/browser/storage_partition.h"
81 #include "content/public/browser/zoom_level_delegate.h"
82 #include "content/public/test/mock_resource_context.h"
83 #include "content/public/test/test_utils.h"
84 #include "extensions/common/constants.h"
85 #include "net/cookies/cookie_monster.h"
86 #include "net/url_request/url_request_context.h"
87 #include "net/url_request/url_request_context_getter.h"
88 #include "net/url_request/url_request_test_util.h"
89 #include "testing/gmock/include/gmock/gmock.h"
91 #if defined(ENABLE_CONFIGURATION_POLICY)
92 #include "chrome/browser/policy/schema_registry_service.h"
93 #include "chrome/browser/policy/schema_registry_service_factory.h"
94 #include "components/policy/core/common/configuration_policy_provider.h"
95 #include "components/policy/core/common/policy_service_impl.h"
96 #include "components/policy/core/common/schema.h"
98 #include "components/policy/core/common/policy_service_stub.h"
99 #endif // defined(ENABLE_CONFIGURATION_POLICY)
101 #if defined(ENABLE_EXTENSIONS)
102 #include "chrome/browser/extensions/extension_service.h"
103 #include "chrome/browser/extensions/extension_special_storage_policy.h"
104 #include "chrome/browser/extensions/extension_system_factory.h"
105 #include "chrome/browser/extensions/test_extension_system.h"
106 #include "extensions/browser/extension_system.h"
107 #include "extensions/browser/guest_view/guest_view_manager.h"
110 #if defined(OS_ANDROID)
111 #include "chrome/browser/signin/android_profile_oauth2_token_service.h"
114 #if defined(ENABLE_SUPERVISED_USERS)
115 #include "chrome/browser/supervised_user/supervised_user_constants.h"
116 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
117 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
121 using bookmarks::BookmarkModel
;
122 using content::BrowserThread
;
123 using content::DownloadManagerDelegate
;
124 using testing::NiceMock
;
125 using testing::Return
;
129 // TopSitesImpl::Shutdown schedules some tasks (from TopSitesBackend) that
130 // need to be run to properly shutdown. Run all pending tasks now. This is
131 // normally handled by browser_process shutdown.
133 void CleanupAfterTopSitesDestroyed() {
134 if (base::MessageLoop::current())
135 base::MessageLoop::current()->RunUntilIdle();
138 // Returns true if a TopSites service has been registered for |profile|.
139 bool HasTopSites(Profile
* profile
) {
140 return !!TopSitesFactory::GetInstance()->GetForProfileIfExists(profile
);
143 // Used to make sure TopSites has finished loading
144 class WaitTopSitesLoadedObserver
: public history::TopSitesObserver
{
146 explicit WaitTopSitesLoadedObserver(content::MessageLoopRunner
* runner
)
148 void TopSitesLoaded(history::TopSites
* top_sites
) override
{
151 void TopSitesChanged(history::TopSites
* top_sites
) override
{}
155 content::MessageLoopRunner
* runner_
;
158 // Task used to make sure history has finished processing a request. Intended
159 // for use with BlockUntilHistoryProcessesPendingRequests.
161 class QuittingHistoryDBTask
: public history::HistoryDBTask
{
163 QuittingHistoryDBTask() {}
165 bool RunOnDBThread(history::HistoryBackend
* backend
,
166 history::HistoryDatabase
* db
) override
{
170 void DoneRunOnMainThread() override
{ base::MessageLoop::current()->Quit(); }
173 ~QuittingHistoryDBTask() override
{}
175 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask
);
178 class TestExtensionURLRequestContext
: public net::URLRequestContext
{
180 TestExtensionURLRequestContext() {
181 net::CookieMonster
* cookie_monster
=
182 content::CreateCookieStore(content::CookieStoreConfig())->
184 const char* const schemes
[] = {extensions::kExtensionScheme
};
185 cookie_monster
->SetCookieableSchemes(schemes
, arraysize(schemes
));
186 set_cookie_store(cookie_monster
);
189 ~TestExtensionURLRequestContext() override
{ AssertNoURLRequests(); }
192 class TestExtensionURLRequestContextGetter
193 : public net::URLRequestContextGetter
{
195 net::URLRequestContext
* GetURLRequestContext() override
{
197 context_
.reset(new TestExtensionURLRequestContext());
198 return context_
.get();
200 scoped_refptr
<base::SingleThreadTaskRunner
> GetNetworkTaskRunner()
202 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
206 ~TestExtensionURLRequestContextGetter() override
{}
209 scoped_ptr
<net::URLRequestContext
> context_
;
212 #if defined(ENABLE_NOTIFICATIONS)
213 KeyedService
* CreateTestDesktopNotificationService(
214 content::BrowserContext
* profile
) {
215 return new DesktopNotificationService(static_cast<Profile
*>(profile
));
219 KeyedService
* BuildFaviconService(content::BrowserContext
* context
) {
220 Profile
* profile
= Profile::FromBrowserContext(context
);
221 return new favicon::FaviconService(
222 ChromeFaviconClientFactory::GetForProfile(profile
),
223 HistoryServiceFactory::GetForProfile(profile
,
224 ServiceAccessType::EXPLICIT_ACCESS
));
227 KeyedService
* BuildHistoryService(content::BrowserContext
* context
) {
228 Profile
* profile
= Profile::FromBrowserContext(context
);
229 history::HistoryService
* history_service
= new history::HistoryService(
230 ChromeHistoryClientFactory::GetForProfile(profile
),
231 scoped_ptr
<history::VisitDelegate
>(
232 new history::ContentVisitDelegate(profile
)));
233 return history_service
;
236 KeyedService
* BuildInMemoryURLIndex(content::BrowserContext
* context
) {
237 Profile
* profile
= Profile::FromBrowserContext(context
);
238 InMemoryURLIndex
* in_memory_url_index
= new InMemoryURLIndex(
239 BookmarkModelFactory::GetForProfile(profile
),
240 HistoryServiceFactory::GetForProfile(profile
,
241 ServiceAccessType::IMPLICIT_ACCESS
),
243 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
244 in_memory_url_index
->Init();
245 return in_memory_url_index
;
248 KeyedService
* BuildBookmarkModel(content::BrowserContext
* context
) {
249 Profile
* profile
= static_cast<Profile
*>(context
);
250 ChromeBookmarkClient
* bookmark_client
=
251 ChromeBookmarkClientFactory::GetForProfile(profile
);
252 BookmarkModel
* bookmark_model
= new BookmarkModel(bookmark_client
);
253 bookmark_client
->Init(bookmark_model
);
254 bookmark_model
->Load(profile
->GetPrefs(),
255 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
),
257 profile
->GetIOTaskRunner(),
258 content::BrowserThread::GetMessageLoopProxyForThread(
259 content::BrowserThread::UI
));
260 return bookmark_model
;
263 KeyedService
* BuildChromeBookmarkClient(
264 content::BrowserContext
* context
) {
265 return new ChromeBookmarkClient(static_cast<Profile
*>(context
));
268 KeyedService
* BuildChromeHistoryClient(
269 content::BrowserContext
* context
) {
270 Profile
* profile
= static_cast<Profile
*>(context
);
271 return new ChromeHistoryClient(BookmarkModelFactory::GetForProfile(profile
));
274 void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type
,
275 sql::InitStatus status
) {
279 KeyedService
* BuildWebDataService(content::BrowserContext
* context
) {
280 const base::FilePath
& context_path
= context
->GetPath();
281 return new WebDataServiceWrapper(
282 context_path
, g_browser_process
->GetApplicationLocale(),
283 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI
),
284 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB
),
285 sync_start_util::GetFlareForSyncableService(context_path
),
286 &TestProfileErrorCallback
);
289 scoped_refptr
<RefcountedKeyedService
> BuildTopSites(
290 content::BrowserContext
* context
) {
291 return TopSitesFactory::BuildTopSites(context
,
292 history::PrepopulatedPageList());
298 #if defined(OS_CHROMEOS)
299 // Must be kept in sync with
300 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
301 const char TestingProfile::kTestUserProfileDir
[] = "test-user";
303 const char TestingProfile::kTestUserProfileDir
[] = "Default";
306 TestingProfile::TestingProfile()
307 : start_time_(Time::Now()),
308 testing_prefs_(NULL
),
309 force_incognito_(false),
310 original_profile_(NULL
),
311 guest_session_(false),
312 last_session_exited_cleanly_(true),
313 browser_context_dependency_manager_(
314 BrowserContextDependencyManager::GetInstance()),
315 resource_context_(NULL
),
317 CreateTempProfileDir();
318 profile_path_
= temp_dir_
.path();
324 TestingProfile::TestingProfile(const base::FilePath
& path
)
325 : start_time_(Time::Now()),
326 testing_prefs_(NULL
),
327 force_incognito_(false),
328 original_profile_(NULL
),
329 guest_session_(false),
330 last_session_exited_cleanly_(true),
332 browser_context_dependency_manager_(
333 BrowserContextDependencyManager::GetInstance()),
334 resource_context_(NULL
),
340 TestingProfile::TestingProfile(const base::FilePath
& path
,
342 : start_time_(Time::Now()),
343 testing_prefs_(NULL
),
344 force_incognito_(false),
345 original_profile_(NULL
),
346 guest_session_(false),
347 last_session_exited_cleanly_(true),
349 browser_context_dependency_manager_(
350 BrowserContextDependencyManager::GetInstance()),
351 resource_context_(NULL
),
352 delegate_(delegate
) {
355 base::MessageLoop::current()->PostTask(
357 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
363 TestingProfile::TestingProfile(
364 const base::FilePath
& path
,
366 #if defined(ENABLE_EXTENSIONS)
367 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy
,
369 scoped_ptr
<PrefServiceSyncable
> prefs
,
370 TestingProfile
* parent
,
372 const std::string
& supervised_user_id
,
373 scoped_ptr
<policy::PolicyService
> policy_service
,
374 const TestingFactories
& factories
)
375 : start_time_(Time::Now()),
376 prefs_(prefs
.release()),
377 testing_prefs_(NULL
),
378 force_incognito_(false),
379 original_profile_(parent
),
380 guest_session_(guest_session
),
381 last_session_exited_cleanly_(true),
382 #if defined(ENABLE_EXTENSIONS)
383 extension_special_storage_policy_(extension_policy
),
386 browser_context_dependency_manager_(
387 BrowserContextDependencyManager::GetInstance()),
388 resource_context_(NULL
),
390 policy_service_(policy_service
.release()) {
392 parent
->SetOffTheRecordProfile(scoped_ptr
<Profile
>(this));
394 // If no profile path was supplied, create one.
395 if (profile_path_
.empty()) {
396 CreateTempProfileDir();
397 profile_path_
= temp_dir_
.path();
400 // Set any testing factories prior to initializing the services.
401 for (TestingFactories::const_iterator it
= factories
.begin();
402 it
!= factories
.end(); ++it
) {
403 it
->first
->SetTestingFactory(this, it
->second
);
407 // If caller supplied a delegate, delay the FinishInit invocation until other
409 // TODO(atwilson): See if this is still required once we convert the current
410 // users of the constructor that takes a Delegate* param.
412 base::MessageLoop::current()->PostTask(
414 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
419 SetSupervisedUserId(supervised_user_id
);
422 void TestingProfile::CreateTempProfileDir() {
423 if (!temp_dir_
.CreateUniqueTempDir()) {
424 LOG(ERROR
) << "Failed to create unique temporary directory.";
426 // Fallback logic in case we fail to create unique temporary directory.
427 base::FilePath system_tmp_dir
;
428 bool success
= PathService::Get(base::DIR_TEMP
, &system_tmp_dir
);
430 // We're severly screwed if we can't get the system temporary
431 // directory. Die now to avoid writing to the filesystem root
432 // or other bad places.
435 base::FilePath
fallback_dir(
436 system_tmp_dir
.AppendASCII("TestingProfilePath"));
437 base::DeleteFile(fallback_dir
, true);
438 base::CreateDirectory(fallback_dir
);
439 if (!temp_dir_
.Set(fallback_dir
)) {
440 // That shouldn't happen, but if it does, try to recover.
441 LOG(ERROR
) << "Failed to use a fallback temporary directory.";
443 // We're screwed if this fails, see CHECK above.
444 CHECK(temp_dir_
.Set(system_tmp_dir
));
449 void TestingProfile::Init() {
450 // If threads have been initialized, we should be on the UI thread.
451 DCHECK(!content::BrowserThread::IsThreadInitialized(
452 content::BrowserThread::UI
) ||
453 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
455 set_is_guest_profile(guest_session_
);
457 #if defined(OS_ANDROID)
458 // Make sure token service knows its running in tests.
459 AndroidProfileOAuth2TokenService::set_is_testing_profile();
462 // Normally this would happen during browser startup, but for tests
463 // we need to trigger creation of Profile-related services.
464 ChromeBrowserMainExtraPartsProfiles::
465 EnsureBrowserContextKeyedServiceFactoriesBuilt();
468 user_prefs::UserPrefs::Set(this, prefs_
.get());
469 else if (IsOffTheRecord())
470 CreateIncognitoPrefService();
472 CreateTestingPrefService();
474 if (!base::PathExists(profile_path_
))
475 base::CreateDirectory(profile_path_
);
477 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
478 // anymore, after converting the PrefService to a PKS. Until then it must
479 // be associated with a TestingProfile too.
480 if (!IsOffTheRecord())
481 CreateProfilePolicyConnector();
483 #if defined(ENABLE_EXTENSIONS)
484 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
485 this, extensions::TestExtensionSystem::Build
);
488 // Prefs for incognito profiles are set in CreateIncognitoPrefService() by
489 // simulating ProfileImpl::GetOffTheRecordPrefs().
490 if (!IsOffTheRecord()) {
491 DCHECK(!original_profile_
);
492 user_prefs::PrefRegistrySyncable
* pref_registry
=
493 static_cast<user_prefs::PrefRegistrySyncable
*>(
494 prefs_
->DeprecatedGetPrefRegistry());
495 browser_context_dependency_manager_
->
496 RegisterProfilePrefsForServices(this, pref_registry
);
499 browser_context_dependency_manager_
->CreateBrowserContextServicesForTest(
502 #if defined(ENABLE_NOTIFICATIONS)
503 // Install profile keyed service factory hooks for dummy/test services
504 DesktopNotificationServiceFactory::GetInstance()->SetTestingFactory(
505 this, CreateTestDesktopNotificationService
);
508 #if defined(ENABLE_SUPERVISED_USERS)
509 if (!IsOffTheRecord()) {
510 SupervisedUserSettingsService
* settings_service
=
511 SupervisedUserSettingsServiceFactory::GetForProfile(this);
512 TestingPrefStore
* store
= new TestingPrefStore();
513 settings_service
->Init(store
);
514 store
->SetInitializationCompleted();
518 profile_name_
= "testing_profile";
521 void TestingProfile::FinishInit() {
522 DCHECK(content::NotificationService::current());
523 content::NotificationService::current()->Notify(
524 chrome::NOTIFICATION_PROFILE_CREATED
,
525 content::Source
<Profile
>(static_cast<Profile
*>(this)),
526 content::NotificationService::NoDetails());
528 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
530 profile_manager
->InitProfileUserPrefs(this);
533 delegate_
->OnProfileCreated(this, true, false);
536 TestingProfile::~TestingProfile() {
537 // Revert to non-incognito mode before shutdown.
538 force_incognito_
= false;
540 // If this profile owns an incognito profile, tear it down first.
541 incognito_profile_
.reset();
543 // Any objects holding live URLFetchers should be deleted before teardown.
544 TemplateURLFetcherFactory::ShutdownForProfile(this);
546 MaybeSendDestroyedNotification();
548 // Remember whether a TopSites has been created for the current profile,
549 // so that we can run cleanup after destroying all services.
550 bool had_top_sites
= HasTopSites(this);
552 browser_context_dependency_manager_
->DestroyBrowserContextServices(this);
554 if (host_content_settings_map_
.get())
555 host_content_settings_map_
->ShutdownOnUIThread();
557 // Wait until TopSites shutdown tasks have completed if a TopSites has
558 // been created for the current profile.
560 CleanupAfterTopSitesDestroyed();
562 if (pref_proxy_config_tracker_
.get())
563 pref_proxy_config_tracker_
->DetachFromPrefService();
564 // Failing a post == leaks == heapcheck failure. Make that an immediate test
566 if (resource_context_
) {
567 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO
, FROM_HERE
,
569 resource_context_
= NULL
;
570 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
574 void TestingProfile::CreateFaviconService() {
575 // It is up to the caller to create the history service if one is needed.
576 FaviconServiceFactory::GetInstance()->SetTestingFactory(
577 this, BuildFaviconService
);
580 bool TestingProfile::CreateHistoryService(bool delete_file
, bool no_db
) {
581 DestroyHistoryService();
583 base::FilePath path
= GetPath();
584 path
= path
.Append(history::kHistoryFilename
);
585 if (!base::DeleteFile(path
, false) || base::PathExists(path
))
588 // This will create and init the history service.
589 history::HistoryService
* history_service
=
590 static_cast<history::HistoryService
*>(
591 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
592 this, BuildHistoryService
));
593 if (!history_service
->Init(
594 no_db
, GetPrefs()->GetString(prefs::kAcceptLanguages
),
595 history::HistoryDatabaseParamsForPath(GetPath()))) {
596 HistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
599 // Some tests expect that CreateHistoryService() will also make the
600 // InMemoryURLIndex available.
601 InMemoryURLIndexFactory::GetInstance()->SetTestingFactory(
602 this, BuildInMemoryURLIndex
);
603 // Disable WebHistoryService by default, since it makes network requests.
604 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
608 void TestingProfile::DestroyHistoryService() {
609 history::HistoryService
* history_service
=
610 HistoryServiceFactory::GetForProfileWithoutCreating(this);
611 if (!history_service
)
614 history_service
->ClearCachedDataForContextID(0);
615 history_service
->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
616 history_service
->Cleanup();
617 HistoryServiceFactory::ShutdownForProfile(this);
619 // Wait for the backend class to terminate before deleting the files and
620 // moving to the next test. Note: if this never terminates, somebody is
621 // probably leaking a reference to the history backend, so it never calls
623 base::MessageLoop::current()->Run();
625 // Make sure we don't have any event pending that could disrupt the next
627 base::MessageLoop::current()->PostTask(FROM_HERE
,
628 base::MessageLoop::QuitClosure());
629 base::MessageLoop::current()->Run();
632 void TestingProfile::CreateTopSites() {
634 TopSitesFactory::GetInstance()->SetTestingFactoryAndUse(this, BuildTopSites
);
637 void TestingProfile::DestroyTopSites() {
638 TopSitesFactory
* top_sites_factory
= TopSitesFactory::GetInstance();
639 if (top_sites_factory
->GetForProfileIfExists(this)) {
640 // BrowserContextKeyedServiceFactory will destroy the previous service when
641 // registering a new testing factory so use this to ensure that destroy the
643 top_sites_factory
->SetTestingFactory(this, nullptr);
644 CleanupAfterTopSitesDestroyed();
648 void TestingProfile::CreateBookmarkModel(bool delete_file
) {
650 base::FilePath path
= GetPath().Append(bookmarks::kBookmarksFileName
);
651 base::DeleteFile(path
, false);
653 ChromeHistoryClientFactory::GetInstance()->SetTestingFactory(
654 this, BuildChromeHistoryClient
);
655 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
656 this, BuildChromeBookmarkClient
);
657 // This creates the BookmarkModel.
658 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
659 this, BuildBookmarkModel
));
662 void TestingProfile::CreateWebDataService() {
663 WebDataServiceFactory::GetInstance()->SetTestingFactory(
664 this, BuildWebDataService
);
667 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
668 // Only get the history service if it actually exists since the caller of the
669 // test should explicitly call CreateHistoryService to build it.
670 history::HistoryService
* history_service
=
671 HistoryServiceFactory::GetForProfileWithoutCreating(this);
672 DCHECK(history_service
);
673 InMemoryURLIndex
* index
= InMemoryURLIndexFactory::GetForProfile(this);
674 if (!index
|| index
->restored())
676 base::RunLoop run_loop
;
677 HistoryIndexRestoreObserver
observer(
678 content::GetQuitTaskForRunLoop(&run_loop
));
679 index
->set_restore_cache_observer(&observer
);
681 index
->set_restore_cache_observer(NULL
);
682 DCHECK(index
->restored());
685 // TODO(phajdan.jr): Doesn't this hang if Top Sites are already loaded?
686 void TestingProfile::BlockUntilTopSitesLoaded() {
687 scoped_refptr
<content::MessageLoopRunner
> runner
=
688 new content::MessageLoopRunner
;
689 WaitTopSitesLoadedObserver
observer(runner
.get());
690 scoped_refptr
<history::TopSites
> top_sites
=
691 TopSitesFactory::GetForProfile(this);
692 top_sites
->AddObserver(&observer
);
694 top_sites
->RemoveObserver(&observer
);
697 void TestingProfile::SetGuestSession(bool guest
) {
698 guest_session_
= guest
;
701 base::FilePath
TestingProfile::GetPath() const {
702 return profile_path_
;
705 scoped_ptr
<content::ZoomLevelDelegate
> TestingProfile::CreateZoomLevelDelegate(
706 const base::FilePath
& partition_path
) {
707 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
708 GetPrefs(), GetPath(), partition_path
,
709 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
712 scoped_refptr
<base::SequencedTaskRunner
> TestingProfile::GetIOTaskRunner() {
713 return base::MessageLoop::current()->message_loop_proxy();
716 TestingPrefServiceSyncable
* TestingProfile::GetTestingPrefService() {
718 DCHECK(testing_prefs_
);
719 return testing_prefs_
;
722 TestingProfile
* TestingProfile::AsTestingProfile() {
726 std::string
TestingProfile::GetProfileUserName() const {
727 return profile_name_
;
730 Profile::ProfileType
TestingProfile::GetProfileType() const {
732 return GUEST_PROFILE
;
733 if (force_incognito_
|| original_profile_
)
734 return INCOGNITO_PROFILE
;
735 return REGULAR_PROFILE
;
738 bool TestingProfile::IsOffTheRecord() const {
739 return force_incognito_
|| original_profile_
;
742 void TestingProfile::SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
) {
743 DCHECK(!IsOffTheRecord());
744 DCHECK_EQ(this, profile
->GetOriginalProfile());
745 incognito_profile_
= profile
.Pass();
748 Profile
* TestingProfile::GetOffTheRecordProfile() {
749 if (IsOffTheRecord())
751 if (!incognito_profile_
)
752 TestingProfile::Builder().BuildIncognito(this);
753 return incognito_profile_
.get();
756 bool TestingProfile::HasOffTheRecordProfile() {
757 return incognito_profile_
.get() != NULL
;
760 Profile
* TestingProfile::GetOriginalProfile() {
761 if (original_profile_
)
762 return original_profile_
;
766 void TestingProfile::SetSupervisedUserId(const std::string
& id
) {
767 supervised_user_id_
= id
;
769 GetPrefs()->SetString(prefs::kSupervisedUserId
, id
);
771 GetPrefs()->ClearPref(prefs::kSupervisedUserId
);
774 bool TestingProfile::IsSupervised() {
775 return !supervised_user_id_
.empty();
778 bool TestingProfile::IsChild() {
779 #if defined(ENABLE_SUPERVISED_USERS)
780 return supervised_user_id_
== supervised_users::kChildAccountSUID
;
786 bool TestingProfile::IsLegacySupervised() {
787 return IsSupervised() && !IsChild();
790 #if defined(ENABLE_EXTENSIONS)
791 void TestingProfile::SetExtensionSpecialStoragePolicy(
792 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
) {
793 extension_special_storage_policy_
= extension_special_storage_policy
;
797 ExtensionSpecialStoragePolicy
*
798 TestingProfile::GetExtensionSpecialStoragePolicy() {
799 #if defined(ENABLE_EXTENSIONS)
800 if (!extension_special_storage_policy_
.get())
801 extension_special_storage_policy_
= new ExtensionSpecialStoragePolicy(NULL
);
802 return extension_special_storage_policy_
.get();
808 net::CookieMonster
* TestingProfile::GetCookieMonster() {
809 if (!GetRequestContext())
811 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
815 void TestingProfile::CreateTestingPrefService() {
816 DCHECK(!prefs_
.get());
817 testing_prefs_
= new TestingPrefServiceSyncable();
818 prefs_
.reset(testing_prefs_
);
819 user_prefs::UserPrefs::Set(this, prefs_
.get());
820 chrome::RegisterUserProfilePrefs(testing_prefs_
->registry());
823 void TestingProfile::CreateIncognitoPrefService() {
824 DCHECK(original_profile_
);
825 DCHECK(!testing_prefs_
);
826 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
827 // leaves testing_prefs_ unset.
828 prefs_
.reset(original_profile_
->prefs_
->CreateIncognitoPrefService(NULL
));
829 user_prefs::UserPrefs::Set(this, prefs_
.get());
832 void TestingProfile::CreateProfilePolicyConnector() {
833 #if defined(ENABLE_CONFIGURATION_POLICY)
834 schema_registry_service_
=
835 policy::SchemaRegistryServiceFactory::CreateForContext(
836 this, policy::Schema(), NULL
);
837 CHECK_EQ(schema_registry_service_
.get(),
838 policy::SchemaRegistryServiceFactory::GetForContext(this));
839 #endif // defined(ENABLE_CONFIGURATION_POLICY)
841 if (!policy_service_
) {
842 #if defined(ENABLE_CONFIGURATION_POLICY)
843 std::vector
<policy::ConfigurationPolicyProvider
*> providers
;
844 policy_service_
.reset(new policy::PolicyServiceImpl(providers
));
846 policy_service_
.reset(new policy::PolicyServiceStub());
849 profile_policy_connector_
.reset(new policy::ProfilePolicyConnector());
850 profile_policy_connector_
->InitForTesting(policy_service_
.Pass());
851 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
852 this, profile_policy_connector_
.get());
853 CHECK_EQ(profile_policy_connector_
.get(),
854 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(this));
857 PrefService
* TestingProfile::GetPrefs() {
862 const PrefService
* TestingProfile::GetPrefs() const {
867 chrome::ChromeZoomLevelPrefs
* TestingProfile::GetZoomLevelPrefs() {
868 return static_cast<chrome::ChromeZoomLevelPrefs
*>(
869 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
872 DownloadManagerDelegate
* TestingProfile::GetDownloadManagerDelegate() {
876 net::URLRequestContextGetter
* TestingProfile::GetRequestContext() {
877 return GetDefaultStoragePartition(this)->GetURLRequestContext();
880 net::URLRequestContextGetter
* TestingProfile::CreateRequestContext(
881 content::ProtocolHandlerMap
* protocol_handlers
,
882 content::URLRequestInterceptorScopedVector request_interceptors
) {
883 return new net::TestURLRequestContextGetter(
884 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
887 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForRenderProcess(
888 int renderer_child_id
) {
889 content::RenderProcessHost
* rph
= content::RenderProcessHost::FromID(
891 return rph
->GetStoragePartition()->GetURLRequestContext();
894 net::URLRequestContextGetter
* TestingProfile::GetMediaRequestContext() {
898 net::URLRequestContextGetter
*
899 TestingProfile::GetMediaRequestContextForRenderProcess(
900 int renderer_child_id
) {
904 net::URLRequestContextGetter
*
905 TestingProfile::GetMediaRequestContextForStoragePartition(
906 const base::FilePath
& partition_path
,
911 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForExtensions() {
912 if (!extensions_request_context_
.get())
913 extensions_request_context_
= new TestExtensionURLRequestContextGetter();
914 return extensions_request_context_
.get();
917 net::SSLConfigService
* TestingProfile::GetSSLConfigService() {
918 if (!GetRequestContext())
920 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
923 net::URLRequestContextGetter
*
924 TestingProfile::CreateRequestContextForStoragePartition(
925 const base::FilePath
& partition_path
,
927 content::ProtocolHandlerMap
* protocol_handlers
,
928 content::URLRequestInterceptorScopedVector request_interceptors
) {
929 // We don't test storage partitions here yet, so returning the same dummy
930 // context is sufficient for now.
931 return GetRequestContext();
934 content::ResourceContext
* TestingProfile::GetResourceContext() {
935 if (!resource_context_
)
936 resource_context_
= new content::MockResourceContext();
937 return resource_context_
;
940 HostContentSettingsMap
* TestingProfile::GetHostContentSettingsMap() {
941 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
942 if (!host_content_settings_map_
.get()) {
943 host_content_settings_map_
= new HostContentSettingsMap(GetPrefs(), false);
944 #if defined(ENABLE_EXTENSIONS)
945 ExtensionService
* extension_service
=
946 extensions::ExtensionSystem::Get(this)->extension_service();
947 if (extension_service
) {
948 extension_service
->RegisterContentSettings(
949 host_content_settings_map_
.get());
953 return host_content_settings_map_
.get();
956 content::BrowserPluginGuestManager
* TestingProfile::GetGuestManager() {
957 #if defined(ENABLE_EXTENSIONS)
958 return extensions::GuestViewManager::FromBrowserContext(this);
964 content::PushMessagingService
* TestingProfile::GetPushMessagingService() {
968 bool TestingProfile::IsSameProfile(Profile
*p
) {
972 base::Time
TestingProfile::GetStartTime() const {
976 base::FilePath
TestingProfile::last_selected_directory() {
977 return last_selected_directory_
;
980 void TestingProfile::set_last_selected_directory(const base::FilePath
& path
) {
981 last_selected_directory_
= path
;
984 PrefProxyConfigTracker
* TestingProfile::GetProxyConfigTracker() {
985 if (!pref_proxy_config_tracker_
.get()) {
986 // TestingProfile is used in unit tests, where local state is not available.
987 pref_proxy_config_tracker_
.reset(
988 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
991 return pref_proxy_config_tracker_
.get();
994 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
995 history::HistoryService
* history_service
=
996 HistoryServiceFactory::GetForProfile(this,
997 ServiceAccessType::EXPLICIT_ACCESS
);
998 DCHECK(history_service
);
999 DCHECK(base::MessageLoop::current());
1001 base::CancelableTaskTracker tracker
;
1002 history_service
->ScheduleDBTask(
1003 scoped_ptr
<history::HistoryDBTask
>(
1004 new QuittingHistoryDBTask()),
1006 base::MessageLoop::current()->Run();
1009 chrome_browser_net::Predictor
* TestingProfile::GetNetworkPredictor() {
1013 DevToolsNetworkController
* TestingProfile::GetDevToolsNetworkController() {
1017 void TestingProfile::ClearNetworkingHistorySince(
1019 const base::Closure
& completion
) {
1020 if (!completion
.is_null()) {
1021 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, completion
);
1025 GURL
TestingProfile::GetHomePage() {
1026 return GURL(chrome::kChromeUINewTabURL
);
1029 PrefService
* TestingProfile::GetOffTheRecordPrefs() {
1033 storage::SpecialStoragePolicy
* TestingProfile::GetSpecialStoragePolicy() {
1034 #if defined(ENABLE_EXTENSIONS)
1035 return GetExtensionSpecialStoragePolicy();
1041 content::SSLHostStateDelegate
* TestingProfile::GetSSLHostStateDelegate() {
1045 content::PermissionManager
* TestingProfile::GetPermissionManager() {
1049 bool TestingProfile::WasCreatedByVersionOrLater(const std::string
& version
) {
1053 bool TestingProfile::IsGuestSession() const {
1054 return guest_session_
;
1057 Profile::ExitType
TestingProfile::GetLastSessionExitType() {
1058 return last_session_exited_cleanly_
? EXIT_NORMAL
: EXIT_CRASHED
;
1061 TestingProfile::Builder::Builder()
1062 : build_called_(false),
1064 guest_session_(false) {
1067 TestingProfile::Builder::~Builder() {
1070 void TestingProfile::Builder::SetPath(const base::FilePath
& path
) {
1074 void TestingProfile::Builder::SetDelegate(Delegate
* delegate
) {
1075 delegate_
= delegate
;
1078 #if defined(ENABLE_EXTENSIONS)
1079 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
1080 scoped_refptr
<ExtensionSpecialStoragePolicy
> policy
) {
1081 extension_policy_
= policy
;
1085 void TestingProfile::Builder::SetPrefService(
1086 scoped_ptr
<PrefServiceSyncable
> prefs
) {
1087 pref_service_
= prefs
.Pass();
1090 void TestingProfile::Builder::SetGuestSession() {
1091 guest_session_
= true;
1094 void TestingProfile::Builder::SetSupervisedUserId(
1095 const std::string
& supervised_user_id
) {
1096 supervised_user_id_
= supervised_user_id
;
1099 void TestingProfile::Builder::SetPolicyService(
1100 scoped_ptr
<policy::PolicyService
> policy_service
) {
1101 policy_service_
= policy_service
.Pass();
1104 void TestingProfile::Builder::AddTestingFactory(
1105 BrowserContextKeyedServiceFactory
* service_factory
,
1106 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback
) {
1107 testing_factories_
.push_back(std::make_pair(service_factory
, callback
));
1110 scoped_ptr
<TestingProfile
> TestingProfile::Builder::Build() {
1111 DCHECK(!build_called_
);
1112 build_called_
= true;
1114 return scoped_ptr
<TestingProfile
>(new TestingProfile(path_
,
1116 #if defined(ENABLE_EXTENSIONS)
1119 pref_service_
.Pass(),
1122 supervised_user_id_
,
1123 policy_service_
.Pass(),
1124 testing_factories_
));
1127 TestingProfile
* TestingProfile::Builder::BuildIncognito(
1128 TestingProfile
* original_profile
) {
1129 DCHECK(!build_called_
);
1130 DCHECK(original_profile
);
1131 build_called_
= true;
1133 // Note: Owned by |original_profile|.
1134 return new TestingProfile(path_
,
1136 #if defined(ENABLE_EXTENSIONS)
1139 pref_service_
.Pass(),
1142 supervised_user_id_
,
1143 policy_service_
.Pass(),
1144 testing_factories_
);