bluetooth: Initial JNI setup for device/bluetooth.
[chromium-blink-merge.git] / chrome / test / base / testing_profile.cc
blobf544479ab863b3f719ae67baf93320ebc60abf5c
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/test/base/testing_profile.h"
7 #include "base/base_paths.h"
8 #include "base/command_line.h"
9 #include "base/files/file_util.h"
10 #include "base/message_loop/message_loop_proxy.h"
11 #include "base/path_service.h"
12 #include "base/prefs/testing_pref_store.h"
13 #include "base/run_loop.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
16 #include "chrome/browser/autocomplete/in_memory_url_index.h"
17 #include "chrome/browser/autocomplete/in_memory_url_index_factory.h"
18 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
19 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
20 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
21 #include "chrome/browser/browser_process.h"
22 #include "chrome/browser/chrome_notification_types.h"
23 #include "chrome/browser/favicon/chrome_fallback_icon_client_factory.h"
24 #include "chrome/browser/favicon/chrome_favicon_client_factory.h"
25 #include "chrome/browser/favicon/fallback_icon_service_factory.h"
26 #include "chrome/browser/favicon/favicon_service_factory.h"
27 #include "chrome/browser/history/chrome_history_client.h"
28 #include "chrome/browser/history/chrome_history_client_factory.h"
29 #include "chrome/browser/history/history_service_factory.h"
30 #include "chrome/browser/history/web_history_service_factory.h"
31 #include "chrome/browser/net/pref_proxy_config_tracker.h"
32 #include "chrome/browser/net/proxy_service_factory.h"
33 #include "chrome/browser/notifications/desktop_notification_service.h"
34 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
35 #include "chrome/browser/policy/profile_policy_connector.h"
36 #include "chrome/browser/policy/profile_policy_connector_factory.h"
37 #include "chrome/browser/prefs/browser_prefs.h"
38 #include "chrome/browser/prefs/pref_service_syncable.h"
39 #include "chrome/browser/prerender/prerender_manager.h"
40 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
41 #include "chrome/browser/profiles/profile_manager.h"
42 #include "chrome/browser/profiles/storage_partition_descriptor.h"
43 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
44 #include "chrome/browser/sync/glue/sync_start_util.h"
45 #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
46 #include "chrome/browser/webdata/web_data_service_factory.h"
47 #include "chrome/common/chrome_constants.h"
48 #include "chrome/common/chrome_switches.h"
49 #include "chrome/common/pref_names.h"
50 #include "chrome/common/url_constants.h"
51 #include "chrome/test/base/history_index_restore_observer.h"
52 #include "chrome/test/base/testing_pref_service_syncable.h"
53 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
54 #include "components/bookmarks/browser/bookmark_model.h"
55 #include "components/bookmarks/common/bookmark_constants.h"
56 #include "components/content_settings/core/browser/host_content_settings_map.h"
57 #include "components/favicon/core/fallback_icon_service.h"
58 #include "components/favicon/core/favicon_service.h"
59 #include "components/history/content/browser/content_visit_delegate.h"
60 #include "components/history/content/browser/history_database_helper.h"
61 #include "components/history/core/browser/history_backend.h"
62 #include "components/history/core/browser/history_constants.h"
63 #include "components/history/core/browser/history_database_params.h"
64 #include "components/history/core/browser/history_db_task.h"
65 #include "components/history/core/browser/history_service.h"
66 #include "components/keyed_service/content/browser_context_dependency_manager.h"
67 #include "components/keyed_service/core/refcounted_keyed_service.h"
68 #include "components/policy/core/common/policy_service.h"
69 #include "components/ui/zoom/zoom_event_manager.h"
70 #include "components/user_prefs/user_prefs.h"
71 #include "components/webdata_services/web_data_service_wrapper.h"
72 #include "content/public/browser/browser_thread.h"
73 #include "content/public/browser/cookie_store_factory.h"
74 #include "content/public/browser/notification_service.h"
75 #include "content/public/browser/render_process_host.h"
76 #include "content/public/browser/storage_partition.h"
77 #include "content/public/browser/zoom_level_delegate.h"
78 #include "content/public/test/mock_resource_context.h"
79 #include "content/public/test/test_utils.h"
80 #include "extensions/common/constants.h"
81 #include "net/cookies/cookie_monster.h"
82 #include "net/url_request/url_request_context.h"
83 #include "net/url_request/url_request_context_getter.h"
84 #include "net/url_request/url_request_test_util.h"
85 #include "testing/gmock/include/gmock/gmock.h"
87 #if defined(ENABLE_CONFIGURATION_POLICY)
88 #include "chrome/browser/policy/schema_registry_service.h"
89 #include "chrome/browser/policy/schema_registry_service_factory.h"
90 #include "components/policy/core/common/configuration_policy_provider.h"
91 #include "components/policy/core/common/policy_service_impl.h"
92 #include "components/policy/core/common/schema.h"
93 #else
94 #include "components/policy/core/common/policy_service_stub.h"
95 #endif // defined(ENABLE_CONFIGURATION_POLICY)
97 #if defined(ENABLE_EXTENSIONS)
98 #include "chrome/browser/extensions/extension_service.h"
99 #include "chrome/browser/extensions/extension_special_storage_policy.h"
100 #include "chrome/browser/extensions/extension_system_factory.h"
101 #include "chrome/browser/extensions/test_extension_system.h"
102 #include "components/guest_view/browser/guest_view_manager.h"
103 #include "extensions/browser/extension_system.h"
104 #endif
106 #if defined(OS_ANDROID)
107 #include "chrome/browser/signin/android_profile_oauth2_token_service.h"
108 #endif
110 #if defined(ENABLE_SUPERVISED_USERS)
111 #include "chrome/browser/supervised_user/supervised_user_constants.h"
112 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
113 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
114 #endif
116 using base::Time;
117 using bookmarks::BookmarkModel;
118 using content::BrowserThread;
119 using content::DownloadManagerDelegate;
120 using testing::NiceMock;
121 using testing::Return;
123 namespace {
125 // Task used to make sure history has finished processing a request. Intended
126 // for use with BlockUntilHistoryProcessesPendingRequests.
128 class QuittingHistoryDBTask : public history::HistoryDBTask {
129 public:
130 QuittingHistoryDBTask() {}
132 bool RunOnDBThread(history::HistoryBackend* backend,
133 history::HistoryDatabase* db) override {
134 return true;
137 void DoneRunOnMainThread() override { base::MessageLoop::current()->Quit(); }
139 private:
140 ~QuittingHistoryDBTask() override {}
142 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
145 class TestExtensionURLRequestContext : public net::URLRequestContext {
146 public:
147 TestExtensionURLRequestContext() {
148 net::CookieMonster* cookie_monster =
149 content::CreateCookieStore(content::CookieStoreConfig())->
150 GetCookieMonster();
151 const char* const schemes[] = {extensions::kExtensionScheme};
152 cookie_monster->SetCookieableSchemes(schemes, arraysize(schemes));
153 set_cookie_store(cookie_monster);
156 ~TestExtensionURLRequestContext() override { AssertNoURLRequests(); }
159 class TestExtensionURLRequestContextGetter
160 : public net::URLRequestContextGetter {
161 public:
162 net::URLRequestContext* GetURLRequestContext() override {
163 if (!context_.get())
164 context_.reset(new TestExtensionURLRequestContext());
165 return context_.get();
167 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
168 const override {
169 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
172 protected:
173 ~TestExtensionURLRequestContextGetter() override {}
175 private:
176 scoped_ptr<net::URLRequestContext> context_;
179 #if defined(ENABLE_NOTIFICATIONS)
180 KeyedService* CreateTestDesktopNotificationService(
181 content::BrowserContext* profile) {
182 return new DesktopNotificationService(static_cast<Profile*>(profile));
184 #endif
186 KeyedService* BuildFaviconService(content::BrowserContext* context) {
187 Profile* profile = Profile::FromBrowserContext(context);
188 return new favicon::FaviconService(
189 ChromeFaviconClientFactory::GetForProfile(profile),
190 HistoryServiceFactory::GetForProfile(profile,
191 ServiceAccessType::EXPLICIT_ACCESS));
194 KeyedService* BuildHistoryService(content::BrowserContext* context) {
195 Profile* profile = Profile::FromBrowserContext(context);
196 history::HistoryService* history_service = new history::HistoryService(
197 ChromeHistoryClientFactory::GetForProfile(profile),
198 scoped_ptr<history::VisitDelegate>(
199 new history::ContentVisitDelegate(profile)));
200 return history_service;
203 KeyedService* BuildInMemoryURLIndex(content::BrowserContext* context) {
204 Profile* profile = Profile::FromBrowserContext(context);
205 InMemoryURLIndex* in_memory_url_index = new InMemoryURLIndex(
206 BookmarkModelFactory::GetForProfile(profile),
207 HistoryServiceFactory::GetForProfile(profile,
208 ServiceAccessType::IMPLICIT_ACCESS),
209 profile->GetPath(),
210 profile->GetPrefs()->GetString(prefs::kAcceptLanguages));
211 in_memory_url_index->Init();
212 return in_memory_url_index;
215 KeyedService* BuildBookmarkModel(content::BrowserContext* context) {
216 Profile* profile = static_cast<Profile*>(context);
217 ChromeBookmarkClient* bookmark_client =
218 ChromeBookmarkClientFactory::GetForProfile(profile);
219 BookmarkModel* bookmark_model = new BookmarkModel(bookmark_client);
220 bookmark_client->Init(bookmark_model);
221 bookmark_model->Load(profile->GetPrefs(),
222 profile->GetPrefs()->GetString(prefs::kAcceptLanguages),
223 profile->GetPath(),
224 profile->GetIOTaskRunner(),
225 content::BrowserThread::GetMessageLoopProxyForThread(
226 content::BrowserThread::UI));
227 return bookmark_model;
230 KeyedService* BuildChromeBookmarkClient(
231 content::BrowserContext* context) {
232 return new ChromeBookmarkClient(static_cast<Profile*>(context));
235 KeyedService* BuildChromeHistoryClient(
236 content::BrowserContext* context) {
237 Profile* profile = static_cast<Profile*>(context);
238 return new ChromeHistoryClient(BookmarkModelFactory::GetForProfile(profile));
241 void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type,
242 sql::InitStatus status) {
243 NOTREACHED();
246 KeyedService* BuildWebDataService(content::BrowserContext* context) {
247 const base::FilePath& context_path = context->GetPath();
248 return new WebDataServiceWrapper(
249 context_path, g_browser_process->GetApplicationLocale(),
250 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
251 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB),
252 sync_start_util::GetFlareForSyncableService(context_path),
253 &TestProfileErrorCallback);
256 } // namespace
258 // static
259 #if defined(OS_CHROMEOS)
260 // Must be kept in sync with
261 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
262 const char TestingProfile::kTestUserProfileDir[] = "test-user";
263 #else
264 const char TestingProfile::kTestUserProfileDir[] = "Default";
265 #endif
267 TestingProfile::TestingProfile()
268 : start_time_(Time::Now()),
269 testing_prefs_(NULL),
270 force_incognito_(false),
271 original_profile_(NULL),
272 guest_session_(false),
273 last_session_exited_cleanly_(true),
274 browser_context_dependency_manager_(
275 BrowserContextDependencyManager::GetInstance()),
276 resource_context_(NULL),
277 delegate_(NULL) {
278 CreateTempProfileDir();
279 profile_path_ = temp_dir_.path();
281 Init();
282 FinishInit();
285 TestingProfile::TestingProfile(const base::FilePath& path)
286 : start_time_(Time::Now()),
287 testing_prefs_(NULL),
288 force_incognito_(false),
289 original_profile_(NULL),
290 guest_session_(false),
291 last_session_exited_cleanly_(true),
292 profile_path_(path),
293 browser_context_dependency_manager_(
294 BrowserContextDependencyManager::GetInstance()),
295 resource_context_(NULL),
296 delegate_(NULL) {
297 Init();
298 FinishInit();
301 TestingProfile::TestingProfile(const base::FilePath& path,
302 Delegate* delegate)
303 : start_time_(Time::Now()),
304 testing_prefs_(NULL),
305 force_incognito_(false),
306 original_profile_(NULL),
307 guest_session_(false),
308 last_session_exited_cleanly_(true),
309 profile_path_(path),
310 browser_context_dependency_manager_(
311 BrowserContextDependencyManager::GetInstance()),
312 resource_context_(NULL),
313 delegate_(delegate) {
314 Init();
315 if (delegate_) {
316 base::MessageLoop::current()->PostTask(
317 FROM_HERE,
318 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
319 } else {
320 FinishInit();
324 TestingProfile::TestingProfile(
325 const base::FilePath& path,
326 Delegate* delegate,
327 #if defined(ENABLE_EXTENSIONS)
328 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
329 #endif
330 scoped_ptr<PrefServiceSyncable> prefs,
331 TestingProfile* parent,
332 bool guest_session,
333 const std::string& supervised_user_id,
334 scoped_ptr<policy::PolicyService> policy_service,
335 const TestingFactories& factories)
336 : start_time_(Time::Now()),
337 prefs_(prefs.release()),
338 testing_prefs_(NULL),
339 force_incognito_(false),
340 original_profile_(parent),
341 guest_session_(guest_session),
342 last_session_exited_cleanly_(true),
343 #if defined(ENABLE_EXTENSIONS)
344 extension_special_storage_policy_(extension_policy),
345 #endif
346 profile_path_(path),
347 browser_context_dependency_manager_(
348 BrowserContextDependencyManager::GetInstance()),
349 resource_context_(NULL),
350 delegate_(delegate),
351 policy_service_(policy_service.release()) {
352 if (parent)
353 parent->SetOffTheRecordProfile(scoped_ptr<Profile>(this));
355 // If no profile path was supplied, create one.
356 if (profile_path_.empty()) {
357 CreateTempProfileDir();
358 profile_path_ = temp_dir_.path();
361 // Set any testing factories prior to initializing the services.
362 for (TestingFactories::const_iterator it = factories.begin();
363 it != factories.end(); ++it) {
364 it->first->SetTestingFactory(this, it->second);
367 Init();
368 // If caller supplied a delegate, delay the FinishInit invocation until other
369 // tasks have run.
370 // TODO(atwilson): See if this is still required once we convert the current
371 // users of the constructor that takes a Delegate* param.
372 if (delegate_) {
373 base::MessageLoop::current()->PostTask(
374 FROM_HERE,
375 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
376 } else {
377 FinishInit();
380 SetSupervisedUserId(supervised_user_id);
383 void TestingProfile::CreateTempProfileDir() {
384 if (!temp_dir_.CreateUniqueTempDir()) {
385 LOG(ERROR) << "Failed to create unique temporary directory.";
387 // Fallback logic in case we fail to create unique temporary directory.
388 base::FilePath system_tmp_dir;
389 bool success = PathService::Get(base::DIR_TEMP, &system_tmp_dir);
391 // We're severly screwed if we can't get the system temporary
392 // directory. Die now to avoid writing to the filesystem root
393 // or other bad places.
394 CHECK(success);
396 base::FilePath fallback_dir(
397 system_tmp_dir.AppendASCII("TestingProfilePath"));
398 base::DeleteFile(fallback_dir, true);
399 base::CreateDirectory(fallback_dir);
400 if (!temp_dir_.Set(fallback_dir)) {
401 // That shouldn't happen, but if it does, try to recover.
402 LOG(ERROR) << "Failed to use a fallback temporary directory.";
404 // We're screwed if this fails, see CHECK above.
405 CHECK(temp_dir_.Set(system_tmp_dir));
410 void TestingProfile::Init() {
411 // If threads have been initialized, we should be on the UI thread.
412 DCHECK(!content::BrowserThread::IsThreadInitialized(
413 content::BrowserThread::UI) ||
414 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
416 set_is_guest_profile(guest_session_);
418 #if defined(OS_ANDROID)
419 // Make sure token service knows its running in tests.
420 AndroidProfileOAuth2TokenService::set_is_testing_profile();
421 #endif
423 // Normally this would happen during browser startup, but for tests
424 // we need to trigger creation of Profile-related services.
425 ChromeBrowserMainExtraPartsProfiles::
426 EnsureBrowserContextKeyedServiceFactoriesBuilt();
428 if (prefs_.get())
429 user_prefs::UserPrefs::Set(this, prefs_.get());
430 else if (IsOffTheRecord())
431 CreateIncognitoPrefService();
432 else
433 CreateTestingPrefService();
435 if (!base::PathExists(profile_path_))
436 base::CreateDirectory(profile_path_);
438 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
439 // anymore, after converting the PrefService to a PKS. Until then it must
440 // be associated with a TestingProfile too.
441 if (!IsOffTheRecord())
442 CreateProfilePolicyConnector();
444 #if defined(ENABLE_EXTENSIONS)
445 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
446 this, extensions::TestExtensionSystem::Build);
447 #endif
449 // Prefs for incognito profiles are set in CreateIncognitoPrefService() by
450 // simulating ProfileImpl::GetOffTheRecordPrefs().
451 if (!IsOffTheRecord()) {
452 DCHECK(!original_profile_);
453 user_prefs::PrefRegistrySyncable* pref_registry =
454 static_cast<user_prefs::PrefRegistrySyncable*>(
455 prefs_->DeprecatedGetPrefRegistry());
456 browser_context_dependency_manager_->
457 RegisterProfilePrefsForServices(this, pref_registry);
460 browser_context_dependency_manager_->CreateBrowserContextServicesForTest(
461 this);
463 #if defined(ENABLE_NOTIFICATIONS)
464 // Install profile keyed service factory hooks for dummy/test services
465 DesktopNotificationServiceFactory::GetInstance()->SetTestingFactory(
466 this, CreateTestDesktopNotificationService);
467 #endif
469 #if defined(ENABLE_SUPERVISED_USERS)
470 if (!IsOffTheRecord()) {
471 SupervisedUserSettingsService* settings_service =
472 SupervisedUserSettingsServiceFactory::GetForProfile(this);
473 TestingPrefStore* store = new TestingPrefStore();
474 settings_service->Init(store);
475 store->SetInitializationCompleted();
477 #endif
479 profile_name_ = "testing_profile";
482 void TestingProfile::FinishInit() {
483 DCHECK(content::NotificationService::current());
484 content::NotificationService::current()->Notify(
485 chrome::NOTIFICATION_PROFILE_CREATED,
486 content::Source<Profile>(static_cast<Profile*>(this)),
487 content::NotificationService::NoDetails());
489 ProfileManager* profile_manager = g_browser_process->profile_manager();
490 if (profile_manager)
491 profile_manager->InitProfileUserPrefs(this);
493 if (delegate_)
494 delegate_->OnProfileCreated(this, true, false);
497 TestingProfile::~TestingProfile() {
498 // Revert to non-incognito mode before shutdown.
499 force_incognito_ = false;
501 // If this profile owns an incognito profile, tear it down first.
502 incognito_profile_.reset();
504 // Any objects holding live URLFetchers should be deleted before teardown.
505 TemplateURLFetcherFactory::ShutdownForProfile(this);
507 MaybeSendDestroyedNotification();
509 browser_context_dependency_manager_->DestroyBrowserContextServices(this);
511 if (host_content_settings_map_.get())
512 host_content_settings_map_->ShutdownOnUIThread();
514 if (pref_proxy_config_tracker_.get())
515 pref_proxy_config_tracker_->DetachFromPrefService();
516 // Failing a post == leaks == heapcheck failure. Make that an immediate test
517 // failure.
518 if (resource_context_) {
519 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
520 resource_context_));
521 resource_context_ = NULL;
522 content::RunAllPendingInMessageLoop(BrowserThread::IO);
526 void TestingProfile::CreateFaviconService() {
527 // It is up to the caller to create the history service if one is needed.
528 FaviconServiceFactory::GetInstance()->SetTestingFactory(
529 this, BuildFaviconService);
532 bool TestingProfile::CreateHistoryService(bool delete_file, bool no_db) {
533 DestroyHistoryService();
534 if (delete_file) {
535 base::FilePath path = GetPath();
536 path = path.Append(history::kHistoryFilename);
537 if (!base::DeleteFile(path, false) || base::PathExists(path))
538 return false;
540 // This will create and init the history service.
541 history::HistoryService* history_service =
542 static_cast<history::HistoryService*>(
543 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
544 this, BuildHistoryService));
545 if (!history_service->Init(
546 no_db, GetPrefs()->GetString(prefs::kAcceptLanguages),
547 history::HistoryDatabaseParamsForPath(GetPath()))) {
548 HistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
549 return false;
551 // Some tests expect that CreateHistoryService() will also make the
552 // InMemoryURLIndex available.
553 InMemoryURLIndexFactory::GetInstance()->SetTestingFactory(
554 this, BuildInMemoryURLIndex);
555 // Disable WebHistoryService by default, since it makes network requests.
556 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
557 return true;
560 void TestingProfile::DestroyHistoryService() {
561 history::HistoryService* history_service =
562 HistoryServiceFactory::GetForProfileWithoutCreating(this);
563 if (!history_service)
564 return;
566 history_service->ClearCachedDataForContextID(0);
567 history_service->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
568 history_service->Cleanup();
569 HistoryServiceFactory::ShutdownForProfile(this);
571 // Wait for the backend class to terminate before deleting the files and
572 // moving to the next test. Note: if this never terminates, somebody is
573 // probably leaking a reference to the history backend, so it never calls
574 // our destroy task.
575 base::MessageLoop::current()->Run();
577 // Make sure we don't have any event pending that could disrupt the next
578 // test.
579 base::MessageLoop::current()->PostTask(FROM_HERE,
580 base::MessageLoop::QuitClosure());
581 base::MessageLoop::current()->Run();
584 void TestingProfile::CreateBookmarkModel(bool delete_file) {
585 if (delete_file) {
586 base::FilePath path = GetPath().Append(bookmarks::kBookmarksFileName);
587 base::DeleteFile(path, false);
589 ChromeHistoryClientFactory::GetInstance()->SetTestingFactory(
590 this, BuildChromeHistoryClient);
591 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
592 this, BuildChromeBookmarkClient);
593 // This creates the BookmarkModel.
594 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
595 this, BuildBookmarkModel));
598 void TestingProfile::CreateWebDataService() {
599 WebDataServiceFactory::GetInstance()->SetTestingFactory(
600 this, BuildWebDataService);
603 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
604 // Only get the history service if it actually exists since the caller of the
605 // test should explicitly call CreateHistoryService to build it.
606 history::HistoryService* history_service =
607 HistoryServiceFactory::GetForProfileWithoutCreating(this);
608 DCHECK(history_service);
609 InMemoryURLIndex* index = InMemoryURLIndexFactory::GetForProfile(this);
610 if (!index || index->restored())
611 return;
612 base::RunLoop run_loop;
613 HistoryIndexRestoreObserver observer(
614 content::GetQuitTaskForRunLoop(&run_loop));
615 index->set_restore_cache_observer(&observer);
616 run_loop.Run();
617 index->set_restore_cache_observer(NULL);
618 DCHECK(index->restored());
621 void TestingProfile::SetGuestSession(bool guest) {
622 guest_session_ = guest;
625 base::FilePath TestingProfile::GetPath() const {
626 return profile_path_;
629 scoped_ptr<content::ZoomLevelDelegate> TestingProfile::CreateZoomLevelDelegate(
630 const base::FilePath& partition_path) {
631 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
632 GetPrefs(), GetPath(), partition_path,
633 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
636 scoped_refptr<base::SequencedTaskRunner> TestingProfile::GetIOTaskRunner() {
637 return base::MessageLoop::current()->message_loop_proxy();
640 TestingPrefServiceSyncable* TestingProfile::GetTestingPrefService() {
641 DCHECK(prefs_);
642 DCHECK(testing_prefs_);
643 return testing_prefs_;
646 TestingProfile* TestingProfile::AsTestingProfile() {
647 return this;
650 std::string TestingProfile::GetProfileUserName() const {
651 return profile_name_;
654 Profile::ProfileType TestingProfile::GetProfileType() const {
655 if (guest_session_)
656 return GUEST_PROFILE;
657 if (force_incognito_ || original_profile_)
658 return INCOGNITO_PROFILE;
659 return REGULAR_PROFILE;
662 bool TestingProfile::IsOffTheRecord() const {
663 return force_incognito_ || original_profile_;
666 void TestingProfile::SetOffTheRecordProfile(scoped_ptr<Profile> profile) {
667 DCHECK(!IsOffTheRecord());
668 DCHECK_EQ(this, profile->GetOriginalProfile());
669 incognito_profile_ = profile.Pass();
672 Profile* TestingProfile::GetOffTheRecordProfile() {
673 if (IsOffTheRecord())
674 return this;
675 if (!incognito_profile_)
676 TestingProfile::Builder().BuildIncognito(this);
677 return incognito_profile_.get();
680 bool TestingProfile::HasOffTheRecordProfile() {
681 return incognito_profile_.get() != NULL;
684 Profile* TestingProfile::GetOriginalProfile() {
685 if (original_profile_)
686 return original_profile_;
687 return this;
690 void TestingProfile::SetSupervisedUserId(const std::string& id) {
691 supervised_user_id_ = id;
692 if (!id.empty())
693 GetPrefs()->SetString(prefs::kSupervisedUserId, id);
694 else
695 GetPrefs()->ClearPref(prefs::kSupervisedUserId);
698 bool TestingProfile::IsSupervised() {
699 return !supervised_user_id_.empty();
702 bool TestingProfile::IsChild() {
703 #if defined(ENABLE_SUPERVISED_USERS)
704 return supervised_user_id_ == supervised_users::kChildAccountSUID;
705 #else
706 return false;
707 #endif
710 bool TestingProfile::IsLegacySupervised() {
711 return IsSupervised() && !IsChild();
714 #if defined(ENABLE_EXTENSIONS)
715 void TestingProfile::SetExtensionSpecialStoragePolicy(
716 ExtensionSpecialStoragePolicy* extension_special_storage_policy) {
717 extension_special_storage_policy_ = extension_special_storage_policy;
719 #endif
721 ExtensionSpecialStoragePolicy*
722 TestingProfile::GetExtensionSpecialStoragePolicy() {
723 #if defined(ENABLE_EXTENSIONS)
724 if (!extension_special_storage_policy_.get())
725 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(NULL);
726 return extension_special_storage_policy_.get();
727 #else
728 return NULL;
729 #endif
732 net::CookieMonster* TestingProfile::GetCookieMonster() {
733 if (!GetRequestContext())
734 return NULL;
735 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
736 GetCookieMonster();
739 void TestingProfile::CreateTestingPrefService() {
740 DCHECK(!prefs_.get());
741 testing_prefs_ = new TestingPrefServiceSyncable();
742 prefs_.reset(testing_prefs_);
743 user_prefs::UserPrefs::Set(this, prefs_.get());
744 chrome::RegisterUserProfilePrefs(testing_prefs_->registry());
747 void TestingProfile::CreateIncognitoPrefService() {
748 DCHECK(original_profile_);
749 DCHECK(!testing_prefs_);
750 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
751 // leaves testing_prefs_ unset.
752 prefs_.reset(original_profile_->prefs_->CreateIncognitoPrefService(NULL));
753 user_prefs::UserPrefs::Set(this, prefs_.get());
756 void TestingProfile::CreateProfilePolicyConnector() {
757 #if defined(ENABLE_CONFIGURATION_POLICY)
758 schema_registry_service_ =
759 policy::SchemaRegistryServiceFactory::CreateForContext(
760 this, policy::Schema(), NULL);
761 CHECK_EQ(schema_registry_service_.get(),
762 policy::SchemaRegistryServiceFactory::GetForContext(this));
763 #endif // defined(ENABLE_CONFIGURATION_POLICY)
765 if (!policy_service_) {
766 #if defined(ENABLE_CONFIGURATION_POLICY)
767 std::vector<policy::ConfigurationPolicyProvider*> providers;
768 policy_service_.reset(new policy::PolicyServiceImpl(providers));
769 #else
770 policy_service_.reset(new policy::PolicyServiceStub());
771 #endif
773 profile_policy_connector_.reset(new policy::ProfilePolicyConnector());
774 profile_policy_connector_->InitForTesting(policy_service_.Pass());
775 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
776 this, profile_policy_connector_.get());
777 CHECK_EQ(profile_policy_connector_.get(),
778 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(this));
781 PrefService* TestingProfile::GetPrefs() {
782 DCHECK(prefs_);
783 return prefs_.get();
786 const PrefService* TestingProfile::GetPrefs() const {
787 DCHECK(prefs_);
788 return prefs_.get();
791 chrome::ChromeZoomLevelPrefs* TestingProfile::GetZoomLevelPrefs() {
792 return static_cast<chrome::ChromeZoomLevelPrefs*>(
793 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
796 DownloadManagerDelegate* TestingProfile::GetDownloadManagerDelegate() {
797 return NULL;
800 net::URLRequestContextGetter* TestingProfile::GetRequestContext() {
801 return GetDefaultStoragePartition(this)->GetURLRequestContext();
804 net::URLRequestContextGetter* TestingProfile::CreateRequestContext(
805 content::ProtocolHandlerMap* protocol_handlers,
806 content::URLRequestInterceptorScopedVector request_interceptors) {
807 return new net::TestURLRequestContextGetter(
808 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
811 net::URLRequestContextGetter* TestingProfile::GetRequestContextForRenderProcess(
812 int renderer_child_id) {
813 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
814 renderer_child_id);
815 return rph->GetStoragePartition()->GetURLRequestContext();
818 net::URLRequestContextGetter* TestingProfile::GetMediaRequestContext() {
819 return NULL;
822 net::URLRequestContextGetter*
823 TestingProfile::GetMediaRequestContextForRenderProcess(
824 int renderer_child_id) {
825 return NULL;
828 net::URLRequestContextGetter*
829 TestingProfile::GetMediaRequestContextForStoragePartition(
830 const base::FilePath& partition_path,
831 bool in_memory) {
832 return NULL;
835 net::URLRequestContextGetter* TestingProfile::GetRequestContextForExtensions() {
836 if (!extensions_request_context_.get())
837 extensions_request_context_ = new TestExtensionURLRequestContextGetter();
838 return extensions_request_context_.get();
841 net::SSLConfigService* TestingProfile::GetSSLConfigService() {
842 if (!GetRequestContext())
843 return NULL;
844 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
847 net::URLRequestContextGetter*
848 TestingProfile::CreateRequestContextForStoragePartition(
849 const base::FilePath& partition_path,
850 bool in_memory,
851 content::ProtocolHandlerMap* protocol_handlers,
852 content::URLRequestInterceptorScopedVector request_interceptors) {
853 // We don't test storage partitions here yet, so returning the same dummy
854 // context is sufficient for now.
855 return GetRequestContext();
858 content::ResourceContext* TestingProfile::GetResourceContext() {
859 if (!resource_context_)
860 resource_context_ = new content::MockResourceContext();
861 return resource_context_;
864 HostContentSettingsMap* TestingProfile::GetHostContentSettingsMap() {
865 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
866 if (!host_content_settings_map_.get()) {
867 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
868 #if defined(ENABLE_EXTENSIONS)
869 ExtensionService* extension_service =
870 extensions::ExtensionSystem::Get(this)->extension_service();
871 if (extension_service) {
872 extension_service->RegisterContentSettings(
873 host_content_settings_map_.get());
875 #endif
877 return host_content_settings_map_.get();
880 content::BrowserPluginGuestManager* TestingProfile::GetGuestManager() {
881 #if defined(ENABLE_EXTENSIONS)
882 return guest_view::GuestViewManager::FromBrowserContext(this);
883 #else
884 return NULL;
885 #endif
888 content::PushMessagingService* TestingProfile::GetPushMessagingService() {
889 return NULL;
892 bool TestingProfile::IsSameProfile(Profile *p) {
893 return this == p;
896 base::Time TestingProfile::GetStartTime() const {
897 return start_time_;
900 base::FilePath TestingProfile::last_selected_directory() {
901 return last_selected_directory_;
904 void TestingProfile::set_last_selected_directory(const base::FilePath& path) {
905 last_selected_directory_ = path;
908 PrefProxyConfigTracker* TestingProfile::GetProxyConfigTracker() {
909 if (!pref_proxy_config_tracker_.get()) {
910 // TestingProfile is used in unit tests, where local state is not available.
911 pref_proxy_config_tracker_.reset(
912 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
913 NULL));
915 return pref_proxy_config_tracker_.get();
918 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
919 history::HistoryService* history_service =
920 HistoryServiceFactory::GetForProfile(this,
921 ServiceAccessType::EXPLICIT_ACCESS);
922 DCHECK(history_service);
923 DCHECK(base::MessageLoop::current());
925 base::CancelableTaskTracker tracker;
926 history_service->ScheduleDBTask(
927 scoped_ptr<history::HistoryDBTask>(
928 new QuittingHistoryDBTask()),
929 &tracker);
930 base::MessageLoop::current()->Run();
933 chrome_browser_net::Predictor* TestingProfile::GetNetworkPredictor() {
934 return NULL;
937 DevToolsNetworkController* TestingProfile::GetDevToolsNetworkController() {
938 return NULL;
941 void TestingProfile::ClearNetworkingHistorySince(
942 base::Time time,
943 const base::Closure& completion) {
944 if (!completion.is_null()) {
945 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, completion);
949 GURL TestingProfile::GetHomePage() {
950 return GURL(chrome::kChromeUINewTabURL);
953 PrefService* TestingProfile::GetOffTheRecordPrefs() {
954 return NULL;
957 storage::SpecialStoragePolicy* TestingProfile::GetSpecialStoragePolicy() {
958 #if defined(ENABLE_EXTENSIONS)
959 return GetExtensionSpecialStoragePolicy();
960 #else
961 return NULL;
962 #endif
965 content::SSLHostStateDelegate* TestingProfile::GetSSLHostStateDelegate() {
966 return NULL;
969 content::PermissionManager* TestingProfile::GetPermissionManager() {
970 return NULL;
973 bool TestingProfile::WasCreatedByVersionOrLater(const std::string& version) {
974 return true;
977 bool TestingProfile::IsGuestSession() const {
978 return guest_session_;
981 Profile::ExitType TestingProfile::GetLastSessionExitType() {
982 return last_session_exited_cleanly_ ? EXIT_NORMAL : EXIT_CRASHED;
985 TestingProfile::Builder::Builder()
986 : build_called_(false),
987 delegate_(NULL),
988 guest_session_(false) {
991 TestingProfile::Builder::~Builder() {
994 void TestingProfile::Builder::SetPath(const base::FilePath& path) {
995 path_ = path;
998 void TestingProfile::Builder::SetDelegate(Delegate* delegate) {
999 delegate_ = delegate;
1002 #if defined(ENABLE_EXTENSIONS)
1003 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
1004 scoped_refptr<ExtensionSpecialStoragePolicy> policy) {
1005 extension_policy_ = policy;
1007 #endif
1009 void TestingProfile::Builder::SetPrefService(
1010 scoped_ptr<PrefServiceSyncable> prefs) {
1011 pref_service_ = prefs.Pass();
1014 void TestingProfile::Builder::SetGuestSession() {
1015 guest_session_ = true;
1018 void TestingProfile::Builder::SetSupervisedUserId(
1019 const std::string& supervised_user_id) {
1020 supervised_user_id_ = supervised_user_id;
1023 void TestingProfile::Builder::SetPolicyService(
1024 scoped_ptr<policy::PolicyService> policy_service) {
1025 policy_service_ = policy_service.Pass();
1028 void TestingProfile::Builder::AddTestingFactory(
1029 BrowserContextKeyedServiceFactory* service_factory,
1030 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback) {
1031 testing_factories_.push_back(std::make_pair(service_factory, callback));
1034 scoped_ptr<TestingProfile> TestingProfile::Builder::Build() {
1035 DCHECK(!build_called_);
1036 build_called_ = true;
1038 return scoped_ptr<TestingProfile>(new TestingProfile(path_,
1039 delegate_,
1040 #if defined(ENABLE_EXTENSIONS)
1041 extension_policy_,
1042 #endif
1043 pref_service_.Pass(),
1044 NULL,
1045 guest_session_,
1046 supervised_user_id_,
1047 policy_service_.Pass(),
1048 testing_factories_));
1051 TestingProfile* TestingProfile::Builder::BuildIncognito(
1052 TestingProfile* original_profile) {
1053 DCHECK(!build_called_);
1054 DCHECK(original_profile);
1055 build_called_ = true;
1057 // Note: Owned by |original_profile|.
1058 return new TestingProfile(path_,
1059 delegate_,
1060 #if defined(ENABLE_EXTENSIONS)
1061 extension_policy_,
1062 #endif
1063 pref_service_.Pass(),
1064 original_profile,
1065 guest_session_,
1066 supervised_user_id_,
1067 policy_service_.Pass(),
1068 testing_factories_);