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_factory.h"
19 #include "chrome/browser/bookmarks/chrome_bookmark_client.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/guest_view/guest_view_manager.h"
32 #include "chrome/browser/history/history_backend.h"
33 #include "chrome/browser/history/history_db_task.h"
34 #include "chrome/browser/history/history_service.h"
35 #include "chrome/browser/history/history_service_factory.h"
36 #include "chrome/browser/history/top_sites.h"
37 #include "chrome/browser/history/web_history_service_factory.h"
38 #include "chrome/browser/net/pref_proxy_config_tracker.h"
39 #include "chrome/browser/net/proxy_service_factory.h"
40 #include "chrome/browser/notifications/desktop_notification_service.h"
41 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
42 #include "chrome/browser/policy/profile_policy_connector.h"
43 #include "chrome/browser/policy/profile_policy_connector_factory.h"
44 #include "chrome/browser/prefs/browser_prefs.h"
45 #include "chrome/browser/prefs/pref_service_syncable.h"
46 #include "chrome/browser/prerender/prerender_manager.h"
47 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
48 #include "chrome/browser/profiles/profile_manager.h"
49 #include "chrome/browser/profiles/storage_partition_descriptor.h"
50 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
51 #include "chrome/browser/webdata/web_data_service.h"
52 #include "chrome/browser/webdata/web_data_service_factory.h"
53 #include "chrome/common/chrome_constants.h"
54 #include "chrome/common/chrome_switches.h"
55 #include "chrome/common/pref_names.h"
56 #include "chrome/common/url_constants.h"
57 #include "chrome/test/base/history_index_restore_observer.h"
58 #include "chrome/test/base/testing_pref_service_syncable.h"
59 #include "chrome/test/base/ui_test_utils.h"
60 #include "components/bookmarks/core/browser/bookmark_model.h"
61 #include "components/bookmarks/core/common/bookmark_constants.h"
62 #include "components/keyed_service/content/browser_context_dependency_manager.h"
63 #include "components/policy/core/common/policy_service.h"
64 #include "components/user_prefs/user_prefs.h"
65 #include "content/public/browser/browser_thread.h"
66 #include "content/public/browser/cookie_store_factory.h"
67 #include "content/public/browser/notification_service.h"
68 #include "content/public/browser/render_process_host.h"
69 #include "content/public/browser/storage_partition.h"
70 #include "content/public/test/mock_resource_context.h"
71 #include "content/public/test/test_utils.h"
72 #include "extensions/browser/extension_system.h"
73 #include "extensions/common/constants.h"
74 #include "net/cookies/cookie_monster.h"
75 #include "net/url_request/url_request_context.h"
76 #include "net/url_request/url_request_context_getter.h"
77 #include "net/url_request/url_request_test_util.h"
78 #include "testing/gmock/include/gmock/gmock.h"
80 #if defined(ENABLE_CONFIGURATION_POLICY)
81 #include "chrome/browser/policy/schema_registry_service.h"
82 #include "chrome/browser/policy/schema_registry_service_factory.h"
83 #include "components/policy/core/common/configuration_policy_provider.h"
84 #include "components/policy/core/common/policy_service_impl.h"
85 #include "components/policy/core/common/schema.h"
87 #include "components/policy/core/common/policy_service_stub.h"
88 #endif // defined(ENABLE_CONFIGURATION_POLICY)
90 #if defined(ENABLE_MANAGED_USERS)
91 #include "chrome/browser/managed_mode/managed_user_settings_service.h"
92 #include "chrome/browser/managed_mode/managed_user_settings_service_factory.h"
96 using content::BrowserThread;
97 using content::DownloadManagerDelegate;
98 using testing::NiceMock;
99 using testing::Return;
103 // Task used to make sure history has finished processing a request. Intended
104 // for use with BlockUntilHistoryProcessesPendingRequests.
106 class QuittingHistoryDBTask : public history::HistoryDBTask {
108 QuittingHistoryDBTask() {}
110 virtual bool RunOnDBThread(history::HistoryBackend* backend,
111 history::HistoryDatabase* db) OVERRIDE {
115 virtual void DoneRunOnMainThread() OVERRIDE {
116 base::MessageLoop::current()->Quit();
120 virtual ~QuittingHistoryDBTask() {}
122 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
125 class TestExtensionURLRequestContext : public net::URLRequestContext {
127 TestExtensionURLRequestContext() {
128 net::CookieMonster* cookie_monster =
129 content::CreateCookieStore(content::CookieStoreConfig())->
131 const char* schemes[] = {extensions::kExtensionScheme};
132 cookie_monster->SetCookieableSchemes(schemes, 1);
133 set_cookie_store(cookie_monster);
136 virtual ~TestExtensionURLRequestContext() {}
139 class TestExtensionURLRequestContextGetter
140 : public net::URLRequestContextGetter {
142 virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE {
144 context_.reset(new TestExtensionURLRequestContext());
145 return context_.get();
147 virtual scoped_refptr<base::SingleThreadTaskRunner>
148 GetNetworkTaskRunner() const OVERRIDE {
149 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
153 virtual ~TestExtensionURLRequestContextGetter() {}
156 scoped_ptr<net::URLRequestContext> context_;
159 #if defined(ENABLE_NOTIFICATIONS)
160 KeyedService* CreateTestDesktopNotificationService(
161 content::BrowserContext* profile) {
162 return new DesktopNotificationService(static_cast<Profile*>(profile), NULL);
169 #if defined(OS_CHROMEOS)
170 // Must be kept in sync with
171 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
172 const char TestingProfile::kTestUserProfileDir[] = "test-user";
174 const char TestingProfile::kTestUserProfileDir[] = "Default";
177 TestingProfile::TestingProfile()
178 : start_time_(Time::Now()),
179 testing_prefs_(NULL),
181 force_incognito_(false),
182 original_profile_(NULL),
183 guest_session_(false),
184 last_session_exited_cleanly_(true),
185 browser_context_dependency_manager_(
186 BrowserContextDependencyManager::GetInstance()),
187 resource_context_(NULL),
189 CreateTempProfileDir();
190 profile_path_ = temp_dir_.path();
196 TestingProfile::TestingProfile(const base::FilePath& path)
197 : start_time_(Time::Now()),
198 testing_prefs_(NULL),
200 force_incognito_(false),
201 original_profile_(NULL),
202 guest_session_(false),
203 last_session_exited_cleanly_(true),
205 browser_context_dependency_manager_(
206 BrowserContextDependencyManager::GetInstance()),
207 resource_context_(NULL),
213 TestingProfile::TestingProfile(const base::FilePath& path,
215 : start_time_(Time::Now()),
216 testing_prefs_(NULL),
218 force_incognito_(false),
219 original_profile_(NULL),
220 guest_session_(false),
221 last_session_exited_cleanly_(true),
223 browser_context_dependency_manager_(
224 BrowserContextDependencyManager::GetInstance()),
225 resource_context_(NULL),
226 delegate_(delegate) {
229 base::MessageLoop::current()->PostTask(
231 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
237 TestingProfile::TestingProfile(
238 const base::FilePath& path,
240 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
241 scoped_ptr<PrefServiceSyncable> prefs,
244 const std::string& managed_user_id,
245 scoped_ptr<policy::PolicyService> policy_service,
246 const TestingFactories& factories)
247 : start_time_(Time::Now()),
248 prefs_(prefs.release()),
249 testing_prefs_(NULL),
250 incognito_(incognito),
251 force_incognito_(false),
252 original_profile_(NULL),
253 guest_session_(guest_session),
254 managed_user_id_(managed_user_id),
255 last_session_exited_cleanly_(true),
256 extension_special_storage_policy_(extension_policy),
258 browser_context_dependency_manager_(
259 BrowserContextDependencyManager::GetInstance()),
260 resource_context_(NULL),
262 policy_service_(policy_service.release()) {
264 // If no profile path was supplied, create one.
265 if (profile_path_.empty()) {
266 CreateTempProfileDir();
267 profile_path_ = temp_dir_.path();
270 // Set any testing factories prior to initializing the services.
271 for (TestingFactories::const_iterator it = factories.begin();
272 it != factories.end(); ++it) {
273 it->first->SetTestingFactory(this, it->second);
277 // If caller supplied a delegate, delay the FinishInit invocation until other
279 // TODO(atwilson): See if this is still required once we convert the current
280 // users of the constructor that takes a Delegate* param.
282 base::MessageLoop::current()->PostTask(
284 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
290 void TestingProfile::CreateTempProfileDir() {
291 if (!temp_dir_.CreateUniqueTempDir()) {
292 LOG(ERROR) << "Failed to create unique temporary directory.";
294 // Fallback logic in case we fail to create unique temporary directory.
295 base::FilePath system_tmp_dir;
296 bool success = PathService::Get(base::DIR_TEMP, &system_tmp_dir);
298 // We're severly screwed if we can't get the system temporary
299 // directory. Die now to avoid writing to the filesystem root
300 // or other bad places.
303 base::FilePath fallback_dir(
304 system_tmp_dir.AppendASCII("TestingProfilePath"));
305 base::DeleteFile(fallback_dir, true);
306 base::CreateDirectory(fallback_dir);
307 if (!temp_dir_.Set(fallback_dir)) {
308 // That shouldn't happen, but if it does, try to recover.
309 LOG(ERROR) << "Failed to use a fallback temporary directory.";
311 // We're screwed if this fails, see CHECK above.
312 CHECK(temp_dir_.Set(system_tmp_dir));
317 void TestingProfile::Init() {
318 // If threads have been initialized, we should be on the UI thread.
319 DCHECK(!content::BrowserThread::IsThreadInitialized(
320 content::BrowserThread::UI) ||
321 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
323 // Normally this would happen during browser startup, but for tests
324 // we need to trigger creation of Profile-related services.
325 ChromeBrowserMainExtraPartsProfiles::
326 EnsureBrowserContextKeyedServiceFactoriesBuilt();
329 user_prefs::UserPrefs::Set(this, prefs_.get());
331 CreateTestingPrefService();
333 if (!base::PathExists(profile_path_))
334 base::CreateDirectory(profile_path_);
336 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
337 // anymore, after converting the PrefService to a PKS. Until then it must
338 // be associated with a TestingProfile too.
339 if (!IsOffTheRecord())
340 CreateProfilePolicyConnector();
342 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
343 this, extensions::TestExtensionSystem::Build);
345 // If no original profile was specified for this profile: register preferences
346 // even if this is an incognito profile - this allows tests to create a
347 // standalone incognito profile while still having prefs registered.
348 if (!IsOffTheRecord() || !original_profile_) {
349 user_prefs::PrefRegistrySyncable* pref_registry =
350 static_cast<user_prefs::PrefRegistrySyncable*>(
351 prefs_->DeprecatedGetPrefRegistry());
352 browser_context_dependency_manager_->
353 RegisterProfilePrefsForServices(this, pref_registry);
356 browser_context_dependency_manager_->CreateBrowserContextServicesForTest(
359 #if defined(ENABLE_NOTIFICATIONS)
360 // Install profile keyed service factory hooks for dummy/test services
361 DesktopNotificationServiceFactory::GetInstance()->SetTestingFactory(
362 this, CreateTestDesktopNotificationService);
365 #if defined(ENABLE_MANAGED_USERS)
366 ManagedUserSettingsService* settings_service =
367 ManagedUserSettingsServiceFactory::GetForProfile(this);
368 TestingPrefStore* store = new TestingPrefStore();
369 settings_service->Init(store);
370 store->SetInitializationCompleted();
373 profile_name_ = "testing_profile";
376 void TestingProfile::FinishInit() {
377 DCHECK(content::NotificationService::current());
378 content::NotificationService::current()->Notify(
379 chrome::NOTIFICATION_PROFILE_CREATED,
380 content::Source<Profile>(static_cast<Profile*>(this)),
381 content::NotificationService::NoDetails());
383 ProfileManager* profile_manager = g_browser_process->profile_manager();
385 profile_manager->InitProfileUserPrefs(this);
388 delegate_->OnProfileCreated(this, true, false);
391 TestingProfile::~TestingProfile() {
392 // Revert to non-incognito mode before shutdown.
393 force_incognito_ = false;
395 // Any objects holding live URLFetchers should be deleted before teardown.
396 TemplateURLFetcherFactory::ShutdownForProfile(this);
398 MaybeSendDestroyedNotification();
400 browser_context_dependency_manager_->DestroyBrowserContextServices(this);
402 if (host_content_settings_map_.get())
403 host_content_settings_map_->ShutdownOnUIThread();
407 if (pref_proxy_config_tracker_.get())
408 pref_proxy_config_tracker_->DetachFromPrefService();
409 // Failing a post == leaks == heapcheck failure. Make that an immediate test
411 if (resource_context_) {
412 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
414 resource_context_ = NULL;
415 content::RunAllPendingInMessageLoop(BrowserThread::IO);
419 static KeyedService* BuildFaviconService(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 KeyedService* BuildHistoryService(content::BrowserContext* profile) {
430 return new HistoryService(static_cast<Profile*>(profile));
433 bool TestingProfile::CreateHistoryService(bool delete_file, bool no_db) {
434 DestroyHistoryService();
436 base::FilePath path = GetPath();
437 path = path.Append(chrome::kHistoryFilename);
438 if (!base::DeleteFile(path, false) || base::PathExists(path))
441 // This will create and init the history service.
442 HistoryService* history_service = static_cast<HistoryService*>(
443 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
444 this, BuildHistoryService));
445 if (!history_service->Init(this->GetPath(),
446 BookmarkModelFactory::GetForProfile(this),
448 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(this, NULL);
450 // Disable WebHistoryService by default, since it makes network requests.
451 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, NULL);
455 void TestingProfile::DestroyHistoryService() {
456 HistoryService* history_service =
457 HistoryServiceFactory::GetForProfileWithoutCreating(this);
458 if (!history_service)
461 history_service->NotifyRenderProcessHostDestruction(0);
462 history_service->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
463 history_service->Cleanup();
464 HistoryServiceFactory::ShutdownForProfile(this);
466 // Wait for the backend class to terminate before deleting the files and
467 // moving to the next test. Note: if this never terminates, somebody is
468 // probably leaking a reference to the history backend, so it never calls
470 base::MessageLoop::current()->Run();
472 // Make sure we don't have any event pending that could disrupt the next
474 base::MessageLoop::current()->PostTask(FROM_HERE,
475 base::MessageLoop::QuitClosure());
476 base::MessageLoop::current()->Run();
479 void TestingProfile::CreateTopSites() {
481 top_sites_ = history::TopSites::Create(
482 this, GetPath().Append(chrome::kTopSitesFilename));
485 void TestingProfile::DestroyTopSites() {
486 if (top_sites_.get()) {
487 top_sites_->Shutdown();
489 // TopSitesImpl::Shutdown schedules some tasks (from TopSitesBackend) that
490 // need to be run to properly shutdown. Run all pending tasks now. This is
491 // normally handled by browser_process shutdown.
492 if (base::MessageLoop::current())
493 base::MessageLoop::current()->RunUntilIdle();
497 static KeyedService* BuildBookmarkModel(content::BrowserContext* context) {
498 Profile* profile = static_cast<Profile*>(context);
499 ChromeBookmarkClient* bookmark_client =
500 new ChromeBookmarkClient(profile, false);
501 bookmark_client->model()->Load(
503 profile->GetPrefs()->GetString(prefs::kAcceptLanguages),
505 profile->GetIOTaskRunner(),
506 content::BrowserThread::GetMessageLoopProxyForThread(
507 content::BrowserThread::UI));
508 return bookmark_client;
511 void TestingProfile::CreateBookmarkModel(bool delete_file) {
513 base::FilePath path = GetPath().Append(bookmarks::kBookmarksFileName);
514 base::DeleteFile(path, false);
516 // This will create a bookmark model.
517 BookmarkModel* bookmark_service =
518 static_cast<ChromeBookmarkClient*>(
519 BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
520 this, BuildBookmarkModel))->model();
522 HistoryService* history_service =
523 HistoryServiceFactory::GetForProfileWithoutCreating(this);
524 if (history_service) {
525 history_service->history_backend_->bookmark_service_ = bookmark_service;
526 history_service->history_backend_->expirer_.bookmark_service_ =
531 static KeyedService* BuildWebDataService(content::BrowserContext* profile) {
532 return new WebDataServiceWrapper(static_cast<Profile*>(profile));
535 void TestingProfile::CreateWebDataService() {
536 WebDataServiceFactory::GetInstance()->SetTestingFactory(
537 this, BuildWebDataService);
540 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
541 // Only get the history service if it actually exists since the caller of the
542 // test should explicitly call CreateHistoryService to build it.
543 HistoryService* history_service =
544 HistoryServiceFactory::GetForProfileWithoutCreating(this);
545 DCHECK(history_service);
546 history::InMemoryURLIndex* index = history_service->InMemoryIndex();
547 if (!index || index->restored())
549 base::RunLoop run_loop;
550 HistoryIndexRestoreObserver observer(
551 content::GetQuitTaskForRunLoop(&run_loop));
552 index->set_restore_cache_observer(&observer);
554 index->set_restore_cache_observer(NULL);
555 DCHECK(index->restored());
558 // TODO(phajdan.jr): Doesn't this hang if Top Sites are already loaded?
559 void TestingProfile::BlockUntilTopSitesLoaded() {
560 content::WindowedNotificationObserver top_sites_loaded_observer(
561 chrome::NOTIFICATION_TOP_SITES_LOADED,
562 content::NotificationService::AllSources());
563 top_sites_loaded_observer.Wait();
566 void TestingProfile::SetGuestSession(bool guest) {
567 guest_session_ = guest;
570 base::FilePath TestingProfile::GetPath() const {
571 return profile_path_;
574 scoped_refptr<base::SequencedTaskRunner> TestingProfile::GetIOTaskRunner() {
575 return base::MessageLoop::current()->message_loop_proxy();
578 TestingPrefServiceSyncable* TestingProfile::GetTestingPrefService() {
580 CreateTestingPrefService();
581 DCHECK(testing_prefs_);
582 return testing_prefs_;
585 TestingProfile* TestingProfile::AsTestingProfile() {
589 std::string TestingProfile::GetProfileName() {
590 return profile_name_;
593 Profile::ProfileType TestingProfile::GetProfileType() const {
595 return GUEST_PROFILE;
596 if (force_incognito_ || incognito_)
597 return INCOGNITO_PROFILE;
598 return REGULAR_PROFILE;
601 bool TestingProfile::IsOffTheRecord() const {
602 return force_incognito_ || incognito_;
605 void TestingProfile::SetOffTheRecordProfile(scoped_ptr<Profile> profile) {
606 DCHECK(!IsOffTheRecord());
607 incognito_profile_ = profile.Pass();
610 void TestingProfile::SetOriginalProfile(Profile* profile) {
611 DCHECK(IsOffTheRecord());
612 original_profile_ = profile;
615 Profile* TestingProfile::GetOffTheRecordProfile() {
616 if (IsOffTheRecord())
618 if (!incognito_profile_) {
619 TestingProfile::Builder builder;
620 builder.SetIncognito();
621 scoped_ptr<TestingProfile> incognito_test_profile(builder.Build());
622 incognito_test_profile->SetOriginalProfile(this);
623 SetOffTheRecordProfile(incognito_test_profile.PassAs<Profile>());
625 return incognito_profile_.get();
628 bool TestingProfile::HasOffTheRecordProfile() {
629 return incognito_profile_.get() != NULL;
632 Profile* TestingProfile::GetOriginalProfile() {
633 if (original_profile_)
634 return original_profile_;
638 bool TestingProfile::IsManaged() {
639 return !managed_user_id_.empty();
642 ExtensionService* TestingProfile::GetExtensionService() {
643 return extensions::ExtensionSystem::Get(this)->extension_service();
646 void TestingProfile::SetExtensionSpecialStoragePolicy(
647 ExtensionSpecialStoragePolicy* extension_special_storage_policy) {
648 extension_special_storage_policy_ = extension_special_storage_policy;
651 ExtensionSpecialStoragePolicy*
652 TestingProfile::GetExtensionSpecialStoragePolicy() {
653 if (!extension_special_storage_policy_.get())
654 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(NULL);
655 return extension_special_storage_policy_.get();
658 net::CookieMonster* TestingProfile::GetCookieMonster() {
659 if (!GetRequestContext())
661 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
665 void TestingProfile::CreateTestingPrefService() {
666 DCHECK(!prefs_.get());
667 testing_prefs_ = new TestingPrefServiceSyncable();
668 prefs_.reset(testing_prefs_);
669 user_prefs::UserPrefs::Set(this, prefs_.get());
670 chrome::RegisterUserProfilePrefs(testing_prefs_->registry());
673 void TestingProfile::CreateProfilePolicyConnector() {
674 #if defined(ENABLE_CONFIGURATION_POLICY)
675 schema_registry_service_ =
676 policy::SchemaRegistryServiceFactory::CreateForContext(
677 this, policy::Schema(), NULL);
678 CHECK_EQ(schema_registry_service_.get(),
679 policy::SchemaRegistryServiceFactory::GetForContext(this));
680 #endif // defined(ENABLE_CONFIGURATION_POLICY)
682 if (!policy_service_) {
683 #if defined(ENABLE_CONFIGURATION_POLICY)
684 std::vector<policy::ConfigurationPolicyProvider*> providers;
685 policy_service_.reset(new policy::PolicyServiceImpl(providers));
687 policy_service_.reset(new policy::PolicyServiceStub());
690 profile_policy_connector_.reset(new policy::ProfilePolicyConnector());
691 profile_policy_connector_->InitForTesting(policy_service_.Pass());
692 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
693 this, profile_policy_connector_.get());
694 CHECK_EQ(profile_policy_connector_.get(),
695 policy::ProfilePolicyConnectorFactory::GetForProfile(this));
698 PrefService* TestingProfile::GetPrefs() {
700 CreateTestingPrefService();
705 history::TopSites* TestingProfile::GetTopSites() {
706 return top_sites_.get();
709 history::TopSites* TestingProfile::GetTopSitesWithoutCreating() {
710 return top_sites_.get();
713 DownloadManagerDelegate* TestingProfile::GetDownloadManagerDelegate() {
717 net::URLRequestContextGetter* TestingProfile::GetRequestContext() {
718 return GetDefaultStoragePartition(this)->GetURLRequestContext();
721 net::URLRequestContextGetter* TestingProfile::CreateRequestContext(
722 content::ProtocolHandlerMap* protocol_handlers,
723 content::ProtocolHandlerScopedVector protocol_interceptors) {
724 return new net::TestURLRequestContextGetter(
725 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
728 net::URLRequestContextGetter* TestingProfile::GetRequestContextForRenderProcess(
729 int renderer_child_id) {
730 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
732 return rph->GetStoragePartition()->GetURLRequestContext();
735 net::URLRequestContextGetter* TestingProfile::GetMediaRequestContext() {
739 net::URLRequestContextGetter*
740 TestingProfile::GetMediaRequestContextForRenderProcess(
741 int renderer_child_id) {
745 net::URLRequestContextGetter*
746 TestingProfile::GetMediaRequestContextForStoragePartition(
747 const base::FilePath& partition_path,
752 void TestingProfile::RequestMidiSysExPermission(
753 int render_process_id,
756 const GURL& requesting_frame,
758 const MidiSysExPermissionCallback& callback) {
759 // Always reject requests for testing.
763 void TestingProfile::CancelMidiSysExPermissionRequest(
764 int render_process_id,
767 const GURL& requesting_frame) {
770 void TestingProfile::RequestProtectedMediaIdentifierPermission(
771 int render_process_id,
775 const GURL& requesting_frame,
776 const ProtectedMediaIdentifierPermissionCallback& callback) {
777 // Always reject requests for testing.
781 void TestingProfile::CancelProtectedMediaIdentifierPermissionRequests(
785 net::URLRequestContextGetter* TestingProfile::GetRequestContextForExtensions() {
786 if (!extensions_request_context_.get())
787 extensions_request_context_ = new TestExtensionURLRequestContextGetter();
788 return extensions_request_context_.get();
791 net::SSLConfigService* TestingProfile::GetSSLConfigService() {
792 if (!GetRequestContext())
794 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
797 net::URLRequestContextGetter*
798 TestingProfile::CreateRequestContextForStoragePartition(
799 const base::FilePath& partition_path,
801 content::ProtocolHandlerMap* protocol_handlers,
802 content::ProtocolHandlerScopedVector protocol_interceptors) {
803 // We don't test storage partitions here yet, so returning the same dummy
804 // context is sufficient for now.
805 return GetRequestContext();
808 content::ResourceContext* TestingProfile::GetResourceContext() {
809 if (!resource_context_)
810 resource_context_ = new content::MockResourceContext();
811 return resource_context_;
814 HostContentSettingsMap* TestingProfile::GetHostContentSettingsMap() {
815 if (!host_content_settings_map_.get()) {
816 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
817 #if defined(ENABLE_EXTENSIONS)
818 ExtensionService* extension_service = GetExtensionService();
819 if (extension_service)
820 host_content_settings_map_->RegisterExtensionService(extension_service);
823 return host_content_settings_map_.get();
826 content::GeolocationPermissionContext*
827 TestingProfile::GetGeolocationPermissionContext() {
828 return ChromeGeolocationPermissionContextFactory::GetForProfile(this);
831 content::BrowserPluginGuestManagerDelegate*
832 TestingProfile::GetGuestManagerDelegate() {
833 return GuestViewManager::FromBrowserContext(this);
836 std::wstring TestingProfile::GetName() {
837 return std::wstring();
840 std::wstring TestingProfile::GetID() {
844 void TestingProfile::SetID(const std::wstring& id) {
848 bool TestingProfile::IsSameProfile(Profile *p) {
852 base::Time TestingProfile::GetStartTime() const {
856 base::FilePath TestingProfile::last_selected_directory() {
857 return last_selected_directory_;
860 void TestingProfile::set_last_selected_directory(const base::FilePath& path) {
861 last_selected_directory_ = path;
864 PrefProxyConfigTracker* TestingProfile::GetProxyConfigTracker() {
865 if (!pref_proxy_config_tracker_.get()) {
866 // TestingProfile is used in unit tests, where local state is not available.
867 pref_proxy_config_tracker_.reset(
868 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
871 return pref_proxy_config_tracker_.get();
874 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
875 HistoryService* history_service =
876 HistoryServiceFactory::GetForProfile(this, Profile::EXPLICIT_ACCESS);
877 DCHECK(history_service);
878 DCHECK(base::MessageLoop::current());
880 CancelableRequestConsumer consumer;
881 history_service->ScheduleDBTask(new QuittingHistoryDBTask(), &consumer);
882 base::MessageLoop::current()->Run();
885 chrome_browser_net::Predictor* TestingProfile::GetNetworkPredictor() {
889 void TestingProfile::ClearNetworkingHistorySince(
891 const base::Closure& completion) {
892 if (!completion.is_null()) {
893 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, completion);
897 GURL TestingProfile::GetHomePage() {
898 return GURL(chrome::kChromeUINewTabURL);
901 PrefService* TestingProfile::GetOffTheRecordPrefs() {
905 quota::SpecialStoragePolicy* TestingProfile::GetSpecialStoragePolicy() {
906 return GetExtensionSpecialStoragePolicy();
909 bool TestingProfile::WasCreatedByVersionOrLater(const std::string& version) {
913 bool TestingProfile::IsGuestSession() const {
914 return guest_session_;
917 Profile::ExitType TestingProfile::GetLastSessionExitType() {
918 return last_session_exited_cleanly_ ? EXIT_NORMAL : EXIT_CRASHED;
921 TestingProfile::Builder::Builder()
922 : build_called_(false),
925 guest_session_(false) {
928 TestingProfile::Builder::~Builder() {
931 void TestingProfile::Builder::SetPath(const base::FilePath& path) {
935 void TestingProfile::Builder::SetDelegate(Delegate* delegate) {
936 delegate_ = delegate;
939 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
940 scoped_refptr<ExtensionSpecialStoragePolicy> policy) {
941 extension_policy_ = policy;
944 void TestingProfile::Builder::SetPrefService(
945 scoped_ptr<PrefServiceSyncable> prefs) {
946 pref_service_ = prefs.Pass();
949 void TestingProfile::Builder::SetIncognito() {
953 void TestingProfile::Builder::SetGuestSession() {
954 guest_session_ = true;
957 void TestingProfile::Builder::SetManagedUserId(
958 const std::string& managed_user_id) {
959 managed_user_id_ = managed_user_id;
962 void TestingProfile::Builder::SetPolicyService(
963 scoped_ptr<policy::PolicyService> policy_service) {
964 policy_service_ = policy_service.Pass();
967 void TestingProfile::Builder::AddTestingFactory(
968 BrowserContextKeyedServiceFactory* service_factory,
969 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback) {
970 testing_factories_.push_back(std::make_pair(service_factory, callback));
973 scoped_ptr<TestingProfile> TestingProfile::Builder::Build() {
974 DCHECK(!build_called_);
975 build_called_ = true;
977 return scoped_ptr<TestingProfile>(new TestingProfile(
981 pref_service_.Pass(),
985 policy_service_.Pass(),
986 testing_factories_));