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/location.h"
11 #include "base/path_service.h"
12 #include "base/prefs/testing_pref_store.h"
13 #include "base/run_loop.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
18 #include "chrome/browser/autocomplete/in_memory_url_index_factory.h"
19 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
20 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
21 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
22 #include "chrome/browser/browser_process.h"
23 #include "chrome/browser/chrome_notification_types.h"
24 #include "chrome/browser/favicon/chrome_fallback_icon_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/history_service_factory.h"
29 #include "chrome/browser/history/web_history_service_factory.h"
30 #include "chrome/browser/net/pref_proxy_config_tracker.h"
31 #include "chrome/browser/net/proxy_service_factory.h"
32 #include "chrome/browser/notifications/desktop_notification_service.h"
33 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
34 #include "chrome/browser/policy/profile_policy_connector.h"
35 #include "chrome/browser/policy/profile_policy_connector_factory.h"
36 #include "chrome/browser/prefs/browser_prefs.h"
37 #include "chrome/browser/prefs/pref_service_syncable.h"
38 #include "chrome/browser/prerender/prerender_manager.h"
39 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
40 #include "chrome/browser/profiles/profile_manager.h"
41 #include "chrome/browser/profiles/storage_partition_descriptor.h"
42 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
43 #include "chrome/browser/sync/glue/sync_start_util.h"
44 #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
45 #include "chrome/browser/web_data_service_factory.h"
46 #include "chrome/common/chrome_constants.h"
47 #include "chrome/common/chrome_switches.h"
48 #include "chrome/common/pref_names.h"
49 #include "chrome/common/url_constants.h"
50 #include "chrome/test/base/history_index_restore_observer.h"
51 #include "chrome/test/base/testing_pref_service_syncable.h"
52 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
53 #include "components/bookmarks/browser/bookmark_model.h"
54 #include "components/bookmarks/common/bookmark_constants.h"
55 #include "components/content_settings/core/browser/host_content_settings_map.h"
56 #include "components/favicon/core/fallback_icon_service.h"
57 #include "components/favicon/core/favicon_service.h"
58 #include "components/history/content/browser/content_visit_delegate.h"
59 #include "components/history/content/browser/history_database_helper.h"
60 #include "components/history/core/browser/history_backend.h"
61 #include "components/history/core/browser/history_constants.h"
62 #include "components/history/core/browser/history_database_params.h"
63 #include "components/history/core/browser/history_db_task.h"
64 #include "components/history/core/browser/history_service.h"
65 #include "components/keyed_service/content/browser_context_dependency_manager.h"
66 #include "components/keyed_service/core/refcounted_keyed_service.h"
67 #include "components/omnibox/in_memory_url_index.h"
68 #include "components/policy/core/common/policy_service.h"
69 #include "components/ui/zoom/zoom_event_manager.h"
70 #include "components/user_prefs/user_prefs.h"
71 #include "components/webdata_services/web_data_service_wrapper.h"
72 #include "content/public/browser/browser_thread.h"
73 #include "content/public/browser/cookie_store_factory.h"
74 #include "content/public/browser/notification_service.h"
75 #include "content/public/browser/render_process_host.h"
76 #include "content/public/browser/storage_partition.h"
77 #include "content/public/browser/zoom_level_delegate.h"
78 #include "content/public/test/mock_resource_context.h"
79 #include "content/public/test/test_utils.h"
80 #include "extensions/common/constants.h"
81 #include "net/cookies/cookie_monster.h"
82 #include "net/url_request/url_request_context.h"
83 #include "net/url_request/url_request_context_getter.h"
84 #include "net/url_request/url_request_test_util.h"
85 #include "testing/gmock/include/gmock/gmock.h"
87 #if defined(ENABLE_CONFIGURATION_POLICY)
88 #include "chrome/browser/policy/schema_registry_service.h"
89 #include "chrome/browser/policy/schema_registry_service_factory.h"
90 #include "components/policy/core/common/configuration_policy_provider.h"
91 #include "components/policy/core/common/policy_service_impl.h"
92 #include "components/policy/core/common/schema.h"
94 #include "components/policy/core/common/policy_service_stub.h"
95 #endif // defined(ENABLE_CONFIGURATION_POLICY)
97 #if defined(ENABLE_EXTENSIONS)
98 #include "chrome/browser/extensions/extension_service.h"
99 #include "chrome/browser/extensions/extension_special_storage_policy.h"
100 #include "chrome/browser/extensions/extension_system_factory.h"
101 #include "chrome/browser/extensions/test_extension_system.h"
102 #include "components/guest_view/browser/guest_view_manager.h"
103 #include "extensions/browser/event_router_factory.h"
104 #include "extensions/browser/extension_prefs.h"
105 #include "extensions/browser/extension_prefs_factory.h"
106 #include "extensions/browser/extension_system.h"
109 #if defined(OS_ANDROID)
110 #include "chrome/browser/signin/android_profile_oauth2_token_service.h"
113 #if defined(ENABLE_SUPERVISED_USERS)
114 #include "chrome/browser/supervised_user/supervised_user_constants.h"
115 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
116 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
120 using bookmarks::BookmarkModel
;
121 using content::BrowserThread
;
122 using content::DownloadManagerDelegate
;
123 using testing::NiceMock
;
124 using testing::Return
;
128 // Task used to make sure history has finished processing a request. Intended
129 // for use with BlockUntilHistoryProcessesPendingRequests.
131 class QuittingHistoryDBTask
: public history::HistoryDBTask
{
133 QuittingHistoryDBTask() {}
135 bool RunOnDBThread(history::HistoryBackend
* backend
,
136 history::HistoryDatabase
* db
) override
{
140 void DoneRunOnMainThread() override
{ base::MessageLoop::current()->Quit(); }
143 ~QuittingHistoryDBTask() override
{}
145 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask
);
148 class TestExtensionURLRequestContext
: public net::URLRequestContext
{
150 TestExtensionURLRequestContext() {
151 net::CookieMonster
* cookie_monster
=
152 content::CreateCookieStore(content::CookieStoreConfig())->
154 const char* const schemes
[] = {extensions::kExtensionScheme
};
155 cookie_monster
->SetCookieableSchemes(schemes
, arraysize(schemes
));
156 set_cookie_store(cookie_monster
);
159 ~TestExtensionURLRequestContext() override
{ AssertNoURLRequests(); }
162 class TestExtensionURLRequestContextGetter
163 : public net::URLRequestContextGetter
{
165 net::URLRequestContext
* GetURLRequestContext() override
{
167 context_
.reset(new TestExtensionURLRequestContext());
168 return context_
.get();
170 scoped_refptr
<base::SingleThreadTaskRunner
> GetNetworkTaskRunner()
172 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
176 ~TestExtensionURLRequestContextGetter() override
{}
179 scoped_ptr
<net::URLRequestContext
> context_
;
182 #if defined(ENABLE_NOTIFICATIONS)
183 scoped_ptr
<KeyedService
> CreateTestDesktopNotificationService(
184 content::BrowserContext
* profile
) {
185 return make_scoped_ptr(
186 new DesktopNotificationService(static_cast<Profile
*>(profile
)));
190 scoped_ptr
<KeyedService
> BuildHistoryService(content::BrowserContext
* context
) {
191 Profile
* profile
= Profile::FromBrowserContext(context
);
192 return make_scoped_ptr(new history::HistoryService(
193 make_scoped_ptr(new ChromeHistoryClient(
194 BookmarkModelFactory::GetForProfile(profile
))),
195 make_scoped_ptr(new history::ContentVisitDelegate(profile
))));
198 scoped_ptr
<KeyedService
> BuildInMemoryURLIndex(
199 content::BrowserContext
* context
) {
200 Profile
* profile
= Profile::FromBrowserContext(context
);
201 scoped_ptr
<InMemoryURLIndex
> in_memory_url_index(new InMemoryURLIndex(
202 BookmarkModelFactory::GetForProfile(profile
),
203 HistoryServiceFactory::GetForProfile(profile
,
204 ServiceAccessType::IMPLICIT_ACCESS
),
205 content::BrowserThread::GetBlockingPool(), profile
->GetPath(),
206 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
),
208 in_memory_url_index
->Init();
209 return in_memory_url_index
.Pass();
212 scoped_ptr
<KeyedService
> BuildBookmarkModel(content::BrowserContext
* context
) {
213 Profile
* profile
= static_cast<Profile
*>(context
);
214 ChromeBookmarkClient
* bookmark_client
=
215 ChromeBookmarkClientFactory::GetForProfile(profile
);
216 scoped_ptr
<BookmarkModel
> bookmark_model(new BookmarkModel(bookmark_client
));
217 bookmark_client
->Init(bookmark_model
.get());
218 bookmark_model
->Load(profile
->GetPrefs(),
219 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
),
221 profile
->GetIOTaskRunner(),
222 content::BrowserThread::GetMessageLoopProxyForThread(
223 content::BrowserThread::UI
));
224 return bookmark_model
.Pass();
227 scoped_ptr
<KeyedService
> BuildChromeBookmarkClient(
228 content::BrowserContext
* context
) {
229 return make_scoped_ptr(
230 new ChromeBookmarkClient(static_cast<Profile
*>(context
)));
233 void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type
,
234 sql::InitStatus status
) {
238 scoped_ptr
<KeyedService
> BuildWebDataService(content::BrowserContext
* context
) {
239 const base::FilePath
& context_path
= context
->GetPath();
240 return make_scoped_ptr(new WebDataServiceWrapper(
241 context_path
, g_browser_process
->GetApplicationLocale(),
242 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI
),
243 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB
),
244 sync_start_util::GetFlareForSyncableService(context_path
),
245 &TestProfileErrorCallback
));
251 #if defined(OS_CHROMEOS)
252 // Must be kept in sync with
253 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
254 const char TestingProfile::kTestUserProfileDir
[] = "test-user";
256 const char TestingProfile::kTestUserProfileDir
[] = "Default";
259 TestingProfile::TestingProfile()
260 : start_time_(Time::Now()),
261 testing_prefs_(NULL
),
262 force_incognito_(false),
263 original_profile_(NULL
),
264 guest_session_(false),
265 last_session_exited_cleanly_(true),
266 browser_context_dependency_manager_(
267 BrowserContextDependencyManager::GetInstance()),
268 resource_context_(NULL
),
270 CreateTempProfileDir();
271 profile_path_
= temp_dir_
.path();
277 TestingProfile::TestingProfile(const base::FilePath
& path
)
278 : start_time_(Time::Now()),
279 testing_prefs_(NULL
),
280 force_incognito_(false),
281 original_profile_(NULL
),
282 guest_session_(false),
283 last_session_exited_cleanly_(true),
285 browser_context_dependency_manager_(
286 BrowserContextDependencyManager::GetInstance()),
287 resource_context_(NULL
),
293 TestingProfile::TestingProfile(const base::FilePath
& path
,
295 : start_time_(Time::Now()),
296 testing_prefs_(NULL
),
297 force_incognito_(false),
298 original_profile_(NULL
),
299 guest_session_(false),
300 last_session_exited_cleanly_(true),
302 browser_context_dependency_manager_(
303 BrowserContextDependencyManager::GetInstance()),
304 resource_context_(NULL
),
305 delegate_(delegate
) {
308 base::ThreadTaskRunnerHandle::Get()->PostTask(
310 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
316 TestingProfile::TestingProfile(
317 const base::FilePath
& path
,
319 #if defined(ENABLE_EXTENSIONS)
320 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy
,
322 scoped_ptr
<PrefServiceSyncable
> prefs
,
323 TestingProfile
* parent
,
325 const std::string
& supervised_user_id
,
326 scoped_ptr
<policy::PolicyService
> policy_service
,
327 const TestingFactories
& factories
)
328 : start_time_(Time::Now()),
329 prefs_(prefs
.release()),
330 testing_prefs_(NULL
),
331 force_incognito_(false),
332 original_profile_(parent
),
333 guest_session_(guest_session
),
334 last_session_exited_cleanly_(true),
335 #if defined(ENABLE_EXTENSIONS)
336 extension_special_storage_policy_(extension_policy
),
339 browser_context_dependency_manager_(
340 BrowserContextDependencyManager::GetInstance()),
341 resource_context_(NULL
),
343 policy_service_(policy_service
.release()) {
345 parent
->SetOffTheRecordProfile(scoped_ptr
<Profile
>(this));
347 // If no profile path was supplied, create one.
348 if (profile_path_
.empty()) {
349 CreateTempProfileDir();
350 profile_path_
= temp_dir_
.path();
353 // Set any testing factories prior to initializing the services.
354 for (TestingFactories::const_iterator it
= factories
.begin();
355 it
!= factories
.end(); ++it
) {
356 it
->first
->SetTestingFactory(this, it
->second
);
360 // If caller supplied a delegate, delay the FinishInit invocation until other
362 // TODO(atwilson): See if this is still required once we convert the current
363 // users of the constructor that takes a Delegate* param.
365 base::ThreadTaskRunnerHandle::Get()->PostTask(
367 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
372 SetSupervisedUserId(supervised_user_id
);
375 void TestingProfile::CreateTempProfileDir() {
376 if (!temp_dir_
.CreateUniqueTempDir()) {
377 LOG(ERROR
) << "Failed to create unique temporary directory.";
379 // Fallback logic in case we fail to create unique temporary directory.
380 base::FilePath system_tmp_dir
;
381 bool success
= PathService::Get(base::DIR_TEMP
, &system_tmp_dir
);
383 // We're severly screwed if we can't get the system temporary
384 // directory. Die now to avoid writing to the filesystem root
385 // or other bad places.
388 base::FilePath
fallback_dir(
389 system_tmp_dir
.AppendASCII("TestingProfilePath"));
390 base::DeleteFile(fallback_dir
, true);
391 base::CreateDirectory(fallback_dir
);
392 if (!temp_dir_
.Set(fallback_dir
)) {
393 // That shouldn't happen, but if it does, try to recover.
394 LOG(ERROR
) << "Failed to use a fallback temporary directory.";
396 // We're screwed if this fails, see CHECK above.
397 CHECK(temp_dir_
.Set(system_tmp_dir
));
402 void TestingProfile::Init() {
403 // If threads have been initialized, we should be on the UI thread.
404 DCHECK(!content::BrowserThread::IsThreadInitialized(
405 content::BrowserThread::UI
) ||
406 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
408 set_is_guest_profile(guest_session_
);
410 #if defined(OS_ANDROID)
411 // Make sure token service knows its running in tests.
412 AndroidProfileOAuth2TokenService::set_is_testing_profile();
415 // Normally this would happen during browser startup, but for tests
416 // we need to trigger creation of Profile-related services.
417 ChromeBrowserMainExtraPartsProfiles::
418 EnsureBrowserContextKeyedServiceFactoriesBuilt();
421 user_prefs::UserPrefs::Set(this, prefs_
.get());
422 else if (IsOffTheRecord())
423 CreateIncognitoPrefService();
425 CreateTestingPrefService();
427 if (!base::PathExists(profile_path_
))
428 base::CreateDirectory(profile_path_
);
430 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
431 // anymore, after converting the PrefService to a PKS. Until then it must
432 // be associated with a TestingProfile too.
433 if (!IsOffTheRecord())
434 CreateProfilePolicyConnector();
436 extensions_path_
= profile_path_
.AppendASCII("Extensions");
438 #if defined(ENABLE_EXTENSIONS)
439 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
440 this, extensions::TestExtensionSystem::Build
);
442 extensions::TestExtensionSystem
* test_extension_system
=
443 static_cast<extensions::TestExtensionSystem
*>(
444 extensions::ExtensionSystem::Get(this));
445 scoped_ptr
<extensions::ExtensionPrefs
> extension_prefs
=
446 test_extension_system
->CreateExtensionPrefs(
447 base::CommandLine::ForCurrentProcess(), extensions_path_
);
448 extensions::ExtensionPrefsFactory::GetInstance()->SetInstanceForTesting(
449 this, extension_prefs
.Pass());
451 extensions::EventRouterFactory::GetInstance()->SetTestingFactory(this,
455 // Prefs for incognito profiles are set in CreateIncognitoPrefService() by
456 // simulating ProfileImpl::GetOffTheRecordPrefs().
457 if (!IsOffTheRecord()) {
458 DCHECK(!original_profile_
);
459 user_prefs::PrefRegistrySyncable
* pref_registry
=
460 static_cast<user_prefs::PrefRegistrySyncable
*>(
461 prefs_
->DeprecatedGetPrefRegistry());
462 browser_context_dependency_manager_
->
463 RegisterProfilePrefsForServices(this, pref_registry
);
466 browser_context_dependency_manager_
->CreateBrowserContextServicesForTest(
469 #if defined(ENABLE_NOTIFICATIONS)
470 // Install profile keyed service factory hooks for dummy/test services
471 DesktopNotificationServiceFactory::GetInstance()->SetTestingFactory(
472 this, CreateTestDesktopNotificationService
);
475 #if defined(ENABLE_SUPERVISED_USERS)
476 if (!IsOffTheRecord()) {
477 SupervisedUserSettingsService
* settings_service
=
478 SupervisedUserSettingsServiceFactory::GetForProfile(this);
479 TestingPrefStore
* store
= new TestingPrefStore();
480 settings_service
->Init(store
);
481 store
->SetInitializationCompleted();
485 profile_name_
= "testing_profile";
488 void TestingProfile::FinishInit() {
489 DCHECK(content::NotificationService::current());
490 content::NotificationService::current()->Notify(
491 chrome::NOTIFICATION_PROFILE_CREATED
,
492 content::Source
<Profile
>(static_cast<Profile
*>(this)),
493 content::NotificationService::NoDetails());
495 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
497 profile_manager
->InitProfileUserPrefs(this);
500 delegate_
->OnProfileCreated(this, true, false);
503 TestingProfile::~TestingProfile() {
504 // Revert to non-incognito mode before shutdown.
505 force_incognito_
= false;
507 // If this profile owns an incognito profile, tear it down first.
508 incognito_profile_
.reset();
510 // Any objects holding live URLFetchers should be deleted before teardown.
511 TemplateURLFetcherFactory::ShutdownForProfile(this);
513 MaybeSendDestroyedNotification();
515 browser_context_dependency_manager_
->DestroyBrowserContextServices(this);
517 if (host_content_settings_map_
.get())
518 host_content_settings_map_
->ShutdownOnUIThread();
520 if (pref_proxy_config_tracker_
.get())
521 pref_proxy_config_tracker_
->DetachFromPrefService();
522 // Failing a post == leaks == heapcheck failure. Make that an immediate test
524 if (resource_context_
) {
525 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO
, FROM_HERE
,
527 resource_context_
= NULL
;
528 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
532 void TestingProfile::CreateFaviconService() {
533 // It is up to the caller to create the history service if one is needed.
534 FaviconServiceFactory::GetInstance()->SetTestingFactory(
535 this, FaviconServiceFactory::GetDefaultFactory());
538 bool TestingProfile::CreateHistoryService(bool delete_file
, bool no_db
) {
539 DestroyHistoryService();
541 base::FilePath path
= GetPath();
542 path
= path
.Append(history::kHistoryFilename
);
543 if (!base::DeleteFile(path
, false) || base::PathExists(path
))
546 // This will create and init the history service.
547 history::HistoryService
* history_service
=
548 static_cast<history::HistoryService
*>(
549 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
550 this, BuildHistoryService
));
551 if (!history_service
->Init(
552 no_db
, GetPrefs()->GetString(prefs::kAcceptLanguages
),
553 history::HistoryDatabaseParamsForPath(GetPath()))) {
554 HistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
557 // Some tests expect that CreateHistoryService() will also make the
558 // InMemoryURLIndex available.
559 InMemoryURLIndexFactory::GetInstance()->SetTestingFactory(
560 this, BuildInMemoryURLIndex
);
561 // Disable WebHistoryService by default, since it makes network requests.
562 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
566 void TestingProfile::DestroyHistoryService() {
567 history::HistoryService
* history_service
=
568 HistoryServiceFactory::GetForProfileWithoutCreating(this);
569 if (!history_service
)
572 history_service
->ClearCachedDataForContextID(0);
573 history_service
->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
574 history_service
->Cleanup();
575 HistoryServiceFactory::ShutdownForProfile(this);
577 // Wait for the backend class to terminate before deleting the files and
578 // moving to the next test. Note: if this never terminates, somebody is
579 // probably leaking a reference to the history backend, so it never calls
581 base::MessageLoop::current()->Run();
583 // Make sure we don't have any event pending that could disrupt the next
585 base::ThreadTaskRunnerHandle::Get()->PostTask(
586 FROM_HERE
, base::MessageLoop::QuitClosure());
587 base::MessageLoop::current()->Run();
590 void TestingProfile::CreateBookmarkModel(bool delete_file
) {
592 base::FilePath path
= GetPath().Append(bookmarks::kBookmarksFileName
);
593 base::DeleteFile(path
, false);
595 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
596 this, BuildChromeBookmarkClient
);
597 // This creates the BookmarkModel.
598 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
599 this, BuildBookmarkModel
));
602 void TestingProfile::CreateWebDataService() {
603 WebDataServiceFactory::GetInstance()->SetTestingFactory(
604 this, BuildWebDataService
);
607 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
608 // Only get the history service if it actually exists since the caller of the
609 // test should explicitly call CreateHistoryService to build it.
610 history::HistoryService
* history_service
=
611 HistoryServiceFactory::GetForProfileWithoutCreating(this);
612 DCHECK(history_service
);
613 InMemoryURLIndex
* index
= InMemoryURLIndexFactory::GetForProfile(this);
614 if (!index
|| index
->restored())
616 base::RunLoop run_loop
;
617 HistoryIndexRestoreObserver
observer(
618 content::GetQuitTaskForRunLoop(&run_loop
));
619 index
->set_restore_cache_observer(&observer
);
621 index
->set_restore_cache_observer(NULL
);
622 DCHECK(index
->restored());
625 void TestingProfile::SetGuestSession(bool guest
) {
626 guest_session_
= guest
;
629 base::FilePath
TestingProfile::GetPath() const {
630 return profile_path_
;
633 scoped_ptr
<content::ZoomLevelDelegate
> TestingProfile::CreateZoomLevelDelegate(
634 const base::FilePath
& partition_path
) {
635 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
636 GetPrefs(), GetPath(), partition_path
,
637 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
640 scoped_refptr
<base::SequencedTaskRunner
> TestingProfile::GetIOTaskRunner() {
641 return base::MessageLoop::current()->task_runner();
644 TestingPrefServiceSyncable
* TestingProfile::GetTestingPrefService() {
646 DCHECK(testing_prefs_
);
647 return testing_prefs_
;
650 TestingProfile
* TestingProfile::AsTestingProfile() {
654 std::string
TestingProfile::GetProfileUserName() const {
655 return profile_name_
;
658 Profile::ProfileType
TestingProfile::GetProfileType() const {
660 return GUEST_PROFILE
;
661 if (force_incognito_
|| original_profile_
)
662 return INCOGNITO_PROFILE
;
663 return REGULAR_PROFILE
;
666 bool TestingProfile::IsOffTheRecord() const {
667 return force_incognito_
|| original_profile_
;
670 void TestingProfile::SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
) {
671 DCHECK(!IsOffTheRecord());
672 DCHECK_EQ(this, profile
->GetOriginalProfile());
673 incognito_profile_
= profile
.Pass();
676 Profile
* TestingProfile::GetOffTheRecordProfile() {
677 if (IsOffTheRecord())
679 if (!incognito_profile_
)
680 TestingProfile::Builder().BuildIncognito(this);
681 return incognito_profile_
.get();
684 bool TestingProfile::HasOffTheRecordProfile() {
685 return incognito_profile_
.get() != NULL
;
688 Profile
* TestingProfile::GetOriginalProfile() {
689 if (original_profile_
)
690 return original_profile_
;
694 void TestingProfile::SetSupervisedUserId(const std::string
& id
) {
695 supervised_user_id_
= id
;
697 GetPrefs()->SetString(prefs::kSupervisedUserId
, id
);
699 GetPrefs()->ClearPref(prefs::kSupervisedUserId
);
702 bool TestingProfile::IsSupervised() {
703 return !supervised_user_id_
.empty();
706 bool TestingProfile::IsChild() {
707 #if defined(ENABLE_SUPERVISED_USERS)
708 return supervised_user_id_
== supervised_users::kChildAccountSUID
;
714 bool TestingProfile::IsLegacySupervised() {
715 return IsSupervised() && !IsChild();
718 #if defined(ENABLE_EXTENSIONS)
719 void TestingProfile::SetExtensionSpecialStoragePolicy(
720 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
) {
721 extension_special_storage_policy_
= extension_special_storage_policy
;
725 ExtensionSpecialStoragePolicy
*
726 TestingProfile::GetExtensionSpecialStoragePolicy() {
727 #if defined(ENABLE_EXTENSIONS)
728 if (!extension_special_storage_policy_
.get())
729 extension_special_storage_policy_
= new ExtensionSpecialStoragePolicy(NULL
);
730 return extension_special_storage_policy_
.get();
736 net::CookieMonster
* TestingProfile::GetCookieMonster() {
737 if (!GetRequestContext())
739 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
743 void TestingProfile::CreateTestingPrefService() {
744 DCHECK(!prefs_
.get());
745 testing_prefs_
= new TestingPrefServiceSyncable();
746 prefs_
.reset(testing_prefs_
);
747 user_prefs::UserPrefs::Set(this, prefs_
.get());
748 chrome::RegisterUserProfilePrefs(testing_prefs_
->registry());
751 void TestingProfile::CreateIncognitoPrefService() {
752 DCHECK(original_profile_
);
753 DCHECK(!testing_prefs_
);
754 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
755 // leaves testing_prefs_ unset.
756 prefs_
.reset(original_profile_
->prefs_
->CreateIncognitoPrefService(NULL
));
757 user_prefs::UserPrefs::Set(this, prefs_
.get());
760 void TestingProfile::CreateProfilePolicyConnector() {
761 #if defined(ENABLE_CONFIGURATION_POLICY)
762 schema_registry_service_
=
763 policy::SchemaRegistryServiceFactory::CreateForContext(
764 this, policy::Schema(), NULL
);
765 CHECK_EQ(schema_registry_service_
.get(),
766 policy::SchemaRegistryServiceFactory::GetForContext(this));
767 #endif // defined(ENABLE_CONFIGURATION_POLICY)
769 if (!policy_service_
) {
770 #if defined(ENABLE_CONFIGURATION_POLICY)
771 std::vector
<policy::ConfigurationPolicyProvider
*> providers
;
772 policy_service_
.reset(new policy::PolicyServiceImpl(providers
));
774 policy_service_
.reset(new policy::PolicyServiceStub());
777 profile_policy_connector_
.reset(new policy::ProfilePolicyConnector());
778 profile_policy_connector_
->InitForTesting(policy_service_
.Pass());
779 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
780 this, profile_policy_connector_
.get());
781 CHECK_EQ(profile_policy_connector_
.get(),
782 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(this));
785 PrefService
* TestingProfile::GetPrefs() {
790 const PrefService
* TestingProfile::GetPrefs() const {
795 chrome::ChromeZoomLevelPrefs
* TestingProfile::GetZoomLevelPrefs() {
796 return static_cast<chrome::ChromeZoomLevelPrefs
*>(
797 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
800 DownloadManagerDelegate
* TestingProfile::GetDownloadManagerDelegate() {
804 net::URLRequestContextGetter
* TestingProfile::GetRequestContext() {
805 return GetDefaultStoragePartition(this)->GetURLRequestContext();
808 net::URLRequestContextGetter
* TestingProfile::CreateRequestContext(
809 content::ProtocolHandlerMap
* protocol_handlers
,
810 content::URLRequestInterceptorScopedVector request_interceptors
) {
811 return new net::TestURLRequestContextGetter(
812 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
815 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForRenderProcess(
816 int renderer_child_id
) {
817 content::RenderProcessHost
* rph
= content::RenderProcessHost::FromID(
819 return rph
->GetStoragePartition()->GetURLRequestContext();
822 net::URLRequestContextGetter
* TestingProfile::GetMediaRequestContext() {
826 net::URLRequestContextGetter
*
827 TestingProfile::GetMediaRequestContextForRenderProcess(
828 int renderer_child_id
) {
832 net::URLRequestContextGetter
*
833 TestingProfile::GetMediaRequestContextForStoragePartition(
834 const base::FilePath
& partition_path
,
839 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForExtensions() {
840 if (!extensions_request_context_
.get())
841 extensions_request_context_
= new TestExtensionURLRequestContextGetter();
842 return extensions_request_context_
.get();
845 net::SSLConfigService
* TestingProfile::GetSSLConfigService() {
846 if (!GetRequestContext())
848 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
851 net::URLRequestContextGetter
*
852 TestingProfile::CreateRequestContextForStoragePartition(
853 const base::FilePath
& partition_path
,
855 content::ProtocolHandlerMap
* protocol_handlers
,
856 content::URLRequestInterceptorScopedVector request_interceptors
) {
857 // We don't test storage partitions here yet, so returning the same dummy
858 // context is sufficient for now.
859 return GetRequestContext();
862 content::ResourceContext
* TestingProfile::GetResourceContext() {
863 if (!resource_context_
)
864 resource_context_
= new content::MockResourceContext();
865 return resource_context_
;
868 HostContentSettingsMap
* TestingProfile::GetHostContentSettingsMap() {
869 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
870 if (!host_content_settings_map_
.get()) {
871 host_content_settings_map_
= new HostContentSettingsMap(GetPrefs(), false);
872 #if defined(ENABLE_EXTENSIONS)
873 ExtensionService
* extension_service
=
874 extensions::ExtensionSystem::Get(this)->extension_service();
875 if (extension_service
) {
876 extension_service
->RegisterContentSettings(
877 host_content_settings_map_
.get());
881 return host_content_settings_map_
.get();
884 content::BrowserPluginGuestManager
* TestingProfile::GetGuestManager() {
885 #if defined(ENABLE_EXTENSIONS)
886 return guest_view::GuestViewManager::FromBrowserContext(this);
892 content::PushMessagingService
* TestingProfile::GetPushMessagingService() {
896 bool TestingProfile::IsSameProfile(Profile
*p
) {
900 base::Time
TestingProfile::GetStartTime() const {
904 base::FilePath
TestingProfile::last_selected_directory() {
905 return last_selected_directory_
;
908 void TestingProfile::set_last_selected_directory(const base::FilePath
& path
) {
909 last_selected_directory_
= path
;
912 PrefProxyConfigTracker
* TestingProfile::GetProxyConfigTracker() {
913 if (!pref_proxy_config_tracker_
.get()) {
914 // TestingProfile is used in unit tests, where local state is not available.
915 pref_proxy_config_tracker_
.reset(
916 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
919 return pref_proxy_config_tracker_
.get();
922 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
923 history::HistoryService
* history_service
=
924 HistoryServiceFactory::GetForProfile(this,
925 ServiceAccessType::EXPLICIT_ACCESS
);
926 DCHECK(history_service
);
927 DCHECK(base::MessageLoop::current());
929 base::CancelableTaskTracker tracker
;
930 history_service
->ScheduleDBTask(
931 scoped_ptr
<history::HistoryDBTask
>(
932 new QuittingHistoryDBTask()),
934 base::MessageLoop::current()->Run();
937 chrome_browser_net::Predictor
* TestingProfile::GetNetworkPredictor() {
941 DevToolsNetworkController
* TestingProfile::GetDevToolsNetworkController() {
945 void TestingProfile::ClearNetworkingHistorySince(
947 const base::Closure
& completion
) {
948 if (!completion
.is_null()) {
949 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, completion
);
953 GURL
TestingProfile::GetHomePage() {
954 return GURL(chrome::kChromeUINewTabURL
);
957 PrefService
* TestingProfile::GetOffTheRecordPrefs() {
961 storage::SpecialStoragePolicy
* TestingProfile::GetSpecialStoragePolicy() {
962 #if defined(ENABLE_EXTENSIONS)
963 return GetExtensionSpecialStoragePolicy();
969 content::SSLHostStateDelegate
* TestingProfile::GetSSLHostStateDelegate() {
973 content::PermissionManager
* TestingProfile::GetPermissionManager() {
977 bool TestingProfile::WasCreatedByVersionOrLater(const std::string
& version
) {
981 bool TestingProfile::IsGuestSession() const {
982 return guest_session_
;
985 Profile::ExitType
TestingProfile::GetLastSessionExitType() {
986 return last_session_exited_cleanly_
? EXIT_NORMAL
: EXIT_CRASHED
;
989 TestingProfile::Builder::Builder()
990 : build_called_(false),
992 guest_session_(false) {
995 TestingProfile::Builder::~Builder() {
998 void TestingProfile::Builder::SetPath(const base::FilePath
& path
) {
1002 void TestingProfile::Builder::SetDelegate(Delegate
* delegate
) {
1003 delegate_
= delegate
;
1006 #if defined(ENABLE_EXTENSIONS)
1007 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
1008 scoped_refptr
<ExtensionSpecialStoragePolicy
> policy
) {
1009 extension_policy_
= policy
;
1013 void TestingProfile::Builder::SetPrefService(
1014 scoped_ptr
<PrefServiceSyncable
> prefs
) {
1015 pref_service_
= prefs
.Pass();
1018 void TestingProfile::Builder::SetGuestSession() {
1019 guest_session_
= true;
1022 void TestingProfile::Builder::SetSupervisedUserId(
1023 const std::string
& supervised_user_id
) {
1024 supervised_user_id_
= supervised_user_id
;
1027 void TestingProfile::Builder::SetPolicyService(
1028 scoped_ptr
<policy::PolicyService
> policy_service
) {
1029 policy_service_
= policy_service
.Pass();
1032 void TestingProfile::Builder::AddTestingFactory(
1033 BrowserContextKeyedServiceFactory
* service_factory
,
1034 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback
) {
1035 testing_factories_
.push_back(std::make_pair(service_factory
, callback
));
1038 scoped_ptr
<TestingProfile
> TestingProfile::Builder::Build() {
1039 DCHECK(!build_called_
);
1040 build_called_
= true;
1042 return scoped_ptr
<TestingProfile
>(new TestingProfile(path_
,
1044 #if defined(ENABLE_EXTENSIONS)
1047 pref_service_
.Pass(),
1050 supervised_user_id_
,
1051 policy_service_
.Pass(),
1052 testing_factories_
));
1055 TestingProfile
* TestingProfile::Builder::BuildIncognito(
1056 TestingProfile
* original_profile
) {
1057 DCHECK(!build_called_
);
1058 DCHECK(original_profile
);
1059 build_called_
= true;
1061 // Note: Owned by |original_profile|.
1062 return new TestingProfile(path_
,
1064 #if defined(ENABLE_EXTENSIONS)
1067 pref_service_
.Pass(),
1070 supervised_user_id_
,
1071 policy_service_
.Pass(),
1072 testing_factories_
);