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/event_router_factory.h"
104 #include "extensions/browser/extension_prefs.h"
105 #include "extensions/browser/extension_prefs_factory.h"
106 #include "extensions/browser/extension_system.h"
109 #if defined(OS_ANDROID)
110 #include "chrome/browser/signin/android_profile_oauth2_token_service.h"
113 #if defined(ENABLE_SUPERVISED_USERS)
114 #include "chrome/browser/supervised_user/supervised_user_constants.h"
115 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
116 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
120 using bookmarks::BookmarkModel
;
121 using content::BrowserThread
;
122 using content::DownloadManagerDelegate
;
123 using testing::NiceMock
;
124 using testing::Return
;
128 // Task used to make sure history has finished processing a request. Intended
129 // for use with BlockUntilHistoryProcessesPendingRequests.
131 class QuittingHistoryDBTask
: public history::HistoryDBTask
{
133 QuittingHistoryDBTask() {}
135 bool RunOnDBThread(history::HistoryBackend
* backend
,
136 history::HistoryDatabase
* db
) override
{
140 void DoneRunOnMainThread() override
{ base::MessageLoop::current()->Quit(); }
143 ~QuittingHistoryDBTask() override
{}
145 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask
);
148 class TestExtensionURLRequestContext
: public net::URLRequestContext
{
150 TestExtensionURLRequestContext() {
151 net::CookieMonster
* cookie_monster
=
152 content::CreateCookieStore(content::CookieStoreConfig())->
154 const char* const schemes
[] = {extensions::kExtensionScheme
};
155 cookie_monster
->SetCookieableSchemes(schemes
, arraysize(schemes
));
156 set_cookie_store(cookie_monster
);
159 ~TestExtensionURLRequestContext() override
{ AssertNoURLRequests(); }
162 class TestExtensionURLRequestContextGetter
163 : public net::URLRequestContextGetter
{
165 net::URLRequestContext
* GetURLRequestContext() override
{
167 context_
.reset(new TestExtensionURLRequestContext());
168 return context_
.get();
170 scoped_refptr
<base::SingleThreadTaskRunner
> GetNetworkTaskRunner()
172 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
176 ~TestExtensionURLRequestContextGetter() override
{}
179 scoped_ptr
<net::URLRequestContext
> context_
;
182 #if defined(ENABLE_NOTIFICATIONS)
183 scoped_ptr
<KeyedService
> CreateTestDesktopNotificationService(
184 content::BrowserContext
* profile
) {
185 return make_scoped_ptr(
186 new DesktopNotificationService(static_cast<Profile
*>(profile
)));
190 scoped_ptr
<KeyedService
> BuildFaviconService(content::BrowserContext
* context
) {
191 Profile
* profile
= Profile::FromBrowserContext(context
);
192 return make_scoped_ptr(new favicon::FaviconService(
193 ChromeFaviconClientFactory::GetForProfile(profile
),
194 HistoryServiceFactory::GetForProfile(
195 profile
, ServiceAccessType::EXPLICIT_ACCESS
)));
198 scoped_ptr
<KeyedService
> BuildHistoryService(content::BrowserContext
* context
) {
199 Profile
* profile
= Profile::FromBrowserContext(context
);
200 return make_scoped_ptr(new history::HistoryService(
201 ChromeHistoryClientFactory::GetForProfile(profile
),
202 scoped_ptr
<history::VisitDelegate
>(
203 new history::ContentVisitDelegate(profile
))));
206 scoped_ptr
<KeyedService
> BuildInMemoryURLIndex(
207 content::BrowserContext
* context
) {
208 Profile
* profile
= Profile::FromBrowserContext(context
);
209 scoped_ptr
<InMemoryURLIndex
> in_memory_url_index(new InMemoryURLIndex(
210 BookmarkModelFactory::GetForProfile(profile
),
211 HistoryServiceFactory::GetForProfile(profile
,
212 ServiceAccessType::IMPLICIT_ACCESS
),
214 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
)));
215 in_memory_url_index
->Init();
216 return in_memory_url_index
.Pass();
219 scoped_ptr
<KeyedService
> BuildBookmarkModel(content::BrowserContext
* context
) {
220 Profile
* profile
= static_cast<Profile
*>(context
);
221 ChromeBookmarkClient
* bookmark_client
=
222 ChromeBookmarkClientFactory::GetForProfile(profile
);
223 scoped_ptr
<BookmarkModel
> bookmark_model(new BookmarkModel(bookmark_client
));
224 bookmark_client
->Init(bookmark_model
.get());
225 bookmark_model
->Load(profile
->GetPrefs(),
226 profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
),
228 profile
->GetIOTaskRunner(),
229 content::BrowserThread::GetMessageLoopProxyForThread(
230 content::BrowserThread::UI
));
231 return bookmark_model
.Pass();
234 scoped_ptr
<KeyedService
> BuildChromeBookmarkClient(
235 content::BrowserContext
* context
) {
236 return make_scoped_ptr(
237 new ChromeBookmarkClient(static_cast<Profile
*>(context
)));
240 scoped_ptr
<KeyedService
> BuildChromeHistoryClient(
241 content::BrowserContext
* context
) {
242 Profile
* profile
= static_cast<Profile
*>(context
);
243 return make_scoped_ptr(
244 new ChromeHistoryClient(BookmarkModelFactory::GetForProfile(profile
)));
247 void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type
,
248 sql::InitStatus status
) {
252 scoped_ptr
<KeyedService
> BuildWebDataService(content::BrowserContext
* context
) {
253 const base::FilePath
& context_path
= context
->GetPath();
254 return make_scoped_ptr(new WebDataServiceWrapper(
255 context_path
, g_browser_process
->GetApplicationLocale(),
256 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI
),
257 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB
),
258 sync_start_util::GetFlareForSyncableService(context_path
),
259 &TestProfileErrorCallback
));
265 #if defined(OS_CHROMEOS)
266 // Must be kept in sync with
267 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
268 const char TestingProfile::kTestUserProfileDir
[] = "test-user";
270 const char TestingProfile::kTestUserProfileDir
[] = "Default";
273 TestingProfile::TestingProfile()
274 : start_time_(Time::Now()),
275 testing_prefs_(NULL
),
276 force_incognito_(false),
277 original_profile_(NULL
),
278 guest_session_(false),
279 last_session_exited_cleanly_(true),
280 browser_context_dependency_manager_(
281 BrowserContextDependencyManager::GetInstance()),
282 resource_context_(NULL
),
284 CreateTempProfileDir();
285 profile_path_
= temp_dir_
.path();
291 TestingProfile::TestingProfile(const base::FilePath
& path
)
292 : start_time_(Time::Now()),
293 testing_prefs_(NULL
),
294 force_incognito_(false),
295 original_profile_(NULL
),
296 guest_session_(false),
297 last_session_exited_cleanly_(true),
299 browser_context_dependency_manager_(
300 BrowserContextDependencyManager::GetInstance()),
301 resource_context_(NULL
),
307 TestingProfile::TestingProfile(const base::FilePath
& path
,
309 : start_time_(Time::Now()),
310 testing_prefs_(NULL
),
311 force_incognito_(false),
312 original_profile_(NULL
),
313 guest_session_(false),
314 last_session_exited_cleanly_(true),
316 browser_context_dependency_manager_(
317 BrowserContextDependencyManager::GetInstance()),
318 resource_context_(NULL
),
319 delegate_(delegate
) {
322 base::MessageLoop::current()->PostTask(
324 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
330 TestingProfile::TestingProfile(
331 const base::FilePath
& path
,
333 #if defined(ENABLE_EXTENSIONS)
334 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy
,
336 scoped_ptr
<PrefServiceSyncable
> prefs
,
337 TestingProfile
* parent
,
339 const std::string
& supervised_user_id
,
340 scoped_ptr
<policy::PolicyService
> policy_service
,
341 const TestingFactories
& factories
)
342 : start_time_(Time::Now()),
343 prefs_(prefs
.release()),
344 testing_prefs_(NULL
),
345 force_incognito_(false),
346 original_profile_(parent
),
347 guest_session_(guest_session
),
348 last_session_exited_cleanly_(true),
349 #if defined(ENABLE_EXTENSIONS)
350 extension_special_storage_policy_(extension_policy
),
353 browser_context_dependency_manager_(
354 BrowserContextDependencyManager::GetInstance()),
355 resource_context_(NULL
),
357 policy_service_(policy_service
.release()) {
359 parent
->SetOffTheRecordProfile(scoped_ptr
<Profile
>(this));
361 // If no profile path was supplied, create one.
362 if (profile_path_
.empty()) {
363 CreateTempProfileDir();
364 profile_path_
= temp_dir_
.path();
367 // Set any testing factories prior to initializing the services.
368 for (TestingFactories::const_iterator it
= factories
.begin();
369 it
!= factories
.end(); ++it
) {
370 it
->first
->SetTestingFactory(this, it
->second
);
374 // If caller supplied a delegate, delay the FinishInit invocation until other
376 // TODO(atwilson): See if this is still required once we convert the current
377 // users of the constructor that takes a Delegate* param.
379 base::MessageLoop::current()->PostTask(
381 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
386 SetSupervisedUserId(supervised_user_id
);
389 void TestingProfile::CreateTempProfileDir() {
390 if (!temp_dir_
.CreateUniqueTempDir()) {
391 LOG(ERROR
) << "Failed to create unique temporary directory.";
393 // Fallback logic in case we fail to create unique temporary directory.
394 base::FilePath system_tmp_dir
;
395 bool success
= PathService::Get(base::DIR_TEMP
, &system_tmp_dir
);
397 // We're severly screwed if we can't get the system temporary
398 // directory. Die now to avoid writing to the filesystem root
399 // or other bad places.
402 base::FilePath
fallback_dir(
403 system_tmp_dir
.AppendASCII("TestingProfilePath"));
404 base::DeleteFile(fallback_dir
, true);
405 base::CreateDirectory(fallback_dir
);
406 if (!temp_dir_
.Set(fallback_dir
)) {
407 // That shouldn't happen, but if it does, try to recover.
408 LOG(ERROR
) << "Failed to use a fallback temporary directory.";
410 // We're screwed if this fails, see CHECK above.
411 CHECK(temp_dir_
.Set(system_tmp_dir
));
416 void TestingProfile::Init() {
417 // If threads have been initialized, we should be on the UI thread.
418 DCHECK(!content::BrowserThread::IsThreadInitialized(
419 content::BrowserThread::UI
) ||
420 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
422 set_is_guest_profile(guest_session_
);
424 #if defined(OS_ANDROID)
425 // Make sure token service knows its running in tests.
426 AndroidProfileOAuth2TokenService::set_is_testing_profile();
429 // Normally this would happen during browser startup, but for tests
430 // we need to trigger creation of Profile-related services.
431 ChromeBrowserMainExtraPartsProfiles::
432 EnsureBrowserContextKeyedServiceFactoriesBuilt();
435 user_prefs::UserPrefs::Set(this, prefs_
.get());
436 else if (IsOffTheRecord())
437 CreateIncognitoPrefService();
439 CreateTestingPrefService();
441 if (!base::PathExists(profile_path_
))
442 base::CreateDirectory(profile_path_
);
444 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
445 // anymore, after converting the PrefService to a PKS. Until then it must
446 // be associated with a TestingProfile too.
447 if (!IsOffTheRecord())
448 CreateProfilePolicyConnector();
450 extensions_path_
= profile_path_
.AppendASCII("Extensions");
452 #if defined(ENABLE_EXTENSIONS)
453 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
454 this, extensions::TestExtensionSystem::Build
);
456 extensions::TestExtensionSystem
* test_extension_system
=
457 static_cast<extensions::TestExtensionSystem
*>(
458 extensions::ExtensionSystem::Get(this));
459 scoped_ptr
<extensions::ExtensionPrefs
> extension_prefs
=
460 test_extension_system
->CreateExtensionPrefs(
461 base::CommandLine::ForCurrentProcess(), extensions_path_
);
462 extensions::ExtensionPrefsFactory::GetInstance()->SetInstanceForTesting(
463 this, extension_prefs
.Pass());
465 extensions::EventRouterFactory::GetInstance()->SetTestingFactory(this,
469 // Prefs for incognito profiles are set in CreateIncognitoPrefService() by
470 // simulating ProfileImpl::GetOffTheRecordPrefs().
471 if (!IsOffTheRecord()) {
472 DCHECK(!original_profile_
);
473 user_prefs::PrefRegistrySyncable
* pref_registry
=
474 static_cast<user_prefs::PrefRegistrySyncable
*>(
475 prefs_
->DeprecatedGetPrefRegistry());
476 browser_context_dependency_manager_
->
477 RegisterProfilePrefsForServices(this, pref_registry
);
480 browser_context_dependency_manager_
->CreateBrowserContextServicesForTest(
483 #if defined(ENABLE_NOTIFICATIONS)
484 // Install profile keyed service factory hooks for dummy/test services
485 DesktopNotificationServiceFactory::GetInstance()->SetTestingFactory(
486 this, CreateTestDesktopNotificationService
);
489 #if defined(ENABLE_SUPERVISED_USERS)
490 if (!IsOffTheRecord()) {
491 SupervisedUserSettingsService
* settings_service
=
492 SupervisedUserSettingsServiceFactory::GetForProfile(this);
493 TestingPrefStore
* store
= new TestingPrefStore();
494 settings_service
->Init(store
);
495 store
->SetInitializationCompleted();
499 profile_name_
= "testing_profile";
502 void TestingProfile::FinishInit() {
503 DCHECK(content::NotificationService::current());
504 content::NotificationService::current()->Notify(
505 chrome::NOTIFICATION_PROFILE_CREATED
,
506 content::Source
<Profile
>(static_cast<Profile
*>(this)),
507 content::NotificationService::NoDetails());
509 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
511 profile_manager
->InitProfileUserPrefs(this);
514 delegate_
->OnProfileCreated(this, true, false);
517 TestingProfile::~TestingProfile() {
518 // Revert to non-incognito mode before shutdown.
519 force_incognito_
= false;
521 // If this profile owns an incognito profile, tear it down first.
522 incognito_profile_
.reset();
524 // Any objects holding live URLFetchers should be deleted before teardown.
525 TemplateURLFetcherFactory::ShutdownForProfile(this);
527 MaybeSendDestroyedNotification();
529 browser_context_dependency_manager_
->DestroyBrowserContextServices(this);
531 if (host_content_settings_map_
.get())
532 host_content_settings_map_
->ShutdownOnUIThread();
534 if (pref_proxy_config_tracker_
.get())
535 pref_proxy_config_tracker_
->DetachFromPrefService();
536 // Failing a post == leaks == heapcheck failure. Make that an immediate test
538 if (resource_context_
) {
539 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO
, FROM_HERE
,
541 resource_context_
= NULL
;
542 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
546 void TestingProfile::CreateFaviconService() {
547 // It is up to the caller to create the history service if one is needed.
548 FaviconServiceFactory::GetInstance()->SetTestingFactory(
549 this, BuildFaviconService
);
552 bool TestingProfile::CreateHistoryService(bool delete_file
, bool no_db
) {
553 DestroyHistoryService();
555 base::FilePath path
= GetPath();
556 path
= path
.Append(history::kHistoryFilename
);
557 if (!base::DeleteFile(path
, false) || base::PathExists(path
))
560 // This will create and init the history service.
561 history::HistoryService
* history_service
=
562 static_cast<history::HistoryService
*>(
563 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
564 this, BuildHistoryService
));
565 if (!history_service
->Init(
566 no_db
, GetPrefs()->GetString(prefs::kAcceptLanguages
),
567 history::HistoryDatabaseParamsForPath(GetPath()))) {
568 HistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
571 // Some tests expect that CreateHistoryService() will also make the
572 // InMemoryURLIndex available.
573 InMemoryURLIndexFactory::GetInstance()->SetTestingFactory(
574 this, BuildInMemoryURLIndex
);
575 // Disable WebHistoryService by default, since it makes network requests.
576 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
580 void TestingProfile::DestroyHistoryService() {
581 history::HistoryService
* history_service
=
582 HistoryServiceFactory::GetForProfileWithoutCreating(this);
583 if (!history_service
)
586 history_service
->ClearCachedDataForContextID(0);
587 history_service
->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
588 history_service
->Cleanup();
589 HistoryServiceFactory::ShutdownForProfile(this);
591 // Wait for the backend class to terminate before deleting the files and
592 // moving to the next test. Note: if this never terminates, somebody is
593 // probably leaking a reference to the history backend, so it never calls
595 base::MessageLoop::current()->Run();
597 // Make sure we don't have any event pending that could disrupt the next
599 base::MessageLoop::current()->PostTask(FROM_HERE
,
600 base::MessageLoop::QuitClosure());
601 base::MessageLoop::current()->Run();
604 void TestingProfile::CreateBookmarkModel(bool delete_file
) {
606 base::FilePath path
= GetPath().Append(bookmarks::kBookmarksFileName
);
607 base::DeleteFile(path
, false);
609 ChromeHistoryClientFactory::GetInstance()->SetTestingFactory(
610 this, BuildChromeHistoryClient
);
611 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
612 this, BuildChromeBookmarkClient
);
613 // This creates the BookmarkModel.
614 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
615 this, BuildBookmarkModel
));
618 void TestingProfile::CreateWebDataService() {
619 WebDataServiceFactory::GetInstance()->SetTestingFactory(
620 this, BuildWebDataService
);
623 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
624 // Only get the history service if it actually exists since the caller of the
625 // test should explicitly call CreateHistoryService to build it.
626 history::HistoryService
* history_service
=
627 HistoryServiceFactory::GetForProfileWithoutCreating(this);
628 DCHECK(history_service
);
629 InMemoryURLIndex
* index
= InMemoryURLIndexFactory::GetForProfile(this);
630 if (!index
|| index
->restored())
632 base::RunLoop run_loop
;
633 HistoryIndexRestoreObserver
observer(
634 content::GetQuitTaskForRunLoop(&run_loop
));
635 index
->set_restore_cache_observer(&observer
);
637 index
->set_restore_cache_observer(NULL
);
638 DCHECK(index
->restored());
641 void TestingProfile::SetGuestSession(bool guest
) {
642 guest_session_
= guest
;
645 base::FilePath
TestingProfile::GetPath() const {
646 return profile_path_
;
649 scoped_ptr
<content::ZoomLevelDelegate
> TestingProfile::CreateZoomLevelDelegate(
650 const base::FilePath
& partition_path
) {
651 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
652 GetPrefs(), GetPath(), partition_path
,
653 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
656 scoped_refptr
<base::SequencedTaskRunner
> TestingProfile::GetIOTaskRunner() {
657 return base::MessageLoop::current()->message_loop_proxy();
660 TestingPrefServiceSyncable
* TestingProfile::GetTestingPrefService() {
662 DCHECK(testing_prefs_
);
663 return testing_prefs_
;
666 TestingProfile
* TestingProfile::AsTestingProfile() {
670 std::string
TestingProfile::GetProfileUserName() const {
671 return profile_name_
;
674 Profile::ProfileType
TestingProfile::GetProfileType() const {
676 return GUEST_PROFILE
;
677 if (force_incognito_
|| original_profile_
)
678 return INCOGNITO_PROFILE
;
679 return REGULAR_PROFILE
;
682 bool TestingProfile::IsOffTheRecord() const {
683 return force_incognito_
|| original_profile_
;
686 void TestingProfile::SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
) {
687 DCHECK(!IsOffTheRecord());
688 DCHECK_EQ(this, profile
->GetOriginalProfile());
689 incognito_profile_
= profile
.Pass();
692 Profile
* TestingProfile::GetOffTheRecordProfile() {
693 if (IsOffTheRecord())
695 if (!incognito_profile_
)
696 TestingProfile::Builder().BuildIncognito(this);
697 return incognito_profile_
.get();
700 bool TestingProfile::HasOffTheRecordProfile() {
701 return incognito_profile_
.get() != NULL
;
704 Profile
* TestingProfile::GetOriginalProfile() {
705 if (original_profile_
)
706 return original_profile_
;
710 void TestingProfile::SetSupervisedUserId(const std::string
& id
) {
711 supervised_user_id_
= id
;
713 GetPrefs()->SetString(prefs::kSupervisedUserId
, id
);
715 GetPrefs()->ClearPref(prefs::kSupervisedUserId
);
718 bool TestingProfile::IsSupervised() {
719 return !supervised_user_id_
.empty();
722 bool TestingProfile::IsChild() {
723 #if defined(ENABLE_SUPERVISED_USERS)
724 return supervised_user_id_
== supervised_users::kChildAccountSUID
;
730 bool TestingProfile::IsLegacySupervised() {
731 return IsSupervised() && !IsChild();
734 #if defined(ENABLE_EXTENSIONS)
735 void TestingProfile::SetExtensionSpecialStoragePolicy(
736 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
) {
737 extension_special_storage_policy_
= extension_special_storage_policy
;
741 ExtensionSpecialStoragePolicy
*
742 TestingProfile::GetExtensionSpecialStoragePolicy() {
743 #if defined(ENABLE_EXTENSIONS)
744 if (!extension_special_storage_policy_
.get())
745 extension_special_storage_policy_
= new ExtensionSpecialStoragePolicy(NULL
);
746 return extension_special_storage_policy_
.get();
752 net::CookieMonster
* TestingProfile::GetCookieMonster() {
753 if (!GetRequestContext())
755 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
759 void TestingProfile::CreateTestingPrefService() {
760 DCHECK(!prefs_
.get());
761 testing_prefs_
= new TestingPrefServiceSyncable();
762 prefs_
.reset(testing_prefs_
);
763 user_prefs::UserPrefs::Set(this, prefs_
.get());
764 chrome::RegisterUserProfilePrefs(testing_prefs_
->registry());
767 void TestingProfile::CreateIncognitoPrefService() {
768 DCHECK(original_profile_
);
769 DCHECK(!testing_prefs_
);
770 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
771 // leaves testing_prefs_ unset.
772 prefs_
.reset(original_profile_
->prefs_
->CreateIncognitoPrefService(NULL
));
773 user_prefs::UserPrefs::Set(this, prefs_
.get());
776 void TestingProfile::CreateProfilePolicyConnector() {
777 #if defined(ENABLE_CONFIGURATION_POLICY)
778 schema_registry_service_
=
779 policy::SchemaRegistryServiceFactory::CreateForContext(
780 this, policy::Schema(), NULL
);
781 CHECK_EQ(schema_registry_service_
.get(),
782 policy::SchemaRegistryServiceFactory::GetForContext(this));
783 #endif // defined(ENABLE_CONFIGURATION_POLICY)
785 if (!policy_service_
) {
786 #if defined(ENABLE_CONFIGURATION_POLICY)
787 std::vector
<policy::ConfigurationPolicyProvider
*> providers
;
788 policy_service_
.reset(new policy::PolicyServiceImpl(providers
));
790 policy_service_
.reset(new policy::PolicyServiceStub());
793 profile_policy_connector_
.reset(new policy::ProfilePolicyConnector());
794 profile_policy_connector_
->InitForTesting(policy_service_
.Pass());
795 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
796 this, profile_policy_connector_
.get());
797 CHECK_EQ(profile_policy_connector_
.get(),
798 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(this));
801 PrefService
* TestingProfile::GetPrefs() {
806 const PrefService
* TestingProfile::GetPrefs() const {
811 chrome::ChromeZoomLevelPrefs
* TestingProfile::GetZoomLevelPrefs() {
812 return static_cast<chrome::ChromeZoomLevelPrefs
*>(
813 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
816 DownloadManagerDelegate
* TestingProfile::GetDownloadManagerDelegate() {
820 net::URLRequestContextGetter
* TestingProfile::GetRequestContext() {
821 return GetDefaultStoragePartition(this)->GetURLRequestContext();
824 net::URLRequestContextGetter
* TestingProfile::CreateRequestContext(
825 content::ProtocolHandlerMap
* protocol_handlers
,
826 content::URLRequestInterceptorScopedVector request_interceptors
) {
827 return new net::TestURLRequestContextGetter(
828 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
831 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForRenderProcess(
832 int renderer_child_id
) {
833 content::RenderProcessHost
* rph
= content::RenderProcessHost::FromID(
835 return rph
->GetStoragePartition()->GetURLRequestContext();
838 net::URLRequestContextGetter
* TestingProfile::GetMediaRequestContext() {
842 net::URLRequestContextGetter
*
843 TestingProfile::GetMediaRequestContextForRenderProcess(
844 int renderer_child_id
) {
848 net::URLRequestContextGetter
*
849 TestingProfile::GetMediaRequestContextForStoragePartition(
850 const base::FilePath
& partition_path
,
855 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForExtensions() {
856 if (!extensions_request_context_
.get())
857 extensions_request_context_
= new TestExtensionURLRequestContextGetter();
858 return extensions_request_context_
.get();
861 net::SSLConfigService
* TestingProfile::GetSSLConfigService() {
862 if (!GetRequestContext())
864 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
867 net::URLRequestContextGetter
*
868 TestingProfile::CreateRequestContextForStoragePartition(
869 const base::FilePath
& partition_path
,
871 content::ProtocolHandlerMap
* protocol_handlers
,
872 content::URLRequestInterceptorScopedVector request_interceptors
) {
873 // We don't test storage partitions here yet, so returning the same dummy
874 // context is sufficient for now.
875 return GetRequestContext();
878 content::ResourceContext
* TestingProfile::GetResourceContext() {
879 if (!resource_context_
)
880 resource_context_
= new content::MockResourceContext();
881 return resource_context_
;
884 HostContentSettingsMap
* TestingProfile::GetHostContentSettingsMap() {
885 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
886 if (!host_content_settings_map_
.get()) {
887 host_content_settings_map_
= new HostContentSettingsMap(GetPrefs(), false);
888 #if defined(ENABLE_EXTENSIONS)
889 ExtensionService
* extension_service
=
890 extensions::ExtensionSystem::Get(this)->extension_service();
891 if (extension_service
) {
892 extension_service
->RegisterContentSettings(
893 host_content_settings_map_
.get());
897 return host_content_settings_map_
.get();
900 content::BrowserPluginGuestManager
* TestingProfile::GetGuestManager() {
901 #if defined(ENABLE_EXTENSIONS)
902 return guest_view::GuestViewManager::FromBrowserContext(this);
908 content::PushMessagingService
* TestingProfile::GetPushMessagingService() {
912 bool TestingProfile::IsSameProfile(Profile
*p
) {
916 base::Time
TestingProfile::GetStartTime() const {
920 base::FilePath
TestingProfile::last_selected_directory() {
921 return last_selected_directory_
;
924 void TestingProfile::set_last_selected_directory(const base::FilePath
& path
) {
925 last_selected_directory_
= path
;
928 PrefProxyConfigTracker
* TestingProfile::GetProxyConfigTracker() {
929 if (!pref_proxy_config_tracker_
.get()) {
930 // TestingProfile is used in unit tests, where local state is not available.
931 pref_proxy_config_tracker_
.reset(
932 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
935 return pref_proxy_config_tracker_
.get();
938 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
939 history::HistoryService
* history_service
=
940 HistoryServiceFactory::GetForProfile(this,
941 ServiceAccessType::EXPLICIT_ACCESS
);
942 DCHECK(history_service
);
943 DCHECK(base::MessageLoop::current());
945 base::CancelableTaskTracker tracker
;
946 history_service
->ScheduleDBTask(
947 scoped_ptr
<history::HistoryDBTask
>(
948 new QuittingHistoryDBTask()),
950 base::MessageLoop::current()->Run();
953 chrome_browser_net::Predictor
* TestingProfile::GetNetworkPredictor() {
957 DevToolsNetworkController
* TestingProfile::GetDevToolsNetworkController() {
961 void TestingProfile::ClearNetworkingHistorySince(
963 const base::Closure
& completion
) {
964 if (!completion
.is_null()) {
965 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, completion
);
969 GURL
TestingProfile::GetHomePage() {
970 return GURL(chrome::kChromeUINewTabURL
);
973 PrefService
* TestingProfile::GetOffTheRecordPrefs() {
977 storage::SpecialStoragePolicy
* TestingProfile::GetSpecialStoragePolicy() {
978 #if defined(ENABLE_EXTENSIONS)
979 return GetExtensionSpecialStoragePolicy();
985 content::SSLHostStateDelegate
* TestingProfile::GetSSLHostStateDelegate() {
989 content::PermissionManager
* TestingProfile::GetPermissionManager() {
993 bool TestingProfile::WasCreatedByVersionOrLater(const std::string
& version
) {
997 bool TestingProfile::IsGuestSession() const {
998 return guest_session_
;
1001 Profile::ExitType
TestingProfile::GetLastSessionExitType() {
1002 return last_session_exited_cleanly_
? EXIT_NORMAL
: EXIT_CRASHED
;
1005 TestingProfile::Builder::Builder()
1006 : build_called_(false),
1008 guest_session_(false) {
1011 TestingProfile::Builder::~Builder() {
1014 void TestingProfile::Builder::SetPath(const base::FilePath
& path
) {
1018 void TestingProfile::Builder::SetDelegate(Delegate
* delegate
) {
1019 delegate_
= delegate
;
1022 #if defined(ENABLE_EXTENSIONS)
1023 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
1024 scoped_refptr
<ExtensionSpecialStoragePolicy
> policy
) {
1025 extension_policy_
= policy
;
1029 void TestingProfile::Builder::SetPrefService(
1030 scoped_ptr
<PrefServiceSyncable
> prefs
) {
1031 pref_service_
= prefs
.Pass();
1034 void TestingProfile::Builder::SetGuestSession() {
1035 guest_session_
= true;
1038 void TestingProfile::Builder::SetSupervisedUserId(
1039 const std::string
& supervised_user_id
) {
1040 supervised_user_id_
= supervised_user_id
;
1043 void TestingProfile::Builder::SetPolicyService(
1044 scoped_ptr
<policy::PolicyService
> policy_service
) {
1045 policy_service_
= policy_service
.Pass();
1048 void TestingProfile::Builder::AddTestingFactory(
1049 BrowserContextKeyedServiceFactory
* service_factory
,
1050 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback
) {
1051 testing_factories_
.push_back(std::make_pair(service_factory
, callback
));
1054 scoped_ptr
<TestingProfile
> TestingProfile::Builder::Build() {
1055 DCHECK(!build_called_
);
1056 build_called_
= true;
1058 return scoped_ptr
<TestingProfile
>(new TestingProfile(path_
,
1060 #if defined(ENABLE_EXTENSIONS)
1063 pref_service_
.Pass(),
1066 supervised_user_id_
,
1067 policy_service_
.Pass(),
1068 testing_factories_
));
1071 TestingProfile
* TestingProfile::Builder::BuildIncognito(
1072 TestingProfile
* original_profile
) {
1073 DCHECK(!build_called_
);
1074 DCHECK(original_profile
);
1075 build_called_
= true;
1077 // Note: Owned by |original_profile|.
1078 return new TestingProfile(path_
,
1080 #if defined(ENABLE_EXTENSIONS)
1083 pref_service_
.Pass(),
1086 supervised_user_id_
,
1087 policy_service_
.Pass(),
1088 testing_factories_
);