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.
7 #include "base/command_line.h"
8 #include "base/file_util.h"
9 #include "base/files/scoped_temp_dir.h"
10 #include "base/path_service.h"
11 #include "base/run_loop.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/values.h"
14 #include "build/build_config.h"
15 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
16 #include "chrome/browser/browser_process.h"
17 #include "chrome/browser/chrome_notification_types.h"
18 #include "chrome/browser/chromeos/settings/cros_settings.h"
19 #include "chrome/browser/history/history_service.h"
20 #include "chrome/browser/history/history_service_factory.h"
21 #include "chrome/browser/io_thread.h"
22 #include "chrome/browser/prefs/browser_prefs.h"
23 #include "chrome/browser/prefs/incognito_mode_prefs.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/profiles/profile_info_cache.h"
26 #include "chrome/browser/profiles/profile_manager.h"
27 #include "chrome/browser/ui/browser.h"
28 #include "chrome/common/chrome_constants.h"
29 #include "chrome/common/chrome_paths.h"
30 #include "chrome/common/chrome_switches.h"
31 #include "chrome/common/pref_names.h"
32 #include "chrome/test/base/scoped_testing_local_state.h"
33 #include "chrome/test/base/test_browser_window.h"
34 #include "chrome/test/base/testing_browser_process.h"
35 #include "chrome/test/base/testing_profile.h"
36 #include "content/public/browser/notification_service.h"
37 #include "content/public/test/test_browser_thread_bundle.h"
38 #include "testing/gmock/include/gmock/gmock.h"
39 #include "testing/gtest/include/gtest/gtest.h"
41 #if defined(OS_CHROMEOS)
42 #include "chrome/browser/chromeos/login/mock_user_manager.h"
43 #include "chrome/browser/chromeos/login/user_manager.h"
44 #include "chrome/browser/chromeos/settings/cros_settings.h"
45 #include "chrome/browser/chromeos/settings/device_settings_service.h"
46 #include "chromeos/chromeos_switches.h"
49 using base::ASCIIToUTF16;
50 using content::BrowserThread;
54 // This global variable is used to check that value returned to different
55 // observers is the same.
56 Profile* g_created_profile;
58 class UnittestProfileManager : public ::ProfileManagerWithoutInit {
60 explicit UnittestProfileManager(const base::FilePath& user_data_dir)
61 : ::ProfileManagerWithoutInit(user_data_dir) {}
64 virtual Profile* CreateProfileHelper(
65 const base::FilePath& file_path) OVERRIDE {
66 if (!base::PathExists(file_path)) {
67 if (!base::CreateDirectory(file_path))
70 return new TestingProfile(file_path, NULL);
73 virtual Profile* CreateProfileAsyncHelper(const base::FilePath& path,
74 Delegate* delegate) OVERRIDE {
75 // This is safe while all file operations are done on the FILE thread.
76 BrowserThread::PostTask(
77 BrowserThread::FILE, FROM_HERE,
78 base::Bind(base::IgnoreResult(&base::CreateDirectory), path));
80 return new TestingProfile(path, this);
86 class ProfileManagerTest : public testing::Test {
90 MOCK_METHOD2(OnProfileCreated,
91 void(Profile* profile, Profile::CreateStatus status));
95 : local_state_(TestingBrowserProcess::GetGlobal()) {
98 virtual void SetUp() {
99 // Create a new temporary directory, and store the path
100 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
101 TestingBrowserProcess::GetGlobal()->SetProfileManager(
102 new UnittestProfileManager(temp_dir_.path()));
104 #if defined(OS_CHROMEOS)
105 CommandLine* cl = CommandLine::ForCurrentProcess();
106 cl->AppendSwitch(switches::kTestType);
110 virtual void TearDown() {
111 TestingBrowserProcess::GetGlobal()->SetProfileManager(NULL);
112 base::RunLoop().RunUntilIdle();
115 // Helper function to create a profile with |name| for a profile |manager|.
116 void CreateProfileAsync(ProfileManager* manager,
117 const std::string& name,
119 MockObserver* mock_observer) {
120 manager->CreateProfileAsync(
121 temp_dir_.path().AppendASCII(name),
122 base::Bind(&MockObserver::OnProfileCreated,
123 base::Unretained(mock_observer)),
124 base::UTF8ToUTF16(name),
125 base::UTF8ToUTF16(ProfileInfoCache::GetDefaultAvatarIconUrl(0)),
126 is_managed ? "Dummy ID" : std::string());
129 #if defined(OS_CHROMEOS)
130 chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
131 chromeos::ScopedTestCrosSettings test_cros_settings_;
134 // The path to temporary directory used to contain the test operations.
135 base::ScopedTempDir temp_dir_;
136 ScopedTestingLocalState local_state_;
138 content::TestBrowserThreadBundle thread_bundle_;
140 #if defined(OS_CHROMEOS)
141 chromeos::ScopedTestUserManager test_user_manager_;
145 TEST_F(ProfileManagerTest, GetProfile) {
146 base::FilePath dest_path = temp_dir_.path();
147 dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
149 ProfileManager* profile_manager = g_browser_process->profile_manager();
151 // Successfully create a profile.
152 Profile* profile = profile_manager->GetProfile(dest_path);
153 EXPECT_TRUE(profile);
155 // The profile already exists when we call GetProfile. Just load it.
156 EXPECT_EQ(profile, profile_manager->GetProfile(dest_path));
159 TEST_F(ProfileManagerTest, DefaultProfileDir) {
160 base::FilePath expected_default =
161 base::FilePath().AppendASCII(chrome::kInitialProfile);
163 expected_default.value(),
164 g_browser_process->profile_manager()->GetInitialProfileDir().value());
167 #if defined(OS_CHROMEOS)
168 // This functionality only exists on Chrome OS.
169 TEST_F(ProfileManagerTest, LoggedInProfileDir) {
170 CommandLine *cl = CommandLine::ForCurrentProcess();
171 std::string profile_dir(chrome::kTestUserProfileDir);
173 cl->AppendSwitchASCII(chromeos::switches::kLoginProfile, profile_dir);
175 base::FilePath expected_default =
176 base::FilePath().AppendASCII(chrome::kInitialProfile);
177 ProfileManager* profile_manager = g_browser_process->profile_manager();
178 EXPECT_EQ(expected_default.value(),
179 profile_manager->GetInitialProfileDir().value());
181 scoped_ptr<chromeos::MockUserManager> mock_user_manager;
182 mock_user_manager.reset(new chromeos::MockUserManager());
183 mock_user_manager->SetActiveUser("user@gmail.com");
184 chromeos::User* active_user = mock_user_manager->GetActiveUser();
185 profile_manager->Observe(chrome::NOTIFICATION_LOGIN_USER_CHANGED,
186 content::NotificationService::AllSources(),
187 content::Details<const chromeos::User>(active_user));
188 base::FilePath expected_logged_in(profile_dir);
189 EXPECT_EQ(expected_logged_in.value(),
190 profile_manager->GetInitialProfileDir().value());
191 VLOG(1) << temp_dir_.path().Append(
192 profile_manager->GetInitialProfileDir()).value();
197 TEST_F(ProfileManagerTest, CreateAndUseTwoProfiles) {
198 base::FilePath dest_path1 = temp_dir_.path();
199 dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
201 base::FilePath dest_path2 = temp_dir_.path();
202 dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
204 ProfileManager* profile_manager = g_browser_process->profile_manager();
206 // Successfully create the profiles.
207 TestingProfile* profile1 =
208 static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
209 ASSERT_TRUE(profile1);
211 TestingProfile* profile2 =
212 static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
213 ASSERT_TRUE(profile2);
215 // Force lazy-init of some profile services to simulate use.
216 ASSERT_TRUE(profile1->CreateHistoryService(true, false));
217 EXPECT_TRUE(HistoryServiceFactory::GetForProfile(profile1,
218 Profile::EXPLICIT_ACCESS));
219 profile1->CreateBookmarkModel(true);
220 EXPECT_TRUE(BookmarkModelFactory::GetForProfile(profile1));
221 profile2->CreateBookmarkModel(true);
222 EXPECT_TRUE(BookmarkModelFactory::GetForProfile(profile2));
223 ASSERT_TRUE(profile2->CreateHistoryService(true, false));
224 EXPECT_TRUE(HistoryServiceFactory::GetForProfile(profile2,
225 Profile::EXPLICIT_ACCESS));
227 // Make sure any pending tasks run before we destroy the profiles.
228 base::RunLoop().RunUntilIdle();
230 TestingBrowserProcess::GetGlobal()->SetProfileManager(NULL);
232 // Make sure history cleans up correctly.
233 base::RunLoop().RunUntilIdle();
236 MATCHER(NotFail, "Profile creation failure status is not reported.") {
237 return arg == Profile::CREATE_STATUS_CREATED ||
238 arg == Profile::CREATE_STATUS_INITIALIZED;
241 MATCHER(SameNotNull, "The same non-NULL value for all calls.") {
242 if (!g_created_profile)
243 g_created_profile = arg;
244 return arg != NULL && arg == g_created_profile;
247 TEST_F(ProfileManagerTest, CreateProfileAsyncMultipleRequests) {
248 g_created_profile = NULL;
250 MockObserver mock_observer1;
251 EXPECT_CALL(mock_observer1, OnProfileCreated(
252 SameNotNull(), NotFail())).Times(testing::AtLeast(1));
253 MockObserver mock_observer2;
254 EXPECT_CALL(mock_observer2, OnProfileCreated(
255 SameNotNull(), NotFail())).Times(testing::AtLeast(1));
256 MockObserver mock_observer3;
257 EXPECT_CALL(mock_observer3, OnProfileCreated(
258 SameNotNull(), NotFail())).Times(testing::AtLeast(1));
260 ProfileManager* profile_manager = g_browser_process->profile_manager();
261 const std::string profile_name = "New Profile";
262 CreateProfileAsync(profile_manager, profile_name, false, &mock_observer1);
263 CreateProfileAsync(profile_manager, profile_name, false, &mock_observer2);
264 CreateProfileAsync(profile_manager, profile_name, false, &mock_observer3);
266 base::RunLoop().RunUntilIdle();
269 TEST_F(ProfileManagerTest, CreateProfilesAsync) {
270 const std::string profile_name1 = "New Profile 1";
271 const std::string profile_name2 = "New Profile 2";
273 MockObserver mock_observer;
274 EXPECT_CALL(mock_observer, OnProfileCreated(
275 testing::NotNull(), NotFail())).Times(testing::AtLeast(3));
277 ProfileManager* profile_manager = g_browser_process->profile_manager();
279 CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
280 CreateProfileAsync(profile_manager, profile_name2, false, &mock_observer);
282 base::RunLoop().RunUntilIdle();
285 TEST_F(ProfileManagerTest, CreateProfileAsyncCheckOmitted) {
286 std::string name = "Managed Profile";
288 MockObserver mock_observer;
289 EXPECT_CALL(mock_observer, OnProfileCreated(
290 testing::NotNull(), NotFail())).Times(testing::AtLeast(2));
292 ProfileManager* profile_manager = g_browser_process->profile_manager();
293 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
294 EXPECT_EQ(0u, cache.GetNumberOfProfiles());
296 CreateProfileAsync(profile_manager, name, true, &mock_observer);
297 base::RunLoop().RunUntilIdle();
299 EXPECT_EQ(1u, cache.GetNumberOfProfiles());
300 // Managed profiles should start out omitted from the profile list.
301 EXPECT_TRUE(cache.IsOmittedProfileAtIndex(0));
303 name = "Regular Profile";
304 CreateProfileAsync(profile_manager, name, false, &mock_observer);
305 base::RunLoop().RunUntilIdle();
307 EXPECT_EQ(2u, cache.GetNumberOfProfiles());
308 // Non-managed profiles should be included in the profile list.
309 EXPECT_FALSE(cache.IsOmittedProfileAtIndex(1));
312 TEST_F(ProfileManagerTest, AddProfileToCacheCheckOmitted) {
313 ProfileManager* profile_manager = g_browser_process->profile_manager();
314 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
315 EXPECT_EQ(0u, cache.GetNumberOfProfiles());
317 const base::FilePath managed_path = temp_dir_.path().AppendASCII("Managed");
318 TestingProfile* managed_profile = new TestingProfile(managed_path, NULL);
319 managed_profile->GetPrefs()->SetString(prefs::kManagedUserId, "An ID");
321 // RegisterTestingProfile adds the profile to the cache and takes ownership.
322 profile_manager->RegisterTestingProfile(managed_profile, true, false);
323 EXPECT_EQ(1u, cache.GetNumberOfProfiles());
324 EXPECT_TRUE(cache.IsOmittedProfileAtIndex(0));
326 const base::FilePath nonmanaged_path = temp_dir_.path().AppendASCII(
328 TestingProfile* nonmanaged_profile = new TestingProfile(nonmanaged_path,
330 profile_manager->RegisterTestingProfile(nonmanaged_profile, true, false);
332 EXPECT_EQ(2u, cache.GetNumberOfProfiles());
333 size_t managed_index = cache.GetIndexOfProfileWithPath(managed_path);
334 EXPECT_TRUE(cache.IsOmittedProfileAtIndex(managed_index));
335 size_t nonmanaged_index = cache.GetIndexOfProfileWithPath(nonmanaged_path);
336 EXPECT_FALSE(cache.IsOmittedProfileAtIndex(nonmanaged_index));
339 TEST_F(ProfileManagerTest, GetGuestProfilePath) {
340 base::FilePath guest_path = ProfileManager::GetGuestProfilePath();
341 base::FilePath expected_path = temp_dir_.path();
342 expected_path = expected_path.Append(chrome::kGuestProfileDir);
343 EXPECT_EQ(expected_path, guest_path);
346 #if defined(OS_CHROMEOS)
347 class UnittestGuestProfileManager : public UnittestProfileManager {
349 explicit UnittestGuestProfileManager(const base::FilePath& user_data_dir)
350 : UnittestProfileManager(user_data_dir) {}
353 virtual Profile* CreateProfileHelper(
354 const base::FilePath& file_path) OVERRIDE {
355 TestingProfile::Builder builder;
356 builder.SetGuestSession();
357 builder.SetPath(file_path);
358 TestingProfile* testing_profile = builder.Build().release();
360 TestingProfile::Builder incognito_builder;
361 incognito_builder.SetIncognito();
362 incognito_builder.SetGuestSession();
363 incognito_builder.SetPath(ProfileManager::GetGuestProfilePath());
364 testing_profile->SetOffTheRecordProfile(
365 incognito_builder.Build().PassAs<Profile>());
367 return testing_profile;
371 class ProfileManagerGuestTest : public ProfileManagerTest {
373 virtual void SetUp() {
374 // Create a new temporary directory, and store the path
375 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
376 TestingBrowserProcess::GetGlobal()->SetProfileManager(
377 new UnittestGuestProfileManager(temp_dir_.path()));
379 CommandLine* cl = CommandLine::ForCurrentProcess();
380 cl->AppendSwitch(switches::kTestType);
381 cl->AppendSwitchASCII(chromeos::switches::kLoginProfile, "user");
382 cl->AppendSwitch(chromeos::switches::kGuestSession);
383 cl->AppendSwitch(::switches::kIncognito);
385 chromeos::UserManager::Get()->UserLoggedIn(
386 chromeos::UserManager::kGuestUserName,
387 chromeos::UserManager::kGuestUserName,
392 TEST_F(ProfileManagerGuestTest, GuestProfileIngonito) {
393 Profile* primary_profile = ProfileManager::GetPrimaryUserProfile();
394 EXPECT_TRUE(primary_profile->IsOffTheRecord());
396 Profile* active_profile = ProfileManager::GetActiveUserProfile();
397 EXPECT_TRUE(active_profile->IsOffTheRecord());
399 EXPECT_TRUE(active_profile->IsSameProfile(primary_profile));
401 Profile* last_used_profile = ProfileManager::GetLastUsedProfile();
402 EXPECT_TRUE(last_used_profile->IsOffTheRecord());
404 EXPECT_TRUE(last_used_profile->IsSameProfile(active_profile));
408 TEST_F(ProfileManagerTest, AutoloadProfilesWithBackgroundApps) {
409 ProfileManager* profile_manager = g_browser_process->profile_manager();
410 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
411 local_state_.Get()->SetUserPref(prefs::kBackgroundModeEnabled,
412 base::Value::CreateBooleanValue(true));
414 // Setting a pref which is not applicable to a system (i.e., Android in this
415 // case) does not necessarily create it. Don't bother continuing with the
416 // test if this pref doesn't exist because it will not load the profiles if
417 // it cannot verify that the pref for background mode is enabled.
418 if (!local_state_.Get()->HasPrefPath(prefs::kBackgroundModeEnabled))
421 EXPECT_EQ(0u, cache.GetNumberOfProfiles());
422 cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_1"),
423 ASCIIToUTF16("name_1"), base::string16(), 0,
425 cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_2"),
426 ASCIIToUTF16("name_2"), base::string16(), 0,
428 cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_3"),
429 ASCIIToUTF16("name_3"), base::string16(), 0,
431 cache.SetBackgroundStatusOfProfileAtIndex(0, true);
432 cache.SetBackgroundStatusOfProfileAtIndex(2, true);
433 EXPECT_EQ(3u, cache.GetNumberOfProfiles());
435 profile_manager->AutoloadProfiles();
437 EXPECT_EQ(2u, profile_manager->GetLoadedProfiles().size());
440 TEST_F(ProfileManagerTest, DoNotAutoloadProfilesIfBackgroundModeOff) {
441 ProfileManager* profile_manager = g_browser_process->profile_manager();
442 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
443 local_state_.Get()->SetUserPref(prefs::kBackgroundModeEnabled,
444 base::Value::CreateBooleanValue(false));
446 EXPECT_EQ(0u, cache.GetNumberOfProfiles());
447 cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_1"),
448 ASCIIToUTF16("name_1"), base::string16(), 0,
450 cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_2"),
451 ASCIIToUTF16("name_2"), base::string16(), 0,
453 cache.SetBackgroundStatusOfProfileAtIndex(0, false);
454 cache.SetBackgroundStatusOfProfileAtIndex(1, true);
455 EXPECT_EQ(2u, cache.GetNumberOfProfiles());
457 profile_manager->AutoloadProfiles();
459 EXPECT_EQ(0u, profile_manager->GetLoadedProfiles().size());
462 TEST_F(ProfileManagerTest, InitProfileUserPrefs) {
463 base::FilePath dest_path = temp_dir_.path();
464 dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
466 ProfileManager* profile_manager = g_browser_process->profile_manager();
470 // Successfully create the profile
471 profile = profile_manager->GetProfile(dest_path);
472 ASSERT_TRUE(profile);
474 // Check that the profile name is non empty
475 std::string profile_name =
476 profile->GetPrefs()->GetString(prefs::kProfileName);
477 EXPECT_FALSE(profile_name.empty());
479 // Check that the profile avatar index is valid
480 size_t avatar_index =
481 profile->GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
482 EXPECT_TRUE(profile_manager->GetProfileInfoCache().IsDefaultAvatarIconIndex(
486 // Tests that a new profile's entry in the profile info cache is setup with the
487 // same values that are in the profile prefs.
488 TEST_F(ProfileManagerTest, InitProfileInfoCacheForAProfile) {
489 base::FilePath dest_path = temp_dir_.path();
490 dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
492 ProfileManager* profile_manager = g_browser_process->profile_manager();
493 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
495 // Successfully create the profile
496 Profile* profile = profile_manager->GetProfile(dest_path);
497 ASSERT_TRUE(profile);
499 std::string profile_name =
500 profile->GetPrefs()->GetString(prefs::kProfileName);
501 size_t avatar_index =
502 profile->GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
504 size_t profile_index = cache.GetIndexOfProfileWithPath(dest_path);
506 // Check if the profile prefs are the same as the cache prefs
507 EXPECT_EQ(profile_name,
508 base::UTF16ToUTF8(cache.GetNameOfProfileAtIndex(profile_index)));
509 EXPECT_EQ(avatar_index,
510 cache.GetAvatarIconIndexOfProfileAtIndex(profile_index));
513 TEST_F(ProfileManagerTest, GetLastUsedProfileAllowedByPolicy) {
514 ProfileManager* profile_manager = g_browser_process->profile_manager();
515 ASSERT_TRUE(profile_manager);
517 Profile* profile = profile_manager->GetLastUsedProfileAllowedByPolicy();
518 ASSERT_TRUE(profile);
519 EXPECT_FALSE(profile->IsOffTheRecord());
520 PrefService* prefs = profile->GetPrefs();
521 EXPECT_EQ(IncognitoModePrefs::ENABLED,
522 IncognitoModePrefs::GetAvailability(prefs));
524 // Attach an incognito Profile to the TestingProfile.
525 ASSERT_FALSE(profile->GetOffTheRecordProfile());
526 TestingProfile::Builder builder;
527 builder.SetIncognito();
528 scoped_ptr<TestingProfile> incognito_profile = builder.Build();
529 EXPECT_TRUE(incognito_profile->IsOffTheRecord());
530 TestingProfile* testing_profile = static_cast<TestingProfile*>(profile);
531 testing_profile->SetOffTheRecordProfile(incognito_profile.PassAs<Profile>());
532 ASSERT_TRUE(profile->GetOffTheRecordProfile());
534 IncognitoModePrefs::SetAvailability(prefs, IncognitoModePrefs::DISABLED);
536 profile_manager->GetLastUsedProfileAllowedByPolicy()->IsOffTheRecord());
538 // GetLastUsedProfileAllowedByPolicy() returns the incognito Profile when
539 // incognito mode is forced.
540 IncognitoModePrefs::SetAvailability(prefs, IncognitoModePrefs::FORCED);
542 profile_manager->GetLastUsedProfileAllowedByPolicy()->IsOffTheRecord());
545 #if !defined(OS_ANDROID)
546 // There's no Browser object on Android.
547 TEST_F(ProfileManagerTest, LastOpenedProfiles) {
548 base::FilePath dest_path1 = temp_dir_.path();
549 dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
551 base::FilePath dest_path2 = temp_dir_.path();
552 dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
554 ProfileManager* profile_manager = g_browser_process->profile_manager();
556 // Successfully create the profiles.
557 TestingProfile* profile1 =
558 static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
559 ASSERT_TRUE(profile1);
561 TestingProfile* profile2 =
562 static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
563 ASSERT_TRUE(profile2);
565 std::vector<Profile*> last_opened_profiles =
566 profile_manager->GetLastOpenedProfiles();
567 ASSERT_EQ(0U, last_opened_profiles.size());
569 // Create a browser for profile1.
570 Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
571 scoped_ptr<Browser> browser1a(
572 chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
574 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
575 ASSERT_EQ(1U, last_opened_profiles.size());
576 EXPECT_EQ(profile1, last_opened_profiles[0]);
579 Browser::CreateParams profile2_params(profile2, chrome::GetActiveDesktop());
580 scoped_ptr<Browser> browser2(
581 chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
583 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
584 ASSERT_EQ(2U, last_opened_profiles.size());
585 EXPECT_EQ(profile1, last_opened_profiles[0]);
586 EXPECT_EQ(profile2, last_opened_profiles[1]);
588 // Adding more browsers doesn't change anything.
589 scoped_ptr<Browser> browser1b(
590 chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
591 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
592 ASSERT_EQ(2U, last_opened_profiles.size());
593 EXPECT_EQ(profile1, last_opened_profiles[0]);
594 EXPECT_EQ(profile2, last_opened_profiles[1]);
596 // Close the browsers.
598 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
599 ASSERT_EQ(2U, last_opened_profiles.size());
600 EXPECT_EQ(profile1, last_opened_profiles[0]);
601 EXPECT_EQ(profile2, last_opened_profiles[1]);
604 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
605 ASSERT_EQ(1U, last_opened_profiles.size());
606 EXPECT_EQ(profile2, last_opened_profiles[0]);
609 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
610 ASSERT_EQ(0U, last_opened_profiles.size());
613 TEST_F(ProfileManagerTest, LastOpenedProfilesAtShutdown) {
614 base::FilePath dest_path1 = temp_dir_.path();
615 dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
617 base::FilePath dest_path2 = temp_dir_.path();
618 dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
620 ProfileManager* profile_manager = g_browser_process->profile_manager();
622 // Successfully create the profiles.
623 TestingProfile* profile1 =
624 static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
625 ASSERT_TRUE(profile1);
627 TestingProfile* profile2 =
628 static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
629 ASSERT_TRUE(profile2);
631 // Create a browser for profile1.
632 Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
633 scoped_ptr<Browser> browser1(
634 chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
637 Browser::CreateParams profile2_params(profile2, chrome::GetActiveDesktop());
638 scoped_ptr<Browser> browser2(
639 chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
641 std::vector<Profile*> last_opened_profiles =
642 profile_manager->GetLastOpenedProfiles();
643 ASSERT_EQ(2U, last_opened_profiles.size());
644 EXPECT_EQ(profile1, last_opened_profiles[0]);
645 EXPECT_EQ(profile2, last_opened_profiles[1]);
647 // Simulate a shutdown.
648 content::NotificationService::current()->Notify(
649 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
650 content::NotificationService::AllSources(),
651 content::NotificationService::NoDetails());
653 // Even if the browsers are destructed during shutdown, the profiles stay
658 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
659 ASSERT_EQ(2U, last_opened_profiles.size());
660 EXPECT_EQ(profile1, last_opened_profiles[0]);
661 EXPECT_EQ(profile2, last_opened_profiles[1]);
664 TEST_F(ProfileManagerTest, LastOpenedProfilesDoesNotContainIncognito) {
665 base::FilePath dest_path1 = temp_dir_.path();
666 dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
667 base::FilePath dest_path2 = temp_dir_.path();
668 dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
670 ProfileManager* profile_manager = g_browser_process->profile_manager();
672 // Successfully create the profiles.
673 TestingProfile* profile1 =
674 static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
675 ASSERT_TRUE(profile1);
677 // Incognito profiles should not be managed by the profile manager but by the
679 TestingProfile::Builder builder;
680 builder.SetIncognito();
681 scoped_ptr<TestingProfile> profile2 = builder.Build();
682 profile1->SetOffTheRecordProfile(profile2.PassAs<Profile>());
684 std::vector<Profile*> last_opened_profiles =
685 profile_manager->GetLastOpenedProfiles();
686 ASSERT_EQ(0U, last_opened_profiles.size());
688 // Create a browser for profile1.
689 Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
690 scoped_ptr<Browser> browser1(
691 chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
693 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
694 ASSERT_EQ(1U, last_opened_profiles.size());
695 EXPECT_EQ(profile1, last_opened_profiles[0]);
698 Browser::CreateParams profile2_params(profile1->GetOffTheRecordProfile(),
699 chrome::GetActiveDesktop());
700 scoped_ptr<Browser> browser2a(
701 chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
703 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
704 ASSERT_EQ(1U, last_opened_profiles.size());
705 EXPECT_EQ(profile1, last_opened_profiles[0]);
707 // Adding more browsers doesn't change anything.
708 scoped_ptr<Browser> browser2b(
709 chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
710 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
711 ASSERT_EQ(1U, last_opened_profiles.size());
712 EXPECT_EQ(profile1, last_opened_profiles[0]);
714 // Close the browsers.
716 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
717 ASSERT_EQ(1U, last_opened_profiles.size());
718 EXPECT_EQ(profile1, last_opened_profiles[0]);
721 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
722 ASSERT_EQ(1U, last_opened_profiles.size());
723 EXPECT_EQ(profile1, last_opened_profiles[0]);
726 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
727 ASSERT_EQ(0U, last_opened_profiles.size());
729 #endif // !defined(OS_ANDROID)
731 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
732 // There's no Browser object on Android and there's no multi-profiles on Chrome.
733 TEST_F(ProfileManagerTest, EphemeralProfilesDontEndUpAsLastProfile) {
734 base::FilePath dest_path = temp_dir_.path();
735 dest_path = dest_path.Append(FILE_PATH_LITERAL("Ephemeral Profile"));
737 ProfileManager* profile_manager = g_browser_process->profile_manager();
739 TestingProfile* profile =
740 static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path));
741 ASSERT_TRUE(profile);
742 profile->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles, true);
744 // Here the last used profile is still the "Default" profile.
745 Profile* last_used_profile = profile_manager->GetLastUsedProfile();
746 EXPECT_NE(profile, last_used_profile);
748 // Create a browser for the profile.
749 Browser::CreateParams profile_params(profile, chrome::GetActiveDesktop());
750 scoped_ptr<Browser> browser(
751 chrome::CreateBrowserWithTestWindowForParams(&profile_params));
752 last_used_profile = profile_manager->GetLastUsedProfile();
753 EXPECT_NE(profile, last_used_profile);
755 // Close the browser.
757 last_used_profile = profile_manager->GetLastUsedProfile();
758 EXPECT_NE(profile, last_used_profile);
761 TEST_F(ProfileManagerTest, EphemeralProfilesDontEndUpAsLastOpenedAtShutdown) {
762 base::FilePath dest_path1 = temp_dir_.path();
763 dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("Normal Profile"));
765 base::FilePath dest_path2 = temp_dir_.path();
766 dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("Ephemeral Profile 1"));
768 base::FilePath dest_path3 = temp_dir_.path();
769 dest_path3 = dest_path3.Append(FILE_PATH_LITERAL("Ephemeral Profile 2"));
771 ProfileManager* profile_manager = g_browser_process->profile_manager();
773 // Successfully create the profiles.
774 TestingProfile* normal_profile =
775 static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
776 ASSERT_TRUE(normal_profile);
778 // Add one ephemeral profile which should not end up in this list.
779 TestingProfile* ephemeral_profile1 =
780 static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
781 ASSERT_TRUE(ephemeral_profile1);
782 ephemeral_profile1->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles,
785 // Add second ephemeral profile but don't mark it as such yet.
786 TestingProfile* ephemeral_profile2 =
787 static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path3));
788 ASSERT_TRUE(ephemeral_profile2);
790 // Create a browser for profile1.
791 Browser::CreateParams profile1_params(normal_profile,
792 chrome::GetActiveDesktop());
793 scoped_ptr<Browser> browser1(
794 chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
796 // Create browsers for the ephemeral profile.
797 Browser::CreateParams profile2_params(ephemeral_profile1,
798 chrome::GetActiveDesktop());
799 scoped_ptr<Browser> browser2(
800 chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
802 Browser::CreateParams profile3_params(ephemeral_profile2,
803 chrome::GetActiveDesktop());
804 scoped_ptr<Browser> browser3(
805 chrome::CreateBrowserWithTestWindowForParams(&profile3_params));
807 std::vector<Profile*> last_opened_profiles =
808 profile_manager->GetLastOpenedProfiles();
809 ASSERT_EQ(2U, last_opened_profiles.size());
810 EXPECT_EQ(normal_profile, last_opened_profiles[0]);
811 EXPECT_EQ(ephemeral_profile2, last_opened_profiles[1]);
813 // Mark the second profile ephemeral.
814 ephemeral_profile2->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles,
817 // Simulate a shutdown.
818 content::NotificationService::current()->Notify(
819 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
820 content::NotificationService::AllSources(),
821 content::NotificationService::NoDetails());
826 last_opened_profiles = profile_manager->GetLastOpenedProfiles();
827 ASSERT_EQ(1U, last_opened_profiles.size());
828 EXPECT_EQ(normal_profile, last_opened_profiles[0]);
831 TEST_F(ProfileManagerTest, ActiveProfileDeleted) {
832 ProfileManager* profile_manager = g_browser_process->profile_manager();
833 ASSERT_TRUE(profile_manager);
835 // Create and load two profiles.
836 const std::string profile_name1 = "New Profile 1";
837 const std::string profile_name2 = "New Profile 2";
838 base::FilePath dest_path1 =
839 temp_dir_.path().AppendASCII(profile_name1);
840 base::FilePath dest_path2 =
841 temp_dir_.path().AppendASCII(profile_name2);
843 MockObserver mock_observer;
844 EXPECT_CALL(mock_observer, OnProfileCreated(
845 testing::NotNull(), NotFail())).Times(testing::AtLeast(3));
847 CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
848 CreateProfileAsync(profile_manager, profile_name2, false, &mock_observer);
849 base::RunLoop().RunUntilIdle();
851 EXPECT_EQ(2u, profile_manager->GetLoadedProfiles().size());
852 EXPECT_EQ(2u, profile_manager->GetProfileInfoCache().GetNumberOfProfiles());
854 // Set the active profile.
855 PrefService* local_state = g_browser_process->local_state();
856 local_state->SetString(prefs::kProfileLastUsed, profile_name1);
858 // Delete the active profile.
859 profile_manager->ScheduleProfileForDeletion(dest_path1,
860 ProfileManager::CreateCallback());
861 // Spin the message loop so that all the callbacks can finish running.
862 base::RunLoop().RunUntilIdle();
864 EXPECT_EQ(dest_path2, profile_manager->GetLastUsedProfile()->GetPath());
865 EXPECT_EQ(profile_name2, local_state->GetString(prefs::kProfileLastUsed));
867 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
869 #if defined(OS_MACOSX)
870 // These tests are for a Mac-only code path that assumes the browser
871 // process isn't killed when all browser windows are closed.
872 TEST_F(ProfileManagerTest, ActiveProfileDeletedNeedsToLoadNextProfile) {
873 ProfileManager* profile_manager = g_browser_process->profile_manager();
874 ASSERT_TRUE(profile_manager);
876 // Create and load one profile, and just create a second profile.
877 const std::string profile_name1 = "New Profile 1";
878 const std::string profile_name2 = "New Profile 2";
879 base::FilePath dest_path1 =
880 temp_dir_.path().AppendASCII(profile_name1);
881 base::FilePath dest_path2 =
882 temp_dir_.path().AppendASCII(profile_name2);
884 MockObserver mock_observer;
885 EXPECT_CALL(mock_observer, OnProfileCreated(
886 testing::NotNull(), NotFail())).Times(testing::AtLeast(2));
887 CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
888 base::RunLoop().RunUntilIdle();
890 // Track the profile, but don't load it.
891 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
892 cache.AddProfileToCache(dest_path2, ASCIIToUTF16(profile_name2),
893 base::string16(), 0, std::string());
894 base::RunLoop().RunUntilIdle();
896 EXPECT_EQ(1u, profile_manager->GetLoadedProfiles().size());
897 EXPECT_EQ(2u, cache.GetNumberOfProfiles());
899 // Set the active profile.
900 PrefService* local_state = g_browser_process->local_state();
901 local_state->SetString(prefs::kProfileLastUsed,
902 dest_path1.BaseName().MaybeAsASCII());
904 // Delete the active profile. This should switch and load the unloaded
906 profile_manager->ScheduleProfileForDeletion(dest_path1,
907 ProfileManager::CreateCallback());
909 // Spin the message loop so that all the callbacks can finish running.
910 base::RunLoop().RunUntilIdle();
912 EXPECT_EQ(dest_path2, profile_manager->GetLastUsedProfile()->GetPath());
913 EXPECT_EQ(profile_name2, local_state->GetString(prefs::kProfileLastUsed));
916 // This tests the recursive call in ProfileManager::OnNewActiveProfileLoaded
917 // by simulating a scenario in which the profile that is being loaded as
918 // the next active profile has also been marked for deletion, so the
919 // ProfileManager needs to recursively select a different next profile.
920 TEST_F(ProfileManagerTest, ActiveProfileDeletedNextProfileDeletedToo) {
921 ProfileManager* profile_manager = g_browser_process->profile_manager();
922 ASSERT_TRUE(profile_manager);
924 // Create and load one profile, and create two more profiles.
925 const std::string profile_name1 = "New Profile 1";
926 const std::string profile_name2 = "New Profile 2";
927 const std::string profile_name3 = "New Profile 3";
928 base::FilePath dest_path1 =
929 temp_dir_.path().AppendASCII(profile_name1);
930 base::FilePath dest_path2 =
931 temp_dir_.path().AppendASCII(profile_name2);
932 base::FilePath dest_path3 =
933 temp_dir_.path().AppendASCII(profile_name3);
935 MockObserver mock_observer;
936 EXPECT_CALL(mock_observer, OnProfileCreated(
937 testing::NotNull(), NotFail())).Times(testing::AtLeast(2));
938 CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
939 base::RunLoop().RunUntilIdle();
941 // Create the other profiles, but don't load them. Assign a fake avatar icon
942 // to ensure that profiles in the info cache are sorted by the profile name,
943 // and not randomly by the avatar name.
944 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
945 cache.AddProfileToCache(dest_path2, ASCIIToUTF16(profile_name2),
946 ASCIIToUTF16(profile_name2), 1, std::string());
947 cache.AddProfileToCache(dest_path3, ASCIIToUTF16(profile_name3),
948 ASCIIToUTF16(profile_name3), 2, std::string());
950 base::RunLoop().RunUntilIdle();
952 EXPECT_EQ(1u, profile_manager->GetLoadedProfiles().size());
953 EXPECT_EQ(3u, cache.GetNumberOfProfiles());
955 // Set the active profile.
956 PrefService* local_state = g_browser_process->local_state();
957 local_state->SetString(prefs::kProfileLastUsed,
958 dest_path1.BaseName().MaybeAsASCII());
960 // Delete the active profile, Profile1.
961 // This will post a CreateProfileAsync message, that tries to load Profile2,
962 // which checks that the profile is not being deleted, and then calls back
963 // FinishDeletingProfile for Profile1.
964 // Try to break this flow by setting the active profile to Profile2 in the
965 // middle (so after the first posted message), and trying to delete Profile2,
966 // so that the ProfileManager has to look for a different profile to load.
967 profile_manager->ScheduleProfileForDeletion(dest_path1,
968 ProfileManager::CreateCallback());
969 local_state->SetString(prefs::kProfileLastUsed,
970 dest_path2.BaseName().MaybeAsASCII());
971 profile_manager->ScheduleProfileForDeletion(dest_path2,
972 ProfileManager::CreateCallback());
973 // Spin the message loop so that all the callbacks can finish running.
974 base::RunLoop().RunUntilIdle();
976 EXPECT_EQ(dest_path3, profile_manager->GetLastUsedProfile()->GetPath());
977 EXPECT_EQ(profile_name3, local_state->GetString(prefs::kProfileLastUsed));
979 #endif // !defined(OS_MACOSX)