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 "build/build_config.h"
9 #include "base/base_paths.h"
10 #include "base/command_line.h"
11 #include "base/file_util.h"
12 #include "base/message_loop/message_loop_proxy.h"
13 #include "base/path_service.h"
14 #include "base/prefs/testing_pref_store.h"
15 #include "base/run_loop.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
18 #include "chrome/browser/bookmarks/bookmark_model.h"
19 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/chrome_notification_types.h"
22 #include "chrome/browser/content_settings/host_content_settings_map.h"
23 #include "chrome/browser/extensions/extension_service.h"
24 #include "chrome/browser/extensions/extension_special_storage_policy.h"
25 #include "chrome/browser/extensions/extension_system_factory.h"
26 #include "chrome/browser/extensions/test_extension_system.h"
27 #include "chrome/browser/favicon/favicon_service.h"
28 #include "chrome/browser/favicon/favicon_service_factory.h"
29 #include "chrome/browser/geolocation/chrome_geolocation_permission_context.h"
30 #include "chrome/browser/geolocation/chrome_geolocation_permission_context_factory.h"
31 #include "chrome/browser/history/history_backend.h"
32 #include "chrome/browser/history/history_db_task.h"
33 #include "chrome/browser/history/history_service.h"
34 #include "chrome/browser/history/history_service_factory.h"
35 #include "chrome/browser/history/shortcuts_backend.h"
36 #include "chrome/browser/history/shortcuts_backend_factory.h"
37 #include "chrome/browser/history/top_sites.h"
38 #include "chrome/browser/history/web_history_service_factory.h"
39 #include "chrome/browser/net/pref_proxy_config_tracker.h"
40 #include "chrome/browser/net/proxy_service_factory.h"
41 #include "chrome/browser/notifications/desktop_notification_service.h"
42 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
43 #include "chrome/browser/policy/profile_policy_connector.h"
44 #include "chrome/browser/policy/profile_policy_connector_factory.h"
45 #include "chrome/browser/prefs/browser_prefs.h"
46 #include "chrome/browser/prefs/pref_service_syncable.h"
47 #include "chrome/browser/prerender/prerender_manager.h"
48 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
49 #include "chrome/browser/profiles/profile_manager.h"
50 #include "chrome/browser/profiles/storage_partition_descriptor.h"
51 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
52 #include "chrome/browser/webdata/web_data_service.h"
53 #include "chrome/browser/webdata/web_data_service_factory.h"
54 #include "chrome/common/chrome_constants.h"
55 #include "chrome/common/chrome_switches.h"
56 #include "chrome/common/pref_names.h"
57 #include "chrome/common/url_constants.h"
58 #include "chrome/test/base/history_index_restore_observer.h"
59 #include "chrome/test/base/testing_pref_service_syncable.h"
60 #include "chrome/test/base/ui_test_utils.h"
61 #include "components/browser_context_keyed_service/browser_context_dependency_manager.h"
62 #include "components/policy/core/common/policy_service.h"
63 #include "components/user_prefs/user_prefs.h"
64 #include "content/public/browser/browser_thread.h"
65 #include "content/public/browser/cookie_store_factory.h"
66 #include "content/public/browser/notification_service.h"
67 #include "content/public/browser/render_process_host.h"
68 #include "content/public/browser/storage_partition.h"
69 #include "content/public/test/mock_resource_context.h"
70 #include "content/public/test/test_utils.h"
71 #include "extensions/browser/extension_system.h"
72 #include "extensions/common/constants.h"
73 #include "net/cookies/cookie_monster.h"
74 #include "net/url_request/url_request_context.h"
75 #include "net/url_request/url_request_context_getter.h"
76 #include "net/url_request/url_request_test_util.h"
77 #include "testing/gmock/include/gmock/gmock.h"
79 #if defined(ENABLE_CONFIGURATION_POLICY)
80 #include "chrome/browser/policy/schema_registry_service.h"
81 #include "chrome/browser/policy/schema_registry_service_factory.h"
82 #include "components/policy/core/common/configuration_policy_provider.h"
83 #include "components/policy/core/common/policy_service_impl.h"
84 #include "components/policy/core/common/schema.h"
86 #include "components/policy/core/common/policy_service_stub.h"
87 #endif // defined(ENABLE_CONFIGURATION_POLICY)
89 #if defined(ENABLE_MANAGED_USERS)
90 #include "chrome/browser/managed_mode/managed_user_settings_service.h"
91 #include "chrome/browser/managed_mode/managed_user_settings_service_factory.h"
95 using content::BrowserThread
;
96 using content::DownloadManagerDelegate
;
97 using testing::NiceMock
;
98 using testing::Return
;
102 // Task used to make sure history has finished processing a request. Intended
103 // for use with BlockUntilHistoryProcessesPendingRequests.
105 class QuittingHistoryDBTask
: public history::HistoryDBTask
{
107 QuittingHistoryDBTask() {}
109 virtual bool RunOnDBThread(history::HistoryBackend
* backend
,
110 history::HistoryDatabase
* db
) OVERRIDE
{
114 virtual void DoneRunOnMainThread() OVERRIDE
{
115 base::MessageLoop::current()->Quit();
119 virtual ~QuittingHistoryDBTask() {}
121 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask
);
124 class TestExtensionURLRequestContext
: public net::URLRequestContext
{
126 TestExtensionURLRequestContext() {
127 net::CookieMonster
* cookie_monster
=
128 content::CreateCookieStore(content::CookieStoreConfig())->
130 const char* schemes
[] = {extensions::kExtensionScheme
};
131 cookie_monster
->SetCookieableSchemes(schemes
, 1);
132 set_cookie_store(cookie_monster
);
135 virtual ~TestExtensionURLRequestContext() {}
138 class TestExtensionURLRequestContextGetter
139 : public net::URLRequestContextGetter
{
141 virtual net::URLRequestContext
* GetURLRequestContext() OVERRIDE
{
143 context_
.reset(new TestExtensionURLRequestContext());
144 return context_
.get();
146 virtual scoped_refptr
<base::SingleThreadTaskRunner
>
147 GetNetworkTaskRunner() const OVERRIDE
{
148 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
152 virtual ~TestExtensionURLRequestContextGetter() {}
155 scoped_ptr
<net::URLRequestContext
> context_
;
158 #if defined(ENABLE_NOTIFICATIONS)
159 BrowserContextKeyedService
* CreateTestDesktopNotificationService(
160 content::BrowserContext
* profile
) {
161 return new DesktopNotificationService(static_cast<Profile
*>(profile
), NULL
);
168 #if defined(OS_CHROMEOS)
169 // Must be kept in sync with
170 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
171 const char TestingProfile::kTestUserProfileDir
[] = "test-user";
173 const char TestingProfile::kTestUserProfileDir
[] = "Default";
176 TestingProfile::TestingProfile()
177 : start_time_(Time::Now()),
178 testing_prefs_(NULL
),
180 force_incognito_(false),
181 original_profile_(NULL
),
182 guest_session_(false),
183 last_session_exited_cleanly_(true),
184 browser_context_dependency_manager_(
185 BrowserContextDependencyManager::GetInstance()),
186 resource_context_(NULL
),
188 CreateTempProfileDir();
189 profile_path_
= temp_dir_
.path();
195 TestingProfile::TestingProfile(const base::FilePath
& path
)
196 : start_time_(Time::Now()),
197 testing_prefs_(NULL
),
199 force_incognito_(false),
200 original_profile_(NULL
),
201 guest_session_(false),
202 last_session_exited_cleanly_(true),
204 browser_context_dependency_manager_(
205 BrowserContextDependencyManager::GetInstance()),
206 resource_context_(NULL
),
212 TestingProfile::TestingProfile(const base::FilePath
& path
,
214 : start_time_(Time::Now()),
215 testing_prefs_(NULL
),
217 force_incognito_(false),
218 original_profile_(NULL
),
219 guest_session_(false),
220 last_session_exited_cleanly_(true),
222 browser_context_dependency_manager_(
223 BrowserContextDependencyManager::GetInstance()),
224 resource_context_(NULL
),
225 delegate_(delegate
) {
228 base::MessageLoop::current()->PostTask(
230 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
236 TestingProfile::TestingProfile(
237 const base::FilePath
& path
,
239 scoped_refptr
<ExtensionSpecialStoragePolicy
> extension_policy
,
240 scoped_ptr
<PrefServiceSyncable
> prefs
,
243 const std::string
& managed_user_id
,
244 scoped_ptr
<policy::PolicyService
> policy_service
,
245 const TestingFactories
& factories
)
246 : start_time_(Time::Now()),
247 prefs_(prefs
.release()),
248 testing_prefs_(NULL
),
249 incognito_(incognito
),
250 force_incognito_(false),
251 original_profile_(NULL
),
252 guest_session_(guest_session
),
253 managed_user_id_(managed_user_id
),
254 last_session_exited_cleanly_(true),
255 extension_special_storage_policy_(extension_policy
),
257 browser_context_dependency_manager_(
258 BrowserContextDependencyManager::GetInstance()),
259 resource_context_(NULL
),
261 policy_service_(policy_service
.release()) {
263 // If no profile path was supplied, create one.
264 if (profile_path_
.empty()) {
265 CreateTempProfileDir();
266 profile_path_
= temp_dir_
.path();
269 // Set any testing factories prior to initializing the services.
270 for (TestingFactories::const_iterator it
= factories
.begin();
271 it
!= factories
.end(); ++it
) {
272 it
->first
->SetTestingFactory(this, it
->second
);
276 // If caller supplied a delegate, delay the FinishInit invocation until other
278 // TODO(atwilson): See if this is still required once we convert the current
279 // users of the constructor that takes a Delegate* param.
281 base::MessageLoop::current()->PostTask(
283 base::Bind(&TestingProfile::FinishInit
, base::Unretained(this)));
289 void TestingProfile::CreateTempProfileDir() {
290 if (!temp_dir_
.CreateUniqueTempDir()) {
291 LOG(ERROR
) << "Failed to create unique temporary directory.";
293 // Fallback logic in case we fail to create unique temporary directory.
294 base::FilePath system_tmp_dir
;
295 bool success
= PathService::Get(base::DIR_TEMP
, &system_tmp_dir
);
297 // We're severly screwed if we can't get the system temporary
298 // directory. Die now to avoid writing to the filesystem root
299 // or other bad places.
302 base::FilePath
fallback_dir(
303 system_tmp_dir
.AppendASCII("TestingProfilePath"));
304 base::DeleteFile(fallback_dir
, true);
305 base::CreateDirectory(fallback_dir
);
306 if (!temp_dir_
.Set(fallback_dir
)) {
307 // That shouldn't happen, but if it does, try to recover.
308 LOG(ERROR
) << "Failed to use a fallback temporary directory.";
310 // We're screwed if this fails, see CHECK above.
311 CHECK(temp_dir_
.Set(system_tmp_dir
));
316 void TestingProfile::Init() {
317 // If threads have been initialized, we should be on the UI thread.
318 DCHECK(!content::BrowserThread::IsThreadInitialized(
319 content::BrowserThread::UI
) ||
320 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
322 // Normally this would happen during browser startup, but for tests
323 // we need to trigger creation of Profile-related services.
324 ChromeBrowserMainExtraPartsProfiles::
325 EnsureBrowserContextKeyedServiceFactoriesBuilt();
328 user_prefs::UserPrefs::Set(this, prefs_
.get());
330 CreateTestingPrefService();
332 if (!base::PathExists(profile_path_
))
333 base::CreateDirectory(profile_path_
);
335 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
336 // anymore, after converting the PrefService to a PKS. Until then it must
337 // be associated with a TestingProfile too.
338 if (!IsOffTheRecord())
339 CreateProfilePolicyConnector();
341 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
342 this, extensions::TestExtensionSystem::Build
);
344 // If no original profile was specified for this profile: register preferences
345 // even if this is an incognito profile - this allows tests to create a
346 // standalone incognito profile while still having prefs registered.
347 if (!IsOffTheRecord() || !original_profile_
) {
348 user_prefs::PrefRegistrySyncable
* pref_registry
=
349 static_cast<user_prefs::PrefRegistrySyncable
*>(
350 prefs_
->DeprecatedGetPrefRegistry());
351 browser_context_dependency_manager_
->
352 RegisterProfilePrefsForServices(this, pref_registry
);
355 browser_context_dependency_manager_
->CreateBrowserContextServicesForTest(
358 #if defined(ENABLE_NOTIFICATIONS)
359 // Install profile keyed service factory hooks for dummy/test services
360 DesktopNotificationServiceFactory::GetInstance()->SetTestingFactory(
361 this, CreateTestDesktopNotificationService
);
364 #if defined(ENABLE_MANAGED_USERS)
365 ManagedUserSettingsService
* settings_service
=
366 ManagedUserSettingsServiceFactory::GetForProfile(this);
367 TestingPrefStore
* store
= new TestingPrefStore();
368 settings_service
->Init(store
);
369 store
->SetInitializationCompleted();
372 profile_name_
= "testing_profile";
375 void TestingProfile::FinishInit() {
376 DCHECK(content::NotificationService::current());
377 content::NotificationService::current()->Notify(
378 chrome::NOTIFICATION_PROFILE_CREATED
,
379 content::Source
<Profile
>(static_cast<Profile
*>(this)),
380 content::NotificationService::NoDetails());
382 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
384 profile_manager
->InitProfileUserPrefs(this);
387 delegate_
->OnProfileCreated(this, true, false);
390 TestingProfile::~TestingProfile() {
391 // Revert to non-incognito mode before shutdown.
392 force_incognito_
= false;
394 // Any objects holding live URLFetchers should be deleted before teardown.
395 TemplateURLFetcherFactory::ShutdownForProfile(this);
397 MaybeSendDestroyedNotification();
399 browser_context_dependency_manager_
->DestroyBrowserContextServices(this);
401 if (host_content_settings_map_
.get())
402 host_content_settings_map_
->ShutdownOnUIThread();
406 if (pref_proxy_config_tracker_
.get())
407 pref_proxy_config_tracker_
->DetachFromPrefService();
408 // Failing a post == leaks == heapcheck failure. Make that an immediate test
410 if (resource_context_
) {
411 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO
, FROM_HERE
,
413 resource_context_
= NULL
;
414 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
418 static BrowserContextKeyedService
* BuildFaviconService(
419 content::BrowserContext
* profile
) {
420 return new FaviconService(static_cast<Profile
*>(profile
));
423 void TestingProfile::CreateFaviconService() {
424 // It is up to the caller to create the history service if one is needed.
425 FaviconServiceFactory::GetInstance()->SetTestingFactory(
426 this, BuildFaviconService
);
429 static BrowserContextKeyedService
* BuildHistoryService(
430 content::BrowserContext
* profile
) {
431 return new HistoryService(static_cast<Profile
*>(profile
));
434 bool TestingProfile::CreateHistoryService(bool delete_file
, bool no_db
) {
435 DestroyHistoryService();
437 base::FilePath path
= GetPath();
438 path
= path
.Append(chrome::kHistoryFilename
);
439 if (!base::DeleteFile(path
, false) || base::PathExists(path
))
442 // This will create and init the history service.
443 HistoryService
* history_service
= static_cast<HistoryService
*>(
444 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
445 this, BuildHistoryService
));
446 if (!history_service
->Init(this->GetPath(),
447 BookmarkModelFactory::GetForProfile(this),
449 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(this, NULL
);
451 // Disable WebHistoryService by default, since it makes network requests.
452 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, NULL
);
456 void TestingProfile::DestroyHistoryService() {
457 HistoryService
* history_service
=
458 HistoryServiceFactory::GetForProfileWithoutCreating(this);
459 if (!history_service
)
462 history_service
->NotifyRenderProcessHostDestruction(0);
463 history_service
->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
464 history_service
->Cleanup();
465 HistoryServiceFactory::ShutdownForProfile(this);
467 // Wait for the backend class to terminate before deleting the files and
468 // moving to the next test. Note: if this never terminates, somebody is
469 // probably leaking a reference to the history backend, so it never calls
471 base::MessageLoop::current()->Run();
473 // Make sure we don't have any event pending that could disrupt the next
475 base::MessageLoop::current()->PostTask(FROM_HERE
,
476 base::MessageLoop::QuitClosure());
477 base::MessageLoop::current()->Run();
480 void TestingProfile::CreateTopSites() {
482 top_sites_
= history::TopSites::Create(
483 this, GetPath().Append(chrome::kTopSitesFilename
));
486 void TestingProfile::DestroyTopSites() {
487 if (top_sites_
.get()) {
488 top_sites_
->Shutdown();
490 // TopSitesImpl::Shutdown schedules some tasks (from TopSitesBackend) that
491 // need to be run to properly shutdown. Run all pending tasks now. This is
492 // normally handled by browser_process shutdown.
493 if (base::MessageLoop::current())
494 base::MessageLoop::current()->RunUntilIdle();
498 static BrowserContextKeyedService
* BuildBookmarkModel(
499 content::BrowserContext
* context
) {
500 Profile
* profile
= static_cast<Profile
*>(context
);
501 BookmarkModel
* bookmark_model
= new BookmarkModel(profile
);
502 bookmark_model
->Load(profile
->GetIOTaskRunner());
503 return bookmark_model
;
506 void TestingProfile::CreateBookmarkModel(bool delete_file
) {
508 base::FilePath path
= GetPath().Append(chrome::kBookmarksFileName
);
509 base::DeleteFile(path
, false);
511 // This will create a bookmark model.
512 BookmarkModel
* bookmark_service
= static_cast<BookmarkModel
*>(
513 BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
514 this, BuildBookmarkModel
));
516 HistoryService
* history_service
=
517 HistoryServiceFactory::GetForProfileWithoutCreating(this);
518 if (history_service
) {
519 history_service
->history_backend_
->bookmark_service_
= bookmark_service
;
520 history_service
->history_backend_
->expirer_
.bookmark_service_
=
525 static BrowserContextKeyedService
* BuildWebDataService(
526 content::BrowserContext
* profile
) {
527 return new WebDataServiceWrapper(static_cast<Profile
*>(profile
));
530 void TestingProfile::CreateWebDataService() {
531 WebDataServiceFactory::GetInstance()->SetTestingFactory(
532 this, BuildWebDataService
);
535 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
536 // Only get the history service if it actually exists since the caller of the
537 // test should explicitly call CreateHistoryService to build it.
538 HistoryService
* history_service
=
539 HistoryServiceFactory::GetForProfileWithoutCreating(this);
540 DCHECK(history_service
);
541 history::InMemoryURLIndex
* index
= history_service
->InMemoryIndex();
542 if (!index
|| index
->restored())
544 base::RunLoop run_loop
;
545 HistoryIndexRestoreObserver
observer(
546 content::GetQuitTaskForRunLoop(&run_loop
));
547 index
->set_restore_cache_observer(&observer
);
549 index
->set_restore_cache_observer(NULL
);
550 DCHECK(index
->restored());
553 // TODO(phajdan.jr): Doesn't this hang if Top Sites are already loaded?
554 void TestingProfile::BlockUntilTopSitesLoaded() {
555 content::WindowedNotificationObserver
top_sites_loaded_observer(
556 chrome::NOTIFICATION_TOP_SITES_LOADED
,
557 content::NotificationService::AllSources());
558 top_sites_loaded_observer
.Wait();
561 base::FilePath
TestingProfile::GetPath() const {
562 return profile_path_
;
565 scoped_refptr
<base::SequencedTaskRunner
> TestingProfile::GetIOTaskRunner() {
566 return base::MessageLoop::current()->message_loop_proxy();
569 TestingPrefServiceSyncable
* TestingProfile::GetTestingPrefService() {
571 CreateTestingPrefService();
572 DCHECK(testing_prefs_
);
573 return testing_prefs_
;
576 TestingProfile
* TestingProfile::AsTestingProfile() {
580 std::string
TestingProfile::GetProfileName() {
581 return profile_name_
;
584 bool TestingProfile::IsOffTheRecord() const {
585 return force_incognito_
|| incognito_
;
588 void TestingProfile::SetOffTheRecordProfile(scoped_ptr
<Profile
> profile
) {
589 DCHECK(!IsOffTheRecord());
590 incognito_profile_
= profile
.Pass();
593 void TestingProfile::SetOriginalProfile(Profile
* profile
) {
594 DCHECK(IsOffTheRecord());
595 original_profile_
= profile
;
598 Profile
* TestingProfile::GetOffTheRecordProfile() {
599 if (IsOffTheRecord())
601 return incognito_profile_
.get();
604 bool TestingProfile::HasOffTheRecordProfile() {
605 return incognito_profile_
.get() != NULL
;
608 Profile
* TestingProfile::GetOriginalProfile() {
609 if (original_profile_
)
610 return original_profile_
;
614 bool TestingProfile::IsManaged() {
615 return !managed_user_id_
.empty();
618 ExtensionService
* TestingProfile::GetExtensionService() {
619 return extensions::ExtensionSystem::Get(this)->extension_service();
622 void TestingProfile::SetExtensionSpecialStoragePolicy(
623 ExtensionSpecialStoragePolicy
* extension_special_storage_policy
) {
624 extension_special_storage_policy_
= extension_special_storage_policy
;
627 ExtensionSpecialStoragePolicy
*
628 TestingProfile::GetExtensionSpecialStoragePolicy() {
629 if (!extension_special_storage_policy_
.get())
630 extension_special_storage_policy_
= new ExtensionSpecialStoragePolicy(NULL
);
631 return extension_special_storage_policy_
.get();
634 net::CookieMonster
* TestingProfile::GetCookieMonster() {
635 if (!GetRequestContext())
637 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
641 void TestingProfile::CreateTestingPrefService() {
642 DCHECK(!prefs_
.get());
643 testing_prefs_
= new TestingPrefServiceSyncable();
644 prefs_
.reset(testing_prefs_
);
645 user_prefs::UserPrefs::Set(this, prefs_
.get());
646 chrome::RegisterUserProfilePrefs(testing_prefs_
->registry());
649 void TestingProfile::CreateProfilePolicyConnector() {
650 #if defined(ENABLE_CONFIGURATION_POLICY)
651 schema_registry_service_
=
652 policy::SchemaRegistryServiceFactory::CreateForContext(
653 this, policy::Schema(), NULL
);
654 CHECK_EQ(schema_registry_service_
.get(),
655 policy::SchemaRegistryServiceFactory::GetForContext(this));
656 #endif // defined(ENABLE_CONFIGURATION_POLICY)
658 if (!policy_service_
) {
659 #if defined(ENABLE_CONFIGURATION_POLICY)
660 std::vector
<policy::ConfigurationPolicyProvider
*> providers
;
661 policy_service_
.reset(new policy::PolicyServiceImpl(providers
));
663 policy_service_
.reset(new policy::PolicyServiceStub());
666 profile_policy_connector_
.reset(new policy::ProfilePolicyConnector());
667 profile_policy_connector_
->InitForTesting(policy_service_
.Pass());
668 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
669 this, profile_policy_connector_
.get());
670 CHECK_EQ(profile_policy_connector_
.get(),
671 policy::ProfilePolicyConnectorFactory::GetForProfile(this));
674 PrefService
* TestingProfile::GetPrefs() {
676 CreateTestingPrefService();
681 history::TopSites
* TestingProfile::GetTopSites() {
682 return top_sites_
.get();
685 history::TopSites
* TestingProfile::GetTopSitesWithoutCreating() {
686 return top_sites_
.get();
689 DownloadManagerDelegate
* TestingProfile::GetDownloadManagerDelegate() {
693 net::URLRequestContextGetter
* TestingProfile::GetRequestContext() {
694 return GetDefaultStoragePartition(this)->GetURLRequestContext();
697 net::URLRequestContextGetter
* TestingProfile::CreateRequestContext(
698 content::ProtocolHandlerMap
* protocol_handlers
) {
699 return new net::TestURLRequestContextGetter(
700 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
703 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForRenderProcess(
704 int renderer_child_id
) {
705 content::RenderProcessHost
* rph
= content::RenderProcessHost::FromID(
707 return rph
->GetStoragePartition()->GetURLRequestContext();
710 net::URLRequestContextGetter
* TestingProfile::GetMediaRequestContext() {
714 net::URLRequestContextGetter
*
715 TestingProfile::GetMediaRequestContextForRenderProcess(
716 int renderer_child_id
) {
720 net::URLRequestContextGetter
*
721 TestingProfile::GetMediaRequestContextForStoragePartition(
722 const base::FilePath
& partition_path
,
727 void TestingProfile::RequestMidiSysExPermission(
728 int render_process_id
,
731 const GURL
& requesting_frame
,
732 const MidiSysExPermissionCallback
& callback
) {
733 // Always reject requests for testing.
737 void TestingProfile::CancelMidiSysExPermissionRequest(
738 int render_process_id
,
741 const GURL
& requesting_frame
) {
744 void TestingProfile::RequestProtectedMediaIdentifierPermission(
745 int render_process_id
,
749 const GURL
& requesting_frame
,
750 const ProtectedMediaIdentifierPermissionCallback
& callback
) {
751 // Always reject requests for testing.
755 void TestingProfile::CancelProtectedMediaIdentifierPermissionRequests(
759 net::URLRequestContextGetter
* TestingProfile::GetRequestContextForExtensions() {
760 if (!extensions_request_context_
.get())
761 extensions_request_context_
= new TestExtensionURLRequestContextGetter();
762 return extensions_request_context_
.get();
765 net::SSLConfigService
* TestingProfile::GetSSLConfigService() {
766 if (!GetRequestContext())
768 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
771 net::URLRequestContextGetter
*
772 TestingProfile::CreateRequestContextForStoragePartition(
773 const base::FilePath
& partition_path
,
775 content::ProtocolHandlerMap
* protocol_handlers
) {
776 // We don't test storage partitions here yet, so returning the same dummy
777 // context is sufficient for now.
778 return GetRequestContext();
781 content::ResourceContext
* TestingProfile::GetResourceContext() {
782 if (!resource_context_
)
783 resource_context_
= new content::MockResourceContext();
784 return resource_context_
;
787 HostContentSettingsMap
* TestingProfile::GetHostContentSettingsMap() {
788 if (!host_content_settings_map_
.get()) {
789 host_content_settings_map_
= new HostContentSettingsMap(GetPrefs(), false);
790 #if defined(ENABLE_EXTENSIONS)
791 ExtensionService
* extension_service
= GetExtensionService();
792 if (extension_service
)
793 host_content_settings_map_
->RegisterExtensionService(extension_service
);
796 return host_content_settings_map_
.get();
799 content::GeolocationPermissionContext
*
800 TestingProfile::GetGeolocationPermissionContext() {
801 return ChromeGeolocationPermissionContextFactory::GetForProfile(this);
804 std::wstring
TestingProfile::GetName() {
805 return std::wstring();
808 std::wstring
TestingProfile::GetID() {
812 void TestingProfile::SetID(const std::wstring
& id
) {
816 bool TestingProfile::IsSameProfile(Profile
*p
) {
820 base::Time
TestingProfile::GetStartTime() const {
824 base::FilePath
TestingProfile::last_selected_directory() {
825 return last_selected_directory_
;
828 void TestingProfile::set_last_selected_directory(const base::FilePath
& path
) {
829 last_selected_directory_
= path
;
832 PrefProxyConfigTracker
* TestingProfile::GetProxyConfigTracker() {
833 if (!pref_proxy_config_tracker_
.get()) {
834 // TestingProfile is used in unit tests, where local state is not available.
835 pref_proxy_config_tracker_
.reset(
836 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
839 return pref_proxy_config_tracker_
.get();
842 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
843 HistoryService
* history_service
=
844 HistoryServiceFactory::GetForProfile(this, Profile::EXPLICIT_ACCESS
);
845 DCHECK(history_service
);
846 DCHECK(base::MessageLoop::current());
848 CancelableRequestConsumer consumer
;
849 history_service
->ScheduleDBTask(new QuittingHistoryDBTask(), &consumer
);
850 base::MessageLoop::current()->Run();
853 chrome_browser_net::Predictor
* TestingProfile::GetNetworkPredictor() {
857 void TestingProfile::ClearNetworkingHistorySince(
859 const base::Closure
& completion
) {
860 if (!completion
.is_null()) {
861 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, completion
);
865 GURL
TestingProfile::GetHomePage() {
866 return GURL(chrome::kChromeUINewTabURL
);
869 PrefService
* TestingProfile::GetOffTheRecordPrefs() {
873 quota::SpecialStoragePolicy
* TestingProfile::GetSpecialStoragePolicy() {
874 return GetExtensionSpecialStoragePolicy();
877 bool TestingProfile::WasCreatedByVersionOrLater(const std::string
& version
) {
881 bool TestingProfile::IsGuestSession() const {
882 return guest_session_
;
885 Profile::ExitType
TestingProfile::GetLastSessionExitType() {
886 return last_session_exited_cleanly_
? EXIT_NORMAL
: EXIT_CRASHED
;
889 TestingProfile::Builder::Builder()
890 : build_called_(false),
893 guest_session_(false) {
896 TestingProfile::Builder::~Builder() {
899 void TestingProfile::Builder::SetPath(const base::FilePath
& path
) {
903 void TestingProfile::Builder::SetDelegate(Delegate
* delegate
) {
904 delegate_
= delegate
;
907 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
908 scoped_refptr
<ExtensionSpecialStoragePolicy
> policy
) {
909 extension_policy_
= policy
;
912 void TestingProfile::Builder::SetPrefService(
913 scoped_ptr
<PrefServiceSyncable
> prefs
) {
914 pref_service_
= prefs
.Pass();
917 void TestingProfile::Builder::SetIncognito() {
921 void TestingProfile::Builder::SetGuestSession() {
922 guest_session_
= true;
925 void TestingProfile::Builder::SetManagedUserId(
926 const std::string
& managed_user_id
) {
927 managed_user_id_
= managed_user_id
;
930 void TestingProfile::Builder::SetPolicyService(
931 scoped_ptr
<policy::PolicyService
> policy_service
) {
932 policy_service_
= policy_service
.Pass();
935 void TestingProfile::Builder::AddTestingFactory(
936 BrowserContextKeyedServiceFactory
* service_factory
,
937 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback
) {
938 testing_factories_
.push_back(std::make_pair(service_factory
, callback
));
941 scoped_ptr
<TestingProfile
> TestingProfile::Builder::Build() {
942 DCHECK(!build_called_
);
943 build_called_
= true;
945 return scoped_ptr
<TestingProfile
>(new TestingProfile(
949 pref_service_
.Pass(),
953 policy_service_
.Pass(),
954 testing_factories_
));