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.
4 
5 #include "chrome/test/base/testing_profile.h"
6 
7 #include <utility>
8 
9 #include "base/base_paths.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/files/file_util.h"
13 #include "base/location.h"
14 #include "base/macros.h"
15 #include "base/no_destructor.h"
16 #include "base/path_service.h"
17 #include "base/run_loop.h"
18 #include "base/single_thread_task_runner.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/test/test_file_util.h"
22 #include "base/threading/thread_restrictions.h"
23 #include "base/threading/thread_task_runner_handle.h"
24 #include "build/build_config.h"
25 #include "chrome/browser/autocomplete/in_memory_url_index_factory.h"
26 #include "chrome/browser/autofill/personal_data_manager_factory.h"
27 #include "chrome/browser/background_fetch/background_fetch_delegate_factory.h"
28 #include "chrome/browser/background_fetch/background_fetch_delegate_impl.h"
29 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
30 #include "chrome/browser/browser_process.h"
31 #include "chrome/browser/browser_process_platform_part.h"
32 #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h"
33 #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_factory.h"
34 #include "chrome/browser/chrome_content_browser_client.h"
35 #include "chrome/browser/chrome_notification_types.h"
36 #include "chrome/browser/content_settings/host_content_settings_map_factory.h"
37 #include "chrome/browser/history/history_service_factory.h"
38 #include "chrome/browser/policy/profile_policy_connector.h"
39 #include "chrome/browser/policy/schema_registry_service.h"
40 #include "chrome/browser/policy/schema_registry_service_builder.h"
41 #include "chrome/browser/prefs/browser_prefs.h"
42 #include "chrome/browser/prefs/pref_service_syncable_util.h"
43 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
44 #include "chrome/browser/profiles/profile_key.h"
45 #include "chrome/browser/profiles/profile_manager.h"
46 #include "chrome/browser/profiles/storage_partition_descriptor.h"
47 #include "chrome/browser/search_engines/template_url_fetcher_factory.h"
48 #include "chrome/browser/search_engines/template_url_service_factory.h"
49 #include "chrome/browser/signin/identity_manager_factory.h"
50 #include "chrome/browser/signin/signin_util.h"
51 #include "chrome/browser/ssl/stateful_ssl_host_state_delegate_factory.h"
52 #include "chrome/browser/transition_manager/full_browser_transition_manager.h"
53 #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
54 #include "chrome/browser/web_data_service_factory.h"
55 #include "chrome/common/buildflags.h"
56 #include "chrome/common/chrome_constants.h"
57 #include "chrome/common/chrome_features.h"
58 #include "chrome/common/chrome_paths_internal.h"
59 #include "chrome/common/chrome_switches.h"
60 #include "chrome/common/pref_names.h"
61 #include "chrome/common/url_constants.h"
62 #include "chrome/test/base/testing_profile_key.h"
63 #include "components/autofill/core/browser/personal_data_manager.h"
64 #include "components/autofill/core/browser/test_autofill_profile_validator.h"
65 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
66 #include "components/content_settings/core/browser/host_content_settings_map.h"
67 #include "components/history/core/browser/history_service.h"
68 #include "components/history/core/test/history_service_test_util.h"
69 #include "components/keyed_service/content/browser_context_dependency_manager.h"
70 #include "components/keyed_service/core/refcounted_keyed_service.h"
71 #include "components/keyed_service/core/simple_dependency_manager.h"
72 #include "components/keyed_service/core/simple_factory_key.h"
73 #include "components/keyed_service/core/simple_key_map.h"
74 #include "components/leveldb_proto/public/proto_database_provider.h"
75 #include "components/omnibox/browser/autocomplete_classifier.h"
76 #include "components/omnibox/browser/history_index_restore_observer.h"
77 #include "components/omnibox/browser/in_memory_url_index.h"
78 #include "components/policy/core/common/cloud/cloud_external_data_manager.h"
79 #include "components/policy/core/common/cloud/mock_user_cloud_policy_store.h"
80 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
81 #include "components/policy/core/common/configuration_policy_provider.h"
82 #include "components/policy/core/common/policy_service.h"
83 #include "components/policy/core/common/policy_service_impl.h"
84 #include "components/policy/core/common/schema.h"
85 #include "components/prefs/pref_notifier_impl.h"
86 #include "components/prefs/testing_pref_store.h"
87 #include "components/security_interstitials/content/stateful_ssl_host_state_delegate.h"
88 #include "components/signin/public/identity_manager/identity_test_utils.h"
89 #include "components/sync/test/model/fake_sync_change_processor.h"
90 #include "components/sync/test/model/sync_error_factory_mock.h"
91 #include "components/sync_preferences/pref_service_syncable.h"
92 #include "components/sync_preferences/testing_pref_service_syncable.h"
93 #include "components/user_prefs/user_prefs.h"
94 #include "components/webdata_services/web_data_service_wrapper.h"
95 #include "components/zoom/zoom_event_manager.h"
96 #include "content/public/browser/browser_task_traits.h"
97 #include "content/public/browser/browser_thread.h"
98 #include "content/public/browser/cookie_store_factory.h"
99 #include "content/public/browser/network_service_instance.h"
100 #include "content/public/browser/notification_service.h"
101 #include "content/public/browser/render_process_host.h"
102 #include "content/public/browser/storage_partition.h"
103 #include "content/public/browser/zoom_level_delegate.h"
104 #include "content/public/test/mock_resource_context.h"
105 #include "content/public/test/test_utils.h"
106 #include "extensions/buildflags/buildflags.h"
107 #include "extensions/common/constants.h"
108 #include "net/cookies/cookie_store.h"
109 #include "services/network/test/test_network_connection_tracker.h"
110 #include "services/service_manager/public/cpp/service.h"
111 #include "testing/gmock/include/gmock/gmock.h"
112 
113 #if BUILDFLAG(ENABLE_EXTENSIONS)
114 #include "chrome/browser/extensions/extension_service.h"
115 #include "chrome/browser/extensions/extension_special_storage_policy.h"
116 #include "chrome/browser/extensions/extension_system_factory.h"
117 #include "chrome/browser/extensions/test_extension_system.h"
118 #include "chrome/browser/web_applications/test/test_web_app_provider.h"
119 #include "chrome/browser/web_applications/web_app_provider_factory.h"
120 #include "components/guest_view/browser/guest_view_manager.h"
121 #include "extensions/browser/event_router_factory.h"
122 #include "extensions/browser/extension_pref_value_map.h"
123 #include "extensions/browser/extension_pref_value_map_factory.h"
124 #include "extensions/browser/extension_prefs.h"
125 #include "extensions/browser/extension_prefs_factory.h"
126 #include "extensions/browser/extension_prefs_observer.h"
127 #include "extensions/browser/extension_system.h"
128 #endif
129 
130 #if defined(OS_CHROMEOS)
131 #include "chrome/browser/chromeos/arc/session/arc_service_launcher.h"
132 #include "chrome/browser/chromeos/net/delay_network_call.h"
133 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
134 #include "chrome/browser/chromeos/settings/cros_settings.h"
135 #include "chromeos/components/account_manager/account_manager.h"
136 #include "chromeos/components/account_manager/account_manager_factory.h"
137 #endif
138 
139 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
140 #include "chrome/browser/supervised_user/supervised_user_constants.h"
141 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
142 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
143 #endif
144 
145 using base::Time;
146 using content::BrowserThread;
147 using content::DownloadManagerDelegate;
148 using testing::NiceMock;
149 using testing::Return;
150 
151 namespace {
152 
153 // Default profile name
154 const char kTestingProfile[] = "testing_profile";
155 
TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type,sql::InitStatus status,const std::string & diagnostics)156 void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type,
157                               sql::InitStatus status,
158                               const std::string& diagnostics) {
159   NOTREACHED();
160 }
161 
BuildWebDataService(content::BrowserContext * context)162 std::unique_ptr<KeyedService> BuildWebDataService(
163     content::BrowserContext* context) {
164   const base::FilePath& context_path = context->GetPath();
165   return std::make_unique<WebDataServiceWrapper>(
166       context_path, g_browser_process->GetApplicationLocale(),
167       content::GetUIThreadTaskRunner({}),
168       base::BindRepeating(&TestProfileErrorCallback));
169 }
170 
BuildPersonalDataManagerInstanceFor(content::BrowserContext * context)171 std::unique_ptr<KeyedService> BuildPersonalDataManagerInstanceFor(
172     content::BrowserContext* context) {
173   return std::unique_ptr<KeyedService>(
174       autofill::PersonalDataManagerFactory::BuildPersonalDataManager(
175           autofill::TestAutofillProfileValidator::GetInstance(), context));
176 }
177 
178 }  // namespace
179 
180 // static
181 #if defined(OS_CHROMEOS)
182 // Must be kept in sync with
183 // ChromeBrowserMainPartsChromeos::PreEarlyInitialization.
184 const char TestingProfile::kTestUserProfileDir[] = "test-user";
185 #else
186 const char TestingProfile::kTestUserProfileDir[] = "Default";
187 #endif
188 
189 // static
SetScopedFeatureListForEphemeralGuestProfiles(base::test::ScopedFeatureList & scoped_feature_list,bool enabled)190 bool TestingProfile::SetScopedFeatureListForEphemeralGuestProfiles(
191     base::test::ScopedFeatureList& scoped_feature_list,
192     bool enabled) {
193 // This feature is now only supported on Windows, Linux, and Mac.
194 #if defined(OS_WIN) || defined(OS_MAC) || \
195     (defined(OS_LINUX) && !defined(OS_CHROMEOS))
196   if (enabled)
197     scoped_feature_list.InitAndEnableFeature(
198         features::kEnableEphemeralGuestProfilesOnDesktop);
199   else
200     scoped_feature_list.InitAndDisableFeature(
201         features::kEnableEphemeralGuestProfilesOnDesktop);
202   return true;
203 #else
204   return false;
205 #endif  // defined(OS_WIN) || defined(OS_MAC) || (defined(OS_LINUX) &&
206         // !defined(OS_CHROMEOS))
207 }
208 
TestingProfile()209 TestingProfile::TestingProfile() : TestingProfile(base::FilePath()) {}
210 
TestingProfile(const base::FilePath & path)211 TestingProfile::TestingProfile(const base::FilePath& path)
212     : TestingProfile(path, nullptr) {}
213 
TestingProfile(const base::FilePath & path,Delegate * delegate)214 TestingProfile::TestingProfile(const base::FilePath& path, Delegate* delegate)
215     : start_time_(Time::Now()),
216       testing_prefs_(nullptr),
217       original_profile_(nullptr),
218       guest_session_(false),
219       allows_browser_windows_(true),
220       last_session_exited_cleanly_(true),
221       profile_path_(path),
222       simple_dependency_manager_(SimpleDependencyManager::GetInstance()),
223       browser_context_dependency_manager_(
224           BrowserContextDependencyManager::GetInstance()),
225       resource_context_(nullptr),
226       delegate_(delegate),
227       profile_name_(kTestingProfile),
228       override_policy_connector_is_managed_(base::nullopt),
229       otr_profile_id_(base::nullopt) {
230   if (profile_path_.empty()) {
231     profile_path_ = base::CreateUniqueTempDirectoryScopedToTest();
232   }
233   Init();
234   if (delegate_) {
235     base::ThreadTaskRunnerHandle::Get()->PostTask(
236         FROM_HERE,
237         base::BindOnce(&TestingProfile::FinishInit, base::Unretained(this)));
238   } else {
239     FinishInit();
240   }
241 }
242 
TestingProfile(const base::FilePath & path,Delegate * delegate,scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,std::unique_ptr<sync_preferences::PrefServiceSyncable> prefs,TestingProfile * parent,bool guest_session,bool allows_browser_windows,base::Optional<bool> is_new_profile,const std::string & supervised_user_id,std::unique_ptr<policy::UserCloudPolicyManagerChromeOS> policy_manager,std::unique_ptr<policy::PolicyService> policy_service,TestingFactories testing_factories,const std::string & profile_name,base::Optional<bool> override_policy_connector_is_managed,base::Optional<OTRProfileID> otr_profile_id)243 TestingProfile::TestingProfile(
244     const base::FilePath& path,
245     Delegate* delegate,
246 #if BUILDFLAG(ENABLE_EXTENSIONS)
247     scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
248 #endif
249     std::unique_ptr<sync_preferences::PrefServiceSyncable> prefs,
250     TestingProfile* parent,
251     bool guest_session,
252     bool allows_browser_windows,
253     base::Optional<bool> is_new_profile,
254     const std::string& supervised_user_id,
255 #if defined(OS_CHROMEOS)
256     std::unique_ptr<policy::UserCloudPolicyManagerChromeOS> policy_manager,
257 #else
258     std::unique_ptr<policy::UserCloudPolicyManager> policy_manager,
259 #endif  // defined(OS_CHROMEOS)
260     std::unique_ptr<policy::PolicyService> policy_service,
261     TestingFactories testing_factories,
262     const std::string& profile_name,
263     base::Optional<bool> override_policy_connector_is_managed,
264     base::Optional<OTRProfileID> otr_profile_id)
265     : start_time_(Time::Now()),
266       prefs_(std::move(prefs)),
267       testing_prefs_(nullptr),
268       original_profile_(parent),
269       guest_session_(guest_session),
270       allows_browser_windows_(allows_browser_windows),
271       is_new_profile_(std::move(is_new_profile)),
272       supervised_user_id_(supervised_user_id),
273       last_session_exited_cleanly_(true),
274 #if BUILDFLAG(ENABLE_EXTENSIONS)
275       extension_special_storage_policy_(extension_policy),
276 #endif
277       profile_path_(path),
278       simple_dependency_manager_(SimpleDependencyManager::GetInstance()),
279       browser_context_dependency_manager_(
280           BrowserContextDependencyManager::GetInstance()),
281       resource_context_(nullptr),
282       user_cloud_policy_manager_(std::move(policy_manager)),
283       delegate_(delegate),
284       profile_name_(profile_name),
285       override_policy_connector_is_managed_(
286           override_policy_connector_is_managed),
287       otr_profile_id_(otr_profile_id),
288       policy_service_(std::move(policy_service)) {
289   if (parent)
290     parent->SetOffTheRecordProfile(std::unique_ptr<Profile>(this));
291 
292   // Only OffTheRecord profiles have an OTRProfileID.
293   DCHECK(!parent || otr_profile_id_.has_value());
294 
295   // If no profile path was supplied, create one.
296   if (profile_path_.empty()) {
297     profile_path_ = base::CreateUniqueTempDirectoryScopedToTest();
298   }
299 
300   // Set any testing factories prior to initializing the services.
301   for (TestingFactories::value_type& pair : testing_factories)
302     pair.first->SetTestingFactory(this, std::move(pair.second));
303   testing_factories.clear();
304 
305   Init();
306   // If caller supplied a delegate, delay the FinishInit invocation until other
307   // tasks have run.
308   // TODO(atwilson): See if this is still required once we convert the current
309   // users of the constructor that takes a Delegate* param.
310   if (delegate_) {
311     base::ThreadTaskRunnerHandle::Get()->PostTask(
312         FROM_HERE,
313         base::BindOnce(&TestingProfile::FinishInit, base::Unretained(this)));
314   } else {
315     FinishInit();
316   }
317 
318   SetSupervisedUserId(supervised_user_id);
319 }
320 
Init()321 void TestingProfile::Init() {
322   base::ScopedAllowBlockingForTesting allow_blocking;
323   // If threads have been initialized, we should be on the UI thread.
324   DCHECK(!content::BrowserThread::IsThreadInitialized(
325              content::BrowserThread::UI) ||
326          content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
327 
328   set_is_guest_profile(guest_session_);
329 
330   ProfileManager* profile_manager = g_browser_process->profile_manager();
331   if (profile_manager) {
332     if (IsOffTheRecord()) {
333       set_is_system_profile(original_profile_->IsSystemProfile());
334     } else {
335       set_is_system_profile(profile_path_ ==
336                             profile_manager->GetSystemProfilePath());
337     }
338   }
339 
340   if (IsOffTheRecord()) {
341     key_ = std::make_unique<TestingProfileKey>(
342         this, original_profile_->GetPath(), original_profile_->GetProfileKey());
343   } else {
344     key_ = std::make_unique<TestingProfileKey>(this, profile_path_);
345   }
346 
347 #if defined(OS_ANDROID)
348   signin::DisableInteractionWithSystemAccounts();
349 #endif
350 
351   // Normally this would happen during browser startup, but for tests
352   // we need to trigger creation of Profile-related services.
353   ChromeBrowserMainExtraPartsProfiles::
354       EnsureBrowserContextKeyedServiceFactoriesBuilt();
355 
356 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
357   if (!IsOffTheRecord()) {
358     SupervisedUserSettingsService* settings_service =
359         SupervisedUserSettingsServiceFactory::GetForKey(key_.get());
360     supervised_user_pref_store_ = new TestingPrefStore();
361     settings_service->Init(supervised_user_pref_store_);
362     settings_service->MergeDataAndStartSyncing(
363         syncer::SUPERVISED_USER_SETTINGS, syncer::SyncDataList(),
364         std::unique_ptr<syncer::SyncChangeProcessor>(
365             new syncer::FakeSyncChangeProcessor),
366         std::unique_ptr<syncer::SyncErrorFactory>(
367             new syncer::SyncErrorFactoryMock));
368 
369     supervised_user_pref_store_->SetInitializationCompleted();
370   }
371 #endif
372 
373   if (prefs_.get())
374     user_prefs::UserPrefs::Set(this, prefs_.get());
375   else if (IsOffTheRecord())
376     CreateIncognitoPrefService();
377 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
378   else if (!supervised_user_id_.empty())
379     CreatePrefServiceForSupervisedUser();
380 #endif
381   else
382     CreateTestingPrefService();
383 
384   if (guest_session_ && IsEphemeralGuestProfileEnabled())
385     GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles, true);
386 
387   key_->SetPrefs(prefs_.get());
388   SimpleKeyMap::GetInstance()->Associate(this, key_.get());
389 
390   if (!base::PathExists(profile_path_))
391     base::CreateDirectory(profile_path_);
392 
393 #if defined(OS_CHROMEOS)
394   // Initialize |chromeos::AccountManager|.
395   chromeos::AccountManagerFactory* factory =
396       g_browser_process->platform_part()->GetAccountManagerFactory();
397   chromeos::AccountManager* account_manager =
398       factory->GetAccountManager(profile_path_.value());
399   chromeos::AccountManager::DelayNetworkCallRunner immediate_callback_runner =
400       base::BindRepeating(
401           [](base::OnceClosure closure) -> void { std::move(closure).Run(); });
402   account_manager->Initialize(profile_path_, GetURLLoaderFactory(),
403                               immediate_callback_runner);
404   account_manager->SetPrefService(GetPrefs());
405   if (!chromeos::CrosSettings::IsInitialized()) {
406     scoped_cros_settings_test_helper_.reset(
407         new chromeos::ScopedCrosSettingsTestHelper);
408   }
409   arc::ArcServiceLauncher* launcher = arc::ArcServiceLauncher::Get();
410   if (launcher)
411     launcher->MaybeSetProfile(this);
412 #endif
413 
414   autofill::PersonalDataManagerFactory::GetInstance()->SetTestingFactory(
415       this, base::BindRepeating(&BuildPersonalDataManagerInstanceFor));
416 
417   // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
418   // anymore, after converting the PrefService to a PKS. Until then it must
419   // be associated with a TestingProfile too.
420   if (!IsOffTheRecord())
421     CreateProfilePolicyConnector();
422 
423   extensions_path_ = profile_path_.AppendASCII("Extensions");
424 
425 #if BUILDFLAG(ENABLE_EXTENSIONS)
426   // Note that the GetPrefs() creates a TestingPrefService, therefore
427   // the extension controlled pref values set in ExtensionPrefs
428   // are not reflected in the pref service. One would need to
429   // inject a new ExtensionPrefStore(extension_pref_value_map, false).
430   bool extensions_disabled = base::CommandLine::ForCurrentProcess()->HasSwitch(
431       switches::kDisableExtensions);
432   std::unique_ptr<extensions::ExtensionPrefs> extension_prefs(
433       extensions::ExtensionPrefs::Create(
434           this, GetPrefs(), extensions_path_,
435           ExtensionPrefValueMapFactory::GetForBrowserContext(this),
436           extensions_disabled,
437           std::vector<extensions::EarlyExtensionPrefsObserver*>()));
438   extensions::ExtensionPrefsFactory::GetInstance()->SetInstanceForTesting(
439       this, std::move(extension_prefs));
440 
441   extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
442       this, base::BindRepeating(&extensions::TestExtensionSystem::Build));
443 
444   extensions::EventRouterFactory::GetInstance()->SetTestingFactory(
445       this, BrowserContextKeyedServiceFactory::TestingFactory());
446 
447   web_app::WebAppProviderFactory::GetInstance()->SetTestingFactory(
448       this, base::BindRepeating(&web_app::TestWebAppProvider::BuildDefault));
449 #endif
450 
451   // Prefs for incognito profiles are set in CreateIncognitoPrefService() by
452   // simulating ProfileImpl::GetOffTheRecordPrefs().
453   SimpleFactoryKey* key = GetProfileKey();
454   if (!IsOffTheRecord()) {
455     DCHECK(!original_profile_);
456     user_prefs::PrefRegistrySyncable* pref_registry =
457         static_cast<user_prefs::PrefRegistrySyncable*>(
458             prefs_->DeprecatedGetPrefRegistry());
459     simple_dependency_manager_->RegisterProfilePrefsForServices(pref_registry);
460     browser_context_dependency_manager_->RegisterProfilePrefsForServices(
461         pref_registry);
462   }
463 
464   FullBrowserTransitionManager::Get()->OnProfileCreated(this);
465 
466   simple_dependency_manager_->CreateServicesForTest(key);
467   browser_context_dependency_manager_->CreateBrowserContextServicesForTest(
468       this);
469 }
470 
FinishInit()471 void TestingProfile::FinishInit() {
472   DCHECK(content::NotificationService::current());
473   content::NotificationService::current()->Notify(
474       chrome::NOTIFICATION_PROFILE_CREATED,
475       content::Source<Profile>(static_cast<Profile*>(this)),
476       content::NotificationService::NoDetails());
477 
478   ProfileManager* profile_manager = g_browser_process->profile_manager();
479   if (profile_manager)
480     profile_manager->InitProfileUserPrefs(this);
481 
482   if (delegate_) {
483     delegate_->OnProfileCreated(this, true, false);
484   } else {
485     // It is the role of the delegate to ensure that the signout allowed is
486     // properly updated after the profile is create is initialized.
487     // For testing profiles that do not have a delegate, the signout allowed
488     // must be initialized when the testing profile finishes its initialization.
489     signin_util::EnsureUserSignoutAllowedIsInitializedForProfile(this);
490   }
491 
492   if (original_profile_)
493     original_profile_->NotifyOffTheRecordProfileCreated(this);
494 }
495 
~TestingProfile()496 TestingProfile::~TestingProfile() {
497   if (!profile_destruction_callback_.is_null())
498     std::move(profile_destruction_callback_).Run();
499 
500   // If this profile owns OffTheRecord profiles, tear them down first.
501   otr_profiles_.clear();
502 
503   // Any objects holding live URLFetchers should be deleted before teardown.
504   TemplateURLFetcherFactory::ShutdownForProfile(this);
505 
506   MaybeSendDestroyedNotification();
507 
508   FullBrowserTransitionManager::Get()->OnProfileDestroyed(this);
509 
510   // The SimpleDependencyManager should always be passed after the
511   // BrowserContextDependencyManager. This is because the KeyedService instances
512   // in the BrowserContextDependencyManager's dependency graph can depend on the
513   // ones in the SimpleDependencyManager's graph.
514   DependencyManager::PerformInterlockedTwoPhaseShutdown(
515       browser_context_dependency_manager_, this, simple_dependency_manager_,
516       key_.get());
517   key_.reset();
518 
519   SimpleKeyMap::GetInstance()->Dissociate(this);
520 
521   if (profile_policy_connector_)
522     profile_policy_connector_->Shutdown();
523 
524   if (user_cloud_policy_manager_)
525     user_cloud_policy_manager_->Shutdown();
526 
527   if (host_content_settings_map_.get())
528     host_content_settings_map_->ShutdownOnUIThread();
529 
530   // Make sure SharedProtoDatabase doesn't post delayed tasks anymore.
531   ForEachStoragePartition(
532       this,
533       base::BindRepeating([](content::StoragePartition* storage_partition) {
534         if (auto* provider =
535                 storage_partition->GetProtoDatabaseProviderForTesting()) {
536           provider->SetSharedDBDeleteObsoleteDelayForTesting(base::TimeDelta());
537         }
538       }));
539 
540   // Shutdown storage partitions before we post a task to delete
541   // the resource context.
542   ShutdownStoragePartitions();
543 
544   // Failing a post == leaks == heapcheck failure. Make that an immediate test
545   // failure.
546   if (resource_context_) {
547     CHECK(BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
548                                     resource_context_));
549     resource_context_ = nullptr;
550     content::RunAllPendingInMessageLoop(BrowserThread::IO);
551   }
552 }
553 
CreateHistoryService()554 bool TestingProfile::CreateHistoryService() {
555   // Should never be created multiple times.
556   DCHECK(!HistoryServiceFactory::GetForProfileWithoutCreating(this));
557 
558   // This will create and init the history service.
559   history::HistoryService* history_service =
560       static_cast<history::HistoryService*>(
561           HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
562               this, HistoryServiceFactory::GetDefaultFactory()));
563   if (!history_service) {
564     HistoryServiceFactory::GetInstance()->SetTestingFactory(
565         this, BrowserContextKeyedServiceFactory::TestingFactory());
566     return false;
567   }
568   return true;
569 }
570 
CreateWebDataService()571 void TestingProfile::CreateWebDataService() {
572   WebDataServiceFactory::GetInstance()->SetTestingFactory(
573       this, base::BindRepeating(&BuildWebDataService));
574 }
575 
SetGuestSession(bool guest)576 void TestingProfile::SetGuestSession(bool guest) {
577   guest_session_ = guest;
578 }
579 
SetIsNewProfile(bool is_new_profile)580 void TestingProfile::SetIsNewProfile(bool is_new_profile) {
581   is_new_profile_ = is_new_profile;
582 }
583 
GetPath()584 base::FilePath TestingProfile::GetPath() {
585   return profile_path_;
586 }
587 
GetPath() const588 base::FilePath TestingProfile::GetPath() const {
589   return profile_path_;
590 }
591 
GetCreationTime() const592 base::Time TestingProfile::GetCreationTime() const {
593   return start_time_;
594 }
595 
596 #if !defined(OS_ANDROID)
597 std::unique_ptr<content::ZoomLevelDelegate>
CreateZoomLevelDelegate(const base::FilePath & partition_path)598 TestingProfile::CreateZoomLevelDelegate(const base::FilePath& partition_path) {
599   return std::make_unique<ChromeZoomLevelPrefs>(
600       GetPrefs(), GetPath(), partition_path,
601       zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr());
602 }
603 #endif  // !defined(OS_ANDROID)
604 
GetIOTaskRunner()605 scoped_refptr<base::SequencedTaskRunner> TestingProfile::GetIOTaskRunner() {
606   return base::ThreadTaskRunnerHandle::Get();
607 }
608 
609 sync_preferences::TestingPrefServiceSyncable*
GetTestingPrefService()610 TestingProfile::GetTestingPrefService() {
611   DCHECK(prefs_);
612   DCHECK(testing_prefs_);
613   return testing_prefs_;
614 }
615 
AsTestingProfile()616 TestingProfile* TestingProfile::AsTestingProfile() {
617   return this;
618 }
619 
GetProfileUserName() const620 std::string TestingProfile::GetProfileUserName() const {
621   return profile_name_;
622 }
623 
IsOffTheRecord()624 bool TestingProfile::IsOffTheRecord() {
625   return original_profile_;
626 }
627 
IsOffTheRecord() const628 bool TestingProfile::IsOffTheRecord() const {
629   return original_profile_;
630 }
631 
GetOTRProfileID() const632 const Profile::OTRProfileID& TestingProfile::GetOTRProfileID() const {
633   DCHECK(IsOffTheRecord());
634   return *otr_profile_id_;
635 }
636 
SetOffTheRecordProfile(std::unique_ptr<Profile> otr_profile)637 void TestingProfile::SetOffTheRecordProfile(
638     std::unique_ptr<Profile> otr_profile) {
639   DCHECK(otr_profile);
640   DCHECK(!IsOffTheRecord());
641   DCHECK_EQ(this, otr_profile->GetOriginalProfile());
642   otr_profiles_[otr_profile->GetOTRProfileID()] = std::move(otr_profile);
643 }
644 
GetOffTheRecordProfile(const OTRProfileID & otr_profile_id)645 Profile* TestingProfile::GetOffTheRecordProfile(
646     const OTRProfileID& otr_profile_id) {
647   if (IsOffTheRecord())
648     return original_profile_->GetOffTheRecordProfile(otr_profile_id);
649 
650   // Ephemeral Guest profiles do not support Incognito.
651   if (IsEphemeralGuestProfile() && otr_profile_id == OTRProfileID::PrimaryID())
652     return nullptr;
653 
654   if (!HasOffTheRecordProfile(otr_profile_id)) {
655     TestingProfile::Builder builder;
656     if (IsGuestSession() && otr_profile_id == OTRProfileID::PrimaryID())
657       builder.SetGuestSession();
658     builder.BuildOffTheRecord(this, otr_profile_id);
659     DCHECK(HasOffTheRecordProfile(otr_profile_id));
660   }
661 
662   return otr_profiles_[otr_profile_id].get();
663 }
664 
GetAllOffTheRecordProfiles()665 std::vector<Profile*> TestingProfile::GetAllOffTheRecordProfiles() {
666   std::vector<Profile*> otr_profiles;
667 
668   for (auto& otr : otr_profiles_)
669     otr_profiles.push_back(otr.second.get());
670 
671   return otr_profiles;
672 }
673 
DestroyOffTheRecordProfile(Profile * otr_profile)674 void TestingProfile::DestroyOffTheRecordProfile(Profile* otr_profile) {
675   if (HasOffTheRecordProfile(otr_profile->GetOTRProfileID()))
676     otr_profiles_.erase(otr_profile->GetOTRProfileID());
677 }
678 
HasOffTheRecordProfile(const OTRProfileID & otr_profile_id)679 bool TestingProfile::HasOffTheRecordProfile(
680     const OTRProfileID& otr_profile_id) {
681   return base::Contains(otr_profiles_, otr_profile_id);
682 }
683 
HasAnyOffTheRecordProfile()684 bool TestingProfile::HasAnyOffTheRecordProfile() {
685   return !otr_profiles_.empty();
686 }
687 
GetOriginalProfile()688 Profile* TestingProfile::GetOriginalProfile() {
689   if (original_profile_)
690     return original_profile_;
691   return this;
692 }
693 
GetOriginalProfile() const694 const Profile* TestingProfile::GetOriginalProfile() const {
695   if (original_profile_)
696     return original_profile_;
697   return this;
698 }
699 
SetSupervisedUserId(const std::string & id)700 void TestingProfile::SetSupervisedUserId(const std::string& id) {
701   supervised_user_id_ = id;
702   if (!id.empty())
703     GetPrefs()->SetString(prefs::kSupervisedUserId, id);
704   else
705     GetPrefs()->ClearPref(prefs::kSupervisedUserId);
706 }
707 
IsSupervised() const708 bool TestingProfile::IsSupervised() const {
709   return !supervised_user_id_.empty();
710 }
711 
IsChild() const712 bool TestingProfile::IsChild() const {
713 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
714   return supervised_user_id_ == supervised_users::kChildAccountSUID;
715 #else
716   return false;
717 #endif
718 }
719 
IsLegacySupervised() const720 bool TestingProfile::IsLegacySupervised() const {
721   return IsSupervised() && !IsChild();
722 }
723 
AllowsBrowserWindows() const724 bool TestingProfile::AllowsBrowserWindows() const {
725   return allows_browser_windows_;
726 }
727 
728 #if BUILDFLAG(ENABLE_EXTENSIONS)
SetExtensionSpecialStoragePolicy(ExtensionSpecialStoragePolicy * extension_special_storage_policy)729 void TestingProfile::SetExtensionSpecialStoragePolicy(
730     ExtensionSpecialStoragePolicy* extension_special_storage_policy) {
731   extension_special_storage_policy_ = extension_special_storage_policy;
732 }
733 #endif
734 
735 ExtensionSpecialStoragePolicy*
GetExtensionSpecialStoragePolicy()736 TestingProfile::GetExtensionSpecialStoragePolicy() {
737 #if BUILDFLAG(ENABLE_EXTENSIONS)
738   if (!extension_special_storage_policy_.get())
739     extension_special_storage_policy_ =
740         new ExtensionSpecialStoragePolicy(nullptr);
741   return extension_special_storage_policy_.get();
742 #else
743   return nullptr;
744 #endif
745 }
746 
CreateTestingPrefService()747 void TestingProfile::CreateTestingPrefService() {
748   DCHECK(!prefs_.get());
749   testing_prefs_ = new sync_preferences::TestingPrefServiceSyncable();
750   prefs_.reset(testing_prefs_);
751   user_prefs::UserPrefs::Set(this, prefs_.get());
752   RegisterUserProfilePrefs(testing_prefs_->registry());
753 }
754 
755 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
CreatePrefServiceForSupervisedUser()756 void TestingProfile::CreatePrefServiceForSupervisedUser() {
757   DCHECK(!prefs_.get());
758   DCHECK(!supervised_user_id_.empty());
759 
760   // Construct testing_prefs_ by hand to add the supervised user pref store.
761   testing_prefs_ = new sync_preferences::TestingPrefServiceSyncable(
762       /*managed_prefs=*/new TestingPrefStore, supervised_user_pref_store_,
763       /*extension_prefs=*/new TestingPrefStore,
764       /*user_prefs=*/new TestingPrefStore,
765       /*recommended_prefs=*/new TestingPrefStore,
766       new user_prefs::PrefRegistrySyncable, new PrefNotifierImpl);
767   prefs_.reset(testing_prefs_);
768   user_prefs::UserPrefs::Set(this, prefs_.get());
769   RegisterUserProfilePrefs(testing_prefs_->registry());
770 }
771 #endif  // BUILDFLAG(ENABLE_SUPERVISED_USERS)
772 
CreateIncognitoPrefService()773 void TestingProfile::CreateIncognitoPrefService() {
774   DCHECK(original_profile_);
775   DCHECK(!testing_prefs_);
776   // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
777   // leaves testing_prefs_ unset.
778   prefs_ = CreateIncognitoPrefServiceSyncable(original_profile_->prefs_.get(),
779                                               nullptr);
780   user_prefs::UserPrefs::Set(this, prefs_.get());
781 }
782 
CreateProfilePolicyConnector()783 void TestingProfile::CreateProfilePolicyConnector() {
784   schema_registry_service_ =
785       BuildSchemaRegistryServiceForProfile(this, policy::Schema(), nullptr);
786 
787   if (!policy_service_) {
788     std::vector<policy::ConfigurationPolicyProvider*> providers;
789     std::unique_ptr<policy::PolicyServiceImpl> policy_service =
790         std::make_unique<policy::PolicyServiceImpl>(std::move(providers));
791     policy_service_ = std::move(policy_service);
792   }
793   profile_policy_connector_.reset(new policy::ProfilePolicyConnector());
794   profile_policy_connector_->InitForTesting(std::move(policy_service_));
795   if (override_policy_connector_is_managed_.has_value())
796     profile_policy_connector_->OverrideIsManagedForTesting(
797         override_policy_connector_is_managed_.value());
798 }
799 
GetPrefs()800 PrefService* TestingProfile::GetPrefs() {
801   DCHECK(prefs_);
802   return prefs_.get();
803 }
804 
GetPrefs() const805 const PrefService* TestingProfile::GetPrefs() const {
806   DCHECK(prefs_);
807   return prefs_.get();
808 }
809 
810 #if !defined(OS_ANDROID)
GetZoomLevelPrefs()811 ChromeZoomLevelPrefs* TestingProfile::GetZoomLevelPrefs() {
812   return static_cast<ChromeZoomLevelPrefs*>(
813       GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
814 }
815 #endif  // !defined(OS_ANDROID)
816 
GetDownloadManagerDelegate()817 DownloadManagerDelegate* TestingProfile::GetDownloadManagerDelegate() {
818   return nullptr;
819 }
820 
821 scoped_refptr<network::SharedURLLoaderFactory>
GetURLLoaderFactory()822 TestingProfile::GetURLLoaderFactory() {
823   return nullptr;
824 }
825 
GetResourceContext()826 content::ResourceContext* TestingProfile::GetResourceContext() {
827   if (!resource_context_)
828     resource_context_ = new content::MockResourceContext();
829   return resource_context_;
830 }
831 
GetGuestManager()832 content::BrowserPluginGuestManager* TestingProfile::GetGuestManager() {
833 #if BUILDFLAG(ENABLE_EXTENSIONS)
834   return guest_view::GuestViewManager::FromBrowserContext(this);
835 #else
836   return nullptr;
837 #endif
838 }
839 
GetPushMessagingService()840 content::PushMessagingService* TestingProfile::GetPushMessagingService() {
841   return nullptr;
842 }
843 
844 content::StorageNotificationService*
GetStorageNotificationService()845 TestingProfile::GetStorageNotificationService() {
846   return nullptr;
847 }
848 
IsSameOrParent(Profile * profile)849 bool TestingProfile::IsSameOrParent(Profile* profile) {
850   if (this == profile)
851     return true;
852   return profile && profile->GetOriginalProfile() == this;
853 }
854 
GetStartTime() const855 base::Time TestingProfile::GetStartTime() const {
856   return start_time_;
857 }
858 
GetProfileKey() const859 ProfileKey* TestingProfile::GetProfileKey() const {
860   DCHECK(key_);
861   return key_.get();
862 }
863 
864 policy::SchemaRegistryService*
GetPolicySchemaRegistryService()865 TestingProfile::GetPolicySchemaRegistryService() {
866   return schema_registry_service_.get();
867 }
868 
869 #if defined(OS_CHROMEOS)
870 policy::UserCloudPolicyManagerChromeOS*
GetUserCloudPolicyManagerChromeOS()871 TestingProfile::GetUserCloudPolicyManagerChromeOS() {
872   return user_cloud_policy_manager_.get();
873 }
874 
875 policy::ActiveDirectoryPolicyManager*
GetActiveDirectoryPolicyManager()876 TestingProfile::GetActiveDirectoryPolicyManager() {
877   return nullptr;
878 }
879 #else
GetUserCloudPolicyManager()880 policy::UserCloudPolicyManager* TestingProfile::GetUserCloudPolicyManager() {
881   return user_cloud_policy_manager_.get();
882 }
883 #endif  // defined(OS_CHROMEOS)
884 
GetProfilePolicyConnector()885 policy::ProfilePolicyConnector* TestingProfile::GetProfilePolicyConnector() {
886   return profile_policy_connector_.get();
887 }
888 
889 const policy::ProfilePolicyConnector*
GetProfilePolicyConnector() const890 TestingProfile::GetProfilePolicyConnector() const {
891   return profile_policy_connector_.get();
892 }
893 
last_selected_directory()894 base::FilePath TestingProfile::last_selected_directory() {
895   return last_selected_directory_;
896 }
897 
set_last_selected_directory(const base::FilePath & path)898 void TestingProfile::set_last_selected_directory(const base::FilePath& path) {
899   last_selected_directory_ = path;
900 }
901 
902 #if defined(OS_CHROMEOS)
ChangeAppLocale(const std::string & locale,AppLocaleChangedVia via)903 void TestingProfile::ChangeAppLocale(const std::string& locale,
904                                      AppLocaleChangedVia via) {
905   requested_locale_ = locale;
906 }
907 
908 chromeos::ScopedCrosSettingsTestHelper*
ScopedCrosSettingsTestHelper()909 TestingProfile::ScopedCrosSettingsTestHelper() {
910   return scoped_cros_settings_test_helper_.get();
911 }
912 #endif
913 
BlockUntilHistoryProcessesPendingRequests()914 void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
915   history::HistoryService* history_service =
916       HistoryServiceFactory::GetForProfile(this,
917                                            ServiceAccessType::EXPLICIT_ACCESS);
918   DCHECK(history_service);
919   history::BlockUntilHistoryProcessesPendingRequests(history_service);
920 }
921 
GetHomePage()922 GURL TestingProfile::GetHomePage() {
923   return GURL(chrome::kChromeUINewTabURL);
924 }
925 
SetCreationTimeForTesting(base::Time creation_time)926 void TestingProfile::SetCreationTimeForTesting(base::Time creation_time) {
927   start_time_ = creation_time;
928 }
929 
GetOffTheRecordPrefs()930 PrefService* TestingProfile::GetOffTheRecordPrefs() {
931   return nullptr;
932 }
933 
GetSpecialStoragePolicy()934 storage::SpecialStoragePolicy* TestingProfile::GetSpecialStoragePolicy() {
935 #if BUILDFLAG(ENABLE_EXTENSIONS)
936   return GetExtensionSpecialStoragePolicy();
937 #else
938   return nullptr;
939 #endif
940 }
941 
GetSSLHostStateDelegate()942 content::SSLHostStateDelegate* TestingProfile::GetSSLHostStateDelegate() {
943   return StatefulSSLHostStateDelegateFactory::GetForProfile(this);
944 }
945 
946 content::PermissionControllerDelegate*
GetPermissionControllerDelegate()947 TestingProfile::GetPermissionControllerDelegate() {
948   return nullptr;
949 }
950 
951 content::ClientHintsControllerDelegate*
GetClientHintsControllerDelegate()952 TestingProfile::GetClientHintsControllerDelegate() {
953   return nullptr;
954 }
955 
GetBackgroundFetchDelegate()956 content::BackgroundFetchDelegate* TestingProfile::GetBackgroundFetchDelegate() {
957   return BackgroundFetchDelegateFactory::GetForProfile(this);
958 }
959 
960 content::BackgroundSyncController*
GetBackgroundSyncController()961 TestingProfile::GetBackgroundSyncController() {
962   return nullptr;
963 }
964 
965 content::BrowsingDataRemoverDelegate*
GetBrowsingDataRemoverDelegate()966 TestingProfile::GetBrowsingDataRemoverDelegate() {
967   // TestingProfile contains a real BrowsingDataRemover from BrowserContext.
968   // Since ChromeBrowsingDataRemoverDelegate is just a Chrome-specific extension
969   // of BrowsingDataRemover, we include it here for consistency.
970   //
971   // This is not a problem, since ChromeBrowsingDataRemoverDelegate mostly
972   // just serves as an interface to deletion mechanisms of various browsing
973   // data backends, which are already mocked if considered too heavy-weight
974   // for TestingProfile.
975   return ChromeBrowsingDataRemoverDelegateFactory::GetForProfile(this);
976 }
977 
SetCorsOriginAccessListForOrigin(const url::Origin & source_origin,std::vector<network::mojom::CorsOriginPatternPtr> allow_patterns,std::vector<network::mojom::CorsOriginPatternPtr> block_patterns,base::OnceClosure closure)978 void TestingProfile::SetCorsOriginAccessListForOrigin(
979     const url::Origin& source_origin,
980     std::vector<network::mojom::CorsOriginPatternPtr> allow_patterns,
981     std::vector<network::mojom::CorsOriginPatternPtr> block_patterns,
982     base::OnceClosure closure) {
983   // Extensions need to set the list, but just can be ignored unless they need
984   // to make actual network requests beyond the CORS policy.
985   base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(closure));
986 }
987 
WasCreatedByVersionOrLater(const std::string & version)988 bool TestingProfile::WasCreatedByVersionOrLater(const std::string& version) {
989   return true;
990 }
991 
IsGuestSession() const992 bool TestingProfile::IsGuestSession() const {
993   return guest_session_ && !IsEphemeralGuestProfileEnabled();
994 }
995 
IsEphemeralGuestProfile() const996 bool TestingProfile::IsEphemeralGuestProfile() const {
997   return guest_session_ && IsEphemeralGuestProfileEnabled();
998 }
999 
IsNewProfile() const1000 bool TestingProfile::IsNewProfile() const {
1001   if (is_new_profile_.has_value())
1002     return is_new_profile_.value();
1003   return Profile::IsNewProfile();
1004 }
1005 
GetLastSessionExitType() const1006 Profile::ExitType TestingProfile::GetLastSessionExitType() const {
1007   return last_session_exited_cleanly_ ? EXIT_NORMAL : EXIT_CRASHED;
1008 }
1009 
ConfigureNetworkContextParams(bool in_memory,const base::FilePath & relative_partition_path,network::mojom::NetworkContextParams * network_context_params,network::mojom::CertVerifierCreationParams * cert_verifier_creation_params)1010 void TestingProfile::ConfigureNetworkContextParams(
1011     bool in_memory,
1012     const base::FilePath& relative_partition_path,
1013     network::mojom::NetworkContextParams* network_context_params,
1014     network::mojom::CertVerifierCreationParams* cert_verifier_creation_params) {
1015   network_context_params->user_agent = GetUserAgent();
1016   network_context_params->accept_language = "en-us,en";
1017 }
1018 
Builder()1019 TestingProfile::Builder::Builder()
1020     : build_called_(false),
1021       delegate_(nullptr),
1022       guest_session_(false),
1023       allows_browser_windows_(true),
1024       profile_name_(kTestingProfile) {}
1025 
~Builder()1026 TestingProfile::Builder::~Builder() {
1027 }
1028 
SetPath(const base::FilePath & path)1029 void TestingProfile::Builder::SetPath(const base::FilePath& path) {
1030   path_ = path;
1031 }
1032 
SetDelegate(Delegate * delegate)1033 void TestingProfile::Builder::SetDelegate(Delegate* delegate) {
1034   delegate_ = delegate;
1035 }
1036 
1037 #if BUILDFLAG(ENABLE_EXTENSIONS)
SetExtensionSpecialStoragePolicy(scoped_refptr<ExtensionSpecialStoragePolicy> policy)1038 void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
1039     scoped_refptr<ExtensionSpecialStoragePolicy> policy) {
1040   extension_policy_ = policy;
1041 }
1042 #endif
1043 
SetPrefService(std::unique_ptr<sync_preferences::PrefServiceSyncable> prefs)1044 void TestingProfile::Builder::SetPrefService(
1045     std::unique_ptr<sync_preferences::PrefServiceSyncable> prefs) {
1046   pref_service_ = std::move(prefs);
1047 }
1048 
SetGuestSession()1049 void TestingProfile::Builder::SetGuestSession() {
1050   guest_session_ = true;
1051 }
1052 
DisallowBrowserWindows()1053 void TestingProfile::Builder::DisallowBrowserWindows() {
1054   allows_browser_windows_ = false;
1055 }
1056 
OverrideIsNewProfile(bool is_new_profile)1057 void TestingProfile::Builder::OverrideIsNewProfile(bool is_new_profile) {
1058   is_new_profile_ = is_new_profile;
1059 }
1060 
SetSupervisedUserId(const std::string & supervised_user_id)1061 void TestingProfile::Builder::SetSupervisedUserId(
1062     const std::string& supervised_user_id) {
1063   supervised_user_id_ = supervised_user_id;
1064 }
1065 
1066 #if defined(OS_CHROMEOS)
SetUserCloudPolicyManagerChromeOS(std::unique_ptr<policy::UserCloudPolicyManagerChromeOS> user_cloud_policy_manager)1067 void TestingProfile::Builder::SetUserCloudPolicyManagerChromeOS(
1068     std::unique_ptr<policy::UserCloudPolicyManagerChromeOS>
1069         user_cloud_policy_manager) {
1070   user_cloud_policy_manager_ = std::move(user_cloud_policy_manager);
1071 }
1072 #else
SetUserCloudPolicyManager(std::unique_ptr<policy::UserCloudPolicyManager> user_cloud_policy_manager)1073 void TestingProfile::Builder::SetUserCloudPolicyManager(
1074     std::unique_ptr<policy::UserCloudPolicyManager> user_cloud_policy_manager) {
1075   user_cloud_policy_manager_ = std::move(user_cloud_policy_manager);
1076 }
1077 #endif
1078 
SetPolicyService(std::unique_ptr<policy::PolicyService> policy_service)1079 void TestingProfile::Builder::SetPolicyService(
1080     std::unique_ptr<policy::PolicyService> policy_service) {
1081   policy_service_ = std::move(policy_service);
1082 }
1083 
SetProfileName(const std::string & profile_name)1084 void TestingProfile::Builder::SetProfileName(const std::string& profile_name) {
1085   profile_name_ = profile_name;
1086 }
1087 
OverridePolicyConnectorIsManagedForTesting(bool is_managed)1088 void TestingProfile::Builder::OverridePolicyConnectorIsManagedForTesting(
1089     bool is_managed) {
1090   override_policy_connector_is_managed_ = is_managed;
1091 }
1092 
AddTestingFactory(BrowserContextKeyedServiceFactory * service_factory,BrowserContextKeyedServiceFactory::TestingFactory testing_factory)1093 void TestingProfile::Builder::AddTestingFactory(
1094     BrowserContextKeyedServiceFactory* service_factory,
1095     BrowserContextKeyedServiceFactory::TestingFactory testing_factory) {
1096   testing_factories_.emplace_back(service_factory, std::move(testing_factory));
1097 }
1098 
AddTestingFactories(const TestingFactories & testing_factories)1099 void TestingProfile::Builder::AddTestingFactories(
1100     const TestingFactories& testing_factories) {
1101   testing_factories_.insert(testing_factories_.end(), testing_factories.begin(),
1102                             testing_factories.end());
1103 }
1104 
Build()1105 std::unique_ptr<TestingProfile> TestingProfile::Builder::Build() {
1106   DCHECK(!build_called_);
1107   build_called_ = true;
1108 
1109   return std::unique_ptr<TestingProfile>(new TestingProfile(
1110       path_, delegate_,
1111 #if BUILDFLAG(ENABLE_EXTENSIONS)
1112       extension_policy_,
1113 #endif
1114       std::move(pref_service_), nullptr, guest_session_,
1115       allows_browser_windows_, std::move(is_new_profile_), supervised_user_id_,
1116       std::move(user_cloud_policy_manager_), std::move(policy_service_),
1117       std::move(testing_factories_), profile_name_,
1118       override_policy_connector_is_managed_, base::Optional<OTRProfileID>()));
1119 }
1120 
BuildOffTheRecord(TestingProfile * original_profile,const OTRProfileID & otr_profile_id)1121 TestingProfile* TestingProfile::Builder::BuildOffTheRecord(
1122     TestingProfile* original_profile,
1123     const OTRProfileID& otr_profile_id) {
1124   DCHECK(!build_called_);
1125   DCHECK(original_profile);
1126   build_called_ = true;
1127 
1128   // Ephemeral guest profiles do not support Incognito.
1129   if (original_profile->IsEphemeralGuestProfile() &&
1130       otr_profile_id == OTRProfileID::PrimaryID())
1131     return nullptr;
1132 
1133   // Note: Owned by |original_profile|.
1134   return new TestingProfile(
1135       path_, delegate_,
1136 #if BUILDFLAG(ENABLE_EXTENSIONS)
1137       extension_policy_,
1138 #endif
1139       std::move(pref_service_), original_profile, guest_session_,
1140       allows_browser_windows_, std::move(is_new_profile_), supervised_user_id_,
1141       std::move(user_cloud_policy_manager_), std::move(policy_service_),
1142       std::move(testing_factories_), profile_name_,
1143       override_policy_connector_is_managed_,
1144       base::Optional<OTRProfileID>(otr_profile_id));
1145 }
1146 
BuildIncognito(TestingProfile * original_profile)1147 TestingProfile* TestingProfile::Builder::BuildIncognito(
1148     TestingProfile* original_profile) {
1149   return BuildOffTheRecord(original_profile, OTRProfileID::PrimaryID());
1150 }
1151