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/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/proxy_config/pref_proxy_config_tracker.h"
69 #include "components/ui/zoom/zoom_event_manager.h"
70 #include "components/user_prefs/user_prefs.h"
71 #include "components/webdata_services/web_data_service_wrapper.h"
72 #include "content/public/browser/browser_thread.h"
73 #include "content/public/browser/cookie_store_factory.h"
74 #include "content/public/browser/notification_service.h"
75 #include "content/public/browser/render_process_host.h"
76 #include "content/public/browser/storage_partition.h"
77 #include "content/public/browser/zoom_level_delegate.h"
78 #include "content/public/test/mock_resource_context.h"
79 #include "content/public/test/test_utils.h"
80 #include "extensions/common/constants.h"
81 #include "net/cookies/cookie_monster.h"
82 #include "net/url_request/url_request_context.h"
83 #include "net/url_request/url_request_context_getter.h"
84 #include "net/url_request/url_request_test_util.h"
85 #include "testing/gmock/include/gmock/gmock.h"
87 #if defined(ENABLE_CONFIGURATION_POLICY)
88 #include "chrome/browser/policy/schema_registry_service.h"
89 #include "chrome/browser/policy/schema_registry_service_factory.h"
90 #include "components/policy/core/common/configuration_policy_provider.h"
91 #include "components/policy/core/common/policy_service_impl.h"
92 #include "components/policy/core/common/schema.h"
94 #include "components/policy/core/common/policy_service_stub.h"
95 #endif // defined(ENABLE_CONFIGURATION_POLICY)
97 #if defined(ENABLE_EXTENSIONS)
98 #include "chrome/browser/extensions/extension_service.h"
99 #include "chrome/browser/extensions/extension_special_storage_policy.h"
100 #include "chrome/browser/extensions/extension_system_factory.h"
101 #include "chrome/browser/extensions/test_extension_system.h"
102 #include "components/guest_view/browser/guest_view_manager.h"
103 #include "extensions/browser/event_router_factory.h"
104 #include "extensions/browser/extension_pref_value_map.h"
105 #include "extensions/browser/extension_pref_value_map_factory.h"
106 #include "extensions/browser/extension_prefs.h"
107 #include "extensions/browser/extension_prefs_factory.h"
108 #include "extensions/browser/extension_prefs_observer.h"
109 #include "extensions/browser/extension_system.h"
112 #if defined(OS_ANDROID)
113 #include "chrome/browser/signin/oauth2_token_service_delegate_android.h"
116 #if defined(ENABLE_SUPERVISED_USERS)
117 #include "chrome/browser/supervised_user/supervised_user_constants.h"
118 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
119 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
123 using bookmarks::BookmarkModel
;
124 using content::BrowserThread
;
125 using content::DownloadManagerDelegate
;
126 using testing::NiceMock
;
127 using testing::Return
;
131 // Task used to make sure history has finished processing a request. Intended
132 // for use with BlockUntilHistoryProcessesPendingRequests.
134 class QuittingHistoryDBTask
: public history::HistoryDBTask
{
136 QuittingHistoryDBTask() {}
138 bool RunOnDBThread(history::HistoryBackend
* backend
,
139 history::HistoryDatabase
* db
) override
{
143 void DoneRunOnMainThread() override
{ base::MessageLoop::current()->Quit(); }
146 ~QuittingHistoryDBTask() override
{}
148 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask
);
151 class TestExtensionURLRequestContext
: public net::URLRequestContext
{
153 TestExtensionURLRequestContext() {
154 net::CookieMonster
* cookie_monster
=
155 content::CreateCookieStore(content::CookieStoreConfig())->
157 const char* const schemes
[] = {extensions::kExtensionScheme
};
158 cookie_monster
->SetCookieableSchemes(schemes
, arraysize(schemes
));
159 set_cookie_store(cookie_monster
);
162 ~TestExtensionURLRequestContext() override
{ AssertNoURLRequests(); }
165 class TestExtensionURLRequestContextGetter
166 : public net::URLRequestContextGetter
{
168 net::URLRequestContext
* GetURLRequestContext() override
{
170 context_
.reset(new TestExtensionURLRequestContext());
171 return context_
.get();
173 scoped_refptr
<base::SingleThreadTaskRunner
> GetNetworkTaskRunner()
175 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
179 ~TestExtensionURLRequestContextGetter() override
{}
182 scoped_ptr
<net::URLRequestContext
> context_
;
185 scoped_ptr
<KeyedService
> BuildHistoryService(content::BrowserContext
* context
) {
186 Profile
* profile
= Profile::FromBrowserContext(context
);
187 return make_scoped_ptr(new history::HistoryService(
188 make_scoped_ptr(new ChromeHistoryClient(
189 BookmarkModelFactory::GetForProfile(profile
))),
190 make_scoped_ptr(new history::ContentVisitDelegate(profile
))));
193 scoped_ptr
<KeyedService
> BuildInMemoryURLIndex(
194 content::BrowserContext
* context
) {
195 Profile
* profile
= Profile::FromBrowserContext(context
);
196 scoped_ptr
<InMemoryURLIndex
> in_memory_url_index(new InMemoryURLIndex(
197 BookmarkModelFactory::GetForProfile(profile
),
198 HistoryServiceFactory::GetForProfile(profile
,
199 ServiceAccessType::IMPLICIT_ACCESS
),
200 content::BrowserThread::GetBlockingPool(), profile
->GetPath(),
201 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
),
203 in_memory_url_index
->Init();
204 return in_memory_url_index
.Pass();
207 scoped_ptr
<KeyedService
> BuildBookmarkModel(content::BrowserContext
* context
) {
208 Profile
* profile
= Profile::FromBrowserContext(context
);
209 ChromeBookmarkClient
* bookmark_client
=
210 ChromeBookmarkClientFactory::GetForProfile(profile
);
211 scoped_ptr
<BookmarkModel
> bookmark_model(new BookmarkModel(bookmark_client
));
212 bookmark_client
->Init(bookmark_model
.get());
213 bookmark_model
->Load(profile
->GetPrefs(),
214 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
),
216 profile
->GetIOTaskRunner(),
217 content::BrowserThread::GetMessageLoopProxyForThread(
218 content::BrowserThread::UI
));
219 return bookmark_model
.Pass();
222 void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type
,
223 sql::InitStatus status
) {
227 scoped_ptr
<KeyedService
> BuildWebDataService(content::BrowserContext
* context
) {
228 const base::FilePath
& context_path
= context
->GetPath();
229 return make_scoped_ptr(new WebDataServiceWrapper(
230 context_path
, g_browser_process
->GetApplicationLocale(),
231 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI
),
232 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB
),
233 sync_start_util::GetFlareForSyncableService(context_path
),
234 &TestProfileErrorCallback
));
240 #if defined(OS_CHROMEOS)
241 // Must be kept in sync with
242 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
243 const char TestingProfile::kTestUserProfileDir
[] = "test-user";
245 const char TestingProfile::kTestUserProfileDir
[] = "Default";
248 TestingProfile::TestingProfile()
249 : start_time_(Time::Now()),
250 testing_prefs_(NULL
),
251 force_incognito_(false),
252 original_profile_(NULL
),
253 guest_session_(false),
254 last_session_exited_cleanly_(true),
255 browser_context_dependency_manager_(
256 BrowserContextDependencyManager::GetInstance()),
257 resource_context_(NULL
),
259 CreateTempProfileDir();
260 profile_path_
= temp_dir_
.path();
266 TestingProfile::TestingProfile(const base::FilePath
& path
)
267 : start_time_(Time::Now()),
268 testing_prefs_(NULL
),
269 force_incognito_(false),
270 original_profile_(NULL
),
271 guest_session_(false),
272 last_session_exited_cleanly_(true),
274 browser_context_dependency_manager_(
275 BrowserContextDependencyManager::GetInstance()),
276 resource_context_(NULL
),
282 TestingProfile::TestingProfile(const base::FilePath
& path
,
284 : start_time_(Time::Now()),
285 testing_prefs_(NULL
),
286 force_incognito_(false),
287 original_profile_(NULL
),
288 guest_session_(false),
289 last_session_exited_cleanly_(true),
291 browser_context_dependency_manager_(
292 BrowserContextDependencyManager::GetInstance()),
293 resource_context_(NULL
),
294 delegate_(delegate
) {
297 base::ThreadTaskRunnerHandle::Get()->PostTask(
299 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
305 TestingProfile::TestingProfile(
306 const base::FilePath
& path
,
308 #if defined(ENABLE_EXTENSIONS)
309 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy
,
311 scoped_ptr
<PrefServiceSyncable
> prefs
,
312 TestingProfile
* parent
,
314 const std::string
& supervised_user_id
,
315 scoped_ptr
<policy::PolicyService
> policy_service
,
316 const TestingFactories
& factories
)
317 : start_time_(Time::Now()),
318 prefs_(prefs
.release()),
319 testing_prefs_(NULL
),
320 force_incognito_(false),
321 original_profile_(parent
),
322 guest_session_(guest_session
),
323 last_session_exited_cleanly_(true),
324 #if defined(ENABLE_EXTENSIONS)
325 extension_special_storage_policy_(extension_policy
),
328 browser_context_dependency_manager_(
329 BrowserContextDependencyManager::GetInstance()),
330 resource_context_(NULL
),
332 policy_service_(policy_service
.release()) {
334 parent
->SetOffTheRecordProfile(scoped_ptr
<Profile
>(this));
336 // If no profile path was supplied, create one.
337 if (profile_path_
.empty()) {
338 CreateTempProfileDir();
339 profile_path_
= temp_dir_
.path();
342 // Set any testing factories prior to initializing the services.
343 for (TestingFactories::const_iterator it
= factories
.begin();
344 it
!= factories
.end(); ++it
) {
345 it
->first
->SetTestingFactory(this, it
->second
);
349 // If caller supplied a delegate, delay the FinishInit invocation until other
351 // TODO(atwilson): See if this is still required once we convert the current
352 // users of the constructor that takes a Delegate* param.
354 base::ThreadTaskRunnerHandle::Get()->PostTask(
356 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
361 SetSupervisedUserId(supervised_user_id
);
364 void TestingProfile::CreateTempProfileDir() {
365 if (!temp_dir_
.CreateUniqueTempDir()) {
366 LOG(ERROR
) << "Failed to create unique temporary directory.";
368 // Fallback logic in case we fail to create unique temporary directory.
369 base::FilePath system_tmp_dir
;
370 bool success
= PathService::Get(base::DIR_TEMP
, &system_tmp_dir
);
372 // We're severly screwed if we can't get the system temporary
373 // directory. Die now to avoid writing to the filesystem root
374 // or other bad places.
377 base::FilePath
fallback_dir(
378 system_tmp_dir
.AppendASCII("TestingProfilePath"));
379 base::DeleteFile(fallback_dir
, true);
380 base::CreateDirectory(fallback_dir
);
381 if (!temp_dir_
.Set(fallback_dir
)) {
382 // That shouldn't happen, but if it does, try to recover.
383 LOG(ERROR
) << "Failed to use a fallback temporary directory.";
385 // We're screwed if this fails, see CHECK above.
386 CHECK(temp_dir_
.Set(system_tmp_dir
));
391 void TestingProfile::Init() {
392 // If threads have been initialized, we should be on the UI thread.
393 DCHECK(!content::BrowserThread::IsThreadInitialized(
394 content::BrowserThread::UI
) ||
395 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
397 set_is_guest_profile(guest_session_
);
399 #if defined(OS_ANDROID)
400 // Make sure token service knows its running in tests.
401 OAuth2TokenServiceDelegateAndroid::set_is_testing_profile();
404 // Normally this would happen during browser startup, but for tests
405 // we need to trigger creation of Profile-related services.
406 ChromeBrowserMainExtraPartsProfiles::
407 EnsureBrowserContextKeyedServiceFactoriesBuilt();
410 user_prefs::UserPrefs::Set(this, prefs_
.get());
411 else if (IsOffTheRecord())
412 CreateIncognitoPrefService();
414 CreateTestingPrefService();
416 if (!base::PathExists(profile_path_
))
417 base::CreateDirectory(profile_path_
);
419 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
420 // anymore, after converting the PrefService to a PKS. Until then it must
421 // be associated with a TestingProfile too.
422 if (!IsOffTheRecord())
423 CreateProfilePolicyConnector();
425 extensions_path_
= profile_path_
.AppendASCII("Extensions");
427 #if defined(ENABLE_EXTENSIONS)
428 // Note that the GetPrefs() creates a TestingPrefService, therefore
429 // the extension controlled pref values set in ExtensionPrefs
430 // are not reflected in the pref service. One would need to
431 // inject a new ExtensionPrefStore(extension_pref_value_map, false).
432 bool extensions_disabled
= base::CommandLine::ForCurrentProcess()->HasSwitch(
433 switches::kDisableExtensions
);
434 scoped_ptr
<extensions::ExtensionPrefs
> extension_prefs(
435 extensions::ExtensionPrefs::Create(
436 this, GetPrefs(), extensions_path_
,
437 ExtensionPrefValueMapFactory::GetForBrowserContext(this),
439 std::vector
<extensions::ExtensionPrefsObserver
*>()));
440 extensions::ExtensionPrefsFactory::GetInstance()->SetInstanceForTesting(
441 this, extension_prefs
.Pass());
443 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
444 this, extensions::TestExtensionSystem::Build
);
446 extensions::EventRouterFactory::GetInstance()->SetTestingFactory(this,
450 // Prefs for incognito profiles are set in CreateIncognitoPrefService() by
451 // simulating ProfileImpl::GetOffTheRecordPrefs().
452 if (!IsOffTheRecord()) {
453 DCHECK(!original_profile_
);
454 user_prefs::PrefRegistrySyncable
* pref_registry
=
455 static_cast<user_prefs::PrefRegistrySyncable
*>(
456 prefs_
->DeprecatedGetPrefRegistry());
457 browser_context_dependency_manager_
->
458 RegisterProfilePrefsForServices(this, pref_registry
);
461 browser_context_dependency_manager_
->CreateBrowserContextServicesForTest(
464 #if defined(ENABLE_SUPERVISED_USERS)
465 if (!IsOffTheRecord()) {
466 SupervisedUserSettingsService
* settings_service
=
467 SupervisedUserSettingsServiceFactory::GetForProfile(this);
468 TestingPrefStore
* store
= new TestingPrefStore();
469 settings_service
->Init(store
);
470 store
->SetInitializationCompleted();
474 profile_name_
= "testing_profile";
477 void TestingProfile::FinishInit() {
478 DCHECK(content::NotificationService::current());
479 content::NotificationService::current()->Notify(
480 chrome::NOTIFICATION_PROFILE_CREATED
,
481 content::Source
<Profile
>(static_cast<Profile
*>(this)),
482 content::NotificationService::NoDetails());
484 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
486 profile_manager
->InitProfileUserPrefs(this);
489 delegate_
->OnProfileCreated(this, true, false);
492 TestingProfile::~TestingProfile() {
493 // Revert to non-incognito mode before shutdown.
494 force_incognito_
= false;
496 // If this profile owns an incognito profile, tear it down first.
497 incognito_profile_
.reset();
499 // Any objects holding live URLFetchers should be deleted before teardown.
500 TemplateURLFetcherFactory::ShutdownForProfile(this);
502 MaybeSendDestroyedNotification();
504 browser_context_dependency_manager_
->DestroyBrowserContextServices(this);
506 if (host_content_settings_map_
.get())
507 host_content_settings_map_
->ShutdownOnUIThread();
509 if (pref_proxy_config_tracker_
.get())
510 pref_proxy_config_tracker_
->DetachFromPrefService();
511 // Failing a post == leaks == heapcheck failure. Make that an immediate test
513 if (resource_context_
) {
514 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO
, FROM_HERE
,
516 resource_context_
= NULL
;
517 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
521 void TestingProfile::CreateFaviconService() {
522 // It is up to the caller to create the history service if one is needed.
523 FaviconServiceFactory::GetInstance()->SetTestingFactory(
524 this, FaviconServiceFactory::GetDefaultFactory());
527 bool TestingProfile::CreateHistoryService(bool delete_file
, bool no_db
) {
528 DestroyHistoryService();
530 base::FilePath path
= GetPath();
531 path
= path
.Append(history::kHistoryFilename
);
532 if (!base::DeleteFile(path
, false) || base::PathExists(path
))
535 // This will create and init the history service.
536 history::HistoryService
* history_service
=
537 static_cast<history::HistoryService
*>(
538 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
539 this, BuildHistoryService
));
540 if (!history_service
->Init(
541 no_db
, GetPrefs()->GetString(prefs::kAcceptLanguages
),
542 history::HistoryDatabaseParamsForPath(GetPath()))) {
543 HistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
546 // Some tests expect that CreateHistoryService() will also make the
547 // InMemoryURLIndex available.
548 InMemoryURLIndexFactory::GetInstance()->SetTestingFactory(
549 this, BuildInMemoryURLIndex
);
550 // Disable WebHistoryService by default, since it makes network requests.
551 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
555 void TestingProfile::DestroyHistoryService() {
556 history::HistoryService
* history_service
=
557 HistoryServiceFactory::GetForProfileWithoutCreating(this);
558 if (!history_service
)
561 history_service
->ClearCachedDataForContextID(0);
562 history_service
->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
563 history_service
->Cleanup();
564 HistoryServiceFactory::ShutdownForProfile(this);
566 // Wait for the backend class to terminate before deleting the files and
567 // moving to the next test. Note: if this never terminates, somebody is
568 // probably leaking a reference to the history backend, so it never calls
570 base::MessageLoop::current()->Run();
572 // Make sure we don't have any event pending that could disrupt the next
574 base::ThreadTaskRunnerHandle::Get()->PostTask(
575 FROM_HERE
, base::MessageLoop::QuitClosure());
576 base::MessageLoop::current()->Run();
579 void TestingProfile::CreateBookmarkModel(bool delete_file
) {
581 base::FilePath path
= GetPath().Append(bookmarks::kBookmarksFileName
);
582 base::DeleteFile(path
, false);
584 ManagedBookmarkServiceFactory::GetInstance()->SetTestingFactory(
585 this, ManagedBookmarkServiceFactory::GetDefaultFactory());
586 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
587 this, ChromeBookmarkClientFactory::GetDefaultFactory());
588 // This creates the BookmarkModel.
589 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
590 this, BuildBookmarkModel
));
593 void TestingProfile::CreateWebDataService() {
594 WebDataServiceFactory::GetInstance()->SetTestingFactory(
595 this, BuildWebDataService
);
598 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
599 // Only get the history service if it actually exists since the caller of the
600 // test should explicitly call CreateHistoryService to build it.
601 history::HistoryService
* history_service
=
602 HistoryServiceFactory::GetForProfileWithoutCreating(this);
603 DCHECK(history_service
);
604 InMemoryURLIndex
* index
= InMemoryURLIndexFactory::GetForProfile(this);
605 if (!index
|| index
->restored())
607 base::RunLoop run_loop
;
608 HistoryIndexRestoreObserver
observer(
609 content::GetQuitTaskForRunLoop(&run_loop
));
610 index
->set_restore_cache_observer(&observer
);
612 index
->set_restore_cache_observer(NULL
);
613 DCHECK(index
->restored());
616 void TestingProfile::SetGuestSession(bool guest
) {
617 guest_session_
= guest
;
620 base::FilePath
TestingProfile::GetPath() const {
621 return profile_path_
;
624 scoped_ptr
<content::ZoomLevelDelegate
> TestingProfile::CreateZoomLevelDelegate(
625 const base::FilePath
& partition_path
) {
626 return make_scoped_ptr(new ChromeZoomLevelPrefs(
627 GetPrefs(), GetPath(), partition_path
,
628 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
631 scoped_refptr
<base::SequencedTaskRunner
> TestingProfile::GetIOTaskRunner() {
632 return base::MessageLoop::current()->task_runner();
635 TestingPrefServiceSyncable
* TestingProfile::GetTestingPrefService() {
637 DCHECK(testing_prefs_
);
638 return testing_prefs_
;
641 TestingProfile
* TestingProfile::AsTestingProfile() {
645 std::string
TestingProfile::GetProfileUserName() const {
646 return profile_name_
;
649 Profile::ProfileType
TestingProfile::GetProfileType() const {
651 return GUEST_PROFILE
;
652 if (force_incognito_
|| original_profile_
)
653 return INCOGNITO_PROFILE
;
654 return REGULAR_PROFILE
;
657 bool TestingProfile::IsOffTheRecord() const {
658 return force_incognito_
|| original_profile_
;
661 void TestingProfile::SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
) {
662 DCHECK(!IsOffTheRecord());
663 DCHECK_EQ(this, profile
->GetOriginalProfile());
664 incognito_profile_
= profile
.Pass();
667 Profile
* TestingProfile::GetOffTheRecordProfile() {
668 if (IsOffTheRecord())
670 if (!incognito_profile_
)
671 TestingProfile::Builder().BuildIncognito(this);
672 return incognito_profile_
.get();
675 bool TestingProfile::HasOffTheRecordProfile() {
676 return incognito_profile_
.get() != NULL
;
679 Profile
* TestingProfile::GetOriginalProfile() {
680 if (original_profile_
)
681 return original_profile_
;
685 void TestingProfile::SetSupervisedUserId(const std::string
& id
) {
686 supervised_user_id_
= id
;
688 GetPrefs()->SetString(prefs::kSupervisedUserId
, id
);
690 GetPrefs()->ClearPref(prefs::kSupervisedUserId
);
693 bool TestingProfile::IsSupervised() const {
694 return !supervised_user_id_
.empty();
697 bool TestingProfile::IsChild() const {
698 #if defined(ENABLE_SUPERVISED_USERS)
699 return supervised_user_id_
== supervised_users::kChildAccountSUID
;
705 bool TestingProfile::IsLegacySupervised() const {
706 return IsSupervised() && !IsChild();
709 #if defined(ENABLE_EXTENSIONS)
710 void TestingProfile::SetExtensionSpecialStoragePolicy(
711 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
) {
712 extension_special_storage_policy_
= extension_special_storage_policy
;
716 ExtensionSpecialStoragePolicy
*
717 TestingProfile::GetExtensionSpecialStoragePolicy() {
718 #if defined(ENABLE_EXTENSIONS)
719 if (!extension_special_storage_policy_
.get())
720 extension_special_storage_policy_
= new ExtensionSpecialStoragePolicy(NULL
);
721 return extension_special_storage_policy_
.get();
727 net::CookieMonster
* TestingProfile::GetCookieMonster() {
728 if (!GetRequestContext())
730 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
734 void TestingProfile::CreateTestingPrefService() {
735 DCHECK(!prefs_
.get());
736 testing_prefs_
= new TestingPrefServiceSyncable();
737 prefs_
.reset(testing_prefs_
);
738 user_prefs::UserPrefs::Set(this, prefs_
.get());
739 chrome::RegisterUserProfilePrefs(testing_prefs_
->registry());
742 void TestingProfile::CreateIncognitoPrefService() {
743 DCHECK(original_profile_
);
744 DCHECK(!testing_prefs_
);
745 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
746 // leaves testing_prefs_ unset.
747 prefs_
.reset(original_profile_
->prefs_
->CreateIncognitoPrefService(NULL
));
748 user_prefs::UserPrefs::Set(this, prefs_
.get());
751 void TestingProfile::CreateProfilePolicyConnector() {
752 #if defined(ENABLE_CONFIGURATION_POLICY)
753 schema_registry_service_
=
754 policy::SchemaRegistryServiceFactory::CreateForContext(
755 this, policy::Schema(), NULL
);
756 CHECK_EQ(schema_registry_service_
.get(),
757 policy::SchemaRegistryServiceFactory::GetForContext(this));
758 #endif // defined(ENABLE_CONFIGURATION_POLICY)
760 if (!policy_service_
) {
761 #if defined(ENABLE_CONFIGURATION_POLICY)
762 std::vector
<policy::ConfigurationPolicyProvider
*> providers
;
763 policy_service_
.reset(new policy::PolicyServiceImpl(providers
));
765 policy_service_
.reset(new policy::PolicyServiceStub());
768 profile_policy_connector_
.reset(new policy::ProfilePolicyConnector());
769 profile_policy_connector_
->InitForTesting(policy_service_
.Pass());
770 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
771 this, profile_policy_connector_
.get());
772 CHECK_EQ(profile_policy_connector_
.get(),
773 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(this));
776 PrefService
* TestingProfile::GetPrefs() {
781 const PrefService
* TestingProfile::GetPrefs() const {
786 ChromeZoomLevelPrefs
* TestingProfile::GetZoomLevelPrefs() {
787 return static_cast<ChromeZoomLevelPrefs
*>(
788 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
791 DownloadManagerDelegate
* TestingProfile::GetDownloadManagerDelegate() {
795 net::URLRequestContextGetter
* TestingProfile::GetRequestContext() {
796 return GetDefaultStoragePartition(this)->GetURLRequestContext();
799 net::URLRequestContextGetter
* TestingProfile::CreateRequestContext(
800 content::ProtocolHandlerMap
* protocol_handlers
,
801 content::URLRequestInterceptorScopedVector request_interceptors
) {
802 return new net::TestURLRequestContextGetter(
803 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
806 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForRenderProcess(
807 int renderer_child_id
) {
808 content::RenderProcessHost
* rph
= content::RenderProcessHost::FromID(
810 return rph
->GetStoragePartition()->GetURLRequestContext();
813 net::URLRequestContextGetter
* TestingProfile::GetMediaRequestContext() {
817 net::URLRequestContextGetter
*
818 TestingProfile::GetMediaRequestContextForRenderProcess(
819 int renderer_child_id
) {
823 net::URLRequestContextGetter
*
824 TestingProfile::GetMediaRequestContextForStoragePartition(
825 const base::FilePath
& partition_path
,
830 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForExtensions() {
831 if (!extensions_request_context_
.get())
832 extensions_request_context_
= new TestExtensionURLRequestContextGetter();
833 return extensions_request_context_
.get();
836 net::SSLConfigService
* TestingProfile::GetSSLConfigService() {
837 if (!GetRequestContext())
839 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
842 net::URLRequestContextGetter
*
843 TestingProfile::CreateRequestContextForStoragePartition(
844 const base::FilePath
& partition_path
,
846 content::ProtocolHandlerMap
* protocol_handlers
,
847 content::URLRequestInterceptorScopedVector request_interceptors
) {
848 // We don't test storage partitions here yet, so returning the same dummy
849 // context is sufficient for now.
850 return GetRequestContext();
853 content::ResourceContext
* TestingProfile::GetResourceContext() {
854 if (!resource_context_
)
855 resource_context_
= new content::MockResourceContext();
856 return resource_context_
;
859 HostContentSettingsMap
* TestingProfile::GetHostContentSettingsMap() {
860 // TODO(peconn): Get rid of this function
861 // Don't forget to remove the #include "host_content_settings_map_factory"!
862 return HostContentSettingsMapFactory::GetForProfile(this);
865 content::BrowserPluginGuestManager
* TestingProfile::GetGuestManager() {
866 #if defined(ENABLE_EXTENSIONS)
867 return guest_view::GuestViewManager::FromBrowserContext(this);
873 content::PushMessagingService
* TestingProfile::GetPushMessagingService() {
877 bool TestingProfile::IsSameProfile(Profile
*p
) {
881 base::Time
TestingProfile::GetStartTime() const {
885 base::FilePath
TestingProfile::last_selected_directory() {
886 return last_selected_directory_
;
889 void TestingProfile::set_last_selected_directory(const base::FilePath
& path
) {
890 last_selected_directory_
= path
;
893 PrefProxyConfigTracker
* TestingProfile::GetProxyConfigTracker() {
894 if (!pref_proxy_config_tracker_
.get()) {
895 // TestingProfile is used in unit tests, where local state is not available.
896 pref_proxy_config_tracker_
.reset(
897 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
900 return pref_proxy_config_tracker_
.get();
903 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
904 history::HistoryService
* history_service
=
905 HistoryServiceFactory::GetForProfile(this,
906 ServiceAccessType::EXPLICIT_ACCESS
);
907 DCHECK(history_service
);
908 DCHECK(base::MessageLoop::current());
910 base::CancelableTaskTracker tracker
;
911 history_service
->ScheduleDBTask(
912 scoped_ptr
<history::HistoryDBTask
>(
913 new QuittingHistoryDBTask()),
915 base::MessageLoop::current()->Run();
918 chrome_browser_net::Predictor
* TestingProfile::GetNetworkPredictor() {
922 DevToolsNetworkControllerHandle
*
923 TestingProfile::GetDevToolsNetworkControllerHandle() {
927 void TestingProfile::ClearNetworkingHistorySince(
929 const base::Closure
& completion
) {
930 if (!completion
.is_null()) {
931 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, completion
);
935 GURL
TestingProfile::GetHomePage() {
936 return GURL(chrome::kChromeUINewTabURL
);
939 PrefService
* TestingProfile::GetOffTheRecordPrefs() {
943 storage::SpecialStoragePolicy
* TestingProfile::GetSpecialStoragePolicy() {
944 #if defined(ENABLE_EXTENSIONS)
945 return GetExtensionSpecialStoragePolicy();
951 content::SSLHostStateDelegate
* TestingProfile::GetSSLHostStateDelegate() {
955 content::PermissionManager
* TestingProfile::GetPermissionManager() {
959 bool TestingProfile::WasCreatedByVersionOrLater(const std::string
& version
) {
963 bool TestingProfile::IsGuestSession() const {
964 return guest_session_
;
967 Profile::ExitType
TestingProfile::GetLastSessionExitType() {
968 return last_session_exited_cleanly_
? EXIT_NORMAL
: EXIT_CRASHED
;
971 TestingProfile::Builder::Builder()
972 : build_called_(false),
974 guest_session_(false) {
977 TestingProfile::Builder::~Builder() {
980 void TestingProfile::Builder::SetPath(const base::FilePath
& path
) {
984 void TestingProfile::Builder::SetDelegate(Delegate
* delegate
) {
985 delegate_
= delegate
;
988 #if defined(ENABLE_EXTENSIONS)
989 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
990 scoped_refptr
<ExtensionSpecialStoragePolicy
> policy
) {
991 extension_policy_
= policy
;
995 void TestingProfile::Builder::SetPrefService(
996 scoped_ptr
<PrefServiceSyncable
> prefs
) {
997 pref_service_
= prefs
.Pass();
1000 void TestingProfile::Builder::SetGuestSession() {
1001 guest_session_
= true;
1004 void TestingProfile::Builder::SetSupervisedUserId(
1005 const std::string
& supervised_user_id
) {
1006 supervised_user_id_
= supervised_user_id
;
1009 void TestingProfile::Builder::SetPolicyService(
1010 scoped_ptr
<policy::PolicyService
> policy_service
) {
1011 policy_service_
= policy_service
.Pass();
1014 void TestingProfile::Builder::AddTestingFactory(
1015 BrowserContextKeyedServiceFactory
* service_factory
,
1016 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback
) {
1017 testing_factories_
.push_back(std::make_pair(service_factory
, callback
));
1020 scoped_ptr
<TestingProfile
> TestingProfile::Builder::Build() {
1021 DCHECK(!build_called_
);
1022 build_called_
= true;
1024 return scoped_ptr
<TestingProfile
>(new TestingProfile(path_
,
1026 #if defined(ENABLE_EXTENSIONS)
1029 pref_service_
.Pass(),
1032 supervised_user_id_
,
1033 policy_service_
.Pass(),
1034 testing_factories_
));
1037 TestingProfile
* TestingProfile::Builder::BuildIncognito(
1038 TestingProfile
* original_profile
) {
1039 DCHECK(!build_called_
);
1040 DCHECK(original_profile
);
1041 build_called_
= true;
1043 // Note: Owned by |original_profile|.
1044 return new TestingProfile(path_
,
1046 #if defined(ENABLE_EXTENSIONS)
1049 pref_service_
.Pass(),
1052 supervised_user_id_
,
1053 policy_service_
.Pass(),
1054 testing_factories_
);