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/bookmarks/bookmark_model_factory.h"
17 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
18 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
19 #include "chrome/browser/browser_process.h"
20 #include "chrome/browser/chrome_notification_types.h"
21 #include "chrome/browser/favicon/chrome_favicon_client_factory.h"
22 #include "chrome/browser/favicon/favicon_service.h"
23 #include "chrome/browser/favicon/favicon_service_factory.h"
24 #include "chrome/browser/history/chrome_history_client.h"
25 #include "chrome/browser/history/chrome_history_client_factory.h"
26 #include "chrome/browser/history/history_backend.h"
27 #include "chrome/browser/history/history_db_task.h"
28 #include "chrome/browser/history/history_service.h"
29 #include "chrome/browser/history/history_service_factory.h"
30 #include "chrome/browser/history/top_sites.h"
31 #include "chrome/browser/history/web_history_service_factory.h"
32 #include "chrome/browser/net/pref_proxy_config_tracker.h"
33 #include "chrome/browser/net/proxy_service_factory.h"
34 #include "chrome/browser/notifications/desktop_notification_service.h"
35 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
36 #include "chrome/browser/policy/profile_policy_connector.h"
37 #include "chrome/browser/policy/profile_policy_connector_factory.h"
38 #include "chrome/browser/prefs/browser_prefs.h"
39 #include "chrome/browser/prefs/pref_service_syncable.h"
40 #include "chrome/browser/prerender/prerender_manager.h"
41 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
42 #include "chrome/browser/profiles/profile_manager.h"
43 #include "chrome/browser/profiles/storage_partition_descriptor.h"
44 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
45 #include "chrome/browser/webdata/web_data_service_factory.h"
46 #include "chrome/common/chrome_constants.h"
47 #include "chrome/common/chrome_switches.h"
48 #include "chrome/common/pref_names.h"
49 #include "chrome/common/url_constants.h"
50 #include "chrome/test/base/history_index_restore_observer.h"
51 #include "chrome/test/base/testing_pref_service_syncable.h"
52 #include "components/bookmarks/browser/bookmark_model.h"
53 #include "components/bookmarks/common/bookmark_constants.h"
54 #include "components/content_settings/core/browser/host_content_settings_map.h"
55 #include "components/history/core/browser/top_sites_observer.h"
56 #include "components/keyed_service/content/browser_context_dependency_manager.h"
57 #include "components/policy/core/common/policy_service.h"
58 #include "components/user_prefs/user_prefs.h"
59 #include "content/public/browser/browser_thread.h"
60 #include "content/public/browser/cookie_store_factory.h"
61 #include "content/public/browser/notification_service.h"
62 #include "content/public/browser/render_process_host.h"
63 #include "content/public/browser/storage_partition.h"
64 #include "content/public/test/mock_resource_context.h"
65 #include "content/public/test/test_utils.h"
66 #include "extensions/common/constants.h"
67 #include "net/cookies/cookie_monster.h"
68 #include "net/url_request/url_request_context.h"
69 #include "net/url_request/url_request_context_getter.h"
70 #include "net/url_request/url_request_test_util.h"
71 #include "testing/gmock/include/gmock/gmock.h"
73 #if defined(ENABLE_CONFIGURATION_POLICY)
74 #include "chrome/browser/policy/schema_registry_service.h"
75 #include "chrome/browser/policy/schema_registry_service_factory.h"
76 #include "components/policy/core/common/configuration_policy_provider.h"
77 #include "components/policy/core/common/policy_service_impl.h"
78 #include "components/policy/core/common/schema.h"
80 #include "components/policy/core/common/policy_service_stub.h"
81 #endif // defined(ENABLE_CONFIGURATION_POLICY)
83 #if defined(ENABLE_EXTENSIONS)
84 #include "chrome/browser/extensions/extension_service.h"
85 #include "chrome/browser/extensions/extension_special_storage_policy.h"
86 #include "chrome/browser/extensions/extension_system_factory.h"
87 #include "chrome/browser/extensions/test_extension_system.h"
88 #include "extensions/browser/extension_system.h"
89 #include "extensions/browser/guest_view/guest_view_manager.h"
92 #if defined(OS_ANDROID)
93 #include "chrome/browser/signin/android_profile_oauth2_token_service.h"
96 #if defined(ENABLE_MANAGED_USERS)
97 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
98 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
102 using content::BrowserThread;
103 using content::DownloadManagerDelegate;
104 using testing::NiceMock;
105 using testing::Return;
109 // Used to make sure TopSites has finished loading
110 class WaitTopSitesLoadedObserver : public history::TopSitesObserver {
112 explicit WaitTopSitesLoadedObserver(content::MessageLoopRunner* runner)
114 void TopSitesLoaded(history::TopSites* top_sites) override {
117 void TopSitesChanged(history::TopSites* top_sites) override {}
121 content::MessageLoopRunner* runner_;
124 // Task used to make sure history has finished processing a request. Intended
125 // for use with BlockUntilHistoryProcessesPendingRequests.
127 class QuittingHistoryDBTask : public history::HistoryDBTask {
129 QuittingHistoryDBTask() {}
131 bool RunOnDBThread(history::HistoryBackend* backend,
132 history::HistoryDatabase* db) override {
136 void DoneRunOnMainThread() override { base::MessageLoop::current()->Quit(); }
139 ~QuittingHistoryDBTask() override {}
141 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
144 class TestExtensionURLRequestContext : public net::URLRequestContext {
146 TestExtensionURLRequestContext() {
147 net::CookieMonster* cookie_monster =
148 content::CreateCookieStore(content::CookieStoreConfig())->
150 const char* const schemes[] = {extensions::kExtensionScheme};
151 cookie_monster->SetCookieableSchemes(schemes, arraysize(schemes));
152 set_cookie_store(cookie_monster);
155 ~TestExtensionURLRequestContext() override { AssertNoURLRequests(); }
158 class TestExtensionURLRequestContextGetter
159 : public net::URLRequestContextGetter {
161 net::URLRequestContext* GetURLRequestContext() override {
163 context_.reset(new TestExtensionURLRequestContext());
164 return context_.get();
166 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
168 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
172 ~TestExtensionURLRequestContextGetter() override {}
175 scoped_ptr<net::URLRequestContext> context_;
178 #if defined(ENABLE_NOTIFICATIONS)
179 KeyedService* CreateTestDesktopNotificationService(
180 content::BrowserContext* profile) {
181 return new DesktopNotificationService(static_cast<Profile*>(profile));
188 #if defined(OS_CHROMEOS)
189 // Must be kept in sync with
190 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
191 const char TestingProfile::kTestUserProfileDir[] = "test-user";
193 const char TestingProfile::kTestUserProfileDir[] = "Default";
196 TestingProfile::TestingProfile()
197 : start_time_(Time::Now()),
198 testing_prefs_(NULL),
199 force_incognito_(false),
200 original_profile_(NULL),
201 guest_session_(false),
202 last_session_exited_cleanly_(true),
203 browser_context_dependency_manager_(
204 BrowserContextDependencyManager::GetInstance()),
205 resource_context_(NULL),
207 CreateTempProfileDir();
208 profile_path_ = temp_dir_.path();
214 TestingProfile::TestingProfile(const base::FilePath& path)
215 : start_time_(Time::Now()),
216 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),
230 TestingProfile::TestingProfile(const base::FilePath& path,
232 : start_time_(Time::Now()),
233 testing_prefs_(NULL),
234 force_incognito_(false),
235 original_profile_(NULL),
236 guest_session_(false),
237 last_session_exited_cleanly_(true),
239 browser_context_dependency_manager_(
240 BrowserContextDependencyManager::GetInstance()),
241 resource_context_(NULL),
242 delegate_(delegate) {
245 base::MessageLoop::current()->PostTask(
247 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
253 TestingProfile::TestingProfile(
254 const base::FilePath& path,
256 #if defined(ENABLE_EXTENSIONS)
257 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
259 scoped_ptr<PrefServiceSyncable> prefs,
260 TestingProfile* parent,
262 const std::string& supervised_user_id,
263 scoped_ptr<policy::PolicyService> policy_service,
264 const TestingFactories& factories)
265 : start_time_(Time::Now()),
266 prefs_(prefs.release()),
267 testing_prefs_(NULL),
268 force_incognito_(false),
269 original_profile_(parent),
270 guest_session_(guest_session),
271 supervised_user_id_(supervised_user_id),
272 last_session_exited_cleanly_(true),
273 #if defined(ENABLE_EXTENSIONS)
274 extension_special_storage_policy_(extension_policy),
277 browser_context_dependency_manager_(
278 BrowserContextDependencyManager::GetInstance()),
279 resource_context_(NULL),
281 policy_service_(policy_service.release()) {
283 parent->SetOffTheRecordProfile(scoped_ptr<Profile>(this));
285 // If no profile path was supplied, create one.
286 if (profile_path_.empty()) {
287 CreateTempProfileDir();
288 profile_path_ = temp_dir_.path();
291 // Set any testing factories prior to initializing the services.
292 for (TestingFactories::const_iterator it = factories.begin();
293 it != factories.end(); ++it) {
294 it->first->SetTestingFactory(this, it->second);
298 // If caller supplied a delegate, delay the FinishInit invocation until other
300 // TODO(atwilson): See if this is still required once we convert the current
301 // users of the constructor that takes a Delegate* param.
303 base::MessageLoop::current()->PostTask(
305 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
311 void TestingProfile::CreateTempProfileDir() {
312 if (!temp_dir_.CreateUniqueTempDir()) {
313 LOG(ERROR) << "Failed to create unique temporary directory.";
315 // Fallback logic in case we fail to create unique temporary directory.
316 base::FilePath system_tmp_dir;
317 bool success = PathService::Get(base::DIR_TEMP, &system_tmp_dir);
319 // We're severly screwed if we can't get the system temporary
320 // directory. Die now to avoid writing to the filesystem root
321 // or other bad places.
324 base::FilePath fallback_dir(
325 system_tmp_dir.AppendASCII("TestingProfilePath"));
326 base::DeleteFile(fallback_dir, true);
327 base::CreateDirectory(fallback_dir);
328 if (!temp_dir_.Set(fallback_dir)) {
329 // That shouldn't happen, but if it does, try to recover.
330 LOG(ERROR) << "Failed to use a fallback temporary directory.";
332 // We're screwed if this fails, see CHECK above.
333 CHECK(temp_dir_.Set(system_tmp_dir));
338 void TestingProfile::Init() {
339 // If threads have been initialized, we should be on the UI thread.
340 DCHECK(!content::BrowserThread::IsThreadInitialized(
341 content::BrowserThread::UI) ||
342 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
344 #if defined(OS_ANDROID)
345 // Make sure token service knows its running in tests.
346 AndroidProfileOAuth2TokenService::set_is_testing_profile();
349 // Normally this would happen during browser startup, but for tests
350 // we need to trigger creation of Profile-related services.
351 ChromeBrowserMainExtraPartsProfiles::
352 EnsureBrowserContextKeyedServiceFactoriesBuilt();
355 user_prefs::UserPrefs::Set(this, prefs_.get());
356 else if (IsOffTheRecord())
357 CreateIncognitoPrefService();
359 CreateTestingPrefService();
361 if (!base::PathExists(profile_path_))
362 base::CreateDirectory(profile_path_);
364 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
365 // anymore, after converting the PrefService to a PKS. Until then it must
366 // be associated with a TestingProfile too.
367 if (!IsOffTheRecord())
368 CreateProfilePolicyConnector();
370 #if defined(ENABLE_EXTENSIONS)
371 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
372 this, extensions::TestExtensionSystem::Build);
375 // Prefs for incognito profiles are set in CreateIncognitoPrefService() by
376 // simulating ProfileImpl::GetOffTheRecordPrefs().
377 if (!IsOffTheRecord()) {
378 DCHECK(!original_profile_);
379 user_prefs::PrefRegistrySyncable* pref_registry =
380 static_cast<user_prefs::PrefRegistrySyncable*>(
381 prefs_->DeprecatedGetPrefRegistry());
382 browser_context_dependency_manager_->
383 RegisterProfilePrefsForServices(this, pref_registry);
386 browser_context_dependency_manager_->CreateBrowserContextServicesForTest(
389 #if defined(ENABLE_NOTIFICATIONS)
390 // Install profile keyed service factory hooks for dummy/test services
391 DesktopNotificationServiceFactory::GetInstance()->SetTestingFactory(
392 this, CreateTestDesktopNotificationService);
395 #if defined(ENABLE_MANAGED_USERS)
396 if (!IsOffTheRecord()) {
397 SupervisedUserSettingsService* settings_service =
398 SupervisedUserSettingsServiceFactory::GetForProfile(this);
399 TestingPrefStore* store = new TestingPrefStore();
400 settings_service->Init(store);
401 store->SetInitializationCompleted();
405 profile_name_ = "testing_profile";
408 void TestingProfile::FinishInit() {
409 DCHECK(content::NotificationService::current());
410 content::NotificationService::current()->Notify(
411 chrome::NOTIFICATION_PROFILE_CREATED,
412 content::Source<Profile>(static_cast<Profile*>(this)),
413 content::NotificationService::NoDetails());
415 ProfileManager* profile_manager = g_browser_process->profile_manager();
417 profile_manager->InitProfileUserPrefs(this);
420 delegate_->OnProfileCreated(this, true, false);
423 TestingProfile::~TestingProfile() {
424 // Revert to non-incognito mode before shutdown.
425 force_incognito_ = false;
427 // If this profile owns an incognito profile, tear it down first.
428 incognito_profile_.reset();
430 // Any objects holding live URLFetchers should be deleted before teardown.
431 TemplateURLFetcherFactory::ShutdownForProfile(this);
433 MaybeSendDestroyedNotification();
435 browser_context_dependency_manager_->DestroyBrowserContextServices(this);
437 if (host_content_settings_map_.get())
438 host_content_settings_map_->ShutdownOnUIThread();
442 if (pref_proxy_config_tracker_.get())
443 pref_proxy_config_tracker_->DetachFromPrefService();
444 // Failing a post == leaks == heapcheck failure. Make that an immediate test
446 if (resource_context_) {
447 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
449 resource_context_ = NULL;
450 content::RunAllPendingInMessageLoop(BrowserThread::IO);
454 static KeyedService* BuildFaviconService(content::BrowserContext* profile) {
455 FaviconClient* favicon_client =
456 ChromeFaviconClientFactory::GetForProfile(static_cast<Profile*>(profile));
457 return new FaviconService(static_cast<Profile*>(profile), favicon_client);
460 void TestingProfile::CreateFaviconService() {
461 // It is up to the caller to create the history service if one is needed.
462 FaviconServiceFactory::GetInstance()->SetTestingFactory(
463 this, BuildFaviconService);
466 static KeyedService* BuildHistoryService(content::BrowserContext* context) {
467 Profile* profile = static_cast<Profile*>(context);
468 ChromeHistoryClient* history_client =
469 ChromeHistoryClientFactory::GetForProfile(profile);
470 HistoryService* history_service = new HistoryService(history_client, profile);
472 history_client->SetHistoryService(history_service);
473 return history_service;
476 bool TestingProfile::CreateHistoryService(bool delete_file, bool no_db) {
477 DestroyHistoryService();
479 base::FilePath path = GetPath();
480 path = path.Append(chrome::kHistoryFilename);
481 if (!base::DeleteFile(path, false) || base::PathExists(path))
484 // This will create and init the history service.
485 HistoryService* history_service = static_cast<HistoryService*>(
486 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
487 this, BuildHistoryService));
488 if (!history_service->Init(this->GetPath(), no_db)) {
489 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(this, NULL);
491 // Disable WebHistoryService by default, since it makes network requests.
492 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, NULL);
496 void TestingProfile::DestroyHistoryService() {
497 // TODO(sdefresne): remove this once ChromeHistoryClient is no longer an
498 // HistoryServiceObserver, http://crbug.com/373326
499 ChromeHistoryClient* history_client =
500 ChromeHistoryClientFactory::GetForProfileWithoutCreating(this);
502 history_client->Shutdown();
504 HistoryService* history_service =
505 HistoryServiceFactory::GetForProfileWithoutCreating(this);
506 if (!history_service)
509 history_service->ClearCachedDataForContextID(0);
510 history_service->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
511 history_service->Cleanup();
512 HistoryServiceFactory::ShutdownForProfile(this);
514 // Wait for the backend class to terminate before deleting the files and
515 // moving to the next test. Note: if this never terminates, somebody is
516 // probably leaking a reference to the history backend, so it never calls
518 base::MessageLoop::current()->Run();
520 // Make sure we don't have any event pending that could disrupt the next
522 base::MessageLoop::current()->PostTask(FROM_HERE,
523 base::MessageLoop::QuitClosure());
524 base::MessageLoop::current()->Run();
527 void TestingProfile::CreateTopSites() {
529 top_sites_ = history::TopSites::Create(
530 this, GetPath().Append(chrome::kTopSitesFilename));
533 void TestingProfile::SetTopSites(history::TopSites* top_sites) {
535 top_sites_ = top_sites;
538 void TestingProfile::DestroyTopSites() {
539 if (top_sites_.get()) {
540 top_sites_->Shutdown();
542 // TopSitesImpl::Shutdown schedules some tasks (from TopSitesBackend) that
543 // need to be run to properly shutdown. Run all pending tasks now. This is
544 // normally handled by browser_process shutdown.
545 if (base::MessageLoop::current())
546 base::MessageLoop::current()->RunUntilIdle();
550 static KeyedService* BuildBookmarkModel(content::BrowserContext* context) {
551 Profile* profile = static_cast<Profile*>(context);
552 ChromeBookmarkClient* bookmark_client =
553 ChromeBookmarkClientFactory::GetForProfile(profile);
554 BookmarkModel* bookmark_model = new BookmarkModel(bookmark_client);
555 bookmark_client->Init(bookmark_model);
556 bookmark_model->Load(profile->GetPrefs(),
557 profile->GetPrefs()->GetString(prefs::kAcceptLanguages),
559 profile->GetIOTaskRunner(),
560 content::BrowserThread::GetMessageLoopProxyForThread(
561 content::BrowserThread::UI));
562 return bookmark_model;
565 static KeyedService* BuildChromeBookmarkClient(
566 content::BrowserContext* context) {
567 return new ChromeBookmarkClient(static_cast<Profile*>(context));
570 static KeyedService* BuildChromeHistoryClient(
571 content::BrowserContext* context) {
572 Profile* profile = static_cast<Profile*>(context);
573 return new ChromeHistoryClient(BookmarkModelFactory::GetForProfile(profile),
575 profile->GetTopSites());
578 void TestingProfile::CreateBookmarkModel(bool delete_file) {
580 base::FilePath path = GetPath().Append(bookmarks::kBookmarksFileName);
581 base::DeleteFile(path, false);
583 ChromeHistoryClientFactory::GetInstance()->SetTestingFactory(
584 this, BuildChromeHistoryClient);
585 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
586 this, BuildChromeBookmarkClient);
587 // This creates the BookmarkModel.
588 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
589 this, BuildBookmarkModel));
592 static KeyedService* BuildWebDataService(content::BrowserContext* profile) {
593 return new WebDataServiceWrapper(static_cast<Profile*>(profile));
596 void TestingProfile::CreateWebDataService() {
597 WebDataServiceFactory::GetInstance()->SetTestingFactory(
598 this, BuildWebDataService);
601 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
602 // Only get the history service if it actually exists since the caller of the
603 // test should explicitly call CreateHistoryService to build it.
604 HistoryService* history_service =
605 HistoryServiceFactory::GetForProfileWithoutCreating(this);
606 DCHECK(history_service);
607 history::InMemoryURLIndex* index = history_service->InMemoryIndex();
608 if (!index || index->restored())
610 base::RunLoop run_loop;
611 HistoryIndexRestoreObserver observer(
612 content::GetQuitTaskForRunLoop(&run_loop));
613 index->set_restore_cache_observer(&observer);
615 index->set_restore_cache_observer(NULL);
616 DCHECK(index->restored());
619 // TODO(phajdan.jr): Doesn't this hang if Top Sites are already loaded?
620 void TestingProfile::BlockUntilTopSitesLoaded() {
621 scoped_refptr<content::MessageLoopRunner> runner =
622 new content::MessageLoopRunner;
623 WaitTopSitesLoadedObserver observer(runner.get());
624 top_sites_->AddObserver(&observer);
626 top_sites_->RemoveObserver(&observer);
629 void TestingProfile::SetGuestSession(bool guest) {
630 guest_session_ = guest;
633 base::FilePath TestingProfile::GetPath() const {
634 return profile_path_;
637 scoped_refptr<base::SequencedTaskRunner> TestingProfile::GetIOTaskRunner() {
638 return base::MessageLoop::current()->message_loop_proxy();
641 TestingPrefServiceSyncable* TestingProfile::GetTestingPrefService() {
643 DCHECK(testing_prefs_);
644 return testing_prefs_;
647 TestingProfile* TestingProfile::AsTestingProfile() {
651 std::string TestingProfile::GetProfileName() {
652 return profile_name_;
655 Profile::ProfileType TestingProfile::GetProfileType() const {
657 return GUEST_PROFILE;
658 if (force_incognito_ || original_profile_)
659 return INCOGNITO_PROFILE;
660 return REGULAR_PROFILE;
663 bool TestingProfile::IsOffTheRecord() const {
664 return force_incognito_ || original_profile_;
667 void TestingProfile::SetOffTheRecordProfile(scoped_ptr<Profile> profile) {
668 DCHECK(!IsOffTheRecord());
669 DCHECK_EQ(this, profile->GetOriginalProfile());
670 incognito_profile_ = profile.Pass();
673 Profile* TestingProfile::GetOffTheRecordProfile() {
674 if (IsOffTheRecord())
676 if (!incognito_profile_)
677 TestingProfile::Builder().BuildIncognito(this);
678 return incognito_profile_.get();
681 bool TestingProfile::HasOffTheRecordProfile() {
682 return incognito_profile_.get() != NULL;
685 Profile* TestingProfile::GetOriginalProfile() {
686 if (original_profile_)
687 return original_profile_;
691 bool TestingProfile::IsSupervised() {
692 return !supervised_user_id_.empty();
695 #if defined(ENABLE_EXTENSIONS)
696 void TestingProfile::SetExtensionSpecialStoragePolicy(
697 ExtensionSpecialStoragePolicy* extension_special_storage_policy) {
698 extension_special_storage_policy_ = extension_special_storage_policy;
702 ExtensionSpecialStoragePolicy*
703 TestingProfile::GetExtensionSpecialStoragePolicy() {
704 #if defined(ENABLE_EXTENSIONS)
705 if (!extension_special_storage_policy_.get())
706 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(NULL);
707 return extension_special_storage_policy_.get();
713 net::CookieMonster* TestingProfile::GetCookieMonster() {
714 if (!GetRequestContext())
716 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
720 void TestingProfile::CreateTestingPrefService() {
721 DCHECK(!prefs_.get());
722 testing_prefs_ = new TestingPrefServiceSyncable();
723 prefs_.reset(testing_prefs_);
724 user_prefs::UserPrefs::Set(this, prefs_.get());
725 chrome::RegisterUserProfilePrefs(testing_prefs_->registry());
728 void TestingProfile::CreateIncognitoPrefService() {
729 DCHECK(original_profile_);
730 DCHECK(!testing_prefs_);
731 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
732 // leaves testing_prefs_ unset.
733 prefs_.reset(original_profile_->prefs_->CreateIncognitoPrefService(NULL));
734 user_prefs::UserPrefs::Set(this, prefs_.get());
737 void TestingProfile::CreateProfilePolicyConnector() {
738 #if defined(ENABLE_CONFIGURATION_POLICY)
739 schema_registry_service_ =
740 policy::SchemaRegistryServiceFactory::CreateForContext(
741 this, policy::Schema(), NULL);
742 CHECK_EQ(schema_registry_service_.get(),
743 policy::SchemaRegistryServiceFactory::GetForContext(this));
744 #endif // defined(ENABLE_CONFIGURATION_POLICY)
746 if (!policy_service_) {
747 #if defined(ENABLE_CONFIGURATION_POLICY)
748 std::vector<policy::ConfigurationPolicyProvider*> providers;
749 policy_service_.reset(new policy::PolicyServiceImpl(providers));
751 policy_service_.reset(new policy::PolicyServiceStub());
754 profile_policy_connector_.reset(new policy::ProfilePolicyConnector());
755 profile_policy_connector_->InitForTesting(policy_service_.Pass());
756 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
757 this, profile_policy_connector_.get());
758 CHECK_EQ(profile_policy_connector_.get(),
759 policy::ProfilePolicyConnectorFactory::GetForProfile(this));
762 PrefService* TestingProfile::GetPrefs() {
767 history::TopSites* TestingProfile::GetTopSites() {
768 return top_sites_.get();
771 history::TopSites* TestingProfile::GetTopSitesWithoutCreating() {
772 return top_sites_.get();
775 DownloadManagerDelegate* TestingProfile::GetDownloadManagerDelegate() {
779 net::URLRequestContextGetter* TestingProfile::GetRequestContext() {
780 return GetDefaultStoragePartition(this)->GetURLRequestContext();
783 net::URLRequestContextGetter* TestingProfile::CreateRequestContext(
784 content::ProtocolHandlerMap* protocol_handlers,
785 content::URLRequestInterceptorScopedVector request_interceptors) {
786 return new net::TestURLRequestContextGetter(
787 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
790 net::URLRequestContextGetter* TestingProfile::GetRequestContextForRenderProcess(
791 int renderer_child_id) {
792 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
794 return rph->GetStoragePartition()->GetURLRequestContext();
797 net::URLRequestContextGetter* TestingProfile::GetMediaRequestContext() {
801 net::URLRequestContextGetter*
802 TestingProfile::GetMediaRequestContextForRenderProcess(
803 int renderer_child_id) {
807 net::URLRequestContextGetter*
808 TestingProfile::GetMediaRequestContextForStoragePartition(
809 const base::FilePath& partition_path,
814 net::URLRequestContextGetter* TestingProfile::GetRequestContextForExtensions() {
815 if (!extensions_request_context_.get())
816 extensions_request_context_ = new TestExtensionURLRequestContextGetter();
817 return extensions_request_context_.get();
820 net::SSLConfigService* TestingProfile::GetSSLConfigService() {
821 if (!GetRequestContext())
823 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
826 net::URLRequestContextGetter*
827 TestingProfile::CreateRequestContextForStoragePartition(
828 const base::FilePath& partition_path,
830 content::ProtocolHandlerMap* protocol_handlers,
831 content::URLRequestInterceptorScopedVector request_interceptors) {
832 // We don't test storage partitions here yet, so returning the same dummy
833 // context is sufficient for now.
834 return GetRequestContext();
837 content::ResourceContext* TestingProfile::GetResourceContext() {
838 if (!resource_context_)
839 resource_context_ = new content::MockResourceContext();
840 return resource_context_;
843 HostContentSettingsMap* TestingProfile::GetHostContentSettingsMap() {
844 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
845 if (!host_content_settings_map_.get()) {
846 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
847 #if defined(ENABLE_EXTENSIONS)
848 ExtensionService* extension_service =
849 extensions::ExtensionSystem::Get(this)->extension_service();
850 if (extension_service) {
851 extension_service->RegisterContentSettings(
852 host_content_settings_map_.get());
856 return host_content_settings_map_.get();
859 content::BrowserPluginGuestManager* TestingProfile::GetGuestManager() {
860 #if defined(ENABLE_EXTENSIONS)
861 return extensions::GuestViewManager::FromBrowserContext(this);
867 content::PushMessagingService* TestingProfile::GetPushMessagingService() {
871 bool TestingProfile::IsSameProfile(Profile *p) {
875 base::Time TestingProfile::GetStartTime() const {
879 base::FilePath TestingProfile::last_selected_directory() {
880 return last_selected_directory_;
883 void TestingProfile::set_last_selected_directory(const base::FilePath& path) {
884 last_selected_directory_ = path;
887 PrefProxyConfigTracker* TestingProfile::GetProxyConfigTracker() {
888 if (!pref_proxy_config_tracker_.get()) {
889 // TestingProfile is used in unit tests, where local state is not available.
890 pref_proxy_config_tracker_.reset(
891 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
894 return pref_proxy_config_tracker_.get();
897 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
898 HistoryService* history_service =
899 HistoryServiceFactory::GetForProfile(this, Profile::EXPLICIT_ACCESS);
900 DCHECK(history_service);
901 DCHECK(base::MessageLoop::current());
903 base::CancelableTaskTracker tracker;
904 history_service->ScheduleDBTask(
905 scoped_ptr<history::HistoryDBTask>(
906 new QuittingHistoryDBTask()),
908 base::MessageLoop::current()->Run();
911 chrome_browser_net::Predictor* TestingProfile::GetNetworkPredictor() {
915 DevToolsNetworkController* TestingProfile::GetDevToolsNetworkController() {
919 void TestingProfile::ClearNetworkingHistorySince(
921 const base::Closure& completion) {
922 if (!completion.is_null()) {
923 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, completion);
927 GURL TestingProfile::GetHomePage() {
928 return GURL(chrome::kChromeUINewTabURL);
931 PrefService* TestingProfile::GetOffTheRecordPrefs() {
935 storage::SpecialStoragePolicy* TestingProfile::GetSpecialStoragePolicy() {
936 #if defined(ENABLE_EXTENSIONS)
937 return GetExtensionSpecialStoragePolicy();
943 content::SSLHostStateDelegate* TestingProfile::GetSSLHostStateDelegate() {
947 bool TestingProfile::WasCreatedByVersionOrLater(const std::string& version) {
951 bool TestingProfile::IsGuestSession() const {
952 return guest_session_;
955 Profile::ExitType TestingProfile::GetLastSessionExitType() {
956 return last_session_exited_cleanly_ ? EXIT_NORMAL : EXIT_CRASHED;
959 TestingProfile::Builder::Builder()
960 : build_called_(false),
962 guest_session_(false) {
965 TestingProfile::Builder::~Builder() {
968 void TestingProfile::Builder::SetPath(const base::FilePath& path) {
972 void TestingProfile::Builder::SetDelegate(Delegate* delegate) {
973 delegate_ = delegate;
976 #if defined(ENABLE_EXTENSIONS)
977 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
978 scoped_refptr<ExtensionSpecialStoragePolicy> policy) {
979 extension_policy_ = policy;
983 void TestingProfile::Builder::SetPrefService(
984 scoped_ptr<PrefServiceSyncable> prefs) {
985 pref_service_ = prefs.Pass();
988 void TestingProfile::Builder::SetGuestSession() {
989 guest_session_ = true;
992 void TestingProfile::Builder::SetSupervisedUserId(
993 const std::string& supervised_user_id) {
994 supervised_user_id_ = supervised_user_id;
997 void TestingProfile::Builder::SetPolicyService(
998 scoped_ptr<policy::PolicyService> policy_service) {
999 policy_service_ = policy_service.Pass();
1002 void TestingProfile::Builder::AddTestingFactory(
1003 BrowserContextKeyedServiceFactory* service_factory,
1004 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback) {
1005 testing_factories_.push_back(std::make_pair(service_factory, callback));
1008 scoped_ptr<TestingProfile> TestingProfile::Builder::Build() {
1009 DCHECK(!build_called_);
1010 build_called_ = true;
1012 return scoped_ptr<TestingProfile>(new TestingProfile(path_,
1014 #if defined(ENABLE_EXTENSIONS)
1017 pref_service_.Pass(),
1020 supervised_user_id_,
1021 policy_service_.Pass(),
1022 testing_factories_));
1025 TestingProfile* TestingProfile::Builder::BuildIncognito(
1026 TestingProfile* original_profile) {
1027 DCHECK(!build_called_);
1028 DCHECK(original_profile);
1029 build_called_ = true;
1031 // Note: Owned by |original_profile|.
1032 return new TestingProfile(path_,
1034 #if defined(ENABLE_EXTENSIONS)
1037 pref_service_.Pass(),
1040 supervised_user_id_,
1041 policy_service_.Pass(),
1042 testing_factories_);