1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/test/base/testing_profile.h"
7 #include "base/base_paths.h"
8 #include "base/command_line.h"
9 #include "base/files/file_util.h"
10 #include "base/message_loop/message_loop_proxy.h"
11 #include "base/path_service.h"
12 #include "base/prefs/testing_pref_store.h"
13 #include "base/run_loop.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
16 #include "chrome/browser/autocomplete/in_memory_url_index.h"
17 #include "chrome/browser/autocomplete/in_memory_url_index_factory.h"
18 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
19 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
20 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
21 #include "chrome/browser/browser_process.h"
22 #include "chrome/browser/chrome_notification_types.h"
23 #include "chrome/browser/favicon/chrome_fallback_icon_client_factory.h"
24 #include "chrome/browser/favicon/chrome_favicon_client_factory.h"
25 #include "chrome/browser/favicon/fallback_icon_service_factory.h"
26 #include "chrome/browser/favicon/favicon_service_factory.h"
27 #include "chrome/browser/history/chrome_history_client.h"
28 #include "chrome/browser/history/chrome_history_client_factory.h"
29 #include "chrome/browser/history/history_service_factory.h"
30 #include "chrome/browser/history/web_history_service_factory.h"
31 #include "chrome/browser/net/pref_proxy_config_tracker.h"
32 #include "chrome/browser/net/proxy_service_factory.h"
33 #include "chrome/browser/notifications/desktop_notification_service.h"
34 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
35 #include "chrome/browser/policy/profile_policy_connector.h"
36 #include "chrome/browser/policy/profile_policy_connector_factory.h"
37 #include "chrome/browser/prefs/browser_prefs.h"
38 #include "chrome/browser/prefs/pref_service_syncable.h"
39 #include "chrome/browser/prerender/prerender_manager.h"
40 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
41 #include "chrome/browser/profiles/profile_manager.h"
42 #include "chrome/browser/profiles/storage_partition_descriptor.h"
43 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
44 #include "chrome/browser/sync/glue/sync_start_util.h"
45 #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
46 #include "chrome/browser/webdata/web_data_service_factory.h"
47 #include "chrome/common/chrome_constants.h"
48 #include "chrome/common/chrome_switches.h"
49 #include "chrome/common/pref_names.h"
50 #include "chrome/common/url_constants.h"
51 #include "chrome/test/base/history_index_restore_observer.h"
52 #include "chrome/test/base/testing_pref_service_syncable.h"
53 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
54 #include "components/bookmarks/browser/bookmark_model.h"
55 #include "components/bookmarks/common/bookmark_constants.h"
56 #include "components/content_settings/core/browser/host_content_settings_map.h"
57 #include "components/favicon/core/fallback_icon_service.h"
58 #include "components/favicon/core/favicon_service.h"
59 #include "components/history/content/browser/content_visit_delegate.h"
60 #include "components/history/content/browser/history_database_helper.h"
61 #include "components/history/core/browser/history_backend.h"
62 #include "components/history/core/browser/history_constants.h"
63 #include "components/history/core/browser/history_database_params.h"
64 #include "components/history/core/browser/history_db_task.h"
65 #include "components/history/core/browser/history_service.h"
66 #include "components/keyed_service/content/browser_context_dependency_manager.h"
67 #include "components/keyed_service/core/refcounted_keyed_service.h"
68 #include "components/policy/core/common/policy_service.h"
69 #include "components/ui/zoom/zoom_event_manager.h"
70 #include "components/user_prefs/user_prefs.h"
71 #include "components/webdata_services/web_data_service_wrapper.h"
72 #include "content/public/browser/browser_thread.h"
73 #include "content/public/browser/cookie_store_factory.h"
74 #include "content/public/browser/notification_service.h"
75 #include "content/public/browser/render_process_host.h"
76 #include "content/public/browser/storage_partition.h"
77 #include "content/public/browser/zoom_level_delegate.h"
78 #include "content/public/test/mock_resource_context.h"
79 #include "content/public/test/test_utils.h"
80 #include "extensions/common/constants.h"
81 #include "net/cookies/cookie_monster.h"
82 #include "net/url_request/url_request_context.h"
83 #include "net/url_request/url_request_context_getter.h"
84 #include "net/url_request/url_request_test_util.h"
85 #include "testing/gmock/include/gmock/gmock.h"
87 #if defined(ENABLE_CONFIGURATION_POLICY)
88 #include "chrome/browser/policy/schema_registry_service.h"
89 #include "chrome/browser/policy/schema_registry_service_factory.h"
90 #include "components/policy/core/common/configuration_policy_provider.h"
91 #include "components/policy/core/common/policy_service_impl.h"
92 #include "components/policy/core/common/schema.h"
94 #include "components/policy/core/common/policy_service_stub.h"
95 #endif // defined(ENABLE_CONFIGURATION_POLICY)
97 #if defined(ENABLE_EXTENSIONS)
98 #include "chrome/browser/extensions/extension_service.h"
99 #include "chrome/browser/extensions/extension_special_storage_policy.h"
100 #include "chrome/browser/extensions/extension_system_factory.h"
101 #include "chrome/browser/extensions/test_extension_system.h"
102 #include "components/guest_view/browser/guest_view_manager.h"
103 #include "extensions/browser/extension_system.h"
106 #if defined(OS_ANDROID)
107 #include "chrome/browser/signin/android_profile_oauth2_token_service.h"
110 #if defined(ENABLE_SUPERVISED_USERS)
111 #include "chrome/browser/supervised_user/supervised_user_constants.h"
112 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
113 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
117 using bookmarks::BookmarkModel
;
118 using content::BrowserThread
;
119 using content::DownloadManagerDelegate
;
120 using testing::NiceMock
;
121 using testing::Return
;
125 // Task used to make sure history has finished processing a request. Intended
126 // for use with BlockUntilHistoryProcessesPendingRequests.
128 class QuittingHistoryDBTask
: public history::HistoryDBTask
{
130 QuittingHistoryDBTask() {}
132 bool RunOnDBThread(history::HistoryBackend
* backend
,
133 history::HistoryDatabase
* db
) override
{
137 void DoneRunOnMainThread() override
{ base::MessageLoop::current()->Quit(); }
140 ~QuittingHistoryDBTask() override
{}
142 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask
);
145 class TestExtensionURLRequestContext
: public net::URLRequestContext
{
147 TestExtensionURLRequestContext() {
148 net::CookieMonster
* cookie_monster
=
149 content::CreateCookieStore(content::CookieStoreConfig())->
151 const char* const schemes
[] = {extensions::kExtensionScheme
};
152 cookie_monster
->SetCookieableSchemes(schemes
, arraysize(schemes
));
153 set_cookie_store(cookie_monster
);
156 ~TestExtensionURLRequestContext() override
{ AssertNoURLRequests(); }
159 class TestExtensionURLRequestContextGetter
160 : public net::URLRequestContextGetter
{
162 net::URLRequestContext
* GetURLRequestContext() override
{
164 context_
.reset(new TestExtensionURLRequestContext());
165 return context_
.get();
167 scoped_refptr
<base::SingleThreadTaskRunner
> GetNetworkTaskRunner()
169 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
173 ~TestExtensionURLRequestContextGetter() override
{}
176 scoped_ptr
<net::URLRequestContext
> context_
;
179 #if defined(ENABLE_NOTIFICATIONS)
180 KeyedService
* CreateTestDesktopNotificationService(
181 content::BrowserContext
* profile
) {
182 return new DesktopNotificationService(static_cast<Profile
*>(profile
));
186 KeyedService
* BuildFaviconService(content::BrowserContext
* context
) {
187 Profile
* profile
= Profile::FromBrowserContext(context
);
188 return new favicon::FaviconService(
189 ChromeFaviconClientFactory::GetForProfile(profile
),
190 HistoryServiceFactory::GetForProfile(profile
,
191 ServiceAccessType::EXPLICIT_ACCESS
));
194 KeyedService
* BuildHistoryService(content::BrowserContext
* context
) {
195 Profile
* profile
= Profile::FromBrowserContext(context
);
196 history::HistoryService
* history_service
= new history::HistoryService(
197 ChromeHistoryClientFactory::GetForProfile(profile
),
198 scoped_ptr
<history::VisitDelegate
>(
199 new history::ContentVisitDelegate(profile
)));
200 return history_service
;
203 KeyedService
* BuildInMemoryURLIndex(content::BrowserContext
* context
) {
204 Profile
* profile
= Profile::FromBrowserContext(context
);
205 InMemoryURLIndex
* in_memory_url_index
= new InMemoryURLIndex(
206 BookmarkModelFactory::GetForProfile(profile
),
207 HistoryServiceFactory::GetForProfile(profile
,
208 ServiceAccessType::IMPLICIT_ACCESS
),
210 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
211 in_memory_url_index
->Init();
212 return in_memory_url_index
;
215 KeyedService
* BuildBookmarkModel(content::BrowserContext
* context
) {
216 Profile
* profile
= static_cast<Profile
*>(context
);
217 ChromeBookmarkClient
* bookmark_client
=
218 ChromeBookmarkClientFactory::GetForProfile(profile
);
219 BookmarkModel
* bookmark_model
= new BookmarkModel(bookmark_client
);
220 bookmark_client
->Init(bookmark_model
);
221 bookmark_model
->Load(profile
->GetPrefs(),
222 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
),
224 profile
->GetIOTaskRunner(),
225 content::BrowserThread::GetMessageLoopProxyForThread(
226 content::BrowserThread::UI
));
227 return bookmark_model
;
230 KeyedService
* BuildChromeBookmarkClient(
231 content::BrowserContext
* context
) {
232 return new ChromeBookmarkClient(static_cast<Profile
*>(context
));
235 KeyedService
* BuildChromeHistoryClient(
236 content::BrowserContext
* context
) {
237 Profile
* profile
= static_cast<Profile
*>(context
);
238 return new ChromeHistoryClient(BookmarkModelFactory::GetForProfile(profile
));
241 void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type
,
242 sql::InitStatus status
) {
246 KeyedService
* BuildWebDataService(content::BrowserContext
* context
) {
247 const base::FilePath
& context_path
= context
->GetPath();
248 return new WebDataServiceWrapper(
249 context_path
, g_browser_process
->GetApplicationLocale(),
250 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI
),
251 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB
),
252 sync_start_util::GetFlareForSyncableService(context_path
),
253 &TestProfileErrorCallback
);
259 #if defined(OS_CHROMEOS)
260 // Must be kept in sync with
261 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
262 const char TestingProfile::kTestUserProfileDir
[] = "test-user";
264 const char TestingProfile::kTestUserProfileDir
[] = "Default";
267 TestingProfile::TestingProfile()
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),
274 browser_context_dependency_manager_(
275 BrowserContextDependencyManager::GetInstance()),
276 resource_context_(NULL
),
278 CreateTempProfileDir();
279 profile_path_
= temp_dir_
.path();
285 TestingProfile::TestingProfile(const base::FilePath
& path
)
286 : start_time_(Time::Now()),
287 testing_prefs_(NULL
),
288 force_incognito_(false),
289 original_profile_(NULL
),
290 guest_session_(false),
291 last_session_exited_cleanly_(true),
293 browser_context_dependency_manager_(
294 BrowserContextDependencyManager::GetInstance()),
295 resource_context_(NULL
),
301 TestingProfile::TestingProfile(const base::FilePath
& path
,
303 : start_time_(Time::Now()),
304 testing_prefs_(NULL
),
305 force_incognito_(false),
306 original_profile_(NULL
),
307 guest_session_(false),
308 last_session_exited_cleanly_(true),
310 browser_context_dependency_manager_(
311 BrowserContextDependencyManager::GetInstance()),
312 resource_context_(NULL
),
313 delegate_(delegate
) {
316 base::MessageLoop::current()->PostTask(
318 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
324 TestingProfile::TestingProfile(
325 const base::FilePath
& path
,
327 #if defined(ENABLE_EXTENSIONS)
328 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy
,
330 scoped_ptr
<PrefServiceSyncable
> prefs
,
331 TestingProfile
* parent
,
333 const std::string
& supervised_user_id
,
334 scoped_ptr
<policy::PolicyService
> policy_service
,
335 const TestingFactories
& factories
)
336 : start_time_(Time::Now()),
337 prefs_(prefs
.release()),
338 testing_prefs_(NULL
),
339 force_incognito_(false),
340 original_profile_(parent
),
341 guest_session_(guest_session
),
342 last_session_exited_cleanly_(true),
343 #if defined(ENABLE_EXTENSIONS)
344 extension_special_storage_policy_(extension_policy
),
347 browser_context_dependency_manager_(
348 BrowserContextDependencyManager::GetInstance()),
349 resource_context_(NULL
),
351 policy_service_(policy_service
.release()) {
353 parent
->SetOffTheRecordProfile(scoped_ptr
<Profile
>(this));
355 // If no profile path was supplied, create one.
356 if (profile_path_
.empty()) {
357 CreateTempProfileDir();
358 profile_path_
= temp_dir_
.path();
361 // Set any testing factories prior to initializing the services.
362 for (TestingFactories::const_iterator it
= factories
.begin();
363 it
!= factories
.end(); ++it
) {
364 it
->first
->SetTestingFactory(this, it
->second
);
368 // If caller supplied a delegate, delay the FinishInit invocation until other
370 // TODO(atwilson): See if this is still required once we convert the current
371 // users of the constructor that takes a Delegate* param.
373 base::MessageLoop::current()->PostTask(
375 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
380 SetSupervisedUserId(supervised_user_id
);
383 void TestingProfile::CreateTempProfileDir() {
384 if (!temp_dir_
.CreateUniqueTempDir()) {
385 LOG(ERROR
) << "Failed to create unique temporary directory.";
387 // Fallback logic in case we fail to create unique temporary directory.
388 base::FilePath system_tmp_dir
;
389 bool success
= PathService::Get(base::DIR_TEMP
, &system_tmp_dir
);
391 // We're severly screwed if we can't get the system temporary
392 // directory. Die now to avoid writing to the filesystem root
393 // or other bad places.
396 base::FilePath
fallback_dir(
397 system_tmp_dir
.AppendASCII("TestingProfilePath"));
398 base::DeleteFile(fallback_dir
, true);
399 base::CreateDirectory(fallback_dir
);
400 if (!temp_dir_
.Set(fallback_dir
)) {
401 // That shouldn't happen, but if it does, try to recover.
402 LOG(ERROR
) << "Failed to use a fallback temporary directory.";
404 // We're screwed if this fails, see CHECK above.
405 CHECK(temp_dir_
.Set(system_tmp_dir
));
410 void TestingProfile::Init() {
411 // If threads have been initialized, we should be on the UI thread.
412 DCHECK(!content::BrowserThread::IsThreadInitialized(
413 content::BrowserThread::UI
) ||
414 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
416 set_is_guest_profile(guest_session_
);
418 #if defined(OS_ANDROID)
419 // Make sure token service knows its running in tests.
420 AndroidProfileOAuth2TokenService::set_is_testing_profile();
423 // Normally this would happen during browser startup, but for tests
424 // we need to trigger creation of Profile-related services.
425 ChromeBrowserMainExtraPartsProfiles::
426 EnsureBrowserContextKeyedServiceFactoriesBuilt();
429 user_prefs::UserPrefs::Set(this, prefs_
.get());
430 else if (IsOffTheRecord())
431 CreateIncognitoPrefService();
433 CreateTestingPrefService();
435 if (!base::PathExists(profile_path_
))
436 base::CreateDirectory(profile_path_
);
438 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
439 // anymore, after converting the PrefService to a PKS. Until then it must
440 // be associated with a TestingProfile too.
441 if (!IsOffTheRecord())
442 CreateProfilePolicyConnector();
444 #if defined(ENABLE_EXTENSIONS)
445 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
446 this, extensions::TestExtensionSystem::Build
);
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_NOTIFICATIONS)
464 // Install profile keyed service factory hooks for dummy/test services
465 DesktopNotificationServiceFactory::GetInstance()->SetTestingFactory(
466 this, CreateTestDesktopNotificationService
);
469 #if defined(ENABLE_SUPERVISED_USERS)
470 if (!IsOffTheRecord()) {
471 SupervisedUserSettingsService
* settings_service
=
472 SupervisedUserSettingsServiceFactory::GetForProfile(this);
473 TestingPrefStore
* store
= new TestingPrefStore();
474 settings_service
->Init(store
);
475 store
->SetInitializationCompleted();
479 profile_name_
= "testing_profile";
482 void TestingProfile::FinishInit() {
483 DCHECK(content::NotificationService::current());
484 content::NotificationService::current()->Notify(
485 chrome::NOTIFICATION_PROFILE_CREATED
,
486 content::Source
<Profile
>(static_cast<Profile
*>(this)),
487 content::NotificationService::NoDetails());
489 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
491 profile_manager
->InitProfileUserPrefs(this);
494 delegate_
->OnProfileCreated(this, true, false);
497 TestingProfile::~TestingProfile() {
498 // Revert to non-incognito mode before shutdown.
499 force_incognito_
= false;
501 // If this profile owns an incognito profile, tear it down first.
502 incognito_profile_
.reset();
504 // Any objects holding live URLFetchers should be deleted before teardown.
505 TemplateURLFetcherFactory::ShutdownForProfile(this);
507 MaybeSendDestroyedNotification();
509 browser_context_dependency_manager_
->DestroyBrowserContextServices(this);
511 if (host_content_settings_map_
.get())
512 host_content_settings_map_
->ShutdownOnUIThread();
514 if (pref_proxy_config_tracker_
.get())
515 pref_proxy_config_tracker_
->DetachFromPrefService();
516 // Failing a post == leaks == heapcheck failure. Make that an immediate test
518 if (resource_context_
) {
519 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO
, FROM_HERE
,
521 resource_context_
= NULL
;
522 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
526 void TestingProfile::CreateFaviconService() {
527 // It is up to the caller to create the history service if one is needed.
528 FaviconServiceFactory::GetInstance()->SetTestingFactory(
529 this, BuildFaviconService
);
532 bool TestingProfile::CreateHistoryService(bool delete_file
, bool no_db
) {
533 DestroyHistoryService();
535 base::FilePath path
= GetPath();
536 path
= path
.Append(history::kHistoryFilename
);
537 if (!base::DeleteFile(path
, false) || base::PathExists(path
))
540 // This will create and init the history service.
541 history::HistoryService
* history_service
=
542 static_cast<history::HistoryService
*>(
543 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
544 this, BuildHistoryService
));
545 if (!history_service
->Init(
546 no_db
, GetPrefs()->GetString(prefs::kAcceptLanguages
),
547 history::HistoryDatabaseParamsForPath(GetPath()))) {
548 HistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
551 // Some tests expect that CreateHistoryService() will also make the
552 // InMemoryURLIndex available.
553 InMemoryURLIndexFactory::GetInstance()->SetTestingFactory(
554 this, BuildInMemoryURLIndex
);
555 // Disable WebHistoryService by default, since it makes network requests.
556 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
560 void TestingProfile::DestroyHistoryService() {
561 history::HistoryService
* history_service
=
562 HistoryServiceFactory::GetForProfileWithoutCreating(this);
563 if (!history_service
)
566 history_service
->ClearCachedDataForContextID(0);
567 history_service
->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
568 history_service
->Cleanup();
569 HistoryServiceFactory::ShutdownForProfile(this);
571 // Wait for the backend class to terminate before deleting the files and
572 // moving to the next test. Note: if this never terminates, somebody is
573 // probably leaking a reference to the history backend, so it never calls
575 base::MessageLoop::current()->Run();
577 // Make sure we don't have any event pending that could disrupt the next
579 base::MessageLoop::current()->PostTask(FROM_HERE
,
580 base::MessageLoop::QuitClosure());
581 base::MessageLoop::current()->Run();
584 void TestingProfile::CreateBookmarkModel(bool delete_file
) {
586 base::FilePath path
= GetPath().Append(bookmarks::kBookmarksFileName
);
587 base::DeleteFile(path
, false);
589 ChromeHistoryClientFactory::GetInstance()->SetTestingFactory(
590 this, BuildChromeHistoryClient
);
591 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
592 this, BuildChromeBookmarkClient
);
593 // This creates the BookmarkModel.
594 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
595 this, BuildBookmarkModel
));
598 void TestingProfile::CreateWebDataService() {
599 WebDataServiceFactory::GetInstance()->SetTestingFactory(
600 this, BuildWebDataService
);
603 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
604 // Only get the history service if it actually exists since the caller of the
605 // test should explicitly call CreateHistoryService to build it.
606 history::HistoryService
* history_service
=
607 HistoryServiceFactory::GetForProfileWithoutCreating(this);
608 DCHECK(history_service
);
609 InMemoryURLIndex
* index
= InMemoryURLIndexFactory::GetForProfile(this);
610 if (!index
|| index
->restored())
612 base::RunLoop run_loop
;
613 HistoryIndexRestoreObserver
observer(
614 content::GetQuitTaskForRunLoop(&run_loop
));
615 index
->set_restore_cache_observer(&observer
);
617 index
->set_restore_cache_observer(NULL
);
618 DCHECK(index
->restored());
621 void TestingProfile::SetGuestSession(bool guest
) {
622 guest_session_
= guest
;
625 base::FilePath
TestingProfile::GetPath() const {
626 return profile_path_
;
629 scoped_ptr
<content::ZoomLevelDelegate
> TestingProfile::CreateZoomLevelDelegate(
630 const base::FilePath
& partition_path
) {
631 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
632 GetPrefs(), GetPath(), partition_path
,
633 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
636 scoped_refptr
<base::SequencedTaskRunner
> TestingProfile::GetIOTaskRunner() {
637 return base::MessageLoop::current()->message_loop_proxy();
640 TestingPrefServiceSyncable
* TestingProfile::GetTestingPrefService() {
642 DCHECK(testing_prefs_
);
643 return testing_prefs_
;
646 TestingProfile
* TestingProfile::AsTestingProfile() {
650 std::string
TestingProfile::GetProfileUserName() const {
651 return profile_name_
;
654 Profile::ProfileType
TestingProfile::GetProfileType() const {
656 return GUEST_PROFILE
;
657 if (force_incognito_
|| original_profile_
)
658 return INCOGNITO_PROFILE
;
659 return REGULAR_PROFILE
;
662 bool TestingProfile::IsOffTheRecord() const {
663 return force_incognito_
|| original_profile_
;
666 void TestingProfile::SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
) {
667 DCHECK(!IsOffTheRecord());
668 DCHECK_EQ(this, profile
->GetOriginalProfile());
669 incognito_profile_
= profile
.Pass();
672 Profile
* TestingProfile::GetOffTheRecordProfile() {
673 if (IsOffTheRecord())
675 if (!incognito_profile_
)
676 TestingProfile::Builder().BuildIncognito(this);
677 return incognito_profile_
.get();
680 bool TestingProfile::HasOffTheRecordProfile() {
681 return incognito_profile_
.get() != NULL
;
684 Profile
* TestingProfile::GetOriginalProfile() {
685 if (original_profile_
)
686 return original_profile_
;
690 void TestingProfile::SetSupervisedUserId(const std::string
& id
) {
691 supervised_user_id_
= id
;
693 GetPrefs()->SetString(prefs::kSupervisedUserId
, id
);
695 GetPrefs()->ClearPref(prefs::kSupervisedUserId
);
698 bool TestingProfile::IsSupervised() {
699 return !supervised_user_id_
.empty();
702 bool TestingProfile::IsChild() {
703 #if defined(ENABLE_SUPERVISED_USERS)
704 return supervised_user_id_
== supervised_users::kChildAccountSUID
;
710 bool TestingProfile::IsLegacySupervised() {
711 return IsSupervised() && !IsChild();
714 #if defined(ENABLE_EXTENSIONS)
715 void TestingProfile::SetExtensionSpecialStoragePolicy(
716 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
) {
717 extension_special_storage_policy_
= extension_special_storage_policy
;
721 ExtensionSpecialStoragePolicy
*
722 TestingProfile::GetExtensionSpecialStoragePolicy() {
723 #if defined(ENABLE_EXTENSIONS)
724 if (!extension_special_storage_policy_
.get())
725 extension_special_storage_policy_
= new ExtensionSpecialStoragePolicy(NULL
);
726 return extension_special_storage_policy_
.get();
732 net::CookieMonster
* TestingProfile::GetCookieMonster() {
733 if (!GetRequestContext())
735 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
739 void TestingProfile::CreateTestingPrefService() {
740 DCHECK(!prefs_
.get());
741 testing_prefs_
= new TestingPrefServiceSyncable();
742 prefs_
.reset(testing_prefs_
);
743 user_prefs::UserPrefs::Set(this, prefs_
.get());
744 chrome::RegisterUserProfilePrefs(testing_prefs_
->registry());
747 void TestingProfile::CreateIncognitoPrefService() {
748 DCHECK(original_profile_
);
749 DCHECK(!testing_prefs_
);
750 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
751 // leaves testing_prefs_ unset.
752 prefs_
.reset(original_profile_
->prefs_
->CreateIncognitoPrefService(NULL
));
753 user_prefs::UserPrefs::Set(this, prefs_
.get());
756 void TestingProfile::CreateProfilePolicyConnector() {
757 #if defined(ENABLE_CONFIGURATION_POLICY)
758 schema_registry_service_
=
759 policy::SchemaRegistryServiceFactory::CreateForContext(
760 this, policy::Schema(), NULL
);
761 CHECK_EQ(schema_registry_service_
.get(),
762 policy::SchemaRegistryServiceFactory::GetForContext(this));
763 #endif // defined(ENABLE_CONFIGURATION_POLICY)
765 if (!policy_service_
) {
766 #if defined(ENABLE_CONFIGURATION_POLICY)
767 std::vector
<policy::ConfigurationPolicyProvider
*> providers
;
768 policy_service_
.reset(new policy::PolicyServiceImpl(providers
));
770 policy_service_
.reset(new policy::PolicyServiceStub());
773 profile_policy_connector_
.reset(new policy::ProfilePolicyConnector());
774 profile_policy_connector_
->InitForTesting(policy_service_
.Pass());
775 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
776 this, profile_policy_connector_
.get());
777 CHECK_EQ(profile_policy_connector_
.get(),
778 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(this));
781 PrefService
* TestingProfile::GetPrefs() {
786 const PrefService
* TestingProfile::GetPrefs() const {
791 chrome::ChromeZoomLevelPrefs
* TestingProfile::GetZoomLevelPrefs() {
792 return static_cast<chrome::ChromeZoomLevelPrefs
*>(
793 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
796 DownloadManagerDelegate
* TestingProfile::GetDownloadManagerDelegate() {
800 net::URLRequestContextGetter
* TestingProfile::GetRequestContext() {
801 return GetDefaultStoragePartition(this)->GetURLRequestContext();
804 net::URLRequestContextGetter
* TestingProfile::CreateRequestContext(
805 content::ProtocolHandlerMap
* protocol_handlers
,
806 content::URLRequestInterceptorScopedVector request_interceptors
) {
807 return new net::TestURLRequestContextGetter(
808 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
811 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForRenderProcess(
812 int renderer_child_id
) {
813 content::RenderProcessHost
* rph
= content::RenderProcessHost::FromID(
815 return rph
->GetStoragePartition()->GetURLRequestContext();
818 net::URLRequestContextGetter
* TestingProfile::GetMediaRequestContext() {
822 net::URLRequestContextGetter
*
823 TestingProfile::GetMediaRequestContextForRenderProcess(
824 int renderer_child_id
) {
828 net::URLRequestContextGetter
*
829 TestingProfile::GetMediaRequestContextForStoragePartition(
830 const base::FilePath
& partition_path
,
835 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForExtensions() {
836 if (!extensions_request_context_
.get())
837 extensions_request_context_
= new TestExtensionURLRequestContextGetter();
838 return extensions_request_context_
.get();
841 net::SSLConfigService
* TestingProfile::GetSSLConfigService() {
842 if (!GetRequestContext())
844 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
847 net::URLRequestContextGetter
*
848 TestingProfile::CreateRequestContextForStoragePartition(
849 const base::FilePath
& partition_path
,
851 content::ProtocolHandlerMap
* protocol_handlers
,
852 content::URLRequestInterceptorScopedVector request_interceptors
) {
853 // We don't test storage partitions here yet, so returning the same dummy
854 // context is sufficient for now.
855 return GetRequestContext();
858 content::ResourceContext
* TestingProfile::GetResourceContext() {
859 if (!resource_context_
)
860 resource_context_
= new content::MockResourceContext();
861 return resource_context_
;
864 HostContentSettingsMap
* TestingProfile::GetHostContentSettingsMap() {
865 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
866 if (!host_content_settings_map_
.get()) {
867 host_content_settings_map_
= new HostContentSettingsMap(GetPrefs(), false);
868 #if defined(ENABLE_EXTENSIONS)
869 ExtensionService
* extension_service
=
870 extensions::ExtensionSystem::Get(this)->extension_service();
871 if (extension_service
) {
872 extension_service
->RegisterContentSettings(
873 host_content_settings_map_
.get());
877 return host_content_settings_map_
.get();
880 content::BrowserPluginGuestManager
* TestingProfile::GetGuestManager() {
881 #if defined(ENABLE_EXTENSIONS)
882 return guest_view::GuestViewManager::FromBrowserContext(this);
888 content::PushMessagingService
* TestingProfile::GetPushMessagingService() {
892 bool TestingProfile::IsSameProfile(Profile
*p
) {
896 base::Time
TestingProfile::GetStartTime() const {
900 base::FilePath
TestingProfile::last_selected_directory() {
901 return last_selected_directory_
;
904 void TestingProfile::set_last_selected_directory(const base::FilePath
& path
) {
905 last_selected_directory_
= path
;
908 PrefProxyConfigTracker
* TestingProfile::GetProxyConfigTracker() {
909 if (!pref_proxy_config_tracker_
.get()) {
910 // TestingProfile is used in unit tests, where local state is not available.
911 pref_proxy_config_tracker_
.reset(
912 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
915 return pref_proxy_config_tracker_
.get();
918 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
919 history::HistoryService
* history_service
=
920 HistoryServiceFactory::GetForProfile(this,
921 ServiceAccessType::EXPLICIT_ACCESS
);
922 DCHECK(history_service
);
923 DCHECK(base::MessageLoop::current());
925 base::CancelableTaskTracker tracker
;
926 history_service
->ScheduleDBTask(
927 scoped_ptr
<history::HistoryDBTask
>(
928 new QuittingHistoryDBTask()),
930 base::MessageLoop::current()->Run();
933 chrome_browser_net::Predictor
* TestingProfile::GetNetworkPredictor() {
937 DevToolsNetworkController
* TestingProfile::GetDevToolsNetworkController() {
941 void TestingProfile::ClearNetworkingHistorySince(
943 const base::Closure
& completion
) {
944 if (!completion
.is_null()) {
945 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, completion
);
949 GURL
TestingProfile::GetHomePage() {
950 return GURL(chrome::kChromeUINewTabURL
);
953 PrefService
* TestingProfile::GetOffTheRecordPrefs() {
957 storage::SpecialStoragePolicy
* TestingProfile::GetSpecialStoragePolicy() {
958 #if defined(ENABLE_EXTENSIONS)
959 return GetExtensionSpecialStoragePolicy();
965 content::SSLHostStateDelegate
* TestingProfile::GetSSLHostStateDelegate() {
969 content::PermissionManager
* TestingProfile::GetPermissionManager() {
973 bool TestingProfile::WasCreatedByVersionOrLater(const std::string
& version
) {
977 bool TestingProfile::IsGuestSession() const {
978 return guest_session_
;
981 Profile::ExitType
TestingProfile::GetLastSessionExitType() {
982 return last_session_exited_cleanly_
? EXIT_NORMAL
: EXIT_CRASHED
;
985 TestingProfile::Builder::Builder()
986 : build_called_(false),
988 guest_session_(false) {
991 TestingProfile::Builder::~Builder() {
994 void TestingProfile::Builder::SetPath(const base::FilePath
& path
) {
998 void TestingProfile::Builder::SetDelegate(Delegate
* delegate
) {
999 delegate_
= delegate
;
1002 #if defined(ENABLE_EXTENSIONS)
1003 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
1004 scoped_refptr
<ExtensionSpecialStoragePolicy
> policy
) {
1005 extension_policy_
= policy
;
1009 void TestingProfile::Builder::SetPrefService(
1010 scoped_ptr
<PrefServiceSyncable
> prefs
) {
1011 pref_service_
= prefs
.Pass();
1014 void TestingProfile::Builder::SetGuestSession() {
1015 guest_session_
= true;
1018 void TestingProfile::Builder::SetSupervisedUserId(
1019 const std::string
& supervised_user_id
) {
1020 supervised_user_id_
= supervised_user_id
;
1023 void TestingProfile::Builder::SetPolicyService(
1024 scoped_ptr
<policy::PolicyService
> policy_service
) {
1025 policy_service_
= policy_service
.Pass();
1028 void TestingProfile::Builder::AddTestingFactory(
1029 BrowserContextKeyedServiceFactory
* service_factory
,
1030 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback
) {
1031 testing_factories_
.push_back(std::make_pair(service_factory
, callback
));
1034 scoped_ptr
<TestingProfile
> TestingProfile::Builder::Build() {
1035 DCHECK(!build_called_
);
1036 build_called_
= true;
1038 return scoped_ptr
<TestingProfile
>(new TestingProfile(path_
,
1040 #if defined(ENABLE_EXTENSIONS)
1043 pref_service_
.Pass(),
1046 supervised_user_id_
,
1047 policy_service_
.Pass(),
1048 testing_factories_
));
1051 TestingProfile
* TestingProfile::Builder::BuildIncognito(
1052 TestingProfile
* original_profile
) {
1053 DCHECK(!build_called_
);
1054 DCHECK(original_profile
);
1055 build_called_
= true;
1057 // Note: Owned by |original_profile|.
1058 return new TestingProfile(path_
,
1060 #if defined(ENABLE_EXTENSIONS)
1063 pref_service_
.Pass(),
1066 supervised_user_id_
,
1067 policy_service_
.Pass(),
1068 testing_factories_
);