Cancel MIDI permission request infobar on MIDIAccess stop.
[chromium-blink-merge.git] / chrome / test / base / testing_profile.cc
blob83de4b47dda01c3d028f0d69c4de14c3b42b2211
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.h"
26 #include "chrome/browser/extensions/extension_system_factory.h"
27 #include "chrome/browser/extensions/test_extension_system.h"
28 #include "chrome/browser/favicon/favicon_service.h"
29 #include "chrome/browser/favicon/favicon_service_factory.h"
30 #include "chrome/browser/geolocation/chrome_geolocation_permission_context.h"
31 #include "chrome/browser/geolocation/chrome_geolocation_permission_context_factory.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/shortcuts_backend.h"
37 #include "chrome/browser/history/shortcuts_backend_factory.h"
38 #include "chrome/browser/history/top_sites.h"
39 #include "chrome/browser/history/web_history_service_factory.h"
40 #include "chrome/browser/net/pref_proxy_config_tracker.h"
41 #include "chrome/browser/net/proxy_service_factory.h"
42 #include "chrome/browser/notifications/desktop_notification_service.h"
43 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
44 #include "chrome/browser/policy/profile_policy_connector.h"
45 #include "chrome/browser/policy/profile_policy_connector_factory.h"
46 #include "chrome/browser/prefs/browser_prefs.h"
47 #include "chrome/browser/prefs/pref_service_syncable.h"
48 #include "chrome/browser/prerender/prerender_manager.h"
49 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
50 #include "chrome/browser/profiles/profile_manager.h"
51 #include "chrome/browser/profiles/storage_partition_descriptor.h"
52 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
53 #include "chrome/browser/webdata/web_data_service.h"
54 #include "chrome/browser/webdata/web_data_service_factory.h"
55 #include "chrome/common/chrome_constants.h"
56 #include "chrome/common/chrome_switches.h"
57 #include "chrome/common/pref_names.h"
58 #include "chrome/common/url_constants.h"
59 #include "chrome/test/base/history_index_restore_observer.h"
60 #include "chrome/test/base/testing_pref_service_syncable.h"
61 #include "chrome/test/base/ui_test_utils.h"
62 #include "components/browser_context_keyed_service/browser_context_dependency_manager.h"
63 #include "components/user_prefs/user_prefs.h"
64 #include "content/public/browser/browser_thread.h"
65 #include "content/public/browser/notification_service.h"
66 #include "content/public/browser/render_process_host.h"
67 #include "content/public/browser/storage_partition.h"
68 #include "content/public/test/mock_resource_context.h"
69 #include "content/public/test/test_utils.h"
70 #include "extensions/common/constants.h"
71 #include "net/cookies/cookie_monster.h"
72 #include "net/url_request/url_request_context.h"
73 #include "net/url_request/url_request_context_getter.h"
74 #include "net/url_request/url_request_test_util.h"
75 #include "testing/gmock/include/gmock/gmock.h"
77 #if defined(ENABLE_CONFIGURATION_POLICY)
78 #include "chrome/browser/policy/configuration_policy_provider.h"
79 #include "chrome/browser/policy/policy_service_impl.h"
80 #else
81 #include "chrome/browser/policy/policy_service_stub.h"
82 #endif // defined(ENABLE_CONFIGURATION_POLICY)
84 #if defined(ENABLE_MANAGED_USERS)
85 #include "chrome/browser/managed_mode/managed_user_settings_service.h"
86 #include "chrome/browser/managed_mode/managed_user_settings_service_factory.h"
87 #endif
89 using base::Time;
90 using content::BrowserThread;
91 using content::DownloadManagerDelegate;
92 using testing::NiceMock;
93 using testing::Return;
95 namespace {
97 // Task used to make sure history has finished processing a request. Intended
98 // for use with BlockUntilHistoryProcessesPendingRequests.
100 class QuittingHistoryDBTask : public history::HistoryDBTask {
101 public:
102 QuittingHistoryDBTask() {}
104 virtual bool RunOnDBThread(history::HistoryBackend* backend,
105 history::HistoryDatabase* db) OVERRIDE {
106 return true;
109 virtual void DoneRunOnMainThread() OVERRIDE {
110 base::MessageLoop::current()->Quit();
113 private:
114 virtual ~QuittingHistoryDBTask() {}
116 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
119 class TestExtensionURLRequestContext : public net::URLRequestContext {
120 public:
121 TestExtensionURLRequestContext() {
122 net::CookieMonster* cookie_monster = new net::CookieMonster(NULL, NULL);
123 const char* schemes[] = {extensions::kExtensionScheme};
124 cookie_monster->SetCookieableSchemes(schemes, 1);
125 set_cookie_store(cookie_monster);
128 virtual ~TestExtensionURLRequestContext() {}
131 class TestExtensionURLRequestContextGetter
132 : public net::URLRequestContextGetter {
133 public:
134 virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE {
135 if (!context_.get())
136 context_.reset(new TestExtensionURLRequestContext());
137 return context_.get();
139 virtual scoped_refptr<base::SingleThreadTaskRunner>
140 GetNetworkTaskRunner() const OVERRIDE {
141 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
144 protected:
145 virtual ~TestExtensionURLRequestContextGetter() {}
147 private:
148 scoped_ptr<net::URLRequestContext> context_;
151 BrowserContextKeyedService* CreateTestDesktopNotificationService(
152 content::BrowserContext* profile) {
153 #if defined(ENABLE_NOTIFICATIONS)
154 return new DesktopNotificationService(static_cast<Profile*>(profile), NULL);
155 #else
156 return NULL;
157 #endif
160 } // namespace
162 // static
163 #if defined(OS_CHROMEOS)
164 // Must be kept in sync with
165 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
166 const char TestingProfile::kTestUserProfileDir[] = "test-user";
167 #else
168 const char TestingProfile::kTestUserProfileDir[] = "Default";
169 #endif
171 TestingProfile::TestingProfile()
172 : start_time_(Time::Now()),
173 testing_prefs_(NULL),
174 incognito_(false),
175 force_incognito_(false),
176 original_profile_(NULL),
177 last_session_exited_cleanly_(true),
178 browser_context_dependency_manager_(
179 BrowserContextDependencyManager::GetInstance()),
180 resource_context_(NULL),
181 delegate_(NULL) {
182 CreateTempProfileDir();
183 profile_path_ = temp_dir_.path();
185 Init();
186 FinishInit();
189 TestingProfile::TestingProfile(const base::FilePath& path)
190 : start_time_(Time::Now()),
191 testing_prefs_(NULL),
192 incognito_(false),
193 force_incognito_(false),
194 original_profile_(NULL),
195 last_session_exited_cleanly_(true),
196 profile_path_(path),
197 browser_context_dependency_manager_(
198 BrowserContextDependencyManager::GetInstance()),
199 resource_context_(NULL),
200 delegate_(NULL) {
201 Init();
202 FinishInit();
205 TestingProfile::TestingProfile(const base::FilePath& path,
206 Delegate* delegate)
207 : start_time_(Time::Now()),
208 testing_prefs_(NULL),
209 incognito_(false),
210 force_incognito_(false),
211 original_profile_(NULL),
212 last_session_exited_cleanly_(true),
213 profile_path_(path),
214 browser_context_dependency_manager_(
215 BrowserContextDependencyManager::GetInstance()),
216 resource_context_(NULL),
217 delegate_(delegate) {
218 Init();
219 if (delegate_) {
220 base::MessageLoop::current()->PostTask(
221 FROM_HERE,
222 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
223 } else {
224 FinishInit();
228 TestingProfile::TestingProfile(
229 const base::FilePath& path,
230 Delegate* delegate,
231 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
232 scoped_ptr<PrefServiceSyncable> prefs,
233 bool incognito,
234 const std::string& managed_user_id,
235 const TestingFactories& factories)
236 : start_time_(Time::Now()),
237 prefs_(prefs.release()),
238 testing_prefs_(NULL),
239 incognito_(incognito),
240 force_incognito_(false),
241 original_profile_(NULL),
242 managed_user_id_(managed_user_id),
243 last_session_exited_cleanly_(true),
244 extension_special_storage_policy_(extension_policy),
245 profile_path_(path),
246 browser_context_dependency_manager_(
247 BrowserContextDependencyManager::GetInstance()),
248 resource_context_(NULL),
249 delegate_(delegate) {
251 // If no profile path was supplied, create one.
252 if (profile_path_.empty()) {
253 CreateTempProfileDir();
254 profile_path_ = temp_dir_.path();
257 // Set any testing factories prior to initializing the services.
258 for (TestingFactories::const_iterator it = factories.begin();
259 it != factories.end(); ++it) {
260 it->first->SetTestingFactory(this, it->second);
263 Init();
264 // If caller supplied a delegate, delay the FinishInit invocation until other
265 // tasks have run.
266 // TODO(atwilson): See if this is still required once we convert the current
267 // users of the constructor that takes a Delegate* param.
268 if (delegate_) {
269 base::MessageLoop::current()->PostTask(
270 FROM_HERE,
271 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
272 } else {
273 FinishInit();
277 void TestingProfile::CreateTempProfileDir() {
278 if (!temp_dir_.CreateUniqueTempDir()) {
279 LOG(ERROR) << "Failed to create unique temporary directory.";
281 // Fallback logic in case we fail to create unique temporary directory.
282 base::FilePath system_tmp_dir;
283 bool success = PathService::Get(base::DIR_TEMP, &system_tmp_dir);
285 // We're severly screwed if we can't get the system temporary
286 // directory. Die now to avoid writing to the filesystem root
287 // or other bad places.
288 CHECK(success);
290 base::FilePath fallback_dir(
291 system_tmp_dir.AppendASCII("TestingProfilePath"));
292 base::DeleteFile(fallback_dir, true);
293 file_util::CreateDirectory(fallback_dir);
294 if (!temp_dir_.Set(fallback_dir)) {
295 // That shouldn't happen, but if it does, try to recover.
296 LOG(ERROR) << "Failed to use a fallback temporary directory.";
298 // We're screwed if this fails, see CHECK above.
299 CHECK(temp_dir_.Set(system_tmp_dir));
304 void TestingProfile::Init() {
305 // If threads have been initialized, we should be on the UI thread.
306 DCHECK(!content::BrowserThread::IsThreadInitialized(
307 content::BrowserThread::UI) ||
308 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
310 // Normally this would happen during browser startup, but for tests
311 // we need to trigger creation of Profile-related services.
312 ChromeBrowserMainExtraPartsProfiles::
313 EnsureBrowserContextKeyedServiceFactoriesBuilt();
315 if (prefs_.get())
316 user_prefs::UserPrefs::Set(this, prefs_.get());
317 else
318 CreateTestingPrefService();
320 if (!base::PathExists(profile_path_))
321 file_util::CreateDirectory(profile_path_);
323 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
324 // anymore, after converting the PrefService to a PKS. Until then it must
325 // be associated with a TestingProfile too.
326 CreateProfilePolicyConnector();
328 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
329 this, extensions::TestExtensionSystem::Build);
331 // If there is no separate original profile specified for this profile, then
332 // force preferences to be registered - this allows tests to create a
333 // standalone incognito profile while still having prefs registered.
334 browser_context_dependency_manager_->CreateBrowserContextServicesForTest(
335 this, !original_profile_);
337 #if defined(ENABLE_NOTIFICATIONS)
338 // Install profile keyed service factory hooks for dummy/test services
339 DesktopNotificationServiceFactory::GetInstance()->SetTestingFactory(
340 this, CreateTestDesktopNotificationService);
341 #endif
343 #if defined(ENABLE_MANAGED_USERS)
344 ManagedUserSettingsService* settings_service =
345 ManagedUserSettingsServiceFactory::GetForProfile(this);
346 TestingPrefStore* store = new TestingPrefStore();
347 settings_service->Init(store);
348 store->SetInitializationCompleted();
349 #endif
351 profile_name_ = "testing_profile";
354 void TestingProfile::FinishInit() {
355 DCHECK(content::NotificationService::current());
356 content::NotificationService::current()->Notify(
357 chrome::NOTIFICATION_PROFILE_CREATED,
358 content::Source<Profile>(static_cast<Profile*>(this)),
359 content::NotificationService::NoDetails());
361 ProfileManager* profile_manager = g_browser_process->profile_manager();
362 if (profile_manager)
363 profile_manager->InitProfileUserPrefs(this);
365 if (delegate_)
366 delegate_->OnProfileCreated(this, true, false);
369 TestingProfile::~TestingProfile() {
370 // Revert to non-incognito mode before shutdown.
371 force_incognito_ = false;
373 // Any objects holding live URLFetchers should be deleted before teardown.
374 TemplateURLFetcherFactory::ShutdownForProfile(this);
376 MaybeSendDestroyedNotification();
378 browser_context_dependency_manager_->DestroyBrowserContextServices(this);
380 if (host_content_settings_map_.get())
381 host_content_settings_map_->ShutdownOnUIThread();
383 DestroyTopSites();
385 if (pref_proxy_config_tracker_.get())
386 pref_proxy_config_tracker_->DetachFromPrefService();
387 // Failing a post == leaks == heapcheck failure. Make that an immediate test
388 // failure.
389 if (resource_context_) {
390 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
391 resource_context_));
392 resource_context_ = NULL;
393 content::RunAllPendingInMessageLoop(BrowserThread::IO);
397 static BrowserContextKeyedService* BuildFaviconService(
398 content::BrowserContext* profile) {
399 return new FaviconService(
400 HistoryServiceFactory::GetForProfileWithoutCreating(
401 static_cast<Profile*>(profile)));
404 void TestingProfile::CreateFaviconService() {
405 // It is up to the caller to create the history service if one is needed.
406 FaviconServiceFactory::GetInstance()->SetTestingFactory(
407 this, BuildFaviconService);
410 static BrowserContextKeyedService* BuildHistoryService(
411 content::BrowserContext* profile) {
412 return new HistoryService(static_cast<Profile*>(profile));
415 bool TestingProfile::CreateHistoryService(bool delete_file, bool no_db) {
416 DestroyHistoryService();
417 if (delete_file) {
418 base::FilePath path = GetPath();
419 path = path.Append(chrome::kHistoryFilename);
420 if (!base::DeleteFile(path, false) || base::PathExists(path))
421 return false;
423 // This will create and init the history service.
424 HistoryService* history_service = static_cast<HistoryService*>(
425 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
426 this, BuildHistoryService));
427 if (!history_service->Init(this->GetPath(),
428 BookmarkModelFactory::GetForProfile(this),
429 no_db)) {
430 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(this, NULL);
432 // Disable WebHistoryService by default, since it makes network requests.
433 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, NULL);
434 return true;
437 void TestingProfile::DestroyHistoryService() {
438 HistoryService* history_service =
439 HistoryServiceFactory::GetForProfileWithoutCreating(this);
440 if (!history_service)
441 return;
443 history_service->NotifyRenderProcessHostDestruction(0);
444 history_service->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
445 history_service->Cleanup();
446 HistoryServiceFactory::ShutdownForProfile(this);
448 // Wait for the backend class to terminate before deleting the files and
449 // moving to the next test. Note: if this never terminates, somebody is
450 // probably leaking a reference to the history backend, so it never calls
451 // our destroy task.
452 base::MessageLoop::current()->Run();
454 // Make sure we don't have any event pending that could disrupt the next
455 // test.
456 base::MessageLoop::current()->PostTask(FROM_HERE,
457 base::MessageLoop::QuitClosure());
458 base::MessageLoop::current()->Run();
461 void TestingProfile::CreateTopSites() {
462 DestroyTopSites();
463 top_sites_ = history::TopSites::Create(
464 this, GetPath().Append(chrome::kTopSitesFilename));
467 void TestingProfile::DestroyTopSites() {
468 if (top_sites_.get()) {
469 top_sites_->Shutdown();
470 top_sites_ = NULL;
471 // TopSitesImpl::Shutdown schedules some tasks (from TopSitesBackend) that
472 // need to be run to properly shutdown. Run all pending tasks now. This is
473 // normally handled by browser_process shutdown.
474 if (base::MessageLoop::current())
475 base::MessageLoop::current()->RunUntilIdle();
479 static BrowserContextKeyedService* BuildBookmarkModel(
480 content::BrowserContext* context) {
481 Profile* profile = static_cast<Profile*>(context);
482 BookmarkModel* bookmark_model = new BookmarkModel(profile);
483 bookmark_model->Load(profile->GetIOTaskRunner());
484 return bookmark_model;
487 void TestingProfile::CreateBookmarkModel(bool delete_file) {
488 if (delete_file) {
489 base::FilePath path = GetPath().Append(chrome::kBookmarksFileName);
490 base::DeleteFile(path, false);
492 // This will create a bookmark model.
493 BookmarkModel* bookmark_service = static_cast<BookmarkModel*>(
494 BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
495 this, BuildBookmarkModel));
497 HistoryService* history_service =
498 HistoryServiceFactory::GetForProfileWithoutCreating(this);
499 if (history_service) {
500 history_service->history_backend_->bookmark_service_ = bookmark_service;
501 history_service->history_backend_->expirer_.bookmark_service_ =
502 bookmark_service;
506 static BrowserContextKeyedService* BuildWebDataService(
507 content::BrowserContext* profile) {
508 return new WebDataServiceWrapper(static_cast<Profile*>(profile));
511 void TestingProfile::CreateWebDataService() {
512 WebDataServiceFactory::GetInstance()->SetTestingFactory(
513 this, BuildWebDataService);
516 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
517 // Only get the history service if it actually exists since the caller of the
518 // test should explicitly call CreateHistoryService to build it.
519 HistoryService* history_service =
520 HistoryServiceFactory::GetForProfileWithoutCreating(this);
521 DCHECK(history_service);
522 history::InMemoryURLIndex* index = history_service->InMemoryIndex();
523 if (!index || index->restored())
524 return;
525 base::RunLoop run_loop;
526 HistoryIndexRestoreObserver observer(
527 content::GetQuitTaskForRunLoop(&run_loop));
528 index->set_restore_cache_observer(&observer);
529 run_loop.Run();
530 index->set_restore_cache_observer(NULL);
531 DCHECK(index->restored());
534 // TODO(phajdan.jr): Doesn't this hang if Top Sites are already loaded?
535 void TestingProfile::BlockUntilTopSitesLoaded() {
536 content::WindowedNotificationObserver top_sites_loaded_observer(
537 chrome::NOTIFICATION_TOP_SITES_LOADED,
538 content::NotificationService::AllSources());
539 top_sites_loaded_observer.Wait();
542 base::FilePath TestingProfile::GetPath() const {
543 return profile_path_;
546 scoped_refptr<base::SequencedTaskRunner> TestingProfile::GetIOTaskRunner() {
547 return base::MessageLoop::current()->message_loop_proxy();
550 TestingPrefServiceSyncable* TestingProfile::GetTestingPrefService() {
551 if (!prefs_.get())
552 CreateTestingPrefService();
553 DCHECK(testing_prefs_);
554 return testing_prefs_;
557 TestingProfile* TestingProfile::AsTestingProfile() {
558 return this;
561 std::string TestingProfile::GetProfileName() {
562 return profile_name_;
565 bool TestingProfile::IsOffTheRecord() const {
566 return force_incognito_ || incognito_;
569 void TestingProfile::SetOffTheRecordProfile(scoped_ptr<Profile> profile) {
570 DCHECK(!IsOffTheRecord());
571 incognito_profile_ = profile.Pass();
574 void TestingProfile::SetOriginalProfile(Profile* profile) {
575 DCHECK(IsOffTheRecord());
576 original_profile_ = profile;
579 Profile* TestingProfile::GetOffTheRecordProfile() {
580 if (IsOffTheRecord())
581 return this;
582 return incognito_profile_.get();
585 bool TestingProfile::HasOffTheRecordProfile() {
586 return incognito_profile_.get() != NULL;
589 Profile* TestingProfile::GetOriginalProfile() {
590 if (original_profile_)
591 return original_profile_;
592 return this;
595 bool TestingProfile::IsManaged() {
596 return !managed_user_id_.empty();
599 ExtensionService* TestingProfile::GetExtensionService() {
600 return extensions::ExtensionSystem::Get(this)->extension_service();
603 void TestingProfile::SetExtensionSpecialStoragePolicy(
604 ExtensionSpecialStoragePolicy* extension_special_storage_policy) {
605 extension_special_storage_policy_ = extension_special_storage_policy;
608 ExtensionSpecialStoragePolicy*
609 TestingProfile::GetExtensionSpecialStoragePolicy() {
610 if (!extension_special_storage_policy_.get())
611 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(NULL);
612 return extension_special_storage_policy_.get();
615 net::CookieMonster* TestingProfile::GetCookieMonster() {
616 if (!GetRequestContext())
617 return NULL;
618 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
619 GetCookieMonster();
622 void TestingProfile::CreateTestingPrefService() {
623 DCHECK(!prefs_.get());
624 testing_prefs_ = new TestingPrefServiceSyncable();
625 prefs_.reset(testing_prefs_);
626 user_prefs::UserPrefs::Set(this, prefs_.get());
627 chrome::RegisterUserProfilePrefs(testing_prefs_->registry());
630 void TestingProfile::CreateProfilePolicyConnector() {
631 scoped_ptr<policy::PolicyService> service;
632 #if defined(ENABLE_CONFIGURATION_POLICY)
633 std::vector<policy::ConfigurationPolicyProvider*> providers;
634 service.reset(new policy::PolicyServiceImpl(providers));
635 #else
636 service.reset(new policy::PolicyServiceStub());
637 #endif
638 profile_policy_connector_.reset(
639 new policy::ProfilePolicyConnector(this));
640 profile_policy_connector_->InitForTesting(service.Pass());
641 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
642 this, profile_policy_connector_.get());
643 CHECK_EQ(profile_policy_connector_.get(),
644 policy::ProfilePolicyConnectorFactory::GetForProfile(this));
647 PrefService* TestingProfile::GetPrefs() {
648 if (!prefs_.get()) {
649 CreateTestingPrefService();
651 return prefs_.get();
654 history::TopSites* TestingProfile::GetTopSites() {
655 return top_sites_.get();
658 history::TopSites* TestingProfile::GetTopSitesWithoutCreating() {
659 return top_sites_.get();
662 DownloadManagerDelegate* TestingProfile::GetDownloadManagerDelegate() {
663 return NULL;
666 net::URLRequestContextGetter* TestingProfile::GetRequestContext() {
667 return GetDefaultStoragePartition(this)->GetURLRequestContext();
670 net::URLRequestContextGetter* TestingProfile::CreateRequestContext(
671 content::ProtocolHandlerMap* protocol_handlers) {
672 return new net::TestURLRequestContextGetter(
673 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
676 net::URLRequestContextGetter* TestingProfile::GetRequestContextForRenderProcess(
677 int renderer_child_id) {
678 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
679 renderer_child_id);
680 return rph->GetStoragePartition()->GetURLRequestContext();
683 net::URLRequestContextGetter* TestingProfile::GetMediaRequestContext() {
684 return NULL;
687 net::URLRequestContextGetter*
688 TestingProfile::GetMediaRequestContextForRenderProcess(
689 int renderer_child_id) {
690 return NULL;
693 net::URLRequestContextGetter*
694 TestingProfile::GetMediaRequestContextForStoragePartition(
695 const base::FilePath& partition_path,
696 bool in_memory) {
697 return NULL;
700 void TestingProfile::RequestMIDISysExPermission(
701 int render_process_id,
702 int render_view_id,
703 int bridge_id,
704 const GURL& requesting_frame,
705 const MIDISysExPermissionCallback& callback) {
706 // Always reject requests for testing.
707 callback.Run(false);
710 void TestingProfile::CancelMIDISysExPermissionRequest(
711 int render_process_id,
712 int render_view_id,
713 int bridge_id,
714 const GURL& requesting_frame) {
717 net::URLRequestContextGetter* TestingProfile::GetRequestContextForExtensions() {
718 if (!extensions_request_context_.get())
719 extensions_request_context_ = new TestExtensionURLRequestContextGetter();
720 return extensions_request_context_.get();
723 net::SSLConfigService* TestingProfile::GetSSLConfigService() {
724 if (!GetRequestContext())
725 return NULL;
726 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
729 net::URLRequestContextGetter*
730 TestingProfile::CreateRequestContextForStoragePartition(
731 const base::FilePath& partition_path,
732 bool in_memory,
733 content::ProtocolHandlerMap* protocol_handlers) {
734 // We don't test storage partitions here yet, so returning the same dummy
735 // context is sufficient for now.
736 return GetRequestContext();
739 content::ResourceContext* TestingProfile::GetResourceContext() {
740 if (!resource_context_)
741 resource_context_ = new content::MockResourceContext();
742 return resource_context_;
745 HostContentSettingsMap* TestingProfile::GetHostContentSettingsMap() {
746 if (!host_content_settings_map_.get()) {
747 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
748 #if defined(ENABLE_EXTENSIONS)
749 ExtensionService* extension_service = GetExtensionService();
750 if (extension_service)
751 host_content_settings_map_->RegisterExtensionService(extension_service);
752 #endif
754 return host_content_settings_map_.get();
757 content::GeolocationPermissionContext*
758 TestingProfile::GetGeolocationPermissionContext() {
759 return ChromeGeolocationPermissionContextFactory::GetForProfile(this);
762 std::wstring TestingProfile::GetName() {
763 return std::wstring();
766 std::wstring TestingProfile::GetID() {
767 return id_;
770 void TestingProfile::SetID(const std::wstring& id) {
771 id_ = id;
774 bool TestingProfile::IsSameProfile(Profile *p) {
775 return this == p;
778 base::Time TestingProfile::GetStartTime() const {
779 return start_time_;
782 base::FilePath TestingProfile::last_selected_directory() {
783 return last_selected_directory_;
786 void TestingProfile::set_last_selected_directory(const base::FilePath& path) {
787 last_selected_directory_ = path;
790 PrefProxyConfigTracker* TestingProfile::GetProxyConfigTracker() {
791 if (!pref_proxy_config_tracker_.get()) {
792 // TestingProfile is used in unit tests, where local state is not available.
793 pref_proxy_config_tracker_.reset(
794 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
795 NULL));
797 return pref_proxy_config_tracker_.get();
800 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
801 HistoryService* history_service =
802 HistoryServiceFactory::GetForProfile(this, Profile::EXPLICIT_ACCESS);
803 DCHECK(history_service);
804 DCHECK(base::MessageLoop::current());
806 CancelableRequestConsumer consumer;
807 history_service->ScheduleDBTask(new QuittingHistoryDBTask(), &consumer);
808 base::MessageLoop::current()->Run();
811 chrome_browser_net::Predictor* TestingProfile::GetNetworkPredictor() {
812 return NULL;
815 void TestingProfile::ClearNetworkingHistorySince(
816 base::Time time,
817 const base::Closure& completion) {
818 if (!completion.is_null()) {
819 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, completion);
823 GURL TestingProfile::GetHomePage() {
824 return GURL(chrome::kChromeUINewTabURL);
827 PrefService* TestingProfile::GetOffTheRecordPrefs() {
828 return NULL;
831 quota::SpecialStoragePolicy* TestingProfile::GetSpecialStoragePolicy() {
832 return GetExtensionSpecialStoragePolicy();
835 bool TestingProfile::WasCreatedByVersionOrLater(const std::string& version) {
836 return true;
839 bool TestingProfile::IsGuestSession() const {
840 return false;
843 Profile::ExitType TestingProfile::GetLastSessionExitType() {
844 return last_session_exited_cleanly_ ? EXIT_NORMAL : EXIT_CRASHED;
847 #if defined(OS_CHROMEOS)
848 bool TestingProfile::IsLoginProfile() {
849 return false;
851 #endif
853 TestingProfile::Builder::Builder()
854 : build_called_(false),
855 delegate_(NULL),
856 incognito_(false) {
859 TestingProfile::Builder::~Builder() {
862 void TestingProfile::Builder::SetPath(const base::FilePath& path) {
863 path_ = path;
866 void TestingProfile::Builder::SetDelegate(Delegate* delegate) {
867 delegate_ = delegate;
870 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
871 scoped_refptr<ExtensionSpecialStoragePolicy> policy) {
872 extension_policy_ = policy;
875 void TestingProfile::Builder::SetPrefService(
876 scoped_ptr<PrefServiceSyncable> prefs) {
877 pref_service_ = prefs.Pass();
880 void TestingProfile::Builder::SetIncognito() {
881 incognito_ = true;
884 void TestingProfile::Builder::SetManagedUserId(
885 const std::string& managed_user_id) {
886 managed_user_id_ = managed_user_id;
889 void TestingProfile::Builder::AddTestingFactory(
890 BrowserContextKeyedServiceFactory* service_factory,
891 BrowserContextKeyedServiceFactory::FactoryFunction callback) {
892 testing_factories_.push_back(std::make_pair(service_factory, callback));
895 scoped_ptr<TestingProfile> TestingProfile::Builder::Build() {
896 DCHECK(!build_called_);
897 build_called_ = true;
899 return scoped_ptr<TestingProfile>(new TestingProfile(
900 path_,
901 delegate_,
902 extension_policy_,
903 pref_service_.Pass(),
904 incognito_,
905 managed_user_id_,
906 testing_factories_));