Allow only one bookmark to be added for multiple fast starring
[chromium-blink-merge.git] / chrome / test / base / testing_profile.cc
blob162fe58baf844d30eb6ece844d92ca02f36879f1
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/location.h"
11 #include "base/path_service.h"
12 #include "base/prefs/testing_pref_store.h"
13 #include "base/run_loop.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/thread_task_runner_handle.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/bookmarks/managed_bookmark_service_factory.h"
22 #include "chrome/browser/browser_process.h"
23 #include "chrome/browser/chrome_notification_types.h"
24 #include "chrome/browser/favicon/chrome_fallback_icon_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/history_service_factory.h"
29 #include "chrome/browser/history/web_history_service_factory.h"
30 #include "chrome/browser/net/pref_proxy_config_tracker.h"
31 #include "chrome/browser/net/proxy_service_factory.h"
32 #include "chrome/browser/policy/profile_policy_connector.h"
33 #include "chrome/browser/policy/profile_policy_connector_factory.h"
34 #include "chrome/browser/prefs/browser_prefs.h"
35 #include "chrome/browser/prefs/pref_service_syncable.h"
36 #include "chrome/browser/prerender/prerender_manager.h"
37 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
38 #include "chrome/browser/profiles/profile_manager.h"
39 #include "chrome/browser/profiles/storage_partition_descriptor.h"
40 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
41 #include "chrome/browser/sync/glue/sync_start_util.h"
42 #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
43 #include "chrome/browser/web_data_service_factory.h"
44 #include "chrome/common/chrome_constants.h"
45 #include "chrome/common/chrome_switches.h"
46 #include "chrome/common/pref_names.h"
47 #include "chrome/common/url_constants.h"
48 #include "chrome/test/base/history_index_restore_observer.h"
49 #include "chrome/test/base/testing_pref_service_syncable.h"
50 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
51 #include "components/bookmarks/browser/bookmark_model.h"
52 #include "components/bookmarks/common/bookmark_constants.h"
53 #include "components/content_settings/core/browser/host_content_settings_map.h"
54 #include "components/favicon/core/fallback_icon_service.h"
55 #include "components/favicon/core/favicon_service.h"
56 #include "components/history/content/browser/content_visit_delegate.h"
57 #include "components/history/content/browser/history_database_helper.h"
58 #include "components/history/core/browser/history_backend.h"
59 #include "components/history/core/browser/history_constants.h"
60 #include "components/history/core/browser/history_database_params.h"
61 #include "components/history/core/browser/history_db_task.h"
62 #include "components/history/core/browser/history_service.h"
63 #include "components/keyed_service/content/browser_context_dependency_manager.h"
64 #include "components/keyed_service/core/refcounted_keyed_service.h"
65 #include "components/omnibox/browser/autocomplete_classifier.h"
66 #include "components/omnibox/browser/in_memory_url_index.h"
67 #include "components/policy/core/common/policy_service.h"
68 #include "components/ui/zoom/zoom_event_manager.h"
69 #include "components/user_prefs/user_prefs.h"
70 #include "components/webdata_services/web_data_service_wrapper.h"
71 #include "content/public/browser/browser_thread.h"
72 #include "content/public/browser/cookie_store_factory.h"
73 #include "content/public/browser/notification_service.h"
74 #include "content/public/browser/render_process_host.h"
75 #include "content/public/browser/storage_partition.h"
76 #include "content/public/browser/zoom_level_delegate.h"
77 #include "content/public/test/mock_resource_context.h"
78 #include "content/public/test/test_utils.h"
79 #include "extensions/common/constants.h"
80 #include "net/cookies/cookie_monster.h"
81 #include "net/url_request/url_request_context.h"
82 #include "net/url_request/url_request_context_getter.h"
83 #include "net/url_request/url_request_test_util.h"
84 #include "testing/gmock/include/gmock/gmock.h"
86 #if defined(ENABLE_CONFIGURATION_POLICY)
87 #include "chrome/browser/policy/schema_registry_service.h"
88 #include "chrome/browser/policy/schema_registry_service_factory.h"
89 #include "components/policy/core/common/configuration_policy_provider.h"
90 #include "components/policy/core/common/policy_service_impl.h"
91 #include "components/policy/core/common/schema.h"
92 #else
93 #include "components/policy/core/common/policy_service_stub.h"
94 #endif // defined(ENABLE_CONFIGURATION_POLICY)
96 #if defined(ENABLE_EXTENSIONS)
97 #include "chrome/browser/extensions/extension_service.h"
98 #include "chrome/browser/extensions/extension_special_storage_policy.h"
99 #include "chrome/browser/extensions/extension_system_factory.h"
100 #include "chrome/browser/extensions/test_extension_system.h"
101 #include "components/guest_view/browser/guest_view_manager.h"
102 #include "extensions/browser/event_router_factory.h"
103 #include "extensions/browser/extension_prefs.h"
104 #include "extensions/browser/extension_prefs_factory.h"
105 #include "extensions/browser/extension_system.h"
106 #endif
108 #if defined(OS_ANDROID)
109 #include "chrome/browser/signin/oauth2_token_service_delegate_android.h"
110 #endif
112 #if defined(ENABLE_SUPERVISED_USERS)
113 #include "chrome/browser/supervised_user/supervised_user_constants.h"
114 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
115 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
116 #endif
118 using base::Time;
119 using bookmarks::BookmarkModel;
120 using content::BrowserThread;
121 using content::DownloadManagerDelegate;
122 using testing::NiceMock;
123 using testing::Return;
125 namespace {
127 // Task used to make sure history has finished processing a request. Intended
128 // for use with BlockUntilHistoryProcessesPendingRequests.
130 class QuittingHistoryDBTask : public history::HistoryDBTask {
131 public:
132 QuittingHistoryDBTask() {}
134 bool RunOnDBThread(history::HistoryBackend* backend,
135 history::HistoryDatabase* db) override {
136 return true;
139 void DoneRunOnMainThread() override { base::MessageLoop::current()->Quit(); }
141 private:
142 ~QuittingHistoryDBTask() override {}
144 DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
147 class TestExtensionURLRequestContext : public net::URLRequestContext {
148 public:
149 TestExtensionURLRequestContext() {
150 net::CookieMonster* cookie_monster =
151 content::CreateCookieStore(content::CookieStoreConfig())->
152 GetCookieMonster();
153 const char* const schemes[] = {extensions::kExtensionScheme};
154 cookie_monster->SetCookieableSchemes(schemes, arraysize(schemes));
155 set_cookie_store(cookie_monster);
158 ~TestExtensionURLRequestContext() override { AssertNoURLRequests(); }
161 class TestExtensionURLRequestContextGetter
162 : public net::URLRequestContextGetter {
163 public:
164 net::URLRequestContext* GetURLRequestContext() override {
165 if (!context_.get())
166 context_.reset(new TestExtensionURLRequestContext());
167 return context_.get();
169 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
170 const override {
171 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
174 protected:
175 ~TestExtensionURLRequestContextGetter() override {}
177 private:
178 scoped_ptr<net::URLRequestContext> context_;
181 scoped_ptr<KeyedService> BuildHistoryService(content::BrowserContext* context) {
182 Profile* profile = Profile::FromBrowserContext(context);
183 return make_scoped_ptr(new history::HistoryService(
184 make_scoped_ptr(new ChromeHistoryClient(
185 BookmarkModelFactory::GetForProfile(profile))),
186 make_scoped_ptr(new history::ContentVisitDelegate(profile))));
189 scoped_ptr<KeyedService> BuildInMemoryURLIndex(
190 content::BrowserContext* context) {
191 Profile* profile = Profile::FromBrowserContext(context);
192 scoped_ptr<InMemoryURLIndex> in_memory_url_index(new InMemoryURLIndex(
193 BookmarkModelFactory::GetForProfile(profile),
194 HistoryServiceFactory::GetForProfile(profile,
195 ServiceAccessType::IMPLICIT_ACCESS),
196 content::BrowserThread::GetBlockingPool(), profile->GetPath(),
197 profile->GetPrefs()->GetString(prefs::kAcceptLanguages),
198 SchemeSet()));
199 in_memory_url_index->Init();
200 return in_memory_url_index.Pass();
203 scoped_ptr<KeyedService> BuildBookmarkModel(content::BrowserContext* context) {
204 Profile* profile = Profile::FromBrowserContext(context);
205 ChromeBookmarkClient* bookmark_client =
206 ChromeBookmarkClientFactory::GetForProfile(profile);
207 scoped_ptr<BookmarkModel> bookmark_model(new BookmarkModel(bookmark_client));
208 bookmark_client->Init(bookmark_model.get());
209 bookmark_model->Load(profile->GetPrefs(),
210 profile->GetPrefs()->GetString(prefs::kAcceptLanguages),
211 profile->GetPath(),
212 profile->GetIOTaskRunner(),
213 content::BrowserThread::GetMessageLoopProxyForThread(
214 content::BrowserThread::UI));
215 return bookmark_model.Pass();
218 void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type,
219 sql::InitStatus status) {
220 NOTREACHED();
223 scoped_ptr<KeyedService> BuildWebDataService(content::BrowserContext* context) {
224 const base::FilePath& context_path = context->GetPath();
225 return make_scoped_ptr(new WebDataServiceWrapper(
226 context_path, g_browser_process->GetApplicationLocale(),
227 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
228 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB),
229 sync_start_util::GetFlareForSyncableService(context_path),
230 &TestProfileErrorCallback));
233 } // namespace
235 // static
236 #if defined(OS_CHROMEOS)
237 // Must be kept in sync with
238 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
239 const char TestingProfile::kTestUserProfileDir[] = "test-user";
240 #else
241 const char TestingProfile::kTestUserProfileDir[] = "Default";
242 #endif
244 TestingProfile::TestingProfile()
245 : start_time_(Time::Now()),
246 testing_prefs_(NULL),
247 force_incognito_(false),
248 original_profile_(NULL),
249 guest_session_(false),
250 last_session_exited_cleanly_(true),
251 browser_context_dependency_manager_(
252 BrowserContextDependencyManager::GetInstance()),
253 resource_context_(NULL),
254 delegate_(NULL) {
255 CreateTempProfileDir();
256 profile_path_ = temp_dir_.path();
258 Init();
259 FinishInit();
262 TestingProfile::TestingProfile(const base::FilePath& path)
263 : start_time_(Time::Now()),
264 testing_prefs_(NULL),
265 force_incognito_(false),
266 original_profile_(NULL),
267 guest_session_(false),
268 last_session_exited_cleanly_(true),
269 profile_path_(path),
270 browser_context_dependency_manager_(
271 BrowserContextDependencyManager::GetInstance()),
272 resource_context_(NULL),
273 delegate_(NULL) {
274 Init();
275 FinishInit();
278 TestingProfile::TestingProfile(const base::FilePath& path,
279 Delegate* delegate)
280 : start_time_(Time::Now()),
281 testing_prefs_(NULL),
282 force_incognito_(false),
283 original_profile_(NULL),
284 guest_session_(false),
285 last_session_exited_cleanly_(true),
286 profile_path_(path),
287 browser_context_dependency_manager_(
288 BrowserContextDependencyManager::GetInstance()),
289 resource_context_(NULL),
290 delegate_(delegate) {
291 Init();
292 if (delegate_) {
293 base::ThreadTaskRunnerHandle::Get()->PostTask(
294 FROM_HERE,
295 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
296 } else {
297 FinishInit();
301 TestingProfile::TestingProfile(
302 const base::FilePath& path,
303 Delegate* delegate,
304 #if defined(ENABLE_EXTENSIONS)
305 scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
306 #endif
307 scoped_ptr<PrefServiceSyncable> prefs,
308 TestingProfile* parent,
309 bool guest_session,
310 const std::string& supervised_user_id,
311 scoped_ptr<policy::PolicyService> policy_service,
312 const TestingFactories& factories)
313 : start_time_(Time::Now()),
314 prefs_(prefs.release()),
315 testing_prefs_(NULL),
316 force_incognito_(false),
317 original_profile_(parent),
318 guest_session_(guest_session),
319 last_session_exited_cleanly_(true),
320 #if defined(ENABLE_EXTENSIONS)
321 extension_special_storage_policy_(extension_policy),
322 #endif
323 profile_path_(path),
324 browser_context_dependency_manager_(
325 BrowserContextDependencyManager::GetInstance()),
326 resource_context_(NULL),
327 delegate_(delegate),
328 policy_service_(policy_service.release()) {
329 if (parent)
330 parent->SetOffTheRecordProfile(scoped_ptr<Profile>(this));
332 // If no profile path was supplied, create one.
333 if (profile_path_.empty()) {
334 CreateTempProfileDir();
335 profile_path_ = temp_dir_.path();
338 // Set any testing factories prior to initializing the services.
339 for (TestingFactories::const_iterator it = factories.begin();
340 it != factories.end(); ++it) {
341 it->first->SetTestingFactory(this, it->second);
344 Init();
345 // If caller supplied a delegate, delay the FinishInit invocation until other
346 // tasks have run.
347 // TODO(atwilson): See if this is still required once we convert the current
348 // users of the constructor that takes a Delegate* param.
349 if (delegate_) {
350 base::ThreadTaskRunnerHandle::Get()->PostTask(
351 FROM_HERE,
352 base::Bind(&TestingProfile::FinishInit, base::Unretained(this)));
353 } else {
354 FinishInit();
357 SetSupervisedUserId(supervised_user_id);
360 void TestingProfile::CreateTempProfileDir() {
361 if (!temp_dir_.CreateUniqueTempDir()) {
362 LOG(ERROR) << "Failed to create unique temporary directory.";
364 // Fallback logic in case we fail to create unique temporary directory.
365 base::FilePath system_tmp_dir;
366 bool success = PathService::Get(base::DIR_TEMP, &system_tmp_dir);
368 // We're severly screwed if we can't get the system temporary
369 // directory. Die now to avoid writing to the filesystem root
370 // or other bad places.
371 CHECK(success);
373 base::FilePath fallback_dir(
374 system_tmp_dir.AppendASCII("TestingProfilePath"));
375 base::DeleteFile(fallback_dir, true);
376 base::CreateDirectory(fallback_dir);
377 if (!temp_dir_.Set(fallback_dir)) {
378 // That shouldn't happen, but if it does, try to recover.
379 LOG(ERROR) << "Failed to use a fallback temporary directory.";
381 // We're screwed if this fails, see CHECK above.
382 CHECK(temp_dir_.Set(system_tmp_dir));
387 void TestingProfile::Init() {
388 // If threads have been initialized, we should be on the UI thread.
389 DCHECK(!content::BrowserThread::IsThreadInitialized(
390 content::BrowserThread::UI) ||
391 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
393 set_is_guest_profile(guest_session_);
395 #if defined(OS_ANDROID)
396 // Make sure token service knows its running in tests.
397 OAuth2TokenServiceDelegateAndroid::set_is_testing_profile();
398 #endif
400 // Normally this would happen during browser startup, but for tests
401 // we need to trigger creation of Profile-related services.
402 ChromeBrowserMainExtraPartsProfiles::
403 EnsureBrowserContextKeyedServiceFactoriesBuilt();
405 if (prefs_.get())
406 user_prefs::UserPrefs::Set(this, prefs_.get());
407 else if (IsOffTheRecord())
408 CreateIncognitoPrefService();
409 else
410 CreateTestingPrefService();
412 if (!base::PathExists(profile_path_))
413 base::CreateDirectory(profile_path_);
415 // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
416 // anymore, after converting the PrefService to a PKS. Until then it must
417 // be associated with a TestingProfile too.
418 if (!IsOffTheRecord())
419 CreateProfilePolicyConnector();
421 extensions_path_ = profile_path_.AppendASCII("Extensions");
423 #if defined(ENABLE_EXTENSIONS)
424 extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
425 this, extensions::TestExtensionSystem::Build);
427 extensions::TestExtensionSystem* test_extension_system =
428 static_cast<extensions::TestExtensionSystem*>(
429 extensions::ExtensionSystem::Get(this));
430 scoped_ptr<extensions::ExtensionPrefs> extension_prefs =
431 test_extension_system->CreateExtensionPrefs(
432 base::CommandLine::ForCurrentProcess(), extensions_path_);
433 extensions::ExtensionPrefsFactory::GetInstance()->SetInstanceForTesting(
434 this, extension_prefs.Pass());
436 extensions::EventRouterFactory::GetInstance()->SetTestingFactory(this,
437 nullptr);
438 #endif
440 // Prefs for incognito profiles are set in CreateIncognitoPrefService() by
441 // simulating ProfileImpl::GetOffTheRecordPrefs().
442 if (!IsOffTheRecord()) {
443 DCHECK(!original_profile_);
444 user_prefs::PrefRegistrySyncable* pref_registry =
445 static_cast<user_prefs::PrefRegistrySyncable*>(
446 prefs_->DeprecatedGetPrefRegistry());
447 browser_context_dependency_manager_->
448 RegisterProfilePrefsForServices(this, pref_registry);
451 browser_context_dependency_manager_->CreateBrowserContextServicesForTest(
452 this);
454 #if defined(ENABLE_SUPERVISED_USERS)
455 if (!IsOffTheRecord()) {
456 SupervisedUserSettingsService* settings_service =
457 SupervisedUserSettingsServiceFactory::GetForProfile(this);
458 TestingPrefStore* store = new TestingPrefStore();
459 settings_service->Init(store);
460 store->SetInitializationCompleted();
462 #endif
464 profile_name_ = "testing_profile";
467 void TestingProfile::FinishInit() {
468 DCHECK(content::NotificationService::current());
469 content::NotificationService::current()->Notify(
470 chrome::NOTIFICATION_PROFILE_CREATED,
471 content::Source<Profile>(static_cast<Profile*>(this)),
472 content::NotificationService::NoDetails());
474 ProfileManager* profile_manager = g_browser_process->profile_manager();
475 if (profile_manager)
476 profile_manager->InitProfileUserPrefs(this);
478 if (delegate_)
479 delegate_->OnProfileCreated(this, true, false);
482 TestingProfile::~TestingProfile() {
483 // Revert to non-incognito mode before shutdown.
484 force_incognito_ = false;
486 // If this profile owns an incognito profile, tear it down first.
487 incognito_profile_.reset();
489 // Any objects holding live URLFetchers should be deleted before teardown.
490 TemplateURLFetcherFactory::ShutdownForProfile(this);
492 MaybeSendDestroyedNotification();
494 browser_context_dependency_manager_->DestroyBrowserContextServices(this);
496 if (host_content_settings_map_.get())
497 host_content_settings_map_->ShutdownOnUIThread();
499 if (pref_proxy_config_tracker_.get())
500 pref_proxy_config_tracker_->DetachFromPrefService();
501 // Failing a post == leaks == heapcheck failure. Make that an immediate test
502 // failure.
503 if (resource_context_) {
504 CHECK(BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
505 resource_context_));
506 resource_context_ = NULL;
507 content::RunAllPendingInMessageLoop(BrowserThread::IO);
511 void TestingProfile::CreateFaviconService() {
512 // It is up to the caller to create the history service if one is needed.
513 FaviconServiceFactory::GetInstance()->SetTestingFactory(
514 this, FaviconServiceFactory::GetDefaultFactory());
517 bool TestingProfile::CreateHistoryService(bool delete_file, bool no_db) {
518 DestroyHistoryService();
519 if (delete_file) {
520 base::FilePath path = GetPath();
521 path = path.Append(history::kHistoryFilename);
522 if (!base::DeleteFile(path, false) || base::PathExists(path))
523 return false;
525 // This will create and init the history service.
526 history::HistoryService* history_service =
527 static_cast<history::HistoryService*>(
528 HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
529 this, BuildHistoryService));
530 if (!history_service->Init(
531 no_db, GetPrefs()->GetString(prefs::kAcceptLanguages),
532 history::HistoryDatabaseParamsForPath(GetPath()))) {
533 HistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
534 return false;
536 // Some tests expect that CreateHistoryService() will also make the
537 // InMemoryURLIndex available.
538 InMemoryURLIndexFactory::GetInstance()->SetTestingFactory(
539 this, BuildInMemoryURLIndex);
540 // Disable WebHistoryService by default, since it makes network requests.
541 WebHistoryServiceFactory::GetInstance()->SetTestingFactory(this, nullptr);
542 return true;
545 void TestingProfile::DestroyHistoryService() {
546 history::HistoryService* history_service =
547 HistoryServiceFactory::GetForProfileWithoutCreating(this);
548 if (!history_service)
549 return;
551 history_service->ClearCachedDataForContextID(0);
552 history_service->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
553 history_service->Cleanup();
554 HistoryServiceFactory::ShutdownForProfile(this);
556 // Wait for the backend class to terminate before deleting the files and
557 // moving to the next test. Note: if this never terminates, somebody is
558 // probably leaking a reference to the history backend, so it never calls
559 // our destroy task.
560 base::MessageLoop::current()->Run();
562 // Make sure we don't have any event pending that could disrupt the next
563 // test.
564 base::ThreadTaskRunnerHandle::Get()->PostTask(
565 FROM_HERE, base::MessageLoop::QuitClosure());
566 base::MessageLoop::current()->Run();
569 void TestingProfile::CreateBookmarkModel(bool delete_file) {
570 if (delete_file) {
571 base::FilePath path = GetPath().Append(bookmarks::kBookmarksFileName);
572 base::DeleteFile(path, false);
574 ManagedBookmarkServiceFactory::GetInstance()->SetTestingFactory(
575 this, ManagedBookmarkServiceFactory::GetDefaultFactory());
576 ChromeBookmarkClientFactory::GetInstance()->SetTestingFactory(
577 this, ChromeBookmarkClientFactory::GetDefaultFactory());
578 // This creates the BookmarkModel.
579 ignore_result(BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
580 this, BuildBookmarkModel));
583 void TestingProfile::CreateWebDataService() {
584 WebDataServiceFactory::GetInstance()->SetTestingFactory(
585 this, BuildWebDataService);
588 void TestingProfile::BlockUntilHistoryIndexIsRefreshed() {
589 // Only get the history service if it actually exists since the caller of the
590 // test should explicitly call CreateHistoryService to build it.
591 history::HistoryService* history_service =
592 HistoryServiceFactory::GetForProfileWithoutCreating(this);
593 DCHECK(history_service);
594 InMemoryURLIndex* index = InMemoryURLIndexFactory::GetForProfile(this);
595 if (!index || index->restored())
596 return;
597 base::RunLoop run_loop;
598 HistoryIndexRestoreObserver observer(
599 content::GetQuitTaskForRunLoop(&run_loop));
600 index->set_restore_cache_observer(&observer);
601 run_loop.Run();
602 index->set_restore_cache_observer(NULL);
603 DCHECK(index->restored());
606 void TestingProfile::SetGuestSession(bool guest) {
607 guest_session_ = guest;
610 base::FilePath TestingProfile::GetPath() const {
611 return profile_path_;
614 scoped_ptr<content::ZoomLevelDelegate> TestingProfile::CreateZoomLevelDelegate(
615 const base::FilePath& partition_path) {
616 return make_scoped_ptr(new chrome::ChromeZoomLevelPrefs(
617 GetPrefs(), GetPath(), partition_path,
618 ui_zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
621 scoped_refptr<base::SequencedTaskRunner> TestingProfile::GetIOTaskRunner() {
622 return base::MessageLoop::current()->task_runner();
625 TestingPrefServiceSyncable* TestingProfile::GetTestingPrefService() {
626 DCHECK(prefs_);
627 DCHECK(testing_prefs_);
628 return testing_prefs_;
631 TestingProfile* TestingProfile::AsTestingProfile() {
632 return this;
635 std::string TestingProfile::GetProfileUserName() const {
636 return profile_name_;
639 Profile::ProfileType TestingProfile::GetProfileType() const {
640 if (guest_session_)
641 return GUEST_PROFILE;
642 if (force_incognito_ || original_profile_)
643 return INCOGNITO_PROFILE;
644 return REGULAR_PROFILE;
647 bool TestingProfile::IsOffTheRecord() const {
648 return force_incognito_ || original_profile_;
651 void TestingProfile::SetOffTheRecordProfile(scoped_ptr<Profile> profile) {
652 DCHECK(!IsOffTheRecord());
653 DCHECK_EQ(this, profile->GetOriginalProfile());
654 incognito_profile_ = profile.Pass();
657 Profile* TestingProfile::GetOffTheRecordProfile() {
658 if (IsOffTheRecord())
659 return this;
660 if (!incognito_profile_)
661 TestingProfile::Builder().BuildIncognito(this);
662 return incognito_profile_.get();
665 bool TestingProfile::HasOffTheRecordProfile() {
666 return incognito_profile_.get() != NULL;
669 Profile* TestingProfile::GetOriginalProfile() {
670 if (original_profile_)
671 return original_profile_;
672 return this;
675 void TestingProfile::SetSupervisedUserId(const std::string& id) {
676 supervised_user_id_ = id;
677 if (!id.empty())
678 GetPrefs()->SetString(prefs::kSupervisedUserId, id);
679 else
680 GetPrefs()->ClearPref(prefs::kSupervisedUserId);
683 bool TestingProfile::IsSupervised() {
684 return !supervised_user_id_.empty();
687 bool TestingProfile::IsChild() {
688 #if defined(ENABLE_SUPERVISED_USERS)
689 return supervised_user_id_ == supervised_users::kChildAccountSUID;
690 #else
691 return false;
692 #endif
695 bool TestingProfile::IsLegacySupervised() {
696 return IsSupervised() && !IsChild();
699 #if defined(ENABLE_EXTENSIONS)
700 void TestingProfile::SetExtensionSpecialStoragePolicy(
701 ExtensionSpecialStoragePolicy* extension_special_storage_policy) {
702 extension_special_storage_policy_ = extension_special_storage_policy;
704 #endif
706 ExtensionSpecialStoragePolicy*
707 TestingProfile::GetExtensionSpecialStoragePolicy() {
708 #if defined(ENABLE_EXTENSIONS)
709 if (!extension_special_storage_policy_.get())
710 extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(NULL);
711 return extension_special_storage_policy_.get();
712 #else
713 return NULL;
714 #endif
717 net::CookieMonster* TestingProfile::GetCookieMonster() {
718 if (!GetRequestContext())
719 return NULL;
720 return GetRequestContext()->GetURLRequestContext()->cookie_store()->
721 GetCookieMonster();
724 void TestingProfile::CreateTestingPrefService() {
725 DCHECK(!prefs_.get());
726 testing_prefs_ = new TestingPrefServiceSyncable();
727 prefs_.reset(testing_prefs_);
728 user_prefs::UserPrefs::Set(this, prefs_.get());
729 chrome::RegisterUserProfilePrefs(testing_prefs_->registry());
732 void TestingProfile::CreateIncognitoPrefService() {
733 DCHECK(original_profile_);
734 DCHECK(!testing_prefs_);
735 // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
736 // leaves testing_prefs_ unset.
737 prefs_.reset(original_profile_->prefs_->CreateIncognitoPrefService(NULL));
738 user_prefs::UserPrefs::Set(this, prefs_.get());
741 void TestingProfile::CreateProfilePolicyConnector() {
742 #if defined(ENABLE_CONFIGURATION_POLICY)
743 schema_registry_service_ =
744 policy::SchemaRegistryServiceFactory::CreateForContext(
745 this, policy::Schema(), NULL);
746 CHECK_EQ(schema_registry_service_.get(),
747 policy::SchemaRegistryServiceFactory::GetForContext(this));
748 #endif // defined(ENABLE_CONFIGURATION_POLICY)
750 if (!policy_service_) {
751 #if defined(ENABLE_CONFIGURATION_POLICY)
752 std::vector<policy::ConfigurationPolicyProvider*> providers;
753 policy_service_.reset(new policy::PolicyServiceImpl(providers));
754 #else
755 policy_service_.reset(new policy::PolicyServiceStub());
756 #endif
758 profile_policy_connector_.reset(new policy::ProfilePolicyConnector());
759 profile_policy_connector_->InitForTesting(policy_service_.Pass());
760 policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting(
761 this, profile_policy_connector_.get());
762 CHECK_EQ(profile_policy_connector_.get(),
763 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(this));
766 PrefService* TestingProfile::GetPrefs() {
767 DCHECK(prefs_);
768 return prefs_.get();
771 const PrefService* TestingProfile::GetPrefs() const {
772 DCHECK(prefs_);
773 return prefs_.get();
776 chrome::ChromeZoomLevelPrefs* TestingProfile::GetZoomLevelPrefs() {
777 return static_cast<chrome::ChromeZoomLevelPrefs*>(
778 GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
781 DownloadManagerDelegate* TestingProfile::GetDownloadManagerDelegate() {
782 return NULL;
785 net::URLRequestContextGetter* TestingProfile::GetRequestContext() {
786 return GetDefaultStoragePartition(this)->GetURLRequestContext();
789 net::URLRequestContextGetter* TestingProfile::CreateRequestContext(
790 content::ProtocolHandlerMap* protocol_handlers,
791 content::URLRequestInterceptorScopedVector request_interceptors) {
792 return new net::TestURLRequestContextGetter(
793 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
796 net::URLRequestContextGetter* TestingProfile::GetRequestContextForRenderProcess(
797 int renderer_child_id) {
798 content::RenderProcessHost* rph = content::RenderProcessHost::FromID(
799 renderer_child_id);
800 return rph->GetStoragePartition()->GetURLRequestContext();
803 net::URLRequestContextGetter* TestingProfile::GetMediaRequestContext() {
804 return NULL;
807 net::URLRequestContextGetter*
808 TestingProfile::GetMediaRequestContextForRenderProcess(
809 int renderer_child_id) {
810 return NULL;
813 net::URLRequestContextGetter*
814 TestingProfile::GetMediaRequestContextForStoragePartition(
815 const base::FilePath& partition_path,
816 bool in_memory) {
817 return NULL;
820 net::URLRequestContextGetter* TestingProfile::GetRequestContextForExtensions() {
821 if (!extensions_request_context_.get())
822 extensions_request_context_ = new TestExtensionURLRequestContextGetter();
823 return extensions_request_context_.get();
826 net::SSLConfigService* TestingProfile::GetSSLConfigService() {
827 if (!GetRequestContext())
828 return NULL;
829 return GetRequestContext()->GetURLRequestContext()->ssl_config_service();
832 net::URLRequestContextGetter*
833 TestingProfile::CreateRequestContextForStoragePartition(
834 const base::FilePath& partition_path,
835 bool in_memory,
836 content::ProtocolHandlerMap* protocol_handlers,
837 content::URLRequestInterceptorScopedVector request_interceptors) {
838 // We don't test storage partitions here yet, so returning the same dummy
839 // context is sufficient for now.
840 return GetRequestContext();
843 content::ResourceContext* TestingProfile::GetResourceContext() {
844 if (!resource_context_)
845 resource_context_ = new content::MockResourceContext();
846 return resource_context_;
849 HostContentSettingsMap* TestingProfile::GetHostContentSettingsMap() {
850 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
851 if (!host_content_settings_map_.get()) {
852 host_content_settings_map_ = new HostContentSettingsMap(GetPrefs(), false);
853 #if defined(ENABLE_EXTENSIONS)
854 ExtensionService* extension_service =
855 extensions::ExtensionSystem::Get(this)->extension_service();
856 if (extension_service) {
857 extension_service->RegisterContentSettings(
858 host_content_settings_map_.get());
860 #endif
862 return host_content_settings_map_.get();
865 content::BrowserPluginGuestManager* TestingProfile::GetGuestManager() {
866 #if defined(ENABLE_EXTENSIONS)
867 return guest_view::GuestViewManager::FromBrowserContext(this);
868 #else
869 return NULL;
870 #endif
873 content::PushMessagingService* TestingProfile::GetPushMessagingService() {
874 return NULL;
877 bool TestingProfile::IsSameProfile(Profile *p) {
878 return this == p;
881 base::Time TestingProfile::GetStartTime() const {
882 return start_time_;
885 base::FilePath TestingProfile::last_selected_directory() {
886 return last_selected_directory_;
889 void TestingProfile::set_last_selected_directory(const base::FilePath& path) {
890 last_selected_directory_ = path;
893 PrefProxyConfigTracker* TestingProfile::GetProxyConfigTracker() {
894 if (!pref_proxy_config_tracker_.get()) {
895 // TestingProfile is used in unit tests, where local state is not available.
896 pref_proxy_config_tracker_.reset(
897 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(GetPrefs(),
898 NULL));
900 return pref_proxy_config_tracker_.get();
903 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
904 history::HistoryService* history_service =
905 HistoryServiceFactory::GetForProfile(this,
906 ServiceAccessType::EXPLICIT_ACCESS);
907 DCHECK(history_service);
908 DCHECK(base::MessageLoop::current());
910 base::CancelableTaskTracker tracker;
911 history_service->ScheduleDBTask(
912 scoped_ptr<history::HistoryDBTask>(
913 new QuittingHistoryDBTask()),
914 &tracker);
915 base::MessageLoop::current()->Run();
918 chrome_browser_net::Predictor* TestingProfile::GetNetworkPredictor() {
919 return NULL;
922 DevToolsNetworkController* TestingProfile::GetDevToolsNetworkController() {
923 return NULL;
926 void TestingProfile::ClearNetworkingHistorySince(
927 base::Time time,
928 const base::Closure& completion) {
929 if (!completion.is_null()) {
930 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, completion);
934 GURL TestingProfile::GetHomePage() {
935 return GURL(chrome::kChromeUINewTabURL);
938 PrefService* TestingProfile::GetOffTheRecordPrefs() {
939 return NULL;
942 storage::SpecialStoragePolicy* TestingProfile::GetSpecialStoragePolicy() {
943 #if defined(ENABLE_EXTENSIONS)
944 return GetExtensionSpecialStoragePolicy();
945 #else
946 return NULL;
947 #endif
950 content::SSLHostStateDelegate* TestingProfile::GetSSLHostStateDelegate() {
951 return NULL;
954 content::PermissionManager* TestingProfile::GetPermissionManager() {
955 return NULL;
958 bool TestingProfile::WasCreatedByVersionOrLater(const std::string& version) {
959 return true;
962 bool TestingProfile::IsGuestSession() const {
963 return guest_session_;
966 Profile::ExitType TestingProfile::GetLastSessionExitType() {
967 return last_session_exited_cleanly_ ? EXIT_NORMAL : EXIT_CRASHED;
970 TestingProfile::Builder::Builder()
971 : build_called_(false),
972 delegate_(NULL),
973 guest_session_(false) {
976 TestingProfile::Builder::~Builder() {
979 void TestingProfile::Builder::SetPath(const base::FilePath& path) {
980 path_ = path;
983 void TestingProfile::Builder::SetDelegate(Delegate* delegate) {
984 delegate_ = delegate;
987 #if defined(ENABLE_EXTENSIONS)
988 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
989 scoped_refptr<ExtensionSpecialStoragePolicy> policy) {
990 extension_policy_ = policy;
992 #endif
994 void TestingProfile::Builder::SetPrefService(
995 scoped_ptr<PrefServiceSyncable> prefs) {
996 pref_service_ = prefs.Pass();
999 void TestingProfile::Builder::SetGuestSession() {
1000 guest_session_ = true;
1003 void TestingProfile::Builder::SetSupervisedUserId(
1004 const std::string& supervised_user_id) {
1005 supervised_user_id_ = supervised_user_id;
1008 void TestingProfile::Builder::SetPolicyService(
1009 scoped_ptr<policy::PolicyService> policy_service) {
1010 policy_service_ = policy_service.Pass();
1013 void TestingProfile::Builder::AddTestingFactory(
1014 BrowserContextKeyedServiceFactory* service_factory,
1015 BrowserContextKeyedServiceFactory::TestingFactoryFunction callback) {
1016 testing_factories_.push_back(std::make_pair(service_factory, callback));
1019 scoped_ptr<TestingProfile> TestingProfile::Builder::Build() {
1020 DCHECK(!build_called_);
1021 build_called_ = true;
1023 return scoped_ptr<TestingProfile>(new TestingProfile(path_,
1024 delegate_,
1025 #if defined(ENABLE_EXTENSIONS)
1026 extension_policy_,
1027 #endif
1028 pref_service_.Pass(),
1029 NULL,
1030 guest_session_,
1031 supervised_user_id_,
1032 policy_service_.Pass(),
1033 testing_factories_));
1036 TestingProfile* TestingProfile::Builder::BuildIncognito(
1037 TestingProfile* original_profile) {
1038 DCHECK(!build_called_);
1039 DCHECK(original_profile);
1040 build_called_ = true;
1042 // Note: Owned by |original_profile|.
1043 return new TestingProfile(path_,
1044 delegate_,
1045 #if defined(ENABLE_EXTENSIONS)
1046 extension_policy_,
1047 #endif
1048 pref_service_.Pass(),
1049 original_profile,
1050 guest_session_,
1051 supervised_user_id_,
1052 policy_service_.Pass(),
1053 testing_factories_);