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/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/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/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 "chrome/test/base/testing_pref_service_syncable.h"
50 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
51 #include "components/bookmarks/browser/bookmark_model.h"
52 #include "components/bookmarks/common/bookmark_constants.h"
53 #include "components/content_settings/core/browser/host_content_settings_map.h"
54 #include "components/favicon/core/fallback_icon_service.h"
55 #include "components/favicon/core/favicon_service.h"
56 #include "components/history/content/browser/content_visit_delegate.h"
57 #include "components/history/content/browser/history_database_helper.h"
58 #include "components/history/core/browser/history_backend.h"
59 #include "components/history/core/browser/history_constants.h"
60 #include "components/history/core/browser/history_database_params.h"
61 #include "components/history/core/browser/history_db_task.h"
62 #include "components/history/core/browser/history_service.h"
63 #include "components/keyed_service/content/browser_context_dependency_manager.h"
64 #include "components/keyed_service/core/refcounted_keyed_service.h"
65 #include "components/omnibox/browser/autocomplete_classifier.h"
66 #include "components/omnibox/browser/in_memory_url_index.h"
67 #include "components/policy/core/common/policy_service.h"
68 #include "components/ui/zoom/zoom_event_manager.h"
69 #include "components/user_prefs/user_prefs.h"
70 #include "components/webdata_services/web_data_service_wrapper.h"
71 #include "content/public/browser/browser_thread.h"
72 #include "content/public/browser/cookie_store_factory.h"
73 #include "content/public/browser/notification_service.h"
74 #include "content/public/browser/render_process_host.h"
75 #include "content/public/browser/storage_partition.h"
76 #include "content/public/browser/zoom_level_delegate.h"
77 #include "content/public/test/mock_resource_context.h"
78 #include "content/public/test/test_utils.h"
79 #include "extensions/common/constants.h"
80 #include "net/cookies/cookie_monster.h"
81 #include "net/url_request/url_request_context.h"
82 #include "net/url_request/url_request_context_getter.h"
83 #include "net/url_request/url_request_test_util.h"
84 #include "testing/gmock/include/gmock/gmock.h"
86 #if defined(ENABLE_CONFIGURATION_POLICY)
87 #include "chrome/browser/policy/schema_registry_service.h"
88 #include "chrome/browser/policy/schema_registry_service_factory.h"
89 #include "components/policy/core/common/configuration_policy_provider.h"
90 #include "components/policy/core/common/policy_service_impl.h"
91 #include "components/policy/core/common/schema.h"
93 #include "components/policy/core/common/policy_service_stub.h"
94 #endif // defined(ENABLE_CONFIGURATION_POLICY)
96 #if defined(ENABLE_EXTENSIONS)
97 #include "chrome/browser/extensions/extension_service.h"
98 #include "chrome/browser/extensions/extension_special_storage_policy.h"
99 #include "chrome/browser/extensions/extension_system_factory.h"
100 #include "chrome/browser/extensions/test_extension_system.h"
101 #include "components/guest_view/browser/guest_view_manager.h"
102 #include "extensions/browser/event_router_factory.h"
103 #include "extensions/browser/extension_pref_value_map.h"
104 #include "extensions/browser/extension_pref_value_map_factory.h"
105 #include "extensions/browser/extension_prefs.h"
106 #include "extensions/browser/extension_prefs_factory.h"
107 #include "extensions/browser/extension_prefs_observer.h"
108 #include "extensions/browser/extension_system.h"
111 #if defined(OS_ANDROID)
112 #include "chrome/browser/signin/oauth2_token_service_delegate_android.h"
115 #if defined(ENABLE_SUPERVISED_USERS)
116 #include "chrome/browser/supervised_user/supervised_user_constants.h"
117 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
118 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
122 using bookmarks::BookmarkModel
;
123 using content::BrowserThread
;
124 using content::DownloadManagerDelegate
;
125 using testing::NiceMock
;
126 using testing::Return
;
130 // Task used to make sure history has finished processing a request. Intended
131 // for use with BlockUntilHistoryProcessesPendingRequests.
133 class QuittingHistoryDBTask
: public history::HistoryDBTask
{
135 QuittingHistoryDBTask() {}
137 bool RunOnDBThread(history::HistoryBackend
* backend
,
138 history::HistoryDatabase
* db
) override
{
142 void DoneRunOnMainThread() override
{ base::MessageLoop::current()->Quit(); }
145 ~QuittingHistoryDBTask() override
{}
147 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask
);
150 class TestExtensionURLRequestContext
: public net::URLRequestContext
{
152 TestExtensionURLRequestContext() {
153 net::CookieMonster
* cookie_monster
=
154 content::CreateCookieStore(content::CookieStoreConfig())->
156 const char* const schemes
[] = {extensions::kExtensionScheme
};
157 cookie_monster
->SetCookieableSchemes(schemes
, arraysize(schemes
));
158 set_cookie_store(cookie_monster
);
161 ~TestExtensionURLRequestContext() override
{ AssertNoURLRequests(); }
164 class TestExtensionURLRequestContextGetter
165 : public net::URLRequestContextGetter
{
167 net::URLRequestContext
* GetURLRequestContext() override
{
169 context_
.reset(new TestExtensionURLRequestContext());
170 return context_
.get();
172 scoped_refptr
<base::SingleThreadTaskRunner
> GetNetworkTaskRunner()
174 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
178 ~TestExtensionURLRequestContextGetter() override
{}
181 scoped_ptr
<net::URLRequestContext
> context_
;
184 scoped_ptr
<KeyedService
> BuildHistoryService(content::BrowserContext
* context
) {
185 Profile
* profile
= Profile::FromBrowserContext(context
);
186 return make_scoped_ptr(new history::HistoryService(
187 make_scoped_ptr(new ChromeHistoryClient(
188 BookmarkModelFactory::GetForProfile(profile
))),
189 make_scoped_ptr(new history::ContentVisitDelegate(profile
))));
192 scoped_ptr
<KeyedService
> BuildInMemoryURLIndex(
193 content::BrowserContext
* context
) {
194 Profile
* profile
= Profile::FromBrowserContext(context
);
195 scoped_ptr
<InMemoryURLIndex
> in_memory_url_index(new InMemoryURLIndex(
196 BookmarkModelFactory::GetForProfile(profile
),
197 HistoryServiceFactory::GetForProfile(profile
,
198 ServiceAccessType::IMPLICIT_ACCESS
),
199 content::BrowserThread::GetBlockingPool(), profile
->GetPath(),
200 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
),
202 in_memory_url_index
->Init();
203 return in_memory_url_index
.Pass();
206 scoped_ptr
<KeyedService
> BuildBookmarkModel(content::BrowserContext
* context
) {
207 Profile
* profile
= Profile::FromBrowserContext(context
);
208 ChromeBookmarkClient
* bookmark_client
=
209 ChromeBookmarkClientFactory::GetForProfile(profile
);
210 scoped_ptr
<BookmarkModel
> bookmark_model(new BookmarkModel(bookmark_client
));
211 bookmark_client
->Init(bookmark_model
.get());
212 bookmark_model
->Load(profile
->GetPrefs(),
213 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
),
215 profile
->GetIOTaskRunner(),
216 content::BrowserThread::GetMessageLoopProxyForThread(
217 content::BrowserThread::UI
));
218 return bookmark_model
.Pass();
221 void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type
,
222 sql::InitStatus status
) {
226 scoped_ptr
<KeyedService
> BuildWebDataService(content::BrowserContext
* context
) {
227 const base::FilePath
& context_path
= context
->GetPath();
228 return make_scoped_ptr(new WebDataServiceWrapper(
229 context_path
, g_browser_process
->GetApplicationLocale(),
230 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI
),
231 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB
),
232 sync_start_util::GetFlareForSyncableService(context_path
),
233 &TestProfileErrorCallback
));
239 #if defined(OS_CHROMEOS)
240 // Must be kept in sync with
241 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
242 const char TestingProfile::kTestUserProfileDir
[] = "test-user";
244 const char TestingProfile::kTestUserProfileDir
[] = "Default";
247 TestingProfile::TestingProfile()
248 : start_time_(Time::Now()),
249 testing_prefs_(NULL
),
250 force_incognito_(false),
251 original_profile_(NULL
),
252 guest_session_(false),
253 last_session_exited_cleanly_(true),
254 browser_context_dependency_manager_(
255 BrowserContextDependencyManager::GetInstance()),
256 resource_context_(NULL
),
258 CreateTempProfileDir();
259 profile_path_
= temp_dir_
.path();
265 TestingProfile::TestingProfile(const base::FilePath
& path
)
266 : start_time_(Time::Now()),
267 testing_prefs_(NULL
),
268 force_incognito_(false),
269 original_profile_(NULL
),
270 guest_session_(false),
271 last_session_exited_cleanly_(true),
273 browser_context_dependency_manager_(
274 BrowserContextDependencyManager::GetInstance()),
275 resource_context_(NULL
),
281 TestingProfile::TestingProfile(const base::FilePath
& path
,
283 : start_time_(Time::Now()),
284 testing_prefs_(NULL
),
285 force_incognito_(false),
286 original_profile_(NULL
),
287 guest_session_(false),
288 last_session_exited_cleanly_(true),
290 browser_context_dependency_manager_(
291 BrowserContextDependencyManager::GetInstance()),
292 resource_context_(NULL
),
293 delegate_(delegate
) {
296 base::ThreadTaskRunnerHandle::Get()->PostTask(
298 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
304 TestingProfile::TestingProfile(
305 const base::FilePath
& path
,
307 #if defined(ENABLE_EXTENSIONS)
308 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy
,
310 scoped_ptr
<PrefServiceSyncable
> prefs
,
311 TestingProfile
* parent
,
313 const std::string
& supervised_user_id
,
314 scoped_ptr
<policy::PolicyService
> policy_service
,
315 const TestingFactories
& factories
)
316 : start_time_(Time::Now()),
317 prefs_(prefs
.release()),
318 testing_prefs_(NULL
),
319 force_incognito_(false),
320 original_profile_(parent
),
321 guest_session_(guest_session
),
322 last_session_exited_cleanly_(true),
323 #if defined(ENABLE_EXTENSIONS)
324 extension_special_storage_policy_(extension_policy
),
327 browser_context_dependency_manager_(
328 BrowserContextDependencyManager::GetInstance()),
329 resource_context_(NULL
),
331 policy_service_(policy_service
.release()) {
333 parent
->SetOffTheRecordProfile(scoped_ptr
<Profile
>(this));
335 // If no profile path was supplied, create one.
336 if (profile_path_
.empty()) {
337 CreateTempProfileDir();
338 profile_path_
= temp_dir_
.path();
341 // Set any testing factories prior to initializing the services.
342 for (TestingFactories::const_iterator it
= factories
.begin();
343 it
!= factories
.end(); ++it
) {
344 it
->first
->SetTestingFactory(this, it
->second
);
348 // If caller supplied a delegate, delay the FinishInit invocation until other
350 // TODO(atwilson): See if this is still required once we convert the current
351 // users of the constructor that takes a Delegate* param.
353 base::ThreadTaskRunnerHandle::Get()->PostTask(
355 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
360 SetSupervisedUserId(supervised_user_id
);
363 void TestingProfile::CreateTempProfileDir() {
364 if (!temp_dir_
.CreateUniqueTempDir()) {
365 LOG(ERROR
) << "Failed to create unique temporary directory.";
367 // Fallback logic in case we fail to create unique temporary directory.
368 base::FilePath system_tmp_dir
;
369 bool success
= PathService::Get(base::DIR_TEMP
, &system_tmp_dir
);
371 // We're severly screwed if we can't get the system temporary
372 // directory. Die now to avoid writing to the filesystem root
373 // or other bad places.
376 base::FilePath
fallback_dir(
377 system_tmp_dir
.AppendASCII("TestingProfilePath"));
378 base::DeleteFile(fallback_dir
, true);
379 base::CreateDirectory(fallback_dir
);
380 if (!temp_dir_
.Set(fallback_dir
)) {
381 // That shouldn't happen, but if it does, try to recover.
382 LOG(ERROR
) << "Failed to use a fallback temporary directory.";
384 // We're screwed if this fails, see CHECK above.
385 CHECK(temp_dir_
.Set(system_tmp_dir
));
390 void TestingProfile::Init() {
391 // If threads have been initialized, we should be on the UI thread.
392 DCHECK(!content::BrowserThread::IsThreadInitialized(
393 content::BrowserThread::UI
) ||
394 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
396 set_is_guest_profile(guest_session_
);
398 #if defined(OS_ANDROID)
399 // Make sure token service knows its running in tests.
400 OAuth2TokenServiceDelegateAndroid::set_is_testing_profile();
403 // Normally this would happen during browser startup, but for tests
404 // we need to trigger creation of Profile-related services.
405 ChromeBrowserMainExtraPartsProfiles::
406 EnsureBrowserContextKeyedServiceFactoriesBuilt();
409 user_prefs::UserPrefs::Set(this, prefs_
.get());
410 else if (IsOffTheRecord())
411 CreateIncognitoPrefService();
413 CreateTestingPrefService();
415 if (!base::PathExists(profile_path_
))
416 base::CreateDirectory(profile_path_
);
418 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
419 // anymore, after converting the PrefService to a PKS. Until then it must
420 // be associated with a TestingProfile too.
421 if (!IsOffTheRecord())
422 CreateProfilePolicyConnector();
424 extensions_path_
= profile_path_
.AppendASCII("Extensions");
426 #if defined(ENABLE_EXTENSIONS)
427 // Note that the GetPrefs() creates a TestingPrefService, therefore
428 // the extension controlled pref values set in ExtensionPrefs
429 // are not reflected in the pref service. One would need to
430 // inject a new ExtensionPrefStore(extension_pref_value_map, false).
431 bool extensions_disabled
= base::CommandLine::ForCurrentProcess()->HasSwitch(
432 switches::kDisableExtensions
);
433 scoped_ptr
<extensions::ExtensionPrefs
> extension_prefs(
434 extensions::ExtensionPrefs::Create(
435 this, GetPrefs(), extensions_path_
,
436 ExtensionPrefValueMapFactory::GetForBrowserContext(this),
438 std::vector
<extensions::ExtensionPrefsObserver
*>()));
439 extensions::ExtensionPrefsFactory::GetInstance()->SetInstanceForTesting(
440 this, extension_prefs
.Pass());
442 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
443 this, extensions::TestExtensionSystem::Build
);
445 extensions::EventRouterFactory::GetInstance()->SetTestingFactory(this,
449 // Prefs for incognito profiles are set in CreateIncognitoPrefService() by
450 // simulating ProfileImpl::GetOffTheRecordPrefs().
451 if (!IsOffTheRecord()) {
452 DCHECK(!original_profile_
);
453 user_prefs::PrefRegistrySyncable
* pref_registry
=
454 static_cast<user_prefs::PrefRegistrySyncable
*>(
455 prefs_
->DeprecatedGetPrefRegistry());
456 browser_context_dependency_manager_
->
457 RegisterProfilePrefsForServices(this, pref_registry
);
460 browser_context_dependency_manager_
->CreateBrowserContextServicesForTest(
463 #if defined(ENABLE_SUPERVISED_USERS)
464 if (!IsOffTheRecord()) {
465 SupervisedUserSettingsService
* settings_service
=
466 SupervisedUserSettingsServiceFactory::GetForProfile(this);
467 TestingPrefStore
* store
= new TestingPrefStore();
468 settings_service
->Init(store
);
469 store
->SetInitializationCompleted();
473 profile_name_
= "testing_profile";
476 void TestingProfile::FinishInit() {
477 DCHECK(content::NotificationService::current());
478 content::NotificationService::current()->Notify(
479 chrome::NOTIFICATION_PROFILE_CREATED
,
480 content::Source
<Profile
>(static_cast<Profile
*>(this)),
481 content::NotificationService::NoDetails());
483 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
485 profile_manager
->InitProfileUserPrefs(this);
488 delegate_
->OnProfileCreated(this, true, false);
491 TestingProfile::~TestingProfile() {
492 // Revert to non-incognito mode before shutdown.
493 force_incognito_
= false;
495 // If this profile owns an incognito profile, tear it down first.
496 incognito_profile_
.reset();
498 // Any objects holding live URLFetchers should be deleted before teardown.
499 TemplateURLFetcherFactory::ShutdownForProfile(this);
501 MaybeSendDestroyedNotification();
503 browser_context_dependency_manager_
->DestroyBrowserContextServices(this);
505 if (host_content_settings_map_
.get())
506 host_content_settings_map_
->ShutdownOnUIThread();
508 if (pref_proxy_config_tracker_
.get())
509 pref_proxy_config_tracker_
->DetachFromPrefService();
510 // Failing a post == leaks == heapcheck failure. Make that an immediate test
512 if (resource_context_
) {
513 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO
, FROM_HERE
,
515 resource_context_
= NULL
;
516 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
520 void TestingProfile::CreateFaviconService() {
521 // It is up to the caller to create the history service if one is needed.
522 FaviconServiceFactory::GetInstance()->SetTestingFactory(
523 this, FaviconServiceFactory::GetDefaultFactory());
526 bool TestingProfile::CreateHistoryService(bool delete_file
, bool no_db
) {
527 DestroyHistoryService();
529 base::FilePath path
= GetPath();
530 path
= path
.Append(history::kHistoryFilename
);
531 if (!base::DeleteFile(path
, false) || base::PathExists(path
))
534 // This will create and init the history service.
535 history::HistoryService
* history_service
=
536 static_cast<history::HistoryService
*>(
537 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
538 this, BuildHistoryService
));
539 if (!history_service
->Init(
540 no_db
, GetPrefs()->GetString(prefs::kAcceptLanguages
),
541 history::HistoryDatabaseParamsForPath(GetPath()))) {
542 HistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
545 // Some tests expect that CreateHistoryService() will also make the
546 // InMemoryURLIndex available.
547 InMemoryURLIndexFactory::GetInstance()->SetTestingFactory(
548 this, BuildInMemoryURLIndex
);
549 // Disable WebHistoryService by default, since it makes network requests.
550 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
554 void TestingProfile::DestroyHistoryService() {
555 history::HistoryService
* history_service
=
556 HistoryServiceFactory::GetForProfileWithoutCreating(this);
557 if (!history_service
)
560 history_service
->ClearCachedDataForContextID(0);
561 history_service
->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
562 history_service
->Cleanup();
563 HistoryServiceFactory::ShutdownForProfile(this);
565 // Wait for the backend class to terminate before deleting the files and
566 // moving to the next test. Note: if this never terminates, somebody is
567 // probably leaking a reference to the history backend, so it never calls
569 base::MessageLoop::current()->Run();
571 // Make sure we don't have any event pending that could disrupt the next
573 base::ThreadTaskRunnerHandle::Get()->PostTask(
574 FROM_HERE
, base::MessageLoop::QuitClosure());
575 base::MessageLoop::current()->Run();
578 void TestingProfile::CreateBookmarkModel(bool delete_file
) {
580 base::FilePath path
= GetPath().Append(bookmarks::kBookmarksFileName
);
581 base::DeleteFile(path
, false);
583 ManagedBookmarkServiceFactory::GetInstance()->SetTestingFactory(
584 this, ManagedBookmarkServiceFactory::GetDefaultFactory());
585 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
586 this, ChromeBookmarkClientFactory::GetDefaultFactory());
587 // This creates the BookmarkModel.
588 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
589 this, BuildBookmarkModel
));
592 void TestingProfile::CreateWebDataService() {
593 WebDataServiceFactory::GetInstance()->SetTestingFactory(
594 this, BuildWebDataService
);
597 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
598 // Only get the history service if it actually exists since the caller of the
599 // test should explicitly call CreateHistoryService to build it.
600 history::HistoryService
* history_service
=
601 HistoryServiceFactory::GetForProfileWithoutCreating(this);
602 DCHECK(history_service
);
603 InMemoryURLIndex
* index
= InMemoryURLIndexFactory::GetForProfile(this);
604 if (!index
|| index
->restored())
606 base::RunLoop run_loop
;
607 HistoryIndexRestoreObserver
observer(
608 content::GetQuitTaskForRunLoop(&run_loop
));
609 index
->set_restore_cache_observer(&observer
);
611 index
->set_restore_cache_observer(NULL
);
612 DCHECK(index
->restored());
615 void TestingProfile::SetGuestSession(bool guest
) {
616 guest_session_
= guest
;
619 base::FilePath
TestingProfile::GetPath() const {
620 return profile_path_
;
623 scoped_ptr
<content::ZoomLevelDelegate
> TestingProfile::CreateZoomLevelDelegate(
624 const base::FilePath
& partition_path
) {
625 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
626 GetPrefs(), GetPath(), partition_path
,
627 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
630 scoped_refptr
<base::SequencedTaskRunner
> TestingProfile::GetIOTaskRunner() {
631 return base::MessageLoop::current()->task_runner();
634 TestingPrefServiceSyncable
* TestingProfile::GetTestingPrefService() {
636 DCHECK(testing_prefs_
);
637 return testing_prefs_
;
640 TestingProfile
* TestingProfile::AsTestingProfile() {
644 std::string
TestingProfile::GetProfileUserName() const {
645 return profile_name_
;
648 Profile::ProfileType
TestingProfile::GetProfileType() const {
650 return GUEST_PROFILE
;
651 if (force_incognito_
|| original_profile_
)
652 return INCOGNITO_PROFILE
;
653 return REGULAR_PROFILE
;
656 bool TestingProfile::IsOffTheRecord() const {
657 return force_incognito_
|| original_profile_
;
660 void TestingProfile::SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
) {
661 DCHECK(!IsOffTheRecord());
662 DCHECK_EQ(this, profile
->GetOriginalProfile());
663 incognito_profile_
= profile
.Pass();
666 Profile
* TestingProfile::GetOffTheRecordProfile() {
667 if (IsOffTheRecord())
669 if (!incognito_profile_
)
670 TestingProfile::Builder().BuildIncognito(this);
671 return incognito_profile_
.get();
674 bool TestingProfile::HasOffTheRecordProfile() {
675 return incognito_profile_
.get() != NULL
;
678 Profile
* TestingProfile::GetOriginalProfile() {
679 if (original_profile_
)
680 return original_profile_
;
684 void TestingProfile::SetSupervisedUserId(const std::string
& id
) {
685 supervised_user_id_
= id
;
687 GetPrefs()->SetString(prefs::kSupervisedUserId
, id
);
689 GetPrefs()->ClearPref(prefs::kSupervisedUserId
);
692 bool TestingProfile::IsSupervised() const {
693 return !supervised_user_id_
.empty();
696 bool TestingProfile::IsChild() const {
697 #if defined(ENABLE_SUPERVISED_USERS)
698 return supervised_user_id_
== supervised_users::kChildAccountSUID
;
704 bool TestingProfile::IsLegacySupervised() const {
705 return IsSupervised() && !IsChild();
708 #if defined(ENABLE_EXTENSIONS)
709 void TestingProfile::SetExtensionSpecialStoragePolicy(
710 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
) {
711 extension_special_storage_policy_
= extension_special_storage_policy
;
715 ExtensionSpecialStoragePolicy
*
716 TestingProfile::GetExtensionSpecialStoragePolicy() {
717 #if defined(ENABLE_EXTENSIONS)
718 if (!extension_special_storage_policy_
.get())
719 extension_special_storage_policy_
= new ExtensionSpecialStoragePolicy(NULL
);
720 return extension_special_storage_policy_
.get();
726 net::CookieMonster
* TestingProfile::GetCookieMonster() {
727 if (!GetRequestContext())
729 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
733 void TestingProfile::CreateTestingPrefService() {
734 DCHECK(!prefs_
.get());
735 testing_prefs_
= new TestingPrefServiceSyncable();
736 prefs_
.reset(testing_prefs_
);
737 user_prefs::UserPrefs::Set(this, prefs_
.get());
738 chrome::RegisterUserProfilePrefs(testing_prefs_
->registry());
741 void TestingProfile::CreateIncognitoPrefService() {
742 DCHECK(original_profile_
);
743 DCHECK(!testing_prefs_
);
744 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
745 // leaves testing_prefs_ unset.
746 prefs_
.reset(original_profile_
->prefs_
->CreateIncognitoPrefService(NULL
));
747 user_prefs::UserPrefs::Set(this, prefs_
.get());
750 void TestingProfile::CreateProfilePolicyConnector() {
751 #if defined(ENABLE_CONFIGURATION_POLICY)
752 schema_registry_service_
=
753 policy::SchemaRegistryServiceFactory::CreateForContext(
754 this, policy::Schema(), NULL
);
755 CHECK_EQ(schema_registry_service_
.get(),
756 policy::SchemaRegistryServiceFactory::GetForContext(this));
757 #endif // defined(ENABLE_CONFIGURATION_POLICY)
759 if (!policy_service_
) {
760 #if defined(ENABLE_CONFIGURATION_POLICY)
761 std::vector
<policy::ConfigurationPolicyProvider
*> providers
;
762 policy_service_
.reset(new policy::PolicyServiceImpl(providers
));
764 policy_service_
.reset(new policy::PolicyServiceStub());
767 profile_policy_connector_
.reset(new policy::ProfilePolicyConnector());
768 profile_policy_connector_
->InitForTesting(policy_service_
.Pass());
769 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
770 this, profile_policy_connector_
.get());
771 CHECK_EQ(profile_policy_connector_
.get(),
772 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(this));
775 PrefService
* TestingProfile::GetPrefs() {
780 const PrefService
* TestingProfile::GetPrefs() const {
785 chrome::ChromeZoomLevelPrefs
* TestingProfile::GetZoomLevelPrefs() {
786 return static_cast<chrome::ChromeZoomLevelPrefs
*>(
787 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
790 DownloadManagerDelegate
* TestingProfile::GetDownloadManagerDelegate() {
794 net::URLRequestContextGetter
* TestingProfile::GetRequestContext() {
795 return GetDefaultStoragePartition(this)->GetURLRequestContext();
798 net::URLRequestContextGetter
* TestingProfile::CreateRequestContext(
799 content::ProtocolHandlerMap
* protocol_handlers
,
800 content::URLRequestInterceptorScopedVector request_interceptors
) {
801 return new net::TestURLRequestContextGetter(
802 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
805 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForRenderProcess(
806 int renderer_child_id
) {
807 content::RenderProcessHost
* rph
= content::RenderProcessHost::FromID(
809 return rph
->GetStoragePartition()->GetURLRequestContext();
812 net::URLRequestContextGetter
* TestingProfile::GetMediaRequestContext() {
816 net::URLRequestContextGetter
*
817 TestingProfile::GetMediaRequestContextForRenderProcess(
818 int renderer_child_id
) {
822 net::URLRequestContextGetter
*
823 TestingProfile::GetMediaRequestContextForStoragePartition(
824 const base::FilePath
& partition_path
,
829 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForExtensions() {
830 if (!extensions_request_context_
.get())
831 extensions_request_context_
= new TestExtensionURLRequestContextGetter();
832 return extensions_request_context_
.get();
835 net::SSLConfigService
* TestingProfile::GetSSLConfigService() {
836 if (!GetRequestContext())
838 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
841 net::URLRequestContextGetter
*
842 TestingProfile::CreateRequestContextForStoragePartition(
843 const base::FilePath
& partition_path
,
845 content::ProtocolHandlerMap
* protocol_handlers
,
846 content::URLRequestInterceptorScopedVector request_interceptors
) {
847 // We don't test storage partitions here yet, so returning the same dummy
848 // context is sufficient for now.
849 return GetRequestContext();
852 content::ResourceContext
* TestingProfile::GetResourceContext() {
853 if (!resource_context_
)
854 resource_context_
= new content::MockResourceContext();
855 return resource_context_
;
858 HostContentSettingsMap
* TestingProfile::GetHostContentSettingsMap() {
859 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
860 if (!host_content_settings_map_
.get()) {
861 host_content_settings_map_
= new HostContentSettingsMap(GetPrefs(), false);
862 #if defined(ENABLE_EXTENSIONS)
863 ExtensionService
* extension_service
=
864 extensions::ExtensionSystem::Get(this)->extension_service();
865 if (extension_service
) {
866 extension_service
->RegisterContentSettings(
867 host_content_settings_map_
.get());
871 return host_content_settings_map_
.get();
874 content::BrowserPluginGuestManager
* TestingProfile::GetGuestManager() {
875 #if defined(ENABLE_EXTENSIONS)
876 return guest_view::GuestViewManager::FromBrowserContext(this);
882 content::PushMessagingService
* TestingProfile::GetPushMessagingService() {
886 bool TestingProfile::IsSameProfile(Profile
*p
) {
890 base::Time
TestingProfile::GetStartTime() const {
894 base::FilePath
TestingProfile::last_selected_directory() {
895 return last_selected_directory_
;
898 void TestingProfile::set_last_selected_directory(const base::FilePath
& path
) {
899 last_selected_directory_
= path
;
902 PrefProxyConfigTracker
* TestingProfile::GetProxyConfigTracker() {
903 if (!pref_proxy_config_tracker_
.get()) {
904 // TestingProfile is used in unit tests, where local state is not available.
905 pref_proxy_config_tracker_
.reset(
906 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
909 return pref_proxy_config_tracker_
.get();
912 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
913 history::HistoryService
* history_service
=
914 HistoryServiceFactory::GetForProfile(this,
915 ServiceAccessType::EXPLICIT_ACCESS
);
916 DCHECK(history_service
);
917 DCHECK(base::MessageLoop::current());
919 base::CancelableTaskTracker tracker
;
920 history_service
->ScheduleDBTask(
921 scoped_ptr
<history::HistoryDBTask
>(
922 new QuittingHistoryDBTask()),
924 base::MessageLoop::current()->Run();
927 chrome_browser_net::Predictor
* TestingProfile::GetNetworkPredictor() {
931 DevToolsNetworkControllerHandle
*
932 TestingProfile::GetDevToolsNetworkControllerHandle() {
936 void TestingProfile::ClearNetworkingHistorySince(
938 const base::Closure
& completion
) {
939 if (!completion
.is_null()) {
940 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, completion
);
944 GURL
TestingProfile::GetHomePage() {
945 return GURL(chrome::kChromeUINewTabURL
);
948 PrefService
* TestingProfile::GetOffTheRecordPrefs() {
952 storage::SpecialStoragePolicy
* TestingProfile::GetSpecialStoragePolicy() {
953 #if defined(ENABLE_EXTENSIONS)
954 return GetExtensionSpecialStoragePolicy();
960 content::SSLHostStateDelegate
* TestingProfile::GetSSLHostStateDelegate() {
964 content::PermissionManager
* TestingProfile::GetPermissionManager() {
968 bool TestingProfile::WasCreatedByVersionOrLater(const std::string
& version
) {
972 bool TestingProfile::IsGuestSession() const {
973 return guest_session_
;
976 Profile::ExitType
TestingProfile::GetLastSessionExitType() {
977 return last_session_exited_cleanly_
? EXIT_NORMAL
: EXIT_CRASHED
;
980 TestingProfile::Builder::Builder()
981 : build_called_(false),
983 guest_session_(false) {
986 TestingProfile::Builder::~Builder() {
989 void TestingProfile::Builder::SetPath(const base::FilePath
& path
) {
993 void TestingProfile::Builder::SetDelegate(Delegate
* delegate
) {
994 delegate_
= delegate
;
997 #if defined(ENABLE_EXTENSIONS)
998 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
999 scoped_refptr
<ExtensionSpecialStoragePolicy
> policy
) {
1000 extension_policy_
= policy
;
1004 void TestingProfile::Builder::SetPrefService(
1005 scoped_ptr
<PrefServiceSyncable
> prefs
) {
1006 pref_service_
= prefs
.Pass();
1009 void TestingProfile::Builder::SetGuestSession() {
1010 guest_session_
= true;
1013 void TestingProfile::Builder::SetSupervisedUserId(
1014 const std::string
& supervised_user_id
) {
1015 supervised_user_id_
= supervised_user_id
;
1018 void TestingProfile::Builder::SetPolicyService(
1019 scoped_ptr
<policy::PolicyService
> policy_service
) {
1020 policy_service_
= policy_service
.Pass();
1023 void TestingProfile::Builder::AddTestingFactory(
1024 BrowserContextKeyedServiceFactory
* service_factory
,
1025 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback
) {
1026 testing_factories_
.push_back(std::make_pair(service_factory
, callback
));
1029 scoped_ptr
<TestingProfile
> TestingProfile::Builder::Build() {
1030 DCHECK(!build_called_
);
1031 build_called_
= true;
1033 return scoped_ptr
<TestingProfile
>(new TestingProfile(path_
,
1035 #if defined(ENABLE_EXTENSIONS)
1038 pref_service_
.Pass(),
1041 supervised_user_id_
,
1042 policy_service_
.Pass(),
1043 testing_factories_
));
1046 TestingProfile
* TestingProfile::Builder::BuildIncognito(
1047 TestingProfile
* original_profile
) {
1048 DCHECK(!build_called_
);
1049 DCHECK(original_profile
);
1050 build_called_
= true;
1052 // Note: Owned by |original_profile|.
1053 return new TestingProfile(path_
,
1055 #if defined(ENABLE_EXTENSIONS)
1058 pref_service_
.Pass(),
1061 supervised_user_id_
,
1062 policy_service_
.Pass(),
1063 testing_factories_
);