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/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/bookmarks/managed_bookmark_service_factory.h"
22 #include "chrome/browser/browser_process.h"
23 #include "chrome/browser/chrome_notification_types.h"
24 #include "chrome/browser/content_settings/host_content_settings_map_factory.h"
25 #include "chrome/browser/favicon/chrome_fallback_icon_client_factory.h"
26 #include "chrome/browser/favicon/fallback_icon_service_factory.h"
27 #include "chrome/browser/favicon/favicon_service_factory.h"
28 #include "chrome/browser/history/chrome_history_client.h"
29 #include "chrome/browser/history/history_service_factory.h"
30 #include "chrome/browser/history/web_history_service_factory.h"
31 #include "chrome/browser/net/proxy_service_factory.h"
32 #include "chrome/browser/policy/profile_policy_connector.h"
33 #include "chrome/browser/policy/profile_policy_connector_factory.h"
34 #include "chrome/browser/prefs/browser_prefs.h"
35 #include "chrome/browser/prefs/pref_service_syncable_util.h"
36 #include "chrome/browser/prerender/prerender_manager.h"
37 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
38 #include "chrome/browser/profiles/profile_manager.h"
39 #include "chrome/browser/profiles/storage_partition_descriptor.h"
40 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
41 #include "chrome/browser/sync/glue/sync_start_util.h"
42 #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
43 #include "chrome/browser/web_data_service_factory.h"
44 #include "chrome/common/chrome_constants.h"
45 #include "chrome/common/chrome_switches.h"
46 #include "chrome/common/pref_names.h"
47 #include "chrome/common/url_constants.h"
48 #include "chrome/test/base/history_index_restore_observer.h"
49 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
50 #include "components/bookmarks/browser/bookmark_model.h"
51 #include "components/bookmarks/common/bookmark_constants.h"
52 #include "components/content_settings/core/browser/host_content_settings_map.h"
53 #include "components/favicon/core/fallback_icon_service.h"
54 #include "components/favicon/core/favicon_service.h"
55 #include "components/history/content/browser/content_visit_delegate.h"
56 #include "components/history/content/browser/history_database_helper.h"
57 #include "components/history/core/browser/history_backend.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/history_service.h"
62 #include "components/keyed_service/content/browser_context_dependency_manager.h"
63 #include "components/keyed_service/core/refcounted_keyed_service.h"
64 #include "components/omnibox/browser/autocomplete_classifier.h"
65 #include "components/omnibox/browser/in_memory_url_index.h"
66 #include "components/policy/core/common/policy_service.h"
67 #include "components/proxy_config/pref_proxy_config_tracker.h"
68 #include "components/syncable_prefs/pref_service_syncable.h"
69 #include "components/syncable_prefs/testing_pref_service_syncable.h"
70 #include "components/ui/zoom/zoom_event_manager.h"
71 #include "components/user_prefs/user_prefs.h"
72 #include "components/webdata_services/web_data_service_wrapper.h"
73 #include "content/public/browser/browser_thread.h"
74 #include "content/public/browser/cookie_store_factory.h"
75 #include "content/public/browser/notification_service.h"
76 #include "content/public/browser/render_process_host.h"
77 #include "content/public/browser/storage_partition.h"
78 #include "content/public/browser/zoom_level_delegate.h"
79 #include "content/public/test/mock_resource_context.h"
80 #include "content/public/test/test_utils.h"
81 #include "extensions/common/constants.h"
82 #include "net/cookies/cookie_monster.h"
83 #include "net/url_request/url_request_context.h"
84 #include "net/url_request/url_request_context_getter.h"
85 #include "net/url_request/url_request_test_util.h"
86 #include "testing/gmock/include/gmock/gmock.h"
88 #if defined(ENABLE_CONFIGURATION_POLICY)
89 #include "chrome/browser/policy/schema_registry_service.h"
90 #include "chrome/browser/policy/schema_registry_service_factory.h"
91 #include "components/policy/core/common/configuration_policy_provider.h"
92 #include "components/policy/core/common/policy_service_impl.h"
93 #include "components/policy/core/common/schema.h"
95 #include "components/policy/core/common/policy_service_stub.h"
96 #endif // defined(ENABLE_CONFIGURATION_POLICY)
98 #if defined(ENABLE_EXTENSIONS)
99 #include "chrome/browser/extensions/extension_service.h"
100 #include "chrome/browser/extensions/extension_special_storage_policy.h"
101 #include "chrome/browser/extensions/extension_system_factory.h"
102 #include "chrome/browser/extensions/test_extension_system.h"
103 #include "components/guest_view/browser/guest_view_manager.h"
104 #include "extensions/browser/event_router_factory.h"
105 #include "extensions/browser/extension_pref_value_map.h"
106 #include "extensions/browser/extension_pref_value_map_factory.h"
107 #include "extensions/browser/extension_prefs.h"
108 #include "extensions/browser/extension_prefs_factory.h"
109 #include "extensions/browser/extension_prefs_observer.h"
110 #include "extensions/browser/extension_system.h"
113 #if defined(OS_ANDROID)
114 #include "chrome/browser/signin/oauth2_token_service_delegate_android.h"
117 #if defined(ENABLE_SUPERVISED_USERS)
118 #include "chrome/browser/supervised_user/supervised_user_constants.h"
119 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
120 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
124 using bookmarks::BookmarkModel
;
125 using content::BrowserThread
;
126 using content::DownloadManagerDelegate
;
127 using testing::NiceMock
;
128 using testing::Return
;
132 // Task used to make sure history has finished processing a request. Intended
133 // for use with BlockUntilHistoryProcessesPendingRequests.
135 class QuittingHistoryDBTask
: public history::HistoryDBTask
{
137 QuittingHistoryDBTask() {}
139 bool RunOnDBThread(history::HistoryBackend
* backend
,
140 history::HistoryDatabase
* db
) override
{
144 void DoneRunOnMainThread() override
{ base::MessageLoop::current()->Quit(); }
147 ~QuittingHistoryDBTask() override
{}
149 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask
);
152 class TestExtensionURLRequestContext
: public net::URLRequestContext
{
154 TestExtensionURLRequestContext() {
155 net::CookieMonster
* cookie_monster
=
156 content::CreateCookieStore(content::CookieStoreConfig())->
158 const char* const schemes
[] = {extensions::kExtensionScheme
};
159 cookie_monster
->SetCookieableSchemes(schemes
, arraysize(schemes
));
160 set_cookie_store(cookie_monster
);
163 ~TestExtensionURLRequestContext() override
{ AssertNoURLRequests(); }
166 class TestExtensionURLRequestContextGetter
167 : public net::URLRequestContextGetter
{
169 net::URLRequestContext
* GetURLRequestContext() override
{
171 context_
.reset(new TestExtensionURLRequestContext());
172 return context_
.get();
174 scoped_refptr
<base::SingleThreadTaskRunner
> GetNetworkTaskRunner()
176 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
180 ~TestExtensionURLRequestContextGetter() override
{}
183 scoped_ptr
<net::URLRequestContext
> context_
;
186 scoped_ptr
<KeyedService
> BuildHistoryService(content::BrowserContext
* context
) {
187 Profile
* profile
= Profile::FromBrowserContext(context
);
188 return make_scoped_ptr(new history::HistoryService(
189 make_scoped_ptr(new ChromeHistoryClient(
190 BookmarkModelFactory::GetForProfile(profile
))),
191 make_scoped_ptr(new history::ContentVisitDelegate(profile
))));
194 scoped_ptr
<KeyedService
> BuildInMemoryURLIndex(
195 content::BrowserContext
* context
) {
196 Profile
* profile
= Profile::FromBrowserContext(context
);
197 scoped_ptr
<InMemoryURLIndex
> in_memory_url_index(new InMemoryURLIndex(
198 BookmarkModelFactory::GetForProfile(profile
),
199 HistoryServiceFactory::GetForProfile(profile
,
200 ServiceAccessType::IMPLICIT_ACCESS
),
201 content::BrowserThread::GetBlockingPool(), profile
->GetPath(),
202 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
),
204 in_memory_url_index
->Init();
205 return in_memory_url_index
.Pass();
208 scoped_ptr
<KeyedService
> BuildBookmarkModel(content::BrowserContext
* context
) {
209 Profile
* profile
= Profile::FromBrowserContext(context
);
210 ChromeBookmarkClient
* bookmark_client
=
211 ChromeBookmarkClientFactory::GetForProfile(profile
);
212 scoped_ptr
<BookmarkModel
> bookmark_model(new BookmarkModel(bookmark_client
));
213 bookmark_client
->Init(bookmark_model
.get());
214 bookmark_model
->Load(profile
->GetPrefs(),
215 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
),
217 profile
->GetIOTaskRunner(),
218 content::BrowserThread::GetMessageLoopProxyForThread(
219 content::BrowserThread::UI
));
220 return bookmark_model
.Pass();
223 void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type
,
224 sql::InitStatus status
) {
228 scoped_ptr
<KeyedService
> BuildWebDataService(content::BrowserContext
* context
) {
229 const base::FilePath
& context_path
= context
->GetPath();
230 return make_scoped_ptr(new WebDataServiceWrapper(
231 context_path
, g_browser_process
->GetApplicationLocale(),
232 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI
),
233 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB
),
234 sync_start_util::GetFlareForSyncableService(context_path
),
235 &TestProfileErrorCallback
));
241 #if defined(OS_CHROMEOS)
242 // Must be kept in sync with
243 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
244 const char TestingProfile::kTestUserProfileDir
[] = "test-user";
246 const char TestingProfile::kTestUserProfileDir
[] = "Default";
249 TestingProfile::TestingProfile()
250 : start_time_(Time::Now()),
251 testing_prefs_(NULL
),
252 force_incognito_(false),
253 original_profile_(NULL
),
254 guest_session_(false),
255 last_session_exited_cleanly_(true),
256 browser_context_dependency_manager_(
257 BrowserContextDependencyManager::GetInstance()),
258 resource_context_(NULL
),
260 CreateTempProfileDir();
261 profile_path_
= temp_dir_
.path();
267 TestingProfile::TestingProfile(const base::FilePath
& path
)
268 : start_time_(Time::Now()),
269 testing_prefs_(NULL
),
270 force_incognito_(false),
271 original_profile_(NULL
),
272 guest_session_(false),
273 last_session_exited_cleanly_(true),
275 browser_context_dependency_manager_(
276 BrowserContextDependencyManager::GetInstance()),
277 resource_context_(NULL
),
283 TestingProfile::TestingProfile(const base::FilePath
& path
,
285 : start_time_(Time::Now()),
286 testing_prefs_(NULL
),
287 force_incognito_(false),
288 original_profile_(NULL
),
289 guest_session_(false),
290 last_session_exited_cleanly_(true),
292 browser_context_dependency_manager_(
293 BrowserContextDependencyManager::GetInstance()),
294 resource_context_(NULL
),
295 delegate_(delegate
) {
298 base::ThreadTaskRunnerHandle::Get()->PostTask(
300 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
306 TestingProfile::TestingProfile(
307 const base::FilePath
& path
,
309 #if defined(ENABLE_EXTENSIONS)
310 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy
,
312 scoped_ptr
<syncable_prefs::PrefServiceSyncable
> prefs
,
313 TestingProfile
* parent
,
315 const std::string
& supervised_user_id
,
316 scoped_ptr
<policy::PolicyService
> policy_service
,
317 const TestingFactories
& factories
)
318 : start_time_(Time::Now()),
319 prefs_(prefs
.release()),
320 testing_prefs_(NULL
),
321 force_incognito_(false),
322 original_profile_(parent
),
323 guest_session_(guest_session
),
324 last_session_exited_cleanly_(true),
325 #if defined(ENABLE_EXTENSIONS)
326 extension_special_storage_policy_(extension_policy
),
329 browser_context_dependency_manager_(
330 BrowserContextDependencyManager::GetInstance()),
331 resource_context_(NULL
),
333 policy_service_(policy_service
.release()) {
335 parent
->SetOffTheRecordProfile(scoped_ptr
<Profile
>(this));
337 // If no profile path was supplied, create one.
338 if (profile_path_
.empty()) {
339 CreateTempProfileDir();
340 profile_path_
= temp_dir_
.path();
343 // Set any testing factories prior to initializing the services.
344 for (TestingFactories::const_iterator it
= factories
.begin();
345 it
!= factories
.end(); ++it
) {
346 it
->first
->SetTestingFactory(this, it
->second
);
350 // If caller supplied a delegate, delay the FinishInit invocation until other
352 // TODO(atwilson): See if this is still required once we convert the current
353 // users of the constructor that takes a Delegate* param.
355 base::ThreadTaskRunnerHandle::Get()->PostTask(
357 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
362 SetSupervisedUserId(supervised_user_id
);
365 void TestingProfile::CreateTempProfileDir() {
366 if (!temp_dir_
.CreateUniqueTempDir()) {
367 LOG(ERROR
) << "Failed to create unique temporary directory.";
369 // Fallback logic in case we fail to create unique temporary directory.
370 base::FilePath system_tmp_dir
;
371 bool success
= PathService::Get(base::DIR_TEMP
, &system_tmp_dir
);
373 // We're severly screwed if we can't get the system temporary
374 // directory. Die now to avoid writing to the filesystem root
375 // or other bad places.
378 base::FilePath
fallback_dir(
379 system_tmp_dir
.AppendASCII("TestingProfilePath"));
380 base::DeleteFile(fallback_dir
, true);
381 base::CreateDirectory(fallback_dir
);
382 if (!temp_dir_
.Set(fallback_dir
)) {
383 // That shouldn't happen, but if it does, try to recover.
384 LOG(ERROR
) << "Failed to use a fallback temporary directory.";
386 // We're screwed if this fails, see CHECK above.
387 CHECK(temp_dir_
.Set(system_tmp_dir
));
392 void TestingProfile::Init() {
393 // If threads have been initialized, we should be on the UI thread.
394 DCHECK(!content::BrowserThread::IsThreadInitialized(
395 content::BrowserThread::UI
) ||
396 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
398 set_is_guest_profile(guest_session_
);
400 #if defined(OS_ANDROID)
401 // Make sure token service knows its running in tests.
402 OAuth2TokenServiceDelegateAndroid::set_is_testing_profile();
405 // Normally this would happen during browser startup, but for tests
406 // we need to trigger creation of Profile-related services.
407 ChromeBrowserMainExtraPartsProfiles::
408 EnsureBrowserContextKeyedServiceFactoriesBuilt();
411 user_prefs::UserPrefs::Set(this, prefs_
.get());
412 else if (IsOffTheRecord())
413 CreateIncognitoPrefService();
415 CreateTestingPrefService();
417 if (!base::PathExists(profile_path_
))
418 base::CreateDirectory(profile_path_
);
420 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
421 // anymore, after converting the PrefService to a PKS. Until then it must
422 // be associated with a TestingProfile too.
423 if (!IsOffTheRecord())
424 CreateProfilePolicyConnector();
426 extensions_path_
= profile_path_
.AppendASCII("Extensions");
428 #if defined(ENABLE_EXTENSIONS)
429 // Note that the GetPrefs() creates a TestingPrefService, therefore
430 // the extension controlled pref values set in ExtensionPrefs
431 // are not reflected in the pref service. One would need to
432 // inject a new ExtensionPrefStore(extension_pref_value_map, false).
433 bool extensions_disabled
= base::CommandLine::ForCurrentProcess()->HasSwitch(
434 switches::kDisableExtensions
);
435 scoped_ptr
<extensions::ExtensionPrefs
> extension_prefs(
436 extensions::ExtensionPrefs::Create(
437 this, GetPrefs(), extensions_path_
,
438 ExtensionPrefValueMapFactory::GetForBrowserContext(this),
440 std::vector
<extensions::ExtensionPrefsObserver
*>()));
441 extensions::ExtensionPrefsFactory::GetInstance()->SetInstanceForTesting(
442 this, extension_prefs
.Pass());
444 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
445 this, extensions::TestExtensionSystem::Build
);
447 extensions::EventRouterFactory::GetInstance()->SetTestingFactory(this,
451 // Prefs for incognito profiles are set in CreateIncognitoPrefService() by
452 // simulating ProfileImpl::GetOffTheRecordPrefs().
453 if (!IsOffTheRecord()) {
454 DCHECK(!original_profile_
);
455 user_prefs::PrefRegistrySyncable
* pref_registry
=
456 static_cast<user_prefs::PrefRegistrySyncable
*>(
457 prefs_
->DeprecatedGetPrefRegistry());
458 browser_context_dependency_manager_
->
459 RegisterProfilePrefsForServices(this, pref_registry
);
462 browser_context_dependency_manager_
->CreateBrowserContextServicesForTest(
465 #if defined(ENABLE_SUPERVISED_USERS)
466 if (!IsOffTheRecord()) {
467 SupervisedUserSettingsService
* settings_service
=
468 SupervisedUserSettingsServiceFactory::GetForProfile(this);
469 TestingPrefStore
* store
= new TestingPrefStore();
470 settings_service
->Init(store
);
471 store
->SetInitializationCompleted();
475 profile_name_
= "testing_profile";
478 void TestingProfile::FinishInit() {
479 DCHECK(content::NotificationService::current());
480 content::NotificationService::current()->Notify(
481 chrome::NOTIFICATION_PROFILE_CREATED
,
482 content::Source
<Profile
>(static_cast<Profile
*>(this)),
483 content::NotificationService::NoDetails());
485 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
487 profile_manager
->InitProfileUserPrefs(this);
490 delegate_
->OnProfileCreated(this, true, false);
493 TestingProfile::~TestingProfile() {
494 // Revert to non-incognito mode before shutdown.
495 force_incognito_
= false;
497 // If this profile owns an incognito profile, tear it down first.
498 incognito_profile_
.reset();
500 // Any objects holding live URLFetchers should be deleted before teardown.
501 TemplateURLFetcherFactory::ShutdownForProfile(this);
503 MaybeSendDestroyedNotification();
505 browser_context_dependency_manager_
->DestroyBrowserContextServices(this);
507 if (host_content_settings_map_
.get())
508 host_content_settings_map_
->ShutdownOnUIThread();
510 if (pref_proxy_config_tracker_
.get())
511 pref_proxy_config_tracker_
->DetachFromPrefService();
512 // Failing a post == leaks == heapcheck failure. Make that an immediate test
514 if (resource_context_
) {
515 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO
, FROM_HERE
,
517 resource_context_
= NULL
;
518 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
522 void TestingProfile::CreateFaviconService() {
523 // It is up to the caller to create the history service if one is needed.
524 FaviconServiceFactory::GetInstance()->SetTestingFactory(
525 this, FaviconServiceFactory::GetDefaultFactory());
528 bool TestingProfile::CreateHistoryService(bool delete_file
, bool no_db
) {
529 DestroyHistoryService();
531 base::FilePath path
= GetPath();
532 path
= path
.Append(history::kHistoryFilename
);
533 if (!base::DeleteFile(path
, false) || base::PathExists(path
))
536 // This will create and init the history service.
537 history::HistoryService
* history_service
=
538 static_cast<history::HistoryService
*>(
539 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
540 this, BuildHistoryService
));
541 if (!history_service
->Init(
542 no_db
, GetPrefs()->GetString(prefs::kAcceptLanguages
),
543 history::HistoryDatabaseParamsForPath(GetPath()))) {
544 HistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
547 // Some tests expect that CreateHistoryService() will also make the
548 // InMemoryURLIndex available.
549 InMemoryURLIndexFactory::GetInstance()->SetTestingFactory(
550 this, BuildInMemoryURLIndex
);
551 // Disable WebHistoryService by default, since it makes network requests.
552 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
556 void TestingProfile::DestroyHistoryService() {
557 history::HistoryService
* history_service
=
558 HistoryServiceFactory::GetForProfileWithoutCreating(this);
559 if (!history_service
)
562 history_service
->ClearCachedDataForContextID(0);
563 history_service
->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
564 history_service
->Cleanup();
565 HistoryServiceFactory::ShutdownForProfile(this);
567 // Wait for the backend class to terminate before deleting the files and
568 // moving to the next test. Note: if this never terminates, somebody is
569 // probably leaking a reference to the history backend, so it never calls
571 base::MessageLoop::current()->Run();
573 // Make sure we don't have any event pending that could disrupt the next
575 base::ThreadTaskRunnerHandle::Get()->PostTask(
576 FROM_HERE
, base::MessageLoop::QuitClosure());
577 base::MessageLoop::current()->Run();
580 void TestingProfile::CreateBookmarkModel(bool delete_file
) {
582 base::FilePath path
= GetPath().Append(bookmarks::kBookmarksFileName
);
583 base::DeleteFile(path
, false);
585 ManagedBookmarkServiceFactory::GetInstance()->SetTestingFactory(
586 this, ManagedBookmarkServiceFactory::GetDefaultFactory());
587 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
588 this, ChromeBookmarkClientFactory::GetDefaultFactory());
589 // This creates the BookmarkModel.
590 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
591 this, BuildBookmarkModel
));
594 void TestingProfile::CreateWebDataService() {
595 WebDataServiceFactory::GetInstance()->SetTestingFactory(
596 this, BuildWebDataService
);
599 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
600 // Only get the history service if it actually exists since the caller of the
601 // test should explicitly call CreateHistoryService to build it.
602 history::HistoryService
* history_service
=
603 HistoryServiceFactory::GetForProfileWithoutCreating(this);
604 DCHECK(history_service
);
605 InMemoryURLIndex
* index
= InMemoryURLIndexFactory::GetForProfile(this);
606 if (!index
|| index
->restored())
608 base::RunLoop run_loop
;
609 HistoryIndexRestoreObserver
observer(
610 content::GetQuitTaskForRunLoop(&run_loop
));
611 index
->set_restore_cache_observer(&observer
);
613 index
->set_restore_cache_observer(NULL
);
614 DCHECK(index
->restored());
617 void TestingProfile::SetGuestSession(bool guest
) {
618 guest_session_
= guest
;
621 base::FilePath
TestingProfile::GetPath() const {
622 return profile_path_
;
625 scoped_ptr
<content::ZoomLevelDelegate
> TestingProfile::CreateZoomLevelDelegate(
626 const base::FilePath
& partition_path
) {
627 return make_scoped_ptr(new ChromeZoomLevelPrefs(
628 GetPrefs(), GetPath(), partition_path
,
629 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
632 scoped_refptr
<base::SequencedTaskRunner
> TestingProfile::GetIOTaskRunner() {
633 return base::MessageLoop::current()->task_runner();
636 syncable_prefs::TestingPrefServiceSyncable
*
637 TestingProfile::GetTestingPrefService() {
639 DCHECK(testing_prefs_
);
640 return testing_prefs_
;
643 TestingProfile
* TestingProfile::AsTestingProfile() {
647 std::string
TestingProfile::GetProfileUserName() const {
648 return profile_name_
;
651 Profile::ProfileType
TestingProfile::GetProfileType() const {
653 return GUEST_PROFILE
;
654 if (force_incognito_
|| original_profile_
)
655 return INCOGNITO_PROFILE
;
656 return REGULAR_PROFILE
;
659 bool TestingProfile::IsOffTheRecord() const {
660 return force_incognito_
|| original_profile_
;
663 void TestingProfile::SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
) {
664 DCHECK(!IsOffTheRecord());
665 DCHECK_EQ(this, profile
->GetOriginalProfile());
666 incognito_profile_
= profile
.Pass();
669 Profile
* TestingProfile::GetOffTheRecordProfile() {
670 if (IsOffTheRecord())
672 if (!incognito_profile_
)
673 TestingProfile::Builder().BuildIncognito(this);
674 return incognito_profile_
.get();
677 bool TestingProfile::HasOffTheRecordProfile() {
678 return incognito_profile_
.get() != NULL
;
681 Profile
* TestingProfile::GetOriginalProfile() {
682 if (original_profile_
)
683 return original_profile_
;
687 void TestingProfile::SetSupervisedUserId(const std::string
& id
) {
688 supervised_user_id_
= id
;
690 GetPrefs()->SetString(prefs::kSupervisedUserId
, id
);
692 GetPrefs()->ClearPref(prefs::kSupervisedUserId
);
695 bool TestingProfile::IsSupervised() const {
696 return !supervised_user_id_
.empty();
699 bool TestingProfile::IsChild() const {
700 #if defined(ENABLE_SUPERVISED_USERS)
701 return supervised_user_id_
== supervised_users::kChildAccountSUID
;
707 bool TestingProfile::IsLegacySupervised() const {
708 return IsSupervised() && !IsChild();
711 #if defined(ENABLE_EXTENSIONS)
712 void TestingProfile::SetExtensionSpecialStoragePolicy(
713 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
) {
714 extension_special_storage_policy_
= extension_special_storage_policy
;
718 ExtensionSpecialStoragePolicy
*
719 TestingProfile::GetExtensionSpecialStoragePolicy() {
720 #if defined(ENABLE_EXTENSIONS)
721 if (!extension_special_storage_policy_
.get())
722 extension_special_storage_policy_
= new ExtensionSpecialStoragePolicy(NULL
);
723 return extension_special_storage_policy_
.get();
729 net::CookieMonster
* TestingProfile::GetCookieMonster() {
730 if (!GetRequestContext())
732 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
736 void TestingProfile::CreateTestingPrefService() {
737 DCHECK(!prefs_
.get());
738 testing_prefs_
= new syncable_prefs::TestingPrefServiceSyncable();
739 prefs_
.reset(testing_prefs_
);
740 user_prefs::UserPrefs::Set(this, prefs_
.get());
741 chrome::RegisterUserProfilePrefs(testing_prefs_
->registry());
744 void TestingProfile::CreateIncognitoPrefService() {
745 DCHECK(original_profile_
);
746 DCHECK(!testing_prefs_
);
747 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
748 // leaves testing_prefs_ unset.
749 prefs_
.reset(CreateIncognitoPrefServiceSyncable(
750 original_profile_
->prefs_
.get(), NULL
));
751 user_prefs::UserPrefs::Set(this, prefs_
.get());
754 void TestingProfile::CreateProfilePolicyConnector() {
755 #if defined(ENABLE_CONFIGURATION_POLICY)
756 schema_registry_service_
=
757 policy::SchemaRegistryServiceFactory::CreateForContext(
758 this, policy::Schema(), NULL
);
759 CHECK_EQ(schema_registry_service_
.get(),
760 policy::SchemaRegistryServiceFactory::GetForContext(this));
761 #endif // defined(ENABLE_CONFIGURATION_POLICY)
763 if (!policy_service_
) {
764 #if defined(ENABLE_CONFIGURATION_POLICY)
765 std::vector
<policy::ConfigurationPolicyProvider
*> providers
;
766 policy_service_
.reset(new policy::PolicyServiceImpl(providers
));
768 policy_service_
.reset(new policy::PolicyServiceStub());
771 profile_policy_connector_
.reset(new policy::ProfilePolicyConnector());
772 profile_policy_connector_
->InitForTesting(policy_service_
.Pass());
773 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
774 this, profile_policy_connector_
.get());
775 CHECK_EQ(profile_policy_connector_
.get(),
776 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(this));
779 PrefService
* TestingProfile::GetPrefs() {
784 const PrefService
* TestingProfile::GetPrefs() const {
789 ChromeZoomLevelPrefs
* TestingProfile::GetZoomLevelPrefs() {
790 return static_cast<ChromeZoomLevelPrefs
*>(
791 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
794 DownloadManagerDelegate
* TestingProfile::GetDownloadManagerDelegate() {
798 net::URLRequestContextGetter
* TestingProfile::GetRequestContext() {
799 return GetDefaultStoragePartition(this)->GetURLRequestContext();
802 net::URLRequestContextGetter
* TestingProfile::CreateRequestContext(
803 content::ProtocolHandlerMap
* protocol_handlers
,
804 content::URLRequestInterceptorScopedVector request_interceptors
) {
805 return new net::TestURLRequestContextGetter(
806 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
809 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForRenderProcess(
810 int renderer_child_id
) {
811 content::RenderProcessHost
* rph
= content::RenderProcessHost::FromID(
813 return rph
->GetStoragePartition()->GetURLRequestContext();
816 net::URLRequestContextGetter
* TestingProfile::GetMediaRequestContext() {
820 net::URLRequestContextGetter
*
821 TestingProfile::GetMediaRequestContextForRenderProcess(
822 int renderer_child_id
) {
826 net::URLRequestContextGetter
*
827 TestingProfile::GetMediaRequestContextForStoragePartition(
828 const base::FilePath
& partition_path
,
833 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForExtensions() {
834 if (!extensions_request_context_
.get())
835 extensions_request_context_
= new TestExtensionURLRequestContextGetter();
836 return extensions_request_context_
.get();
839 net::SSLConfigService
* TestingProfile::GetSSLConfigService() {
840 if (!GetRequestContext())
842 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
845 net::URLRequestContextGetter
*
846 TestingProfile::CreateRequestContextForStoragePartition(
847 const base::FilePath
& partition_path
,
849 content::ProtocolHandlerMap
* protocol_handlers
,
850 content::URLRequestInterceptorScopedVector request_interceptors
) {
851 // We don't test storage partitions here yet, so returning the same dummy
852 // context is sufficient for now.
853 return GetRequestContext();
856 content::ResourceContext
* TestingProfile::GetResourceContext() {
857 if (!resource_context_
)
858 resource_context_
= new content::MockResourceContext();
859 return resource_context_
;
862 content::BrowserPluginGuestManager
* TestingProfile::GetGuestManager() {
863 #if defined(ENABLE_EXTENSIONS)
864 return guest_view::GuestViewManager::FromBrowserContext(this);
870 content::PushMessagingService
* TestingProfile::GetPushMessagingService() {
874 bool TestingProfile::IsSameProfile(Profile
*p
) {
878 base::Time
TestingProfile::GetStartTime() const {
882 base::FilePath
TestingProfile::last_selected_directory() {
883 return last_selected_directory_
;
886 void TestingProfile::set_last_selected_directory(const base::FilePath
& path
) {
887 last_selected_directory_
= path
;
890 PrefProxyConfigTracker
* TestingProfile::GetProxyConfigTracker() {
891 if (!pref_proxy_config_tracker_
.get()) {
892 // TestingProfile is used in unit tests, where local state is not available.
893 pref_proxy_config_tracker_
.reset(
894 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
897 return pref_proxy_config_tracker_
.get();
900 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
901 history::HistoryService
* history_service
=
902 HistoryServiceFactory::GetForProfile(this,
903 ServiceAccessType::EXPLICIT_ACCESS
);
904 DCHECK(history_service
);
905 DCHECK(base::MessageLoop::current());
907 base::CancelableTaskTracker tracker
;
908 history_service
->ScheduleDBTask(
909 scoped_ptr
<history::HistoryDBTask
>(
910 new QuittingHistoryDBTask()),
912 base::MessageLoop::current()->Run();
915 chrome_browser_net::Predictor
* TestingProfile::GetNetworkPredictor() {
919 DevToolsNetworkControllerHandle
*
920 TestingProfile::GetDevToolsNetworkControllerHandle() {
924 void TestingProfile::ClearNetworkingHistorySince(
926 const base::Closure
& completion
) {
927 if (!completion
.is_null()) {
928 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, completion
);
932 GURL
TestingProfile::GetHomePage() {
933 return GURL(chrome::kChromeUINewTabURL
);
936 PrefService
* TestingProfile::GetOffTheRecordPrefs() {
940 storage::SpecialStoragePolicy
* TestingProfile::GetSpecialStoragePolicy() {
941 #if defined(ENABLE_EXTENSIONS)
942 return GetExtensionSpecialStoragePolicy();
948 content::SSLHostStateDelegate
* TestingProfile::GetSSLHostStateDelegate() {
952 content::PermissionManager
* TestingProfile::GetPermissionManager() {
956 bool TestingProfile::WasCreatedByVersionOrLater(const std::string
& version
) {
960 bool TestingProfile::IsGuestSession() const {
961 return guest_session_
;
964 Profile::ExitType
TestingProfile::GetLastSessionExitType() {
965 return last_session_exited_cleanly_
? EXIT_NORMAL
: EXIT_CRASHED
;
968 TestingProfile::Builder::Builder()
969 : build_called_(false),
971 guest_session_(false) {
974 TestingProfile::Builder::~Builder() {
977 void TestingProfile::Builder::SetPath(const base::FilePath
& path
) {
981 void TestingProfile::Builder::SetDelegate(Delegate
* delegate
) {
982 delegate_
= delegate
;
985 #if defined(ENABLE_EXTENSIONS)
986 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
987 scoped_refptr
<ExtensionSpecialStoragePolicy
> policy
) {
988 extension_policy_
= policy
;
992 void TestingProfile::Builder::SetPrefService(
993 scoped_ptr
<syncable_prefs::PrefServiceSyncable
> prefs
) {
994 pref_service_
= prefs
.Pass();
997 void TestingProfile::Builder::SetGuestSession() {
998 guest_session_
= true;
1001 void TestingProfile::Builder::SetSupervisedUserId(
1002 const std::string
& supervised_user_id
) {
1003 supervised_user_id_
= supervised_user_id
;
1006 void TestingProfile::Builder::SetPolicyService(
1007 scoped_ptr
<policy::PolicyService
> policy_service
) {
1008 policy_service_
= policy_service
.Pass();
1011 void TestingProfile::Builder::AddTestingFactory(
1012 BrowserContextKeyedServiceFactory
* service_factory
,
1013 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback
) {
1014 testing_factories_
.push_back(std::make_pair(service_factory
, callback
));
1017 scoped_ptr
<TestingProfile
> TestingProfile::Builder::Build() {
1018 DCHECK(!build_called_
);
1019 build_called_
= true;
1021 return scoped_ptr
<TestingProfile
>(new TestingProfile(path_
,
1023 #if defined(ENABLE_EXTENSIONS)
1026 pref_service_
.Pass(),
1029 supervised_user_id_
,
1030 policy_service_
.Pass(),
1031 testing_factories_
));
1034 TestingProfile
* TestingProfile::Builder::BuildIncognito(
1035 TestingProfile
* original_profile
) {
1036 DCHECK(!build_called_
);
1037 DCHECK(original_profile
);
1038 build_called_
= true;
1040 // Note: Owned by |original_profile|.
1041 return new TestingProfile(path_
,
1043 #if defined(ENABLE_EXTENSIONS)
1046 pref_service_
.Pass(),
1049 supervised_user_id_
,
1050 policy_service_
.Pass(),
1051 testing_factories_
);