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.h"
36 #include "chrome/browser/prefs/pref_service_syncable_util.h"
37 #include "chrome/browser/prerender/prerender_manager.h"
38 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
39 #include "chrome/browser/profiles/profile_manager.h"
40 #include "chrome/browser/profiles/storage_partition_descriptor.h"
41 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
42 #include "chrome/browser/sync/glue/sync_start_util.h"
43 #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
44 #include "chrome/browser/web_data_service_factory.h"
45 #include "chrome/common/chrome_constants.h"
46 #include "chrome/common/chrome_switches.h"
47 #include "chrome/common/pref_names.h"
48 #include "chrome/common/url_constants.h"
49 #include "chrome/test/base/history_index_restore_observer.h"
50 #include "chrome/test/base/testing_pref_service_syncable.h"
51 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
52 #include "components/bookmarks/browser/bookmark_model.h"
53 #include "components/bookmarks/common/bookmark_constants.h"
54 #include "components/content_settings/core/browser/host_content_settings_map.h"
55 #include "components/favicon/core/fallback_icon_service.h"
56 #include "components/favicon/core/favicon_service.h"
57 #include "components/history/content/browser/content_visit_delegate.h"
58 #include "components/history/content/browser/history_database_helper.h"
59 #include "components/history/core/browser/history_backend.h"
60 #include "components/history/core/browser/history_constants.h"
61 #include "components/history/core/browser/history_database_params.h"
62 #include "components/history/core/browser/history_db_task.h"
63 #include "components/history/core/browser/history_service.h"
64 #include "components/keyed_service/content/browser_context_dependency_manager.h"
65 #include "components/keyed_service/core/refcounted_keyed_service.h"
66 #include "components/omnibox/browser/autocomplete_classifier.h"
67 #include "components/omnibox/browser/in_memory_url_index.h"
68 #include "components/policy/core/common/policy_service.h"
69 #include "components/proxy_config/pref_proxy_config_tracker.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
<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 TestingPrefServiceSyncable
* TestingProfile::GetTestingPrefService() {
638 DCHECK(testing_prefs_
);
639 return testing_prefs_
;
642 TestingProfile
* TestingProfile::AsTestingProfile() {
646 std::string
TestingProfile::GetProfileUserName() const {
647 return profile_name_
;
650 Profile::ProfileType
TestingProfile::GetProfileType() const {
652 return GUEST_PROFILE
;
653 if (force_incognito_
|| original_profile_
)
654 return INCOGNITO_PROFILE
;
655 return REGULAR_PROFILE
;
658 bool TestingProfile::IsOffTheRecord() const {
659 return force_incognito_
|| original_profile_
;
662 void TestingProfile::SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
) {
663 DCHECK(!IsOffTheRecord());
664 DCHECK_EQ(this, profile
->GetOriginalProfile());
665 incognito_profile_
= profile
.Pass();
668 Profile
* TestingProfile::GetOffTheRecordProfile() {
669 if (IsOffTheRecord())
671 if (!incognito_profile_
)
672 TestingProfile::Builder().BuildIncognito(this);
673 return incognito_profile_
.get();
676 bool TestingProfile::HasOffTheRecordProfile() {
677 return incognito_profile_
.get() != NULL
;
680 Profile
* TestingProfile::GetOriginalProfile() {
681 if (original_profile_
)
682 return original_profile_
;
686 void TestingProfile::SetSupervisedUserId(const std::string
& id
) {
687 supervised_user_id_
= id
;
689 GetPrefs()->SetString(prefs::kSupervisedUserId
, id
);
691 GetPrefs()->ClearPref(prefs::kSupervisedUserId
);
694 bool TestingProfile::IsSupervised() const {
695 return !supervised_user_id_
.empty();
698 bool TestingProfile::IsChild() const {
699 #if defined(ENABLE_SUPERVISED_USERS)
700 return supervised_user_id_
== supervised_users::kChildAccountSUID
;
706 bool TestingProfile::IsLegacySupervised() const {
707 return IsSupervised() && !IsChild();
710 #if defined(ENABLE_EXTENSIONS)
711 void TestingProfile::SetExtensionSpecialStoragePolicy(
712 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
) {
713 extension_special_storage_policy_
= extension_special_storage_policy
;
717 ExtensionSpecialStoragePolicy
*
718 TestingProfile::GetExtensionSpecialStoragePolicy() {
719 #if defined(ENABLE_EXTENSIONS)
720 if (!extension_special_storage_policy_
.get())
721 extension_special_storage_policy_
= new ExtensionSpecialStoragePolicy(NULL
);
722 return extension_special_storage_policy_
.get();
728 net::CookieMonster
* TestingProfile::GetCookieMonster() {
729 if (!GetRequestContext())
731 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
735 void TestingProfile::CreateTestingPrefService() {
736 DCHECK(!prefs_
.get());
737 testing_prefs_
= new TestingPrefServiceSyncable();
738 prefs_
.reset(testing_prefs_
);
739 user_prefs::UserPrefs::Set(this, prefs_
.get());
740 chrome::RegisterUserProfilePrefs(testing_prefs_
->registry());
743 void TestingProfile::CreateIncognitoPrefService() {
744 DCHECK(original_profile_
);
745 DCHECK(!testing_prefs_
);
746 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
747 // leaves testing_prefs_ unset.
748 prefs_
.reset(CreateIncognitoPrefServiceSyncable(
749 original_profile_
->prefs_
.get(), NULL
));
750 user_prefs::UserPrefs::Set(this, prefs_
.get());
753 void TestingProfile::CreateProfilePolicyConnector() {
754 #if defined(ENABLE_CONFIGURATION_POLICY)
755 schema_registry_service_
=
756 policy::SchemaRegistryServiceFactory::CreateForContext(
757 this, policy::Schema(), NULL
);
758 CHECK_EQ(schema_registry_service_
.get(),
759 policy::SchemaRegistryServiceFactory::GetForContext(this));
760 #endif // defined(ENABLE_CONFIGURATION_POLICY)
762 if (!policy_service_
) {
763 #if defined(ENABLE_CONFIGURATION_POLICY)
764 std::vector
<policy::ConfigurationPolicyProvider
*> providers
;
765 policy_service_
.reset(new policy::PolicyServiceImpl(providers
));
767 policy_service_
.reset(new policy::PolicyServiceStub());
770 profile_policy_connector_
.reset(new policy::ProfilePolicyConnector());
771 profile_policy_connector_
->InitForTesting(policy_service_
.Pass());
772 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
773 this, profile_policy_connector_
.get());
774 CHECK_EQ(profile_policy_connector_
.get(),
775 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(this));
778 PrefService
* TestingProfile::GetPrefs() {
783 const PrefService
* TestingProfile::GetPrefs() const {
788 ChromeZoomLevelPrefs
* TestingProfile::GetZoomLevelPrefs() {
789 return static_cast<ChromeZoomLevelPrefs
*>(
790 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
793 DownloadManagerDelegate
* TestingProfile::GetDownloadManagerDelegate() {
797 net::URLRequestContextGetter
* TestingProfile::GetRequestContext() {
798 return GetDefaultStoragePartition(this)->GetURLRequestContext();
801 net::URLRequestContextGetter
* TestingProfile::CreateRequestContext(
802 content::ProtocolHandlerMap
* protocol_handlers
,
803 content::URLRequestInterceptorScopedVector request_interceptors
) {
804 return new net::TestURLRequestContextGetter(
805 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
808 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForRenderProcess(
809 int renderer_child_id
) {
810 content::RenderProcessHost
* rph
= content::RenderProcessHost::FromID(
812 return rph
->GetStoragePartition()->GetURLRequestContext();
815 net::URLRequestContextGetter
* TestingProfile::GetMediaRequestContext() {
819 net::URLRequestContextGetter
*
820 TestingProfile::GetMediaRequestContextForRenderProcess(
821 int renderer_child_id
) {
825 net::URLRequestContextGetter
*
826 TestingProfile::GetMediaRequestContextForStoragePartition(
827 const base::FilePath
& partition_path
,
832 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForExtensions() {
833 if (!extensions_request_context_
.get())
834 extensions_request_context_
= new TestExtensionURLRequestContextGetter();
835 return extensions_request_context_
.get();
838 net::SSLConfigService
* TestingProfile::GetSSLConfigService() {
839 if (!GetRequestContext())
841 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
844 net::URLRequestContextGetter
*
845 TestingProfile::CreateRequestContextForStoragePartition(
846 const base::FilePath
& partition_path
,
848 content::ProtocolHandlerMap
* protocol_handlers
,
849 content::URLRequestInterceptorScopedVector request_interceptors
) {
850 // We don't test storage partitions here yet, so returning the same dummy
851 // context is sufficient for now.
852 return GetRequestContext();
855 content::ResourceContext
* TestingProfile::GetResourceContext() {
856 if (!resource_context_
)
857 resource_context_
= new content::MockResourceContext();
858 return resource_context_
;
861 HostContentSettingsMap
* TestingProfile::GetHostContentSettingsMap() {
862 // TODO(peconn): Get rid of this function
863 // Don't forget to remove the #include "host_content_settings_map_factory"!
864 return HostContentSettingsMapFactory::GetForProfile(this);
867 content::BrowserPluginGuestManager
* TestingProfile::GetGuestManager() {
868 #if defined(ENABLE_EXTENSIONS)
869 return guest_view::GuestViewManager::FromBrowserContext(this);
875 content::PushMessagingService
* TestingProfile::GetPushMessagingService() {
879 bool TestingProfile::IsSameProfile(Profile
*p
) {
883 base::Time
TestingProfile::GetStartTime() const {
887 base::FilePath
TestingProfile::last_selected_directory() {
888 return last_selected_directory_
;
891 void TestingProfile::set_last_selected_directory(const base::FilePath
& path
) {
892 last_selected_directory_
= path
;
895 PrefProxyConfigTracker
* TestingProfile::GetProxyConfigTracker() {
896 if (!pref_proxy_config_tracker_
.get()) {
897 // TestingProfile is used in unit tests, where local state is not available.
898 pref_proxy_config_tracker_
.reset(
899 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
902 return pref_proxy_config_tracker_
.get();
905 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
906 history::HistoryService
* history_service
=
907 HistoryServiceFactory::GetForProfile(this,
908 ServiceAccessType::EXPLICIT_ACCESS
);
909 DCHECK(history_service
);
910 DCHECK(base::MessageLoop::current());
912 base::CancelableTaskTracker tracker
;
913 history_service
->ScheduleDBTask(
914 scoped_ptr
<history::HistoryDBTask
>(
915 new QuittingHistoryDBTask()),
917 base::MessageLoop::current()->Run();
920 chrome_browser_net::Predictor
* TestingProfile::GetNetworkPredictor() {
924 DevToolsNetworkControllerHandle
*
925 TestingProfile::GetDevToolsNetworkControllerHandle() {
929 void TestingProfile::ClearNetworkingHistorySince(
931 const base::Closure
& completion
) {
932 if (!completion
.is_null()) {
933 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, completion
);
937 GURL
TestingProfile::GetHomePage() {
938 return GURL(chrome::kChromeUINewTabURL
);
941 PrefService
* TestingProfile::GetOffTheRecordPrefs() {
945 storage::SpecialStoragePolicy
* TestingProfile::GetSpecialStoragePolicy() {
946 #if defined(ENABLE_EXTENSIONS)
947 return GetExtensionSpecialStoragePolicy();
953 content::SSLHostStateDelegate
* TestingProfile::GetSSLHostStateDelegate() {
957 content::PermissionManager
* TestingProfile::GetPermissionManager() {
961 bool TestingProfile::WasCreatedByVersionOrLater(const std::string
& version
) {
965 bool TestingProfile::IsGuestSession() const {
966 return guest_session_
;
969 Profile::ExitType
TestingProfile::GetLastSessionExitType() {
970 return last_session_exited_cleanly_
? EXIT_NORMAL
: EXIT_CRASHED
;
973 TestingProfile::Builder::Builder()
974 : build_called_(false),
976 guest_session_(false) {
979 TestingProfile::Builder::~Builder() {
982 void TestingProfile::Builder::SetPath(const base::FilePath
& path
) {
986 void TestingProfile::Builder::SetDelegate(Delegate
* delegate
) {
987 delegate_
= delegate
;
990 #if defined(ENABLE_EXTENSIONS)
991 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
992 scoped_refptr
<ExtensionSpecialStoragePolicy
> policy
) {
993 extension_policy_
= policy
;
997 void TestingProfile::Builder::SetPrefService(
998 scoped_ptr
<PrefServiceSyncable
> prefs
) {
999 pref_service_
= prefs
.Pass();
1002 void TestingProfile::Builder::SetGuestSession() {
1003 guest_session_
= true;
1006 void TestingProfile::Builder::SetSupervisedUserId(
1007 const std::string
& supervised_user_id
) {
1008 supervised_user_id_
= supervised_user_id
;
1011 void TestingProfile::Builder::SetPolicyService(
1012 scoped_ptr
<policy::PolicyService
> policy_service
) {
1013 policy_service_
= policy_service
.Pass();
1016 void TestingProfile::Builder::AddTestingFactory(
1017 BrowserContextKeyedServiceFactory
* service_factory
,
1018 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback
) {
1019 testing_factories_
.push_back(std::make_pair(service_factory
, callback
));
1022 scoped_ptr
<TestingProfile
> TestingProfile::Builder::Build() {
1023 DCHECK(!build_called_
);
1024 build_called_
= true;
1026 return scoped_ptr
<TestingProfile
>(new TestingProfile(path_
,
1028 #if defined(ENABLE_EXTENSIONS)
1031 pref_service_
.Pass(),
1034 supervised_user_id_
,
1035 policy_service_
.Pass(),
1036 testing_factories_
));
1039 TestingProfile
* TestingProfile::Builder::BuildIncognito(
1040 TestingProfile
* original_profile
) {
1041 DCHECK(!build_called_
);
1042 DCHECK(original_profile
);
1043 build_called_
= true;
1045 // Note: Owned by |original_profile|.
1046 return new TestingProfile(path_
,
1048 #if defined(ENABLE_EXTENSIONS)
1051 pref_service_
.Pass(),
1054 supervised_user_id_
,
1055 policy_service_
.Pass(),
1056 testing_factories_
);