45beab1d8cc762450ca8214b303d53bc77f4c3a1
[platform/framework/web/crosswalk.git] / src / chrome / browser / profiles / profile_manager_unittest.cc
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 <string>
6
7 #include "base/command_line.h"
8 #include "base/files/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_avatar_icon_util.h"
26 #include "chrome/browser/profiles/profile_info_cache.h"
27 #include "chrome/browser/profiles/profile_manager.h"
28 #include "chrome/browser/profiles/profiles_state.h"
29 #include "chrome/browser/ui/browser.h"
30 #include "chrome/common/chrome_constants.h"
31 #include "chrome/common/chrome_paths.h"
32 #include "chrome/common/chrome_switches.h"
33 #include "chrome/common/pref_names.h"
34 #include "chrome/grit/generated_resources.h"
35 #include "chrome/test/base/scoped_testing_local_state.h"
36 #include "chrome/test/base/test_browser_window.h"
37 #include "chrome/test/base/testing_browser_process.h"
38 #include "chrome/test/base/testing_profile.h"
39 #include "components/signin/core/common/profile_management_switches.h"
40 #include "content/public/browser/notification_service.h"
41 #include "content/public/common/content_switches.h"
42 #include "content/public/test/test_browser_thread_bundle.h"
43 #include "testing/gmock/include/gmock/gmock.h"
44 #include "testing/gtest/include/gtest/gtest.h"
45 #include "ui/base/l10n/l10n_util.h"
46
47 #if defined(OS_CHROMEOS)
48 #include "chrome/browser/chromeos/login/users/fake_user_manager.h"
49 #include "chrome/browser/chromeos/login/users/scoped_test_user_manager.h"
50 #include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h"
51 #include "chrome/browser/chromeos/profiles/profile_helper.h"
52 #include "chrome/browser/chromeos/settings/cros_settings.h"
53 #include "chrome/browser/chromeos/settings/device_settings_service.h"
54 #include "chromeos/chromeos_switches.h"
55 #include "chromeos/login/user_names.h"
56 #include "components/user_manager/user_manager.h"
57 #endif  // defined(OS_CHROMEOS)
58
59 using base::ASCIIToUTF16;
60 using content::BrowserThread;
61
62 namespace {
63
64 // This global variable is used to check that value returned to different
65 // observers is the same.
66 Profile* g_created_profile;
67
68 class UnittestProfileManager : public ::ProfileManagerWithoutInit {
69  public:
70   explicit UnittestProfileManager(const base::FilePath& user_data_dir)
71       : ::ProfileManagerWithoutInit(user_data_dir) {}
72
73  protected:
74   virtual Profile* CreateProfileHelper(
75       const base::FilePath& file_path) OVERRIDE {
76     if (!base::PathExists(file_path)) {
77       if (!base::CreateDirectory(file_path))
78         return NULL;
79     }
80     return new TestingProfile(file_path, NULL);
81   }
82
83   virtual Profile* CreateProfileAsyncHelper(const base::FilePath& path,
84                                             Delegate* delegate) OVERRIDE {
85     // This is safe while all file operations are done on the FILE thread.
86     BrowserThread::PostTask(
87         BrowserThread::FILE, FROM_HERE,
88         base::Bind(base::IgnoreResult(&base::CreateDirectory), path));
89
90     return new TestingProfile(path, this);
91   }
92 };
93
94 }  // namespace
95
96 class ProfileManagerTest : public testing::Test {
97  protected:
98   class MockObserver {
99    public:
100     MOCK_METHOD2(OnProfileCreated,
101         void(Profile* profile, Profile::CreateStatus status));
102   };
103
104   ProfileManagerTest()
105       : local_state_(TestingBrowserProcess::GetGlobal()) {
106   }
107
108   virtual void SetUp() {
109     // Create a new temporary directory, and store the path
110     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
111     TestingBrowserProcess::GetGlobal()->SetProfileManager(
112         new UnittestProfileManager(temp_dir_.path()));
113
114 #if defined(OS_CHROMEOS)
115     CommandLine* cl = CommandLine::ForCurrentProcess();
116     cl->AppendSwitch(switches::kTestType);
117 #endif
118   }
119
120   virtual void TearDown() {
121     TestingBrowserProcess::GetGlobal()->SetProfileManager(NULL);
122     base::RunLoop().RunUntilIdle();
123   }
124
125   // Helper function to create a profile with |name| for a profile |manager|.
126   void CreateProfileAsync(ProfileManager* manager,
127                           const std::string& name,
128                           bool is_supervised,
129                           MockObserver* mock_observer) {
130     manager->CreateProfileAsync(
131         temp_dir_.path().AppendASCII(name),
132         base::Bind(&MockObserver::OnProfileCreated,
133                    base::Unretained(mock_observer)),
134         base::UTF8ToUTF16(name),
135         base::UTF8ToUTF16(profiles::GetDefaultAvatarIconUrl(0)),
136         is_supervised ? "Dummy ID" : std::string());
137   }
138
139   // Helper function to add a profile with |profile_name| to
140   // |profile_manager|'s ProfileInfoCache, and return the profile created.
141   Profile* AddProfileToCache(ProfileManager* profile_manager,
142                              const std::string& path_suffix,
143                              const base::string16& profile_name) {
144     ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
145     size_t num_profiles = cache.GetNumberOfProfiles();
146     base::FilePath path = temp_dir_.path().AppendASCII(path_suffix);
147     cache.AddProfileToCache(path, profile_name,
148                             base::string16(), 0, std::string());
149     EXPECT_EQ(num_profiles + 1, cache.GetNumberOfProfiles());
150     return profile_manager->GetProfile(path);
151   }
152
153 #if defined(OS_CHROMEOS)
154   // Helper function to register an user with id |user_id| and create profile
155   // with a correct path.
156   void RegisterUser(const std::string& user_id) {
157     chromeos::ProfileHelper* profile_helper = chromeos::ProfileHelper::Get();
158     const std::string user_id_hash =
159         profile_helper->GetUserIdHashByUserIdForTesting(user_id);
160     user_manager::UserManager::Get()->UserLoggedIn(
161         user_id, user_id_hash, false);
162     g_browser_process->profile_manager()->GetProfile(
163         profile_helper->GetProfilePathByUserIdHash(user_id_hash));
164   }
165
166   chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
167   chromeos::ScopedTestCrosSettings test_cros_settings_;
168 #endif
169
170   // The path to temporary directory used to contain the test operations.
171   base::ScopedTempDir temp_dir_;
172   ScopedTestingLocalState local_state_;
173
174   content::TestBrowserThreadBundle thread_bundle_;
175
176 #if defined(OS_CHROMEOS)
177   chromeos::ScopedTestUserManager test_user_manager_;
178 #endif
179
180   DISALLOW_COPY_AND_ASSIGN(ProfileManagerTest);
181 };
182
183 TEST_F(ProfileManagerTest, GetProfile) {
184   base::FilePath dest_path = temp_dir_.path();
185   dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
186
187   ProfileManager* profile_manager = g_browser_process->profile_manager();
188
189   // Successfully create a profile.
190   Profile* profile = profile_manager->GetProfile(dest_path);
191   EXPECT_TRUE(profile);
192
193   // The profile already exists when we call GetProfile. Just load it.
194   EXPECT_EQ(profile, profile_manager->GetProfile(dest_path));
195 }
196
197 TEST_F(ProfileManagerTest, DefaultProfileDir) {
198   base::FilePath expected_default =
199       base::FilePath().AppendASCII(chrome::kInitialProfile);
200   EXPECT_EQ(
201       expected_default.value(),
202       g_browser_process->profile_manager()->GetInitialProfileDir().value());
203 }
204
205 MATCHER(NotFail, "Profile creation failure status is not reported.") {
206   return arg == Profile::CREATE_STATUS_CREATED ||
207          arg == Profile::CREATE_STATUS_INITIALIZED;
208 }
209
210 MATCHER(SameNotNull, "The same non-NULL value for all calls.") {
211   if (!g_created_profile)
212     g_created_profile = arg;
213   return arg != NULL && arg == g_created_profile;
214 }
215
216 #if defined(OS_CHROMEOS)
217
218 // This functionality only exists on Chrome OS.
219 TEST_F(ProfileManagerTest, LoggedInProfileDir) {
220   base::FilePath expected_default =
221       base::FilePath().AppendASCII(chrome::kInitialProfile);
222   ProfileManager* profile_manager = g_browser_process->profile_manager();
223   EXPECT_EQ(expected_default.value(),
224             profile_manager->GetInitialProfileDir().value());
225
226   const char kTestUserName[] = "test-user@example.com";
227   chromeos::FakeUserManager* user_manager = new chromeos::FakeUserManager();
228   chromeos::ScopedUserManagerEnabler enabler(user_manager);
229
230   const user_manager::User* active_user = user_manager->AddUser(kTestUserName);
231   user_manager->LoginUser(kTestUserName);
232   user_manager->SwitchActiveUser(kTestUserName);
233
234   profile_manager->Observe(
235       chrome::NOTIFICATION_LOGIN_USER_CHANGED,
236       content::NotificationService::AllSources(),
237       content::Details<const user_manager::User>(active_user));
238   base::FilePath expected_logged_in(
239       chromeos::ProfileHelper::GetUserProfileDir(active_user->username_hash()));
240   EXPECT_EQ(expected_logged_in.value(),
241             profile_manager->GetInitialProfileDir().value());
242   VLOG(1) << temp_dir_.path().Append(
243       profile_manager->GetInitialProfileDir()).value();
244 }
245
246 #endif
247
248 TEST_F(ProfileManagerTest, CreateAndUseTwoProfiles) {
249   base::FilePath dest_path1 = temp_dir_.path();
250   dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
251
252   base::FilePath dest_path2 = temp_dir_.path();
253   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
254
255   ProfileManager* profile_manager = g_browser_process->profile_manager();
256
257   // Successfully create the profiles.
258   TestingProfile* profile1 =
259       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
260   ASSERT_TRUE(profile1);
261
262   TestingProfile* profile2 =
263       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
264   ASSERT_TRUE(profile2);
265
266   // Force lazy-init of some profile services to simulate use.
267   ASSERT_TRUE(profile1->CreateHistoryService(true, false));
268   EXPECT_TRUE(HistoryServiceFactory::GetForProfile(profile1,
269                                                    Profile::EXPLICIT_ACCESS));
270   profile1->CreateBookmarkModel(true);
271   EXPECT_TRUE(BookmarkModelFactory::GetForProfile(profile1));
272   profile2->CreateBookmarkModel(true);
273   EXPECT_TRUE(BookmarkModelFactory::GetForProfile(profile2));
274   ASSERT_TRUE(profile2->CreateHistoryService(true, false));
275   EXPECT_TRUE(HistoryServiceFactory::GetForProfile(profile2,
276                                                    Profile::EXPLICIT_ACCESS));
277
278   // Make sure any pending tasks run before we destroy the profiles.
279     base::RunLoop().RunUntilIdle();
280
281   TestingBrowserProcess::GetGlobal()->SetProfileManager(NULL);
282
283   // Make sure history cleans up correctly.
284   base::RunLoop().RunUntilIdle();
285 }
286
287 TEST_F(ProfileManagerTest, CreateProfileAsyncMultipleRequests) {
288   g_created_profile = NULL;
289
290   MockObserver mock_observer1;
291   EXPECT_CALL(mock_observer1, OnProfileCreated(
292       SameNotNull(), NotFail())).Times(testing::AtLeast(1));
293   MockObserver mock_observer2;
294   EXPECT_CALL(mock_observer2, OnProfileCreated(
295       SameNotNull(), NotFail())).Times(testing::AtLeast(1));
296   MockObserver mock_observer3;
297   EXPECT_CALL(mock_observer3, OnProfileCreated(
298       SameNotNull(), NotFail())).Times(testing::AtLeast(1));
299
300   ProfileManager* profile_manager = g_browser_process->profile_manager();
301   const std::string profile_name = "New Profile";
302   CreateProfileAsync(profile_manager, profile_name, false, &mock_observer1);
303   CreateProfileAsync(profile_manager, profile_name, false, &mock_observer2);
304   CreateProfileAsync(profile_manager, profile_name, false, &mock_observer3);
305
306   base::RunLoop().RunUntilIdle();
307 }
308
309 TEST_F(ProfileManagerTest, CreateProfilesAsync) {
310   const std::string profile_name1 = "New Profile 1";
311   const std::string profile_name2 = "New Profile 2";
312
313   MockObserver mock_observer;
314   EXPECT_CALL(mock_observer, OnProfileCreated(
315       testing::NotNull(), NotFail())).Times(testing::AtLeast(3));
316
317   ProfileManager* profile_manager = g_browser_process->profile_manager();
318
319   CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
320   CreateProfileAsync(profile_manager, profile_name2, false, &mock_observer);
321
322   base::RunLoop().RunUntilIdle();
323 }
324
325 TEST_F(ProfileManagerTest, CreateProfileAsyncCheckOmitted) {
326   std::string name = "0 Supervised Profile";
327
328   MockObserver mock_observer;
329   EXPECT_CALL(mock_observer, OnProfileCreated(
330       testing::NotNull(), NotFail())).Times(testing::AtLeast(2));
331
332   ProfileManager* profile_manager = g_browser_process->profile_manager();
333   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
334   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
335
336   CreateProfileAsync(profile_manager, name, true, &mock_observer);
337   base::RunLoop().RunUntilIdle();
338
339   EXPECT_EQ(1u, cache.GetNumberOfProfiles());
340   // Supervised profiles should start out omitted from the profile list.
341   EXPECT_TRUE(cache.IsOmittedProfileAtIndex(0));
342
343   name = "1 Regular Profile";
344   CreateProfileAsync(profile_manager, name, false, &mock_observer);
345   base::RunLoop().RunUntilIdle();
346
347   EXPECT_EQ(2u, cache.GetNumberOfProfiles());
348   // Non-supervised profiles should be included in the profile list.
349   EXPECT_FALSE(cache.IsOmittedProfileAtIndex(1));
350 }
351
352 TEST_F(ProfileManagerTest, AddProfileToCacheCheckOmitted) {
353   ProfileManager* profile_manager = g_browser_process->profile_manager();
354   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
355   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
356
357   const base::FilePath supervised_path =
358       temp_dir_.path().AppendASCII("Supervised");
359   TestingProfile* supervised_profile =
360       new TestingProfile(supervised_path, NULL);
361   supervised_profile->GetPrefs()->SetString(prefs::kSupervisedUserId, "An ID");
362
363   // RegisterTestingProfile adds the profile to the cache and takes ownership.
364   profile_manager->RegisterTestingProfile(supervised_profile, true, false);
365   EXPECT_EQ(1u, cache.GetNumberOfProfiles());
366   EXPECT_TRUE(cache.IsOmittedProfileAtIndex(0));
367
368   const base::FilePath nonsupervised_path = temp_dir_.path().AppendASCII(
369       "Non-Supervised");
370   TestingProfile* nonsupervised_profile = new TestingProfile(nonsupervised_path,
371                                                              NULL);
372   profile_manager->RegisterTestingProfile(nonsupervised_profile, true, false);
373
374   EXPECT_EQ(2u, cache.GetNumberOfProfiles());
375   size_t supervised_index = cache.GetIndexOfProfileWithPath(supervised_path);
376   EXPECT_TRUE(cache.IsOmittedProfileAtIndex(supervised_index));
377   size_t nonsupervised_index =
378       cache.GetIndexOfProfileWithPath(nonsupervised_path);
379   EXPECT_FALSE(cache.IsOmittedProfileAtIndex(nonsupervised_index));
380 }
381
382 TEST_F(ProfileManagerTest, GetGuestProfilePath) {
383   base::FilePath guest_path = ProfileManager::GetGuestProfilePath();
384   base::FilePath expected_path = temp_dir_.path();
385   expected_path = expected_path.Append(chrome::kGuestProfileDir);
386   EXPECT_EQ(expected_path, guest_path);
387 }
388
389 class UnittestGuestProfileManager : public UnittestProfileManager {
390  public:
391   explicit UnittestGuestProfileManager(const base::FilePath& user_data_dir)
392       : UnittestProfileManager(user_data_dir) {}
393
394  protected:
395   virtual Profile* CreateProfileHelper(
396       const base::FilePath& file_path) OVERRIDE {
397     TestingProfile::Builder builder;
398     builder.SetGuestSession();
399     builder.SetPath(file_path);
400     TestingProfile* testing_profile = builder.Build().release();
401     return testing_profile;
402   }
403 };
404
405 class ProfileManagerGuestTest : public ProfileManagerTest  {
406  protected:
407   virtual void SetUp() {
408     // Create a new temporary directory, and store the path
409     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
410     TestingBrowserProcess::GetGlobal()->SetProfileManager(
411         new UnittestGuestProfileManager(temp_dir_.path()));
412
413 #if defined(OS_CHROMEOS)
414     CommandLine* cl = CommandLine::ForCurrentProcess();
415     // This switch is needed to skip non-test specific behavior in
416     // ProfileManager (accessing DBusThreadManager).
417     cl->AppendSwitch(switches::kTestType);
418
419     cl->AppendSwitch(chromeos::switches::kGuestSession);
420     cl->AppendSwitch(::switches::kIncognito);
421
422     RegisterUser(chromeos::login::kGuestUserName);
423 #endif
424   }
425 };
426
427 TEST_F(ProfileManagerGuestTest, GetLastUsedProfileAllowedByPolicy) {
428   ProfileManager* profile_manager = g_browser_process->profile_manager();
429   ASSERT_TRUE(profile_manager);
430
431   Profile* profile = profile_manager->GetLastUsedProfileAllowedByPolicy();
432   ASSERT_TRUE(profile);
433   EXPECT_TRUE(profile->IsOffTheRecord());
434 }
435
436 #if defined(OS_CHROMEOS)
437 TEST_F(ProfileManagerGuestTest, GuestProfileIngonito) {
438   Profile* primary_profile = ProfileManager::GetPrimaryUserProfile();
439   EXPECT_TRUE(primary_profile->IsOffTheRecord());
440
441   Profile* active_profile = ProfileManager::GetActiveUserProfile();
442   EXPECT_TRUE(active_profile->IsOffTheRecord());
443
444   EXPECT_TRUE(active_profile->IsSameProfile(primary_profile));
445
446   Profile* last_used_profile = ProfileManager::GetLastUsedProfile();
447   EXPECT_TRUE(last_used_profile->IsOffTheRecord());
448
449   EXPECT_TRUE(last_used_profile->IsSameProfile(active_profile));
450 }
451 #endif
452
453 TEST_F(ProfileManagerTest, AutoloadProfilesWithBackgroundApps) {
454   ProfileManager* profile_manager = g_browser_process->profile_manager();
455   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
456   local_state_.Get()->SetUserPref(prefs::kBackgroundModeEnabled,
457                                   new base::FundamentalValue(true));
458
459   // Setting a pref which is not applicable to a system (i.e., Android in this
460   // case) does not necessarily create it. Don't bother continuing with the
461   // test if this pref doesn't exist because it will not load the profiles if
462   // it cannot verify that the pref for background mode is enabled.
463   if (!local_state_.Get()->HasPrefPath(prefs::kBackgroundModeEnabled))
464     return;
465
466   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
467   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_1"),
468                           ASCIIToUTF16("name_1"), base::string16(), 0,
469                           std::string());
470   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_2"),
471                           ASCIIToUTF16("name_2"), base::string16(), 0,
472                           std::string());
473   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_3"),
474                           ASCIIToUTF16("name_3"), base::string16(), 0,
475                           std::string());
476   cache.SetBackgroundStatusOfProfileAtIndex(0, true);
477   cache.SetBackgroundStatusOfProfileAtIndex(2, true);
478   EXPECT_EQ(3u, cache.GetNumberOfProfiles());
479
480   profile_manager->AutoloadProfiles();
481
482   EXPECT_EQ(2u, profile_manager->GetLoadedProfiles().size());
483 }
484
485 TEST_F(ProfileManagerTest, DoNotAutoloadProfilesIfBackgroundModeOff) {
486   ProfileManager* profile_manager = g_browser_process->profile_manager();
487   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
488   local_state_.Get()->SetUserPref(prefs::kBackgroundModeEnabled,
489                                   new base::FundamentalValue(false));
490
491   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
492   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_1"),
493                           ASCIIToUTF16("name_1"), base::string16(), 0,
494                           std::string());
495   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_2"),
496                           ASCIIToUTF16("name_2"), base::string16(), 0,
497                           std::string());
498   cache.SetBackgroundStatusOfProfileAtIndex(0, false);
499   cache.SetBackgroundStatusOfProfileAtIndex(1, true);
500   EXPECT_EQ(2u, cache.GetNumberOfProfiles());
501
502   profile_manager->AutoloadProfiles();
503
504   EXPECT_EQ(0u, profile_manager->GetLoadedProfiles().size());
505 }
506
507 TEST_F(ProfileManagerTest, InitProfileUserPrefs) {
508   base::FilePath dest_path = temp_dir_.path();
509   dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
510
511   ProfileManager* profile_manager = g_browser_process->profile_manager();
512
513   Profile* profile;
514
515   // Successfully create the profile
516   profile = profile_manager->GetProfile(dest_path);
517   ASSERT_TRUE(profile);
518
519   // Check that the profile name is non empty
520   std::string profile_name =
521       profile->GetPrefs()->GetString(prefs::kProfileName);
522   EXPECT_FALSE(profile_name.empty());
523
524   // Check that the profile avatar index is valid
525   size_t avatar_index =
526       profile->GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
527   EXPECT_TRUE(profiles::IsDefaultAvatarIconIndex(
528       avatar_index));
529 }
530
531 // Tests that a new profile's entry in the profile info cache is setup with the
532 // same values that are in the profile prefs.
533 TEST_F(ProfileManagerTest, InitProfileInfoCacheForAProfile) {
534   base::FilePath dest_path = temp_dir_.path();
535   dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
536
537   ProfileManager* profile_manager = g_browser_process->profile_manager();
538   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
539
540   // Successfully create the profile
541   Profile* profile = profile_manager->GetProfile(dest_path);
542   ASSERT_TRUE(profile);
543
544   std::string profile_name =
545       profile->GetPrefs()->GetString(prefs::kProfileName);
546   size_t avatar_index =
547       profile->GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
548
549   size_t profile_index = cache.GetIndexOfProfileWithPath(dest_path);
550
551   // Check if the profile prefs are the same as the cache prefs
552   EXPECT_EQ(profile_name,
553             base::UTF16ToUTF8(cache.GetNameOfProfileAtIndex(profile_index)));
554   EXPECT_EQ(avatar_index,
555             cache.GetAvatarIconIndexOfProfileAtIndex(profile_index));
556 }
557
558 TEST_F(ProfileManagerTest, GetLastUsedProfileAllowedByPolicy) {
559   ProfileManager* profile_manager = g_browser_process->profile_manager();
560   ASSERT_TRUE(profile_manager);
561
562 #if defined(OS_CHROMEOS)
563   // On CrOS, profile returned by GetLastUsedProfile is a singin profile that
564   // is forced to be incognito. That's why we need to create at least one user
565   // to get a regular profile.
566   RegisterUser("test-user@example.com");
567 #endif
568
569   Profile* profile = profile_manager->GetLastUsedProfileAllowedByPolicy();
570   ASSERT_TRUE(profile);
571   EXPECT_FALSE(profile->IsOffTheRecord());
572   PrefService* prefs = profile->GetPrefs();
573   EXPECT_EQ(IncognitoModePrefs::ENABLED,
574             IncognitoModePrefs::GetAvailability(prefs));
575
576   ASSERT_TRUE(profile->GetOffTheRecordProfile());
577
578   IncognitoModePrefs::SetAvailability(prefs, IncognitoModePrefs::DISABLED);
579   EXPECT_FALSE(
580       profile_manager->GetLastUsedProfileAllowedByPolicy()->IsOffTheRecord());
581
582   // GetLastUsedProfileAllowedByPolicy() returns the incognito Profile when
583   // incognito mode is forced.
584   IncognitoModePrefs::SetAvailability(prefs, IncognitoModePrefs::FORCED);
585   EXPECT_TRUE(
586       profile_manager->GetLastUsedProfileAllowedByPolicy()->IsOffTheRecord());
587 }
588
589 #if !defined(OS_ANDROID)
590 // There's no Browser object on Android.
591 TEST_F(ProfileManagerTest, LastOpenedProfiles) {
592   base::FilePath dest_path1 = temp_dir_.path();
593   dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
594
595   base::FilePath dest_path2 = temp_dir_.path();
596   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
597
598   ProfileManager* profile_manager = g_browser_process->profile_manager();
599
600   // Successfully create the profiles.
601   TestingProfile* profile1 =
602       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
603   ASSERT_TRUE(profile1);
604
605   TestingProfile* profile2 =
606       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
607   ASSERT_TRUE(profile2);
608
609   std::vector<Profile*> last_opened_profiles =
610       profile_manager->GetLastOpenedProfiles();
611   ASSERT_EQ(0U, last_opened_profiles.size());
612
613   // Create a browser for profile1.
614   Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
615   scoped_ptr<Browser> browser1a(
616       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
617
618   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
619   ASSERT_EQ(1U, last_opened_profiles.size());
620   EXPECT_EQ(profile1, last_opened_profiles[0]);
621
622   // And for profile2.
623   Browser::CreateParams profile2_params(profile2, chrome::GetActiveDesktop());
624   scoped_ptr<Browser> browser2(
625       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
626
627   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
628   ASSERT_EQ(2U, last_opened_profiles.size());
629   EXPECT_EQ(profile1, last_opened_profiles[0]);
630   EXPECT_EQ(profile2, last_opened_profiles[1]);
631
632   // Adding more browsers doesn't change anything.
633   scoped_ptr<Browser> browser1b(
634       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
635   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
636   ASSERT_EQ(2U, last_opened_profiles.size());
637   EXPECT_EQ(profile1, last_opened_profiles[0]);
638   EXPECT_EQ(profile2, last_opened_profiles[1]);
639
640   // Close the browsers.
641   browser1a.reset();
642   last_opened_profiles = 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]);
646
647   browser1b.reset();
648   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
649   ASSERT_EQ(1U, last_opened_profiles.size());
650   EXPECT_EQ(profile2, last_opened_profiles[0]);
651
652   browser2.reset();
653   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
654   ASSERT_EQ(0U, last_opened_profiles.size());
655 }
656
657 TEST_F(ProfileManagerTest, LastOpenedProfilesAtShutdown) {
658   base::FilePath dest_path1 = temp_dir_.path();
659   dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
660
661   base::FilePath dest_path2 = temp_dir_.path();
662   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
663
664   ProfileManager* profile_manager = g_browser_process->profile_manager();
665
666   // Successfully create the profiles.
667   TestingProfile* profile1 =
668       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
669   ASSERT_TRUE(profile1);
670
671   TestingProfile* profile2 =
672       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
673   ASSERT_TRUE(profile2);
674
675   // Create a browser for profile1.
676   Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
677   scoped_ptr<Browser> browser1(
678       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
679
680   // And for profile2.
681   Browser::CreateParams profile2_params(profile2, chrome::GetActiveDesktop());
682   scoped_ptr<Browser> browser2(
683       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
684
685   std::vector<Profile*> last_opened_profiles =
686       profile_manager->GetLastOpenedProfiles();
687   ASSERT_EQ(2U, last_opened_profiles.size());
688   EXPECT_EQ(profile1, last_opened_profiles[0]);
689   EXPECT_EQ(profile2, last_opened_profiles[1]);
690
691   // Simulate a shutdown.
692   content::NotificationService::current()->Notify(
693       chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
694       content::NotificationService::AllSources(),
695       content::NotificationService::NoDetails());
696
697   // Even if the browsers are destructed during shutdown, the profiles stay
698   // open.
699   browser1.reset();
700   browser2.reset();
701
702   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
703   ASSERT_EQ(2U, last_opened_profiles.size());
704   EXPECT_EQ(profile1, last_opened_profiles[0]);
705   EXPECT_EQ(profile2, last_opened_profiles[1]);
706 }
707
708 TEST_F(ProfileManagerTest, LastOpenedProfilesDoesNotContainIncognito) {
709   base::FilePath dest_path1 = temp_dir_.path();
710   dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
711   base::FilePath dest_path2 = temp_dir_.path();
712   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
713
714   ProfileManager* profile_manager = g_browser_process->profile_manager();
715
716   // Successfully create the profiles.
717   TestingProfile* profile1 =
718       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
719   ASSERT_TRUE(profile1);
720
721   std::vector<Profile*> last_opened_profiles =
722       profile_manager->GetLastOpenedProfiles();
723   ASSERT_EQ(0U, last_opened_profiles.size());
724
725   // Create a browser for profile1.
726   Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
727   scoped_ptr<Browser> browser1(
728       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
729
730   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
731   ASSERT_EQ(1U, last_opened_profiles.size());
732   EXPECT_EQ(profile1, last_opened_profiles[0]);
733
734   // And for profile2.
735   Browser::CreateParams profile2_params(profile1->GetOffTheRecordProfile(),
736                                         chrome::GetActiveDesktop());
737   scoped_ptr<Browser> browser2a(
738       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
739
740   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
741   ASSERT_EQ(1U, last_opened_profiles.size());
742   EXPECT_EQ(profile1, last_opened_profiles[0]);
743
744   // Adding more browsers doesn't change anything.
745   scoped_ptr<Browser> browser2b(
746       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
747   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
748   ASSERT_EQ(1U, last_opened_profiles.size());
749   EXPECT_EQ(profile1, last_opened_profiles[0]);
750
751   // Close the browsers.
752   browser2a.reset();
753   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
754   ASSERT_EQ(1U, last_opened_profiles.size());
755   EXPECT_EQ(profile1, last_opened_profiles[0]);
756
757   browser2b.reset();
758   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
759   ASSERT_EQ(1U, last_opened_profiles.size());
760   EXPECT_EQ(profile1, last_opened_profiles[0]);
761
762   browser1.reset();
763   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
764   ASSERT_EQ(0U, last_opened_profiles.size());
765 }
766 #endif  // !defined(OS_ANDROID)
767
768 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
769 // There's no Browser object on Android and there's no multi-profiles on Chrome.
770 TEST_F(ProfileManagerTest, EphemeralProfilesDontEndUpAsLastProfile) {
771   base::FilePath dest_path = temp_dir_.path();
772   dest_path = dest_path.Append(FILE_PATH_LITERAL("Ephemeral Profile"));
773
774   ProfileManager* profile_manager = g_browser_process->profile_manager();
775
776   TestingProfile* profile =
777       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path));
778   ASSERT_TRUE(profile);
779   profile->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles, true);
780
781   // Here the last used profile is still the "Default" profile.
782   Profile* last_used_profile = profile_manager->GetLastUsedProfile();
783   EXPECT_NE(profile, last_used_profile);
784
785   // Create a browser for the profile.
786   Browser::CreateParams profile_params(profile, chrome::GetActiveDesktop());
787   scoped_ptr<Browser> browser(
788       chrome::CreateBrowserWithTestWindowForParams(&profile_params));
789   last_used_profile = profile_manager->GetLastUsedProfile();
790   EXPECT_NE(profile, last_used_profile);
791
792   // Close the browser.
793   browser.reset();
794   last_used_profile = profile_manager->GetLastUsedProfile();
795   EXPECT_NE(profile, last_used_profile);
796 }
797
798 TEST_F(ProfileManagerTest, EphemeralProfilesDontEndUpAsLastOpenedAtShutdown) {
799   base::FilePath dest_path1 = temp_dir_.path();
800   dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("Normal Profile"));
801
802   base::FilePath dest_path2 = temp_dir_.path();
803   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("Ephemeral Profile 1"));
804
805   base::FilePath dest_path3 = temp_dir_.path();
806   dest_path3 = dest_path3.Append(FILE_PATH_LITERAL("Ephemeral Profile 2"));
807
808   ProfileManager* profile_manager = g_browser_process->profile_manager();
809
810   // Successfully create the profiles.
811   TestingProfile* normal_profile =
812       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
813   ASSERT_TRUE(normal_profile);
814
815   // Add one ephemeral profile which should not end up in this list.
816   TestingProfile* ephemeral_profile1 =
817       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
818   ASSERT_TRUE(ephemeral_profile1);
819   ephemeral_profile1->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles,
820                                              true);
821
822   // Add second ephemeral profile but don't mark it as such yet.
823   TestingProfile* ephemeral_profile2 =
824       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path3));
825   ASSERT_TRUE(ephemeral_profile2);
826
827   // Create a browser for profile1.
828   Browser::CreateParams profile1_params(normal_profile,
829                                         chrome::GetActiveDesktop());
830   scoped_ptr<Browser> browser1(
831       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
832
833   // Create browsers for the ephemeral profile.
834   Browser::CreateParams profile2_params(ephemeral_profile1,
835                                         chrome::GetActiveDesktop());
836   scoped_ptr<Browser> browser2(
837       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
838
839   Browser::CreateParams profile3_params(ephemeral_profile2,
840                                         chrome::GetActiveDesktop());
841   scoped_ptr<Browser> browser3(
842       chrome::CreateBrowserWithTestWindowForParams(&profile3_params));
843
844   std::vector<Profile*> last_opened_profiles =
845       profile_manager->GetLastOpenedProfiles();
846   ASSERT_EQ(2U, last_opened_profiles.size());
847   EXPECT_EQ(normal_profile, last_opened_profiles[0]);
848   EXPECT_EQ(ephemeral_profile2, last_opened_profiles[1]);
849
850   // Mark the second profile ephemeral.
851   ephemeral_profile2->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles,
852                                              true);
853
854   // Simulate a shutdown.
855   content::NotificationService::current()->Notify(
856       chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
857       content::NotificationService::AllSources(),
858       content::NotificationService::NoDetails());
859   browser1.reset();
860   browser2.reset();
861   browser3.reset();
862
863   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
864   ASSERT_EQ(1U, last_opened_profiles.size());
865   EXPECT_EQ(normal_profile, last_opened_profiles[0]);
866 }
867
868 TEST_F(ProfileManagerTest, ActiveProfileDeleted) {
869   ProfileManager* profile_manager = g_browser_process->profile_manager();
870   ASSERT_TRUE(profile_manager);
871
872   // Create and load two profiles.
873   const std::string profile_name1 = "New Profile 1";
874   const std::string profile_name2 = "New Profile 2";
875   base::FilePath dest_path1 = temp_dir_.path().AppendASCII(profile_name1);
876   base::FilePath dest_path2 = temp_dir_.path().AppendASCII(profile_name2);
877
878   MockObserver mock_observer;
879   EXPECT_CALL(mock_observer, OnProfileCreated(
880       testing::NotNull(), NotFail())).Times(testing::AtLeast(3));
881
882   CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
883   CreateProfileAsync(profile_manager, profile_name2, false, &mock_observer);
884   base::RunLoop().RunUntilIdle();
885
886   EXPECT_EQ(2u, profile_manager->GetLoadedProfiles().size());
887   EXPECT_EQ(2u, profile_manager->GetProfileInfoCache().GetNumberOfProfiles());
888
889   // Set the active profile.
890   PrefService* local_state = g_browser_process->local_state();
891   local_state->SetString(prefs::kProfileLastUsed, profile_name1);
892
893   // Delete the active profile.
894   profile_manager->ScheduleProfileForDeletion(dest_path1,
895                                               ProfileManager::CreateCallback());
896   // Spin the message loop so that all the callbacks can finish running.
897   base::RunLoop().RunUntilIdle();
898
899   EXPECT_EQ(dest_path2, profile_manager->GetLastUsedProfile()->GetPath());
900   EXPECT_EQ(profile_name2, local_state->GetString(prefs::kProfileLastUsed));
901 }
902
903 TEST_F(ProfileManagerTest, LastProfileDeleted) {
904   ProfileManager* profile_manager = g_browser_process->profile_manager();
905   ASSERT_TRUE(profile_manager);
906
907   // Create and load a profile.
908   const std::string profile_name1 = "New Profile 1";
909   base::FilePath dest_path1 = temp_dir_.path().AppendASCII(profile_name1);
910
911   MockObserver mock_observer;
912   EXPECT_CALL(mock_observer, OnProfileCreated(
913       testing::NotNull(), NotFail())).Times(testing::AtLeast(1));
914
915   CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
916   base::RunLoop().RunUntilIdle();
917
918   EXPECT_EQ(1u, profile_manager->GetLoadedProfiles().size());
919   EXPECT_EQ(1u, profile_manager->GetProfileInfoCache().GetNumberOfProfiles());
920
921   // Set it as the active profile.
922   PrefService* local_state = g_browser_process->local_state();
923   local_state->SetString(prefs::kProfileLastUsed, profile_name1);
924
925   // Delete the active profile.
926   profile_manager->ScheduleProfileForDeletion(dest_path1,
927                                               ProfileManager::CreateCallback());
928   // Spin the message loop so that all the callbacks can finish running.
929   base::RunLoop().RunUntilIdle();
930
931   // A new profile should have been created
932   const std::string profile_name2 = "Profile 1";
933   base::FilePath dest_path2 = temp_dir_.path().AppendASCII(profile_name2);
934
935   EXPECT_EQ(dest_path2, profile_manager->GetLastUsedProfile()->GetPath());
936   EXPECT_EQ(profile_name2, local_state->GetString(prefs::kProfileLastUsed));
937   EXPECT_EQ(dest_path2,
938       profile_manager->GetProfileInfoCache().GetPathOfProfileAtIndex(0));
939 }
940
941 TEST_F(ProfileManagerTest, LastProfileDeletedWithGuestActiveProfile) {
942   ProfileManager* profile_manager = g_browser_process->profile_manager();
943   ASSERT_TRUE(profile_manager);
944
945   // Create and load a profile.
946   const std::string profile_name1 = "New Profile 1";
947   base::FilePath dest_path1 = temp_dir_.path().AppendASCII(profile_name1);
948
949   MockObserver mock_observer;
950   EXPECT_CALL(mock_observer, OnProfileCreated(
951       testing::NotNull(), NotFail())).Times(testing::AtLeast(2));
952
953   CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
954   base::RunLoop().RunUntilIdle();
955
956   EXPECT_EQ(1u, profile_manager->GetLoadedProfiles().size());
957   EXPECT_EQ(1u, profile_manager->GetProfileInfoCache().GetNumberOfProfiles());
958
959   // Create the profile and register it.
960   const std::string guest_profile_name =
961       ProfileManager::GetGuestProfilePath().BaseName().MaybeAsASCII();
962
963   TestingProfile::Builder builder;
964   builder.SetGuestSession();
965   builder.SetPath(ProfileManager::GetGuestProfilePath());
966   TestingProfile* guest_profile = builder.Build().release();
967   guest_profile->set_profile_name(guest_profile_name);
968   // Registering the profile passes ownership to the ProfileManager.
969   profile_manager->RegisterTestingProfile(guest_profile, false, false);
970
971   // The Guest profile does not get added to the ProfileInfoCache.
972   EXPECT_EQ(2u, profile_manager->GetLoadedProfiles().size());
973   EXPECT_EQ(1u, profile_manager->GetProfileInfoCache().GetNumberOfProfiles());
974
975   // Set the Guest profile as the active profile.
976   PrefService* local_state = g_browser_process->local_state();
977   local_state->SetString(prefs::kProfileLastUsed, guest_profile_name);
978
979   // Delete the other profile.
980   profile_manager->ScheduleProfileForDeletion(dest_path1,
981                                               ProfileManager::CreateCallback());
982   // Spin the message loop so that all the callbacks can finish running.
983   base::RunLoop().RunUntilIdle();
984
985   // A new profile should have been created.
986   const std::string profile_name2 = "Profile 1";
987   base::FilePath dest_path2 = temp_dir_.path().AppendASCII(profile_name2);
988
989   EXPECT_EQ(3u, profile_manager->GetLoadedProfiles().size());
990   EXPECT_EQ(1u, profile_manager->GetProfileInfoCache().GetNumberOfProfiles());
991   EXPECT_EQ(dest_path2,
992       profile_manager->GetProfileInfoCache().GetPathOfProfileAtIndex(0));
993 }
994
995 TEST_F(ProfileManagerTest, ProfileDisplayNameResetsDefaultName) {
996   if (!profiles::IsMultipleProfilesEnabled())
997     return;
998
999   // The command line is reset at the end of every test by the test suite.
1000   switches::EnableNewAvatarMenuForTesting(CommandLine::ForCurrentProcess());
1001
1002   ProfileManager* profile_manager = g_browser_process->profile_manager();
1003   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1004   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
1005
1006   // Only one local profile means we display IDS_SINGLE_PROFILE_DISPLAY_NAME.
1007   const base::string16 default_profile_name =
1008       l10n_util::GetStringUTF16(IDS_SINGLE_PROFILE_DISPLAY_NAME);
1009   const base::string16 profile_name1 = cache.ChooseNameForNewProfile(0);
1010   Profile* profile1 = AddProfileToCache(profile_manager,
1011                                         "path_1", profile_name1);
1012   EXPECT_EQ(default_profile_name,
1013             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1014
1015   // Multiple profiles means displaying the actual profile names.
1016   const base::string16 profile_name2 = cache.ChooseNameForNewProfile(1);
1017   Profile* profile2 = AddProfileToCache(profile_manager,
1018                                         "path_2", profile_name2);
1019   EXPECT_EQ(profile_name1,
1020             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1021   EXPECT_EQ(profile_name2,
1022             profiles::GetAvatarNameForProfile(profile2->GetPath()));
1023
1024   // Deleting a profile means returning to the default name.
1025   profile_manager->ScheduleProfileForDeletion(profile2->GetPath(),
1026                                               ProfileManager::CreateCallback());
1027   // Spin the message loop so that all the callbacks can finish running.
1028   base::RunLoop().RunUntilIdle();
1029   EXPECT_EQ(default_profile_name,
1030             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1031 }
1032
1033 TEST_F(ProfileManagerTest, ProfileDisplayNamePreservesCustomName) {
1034   if (!profiles::IsMultipleProfilesEnabled())
1035     return;
1036
1037   // The command line is reset at the end of every test by the test suite.
1038   switches::EnableNewAvatarMenuForTesting(CommandLine::ForCurrentProcess());
1039
1040   ProfileManager* profile_manager = g_browser_process->profile_manager();
1041   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1042   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
1043
1044   // Only one local profile means we display IDS_SINGLE_PROFILE_DISPLAY_NAME.
1045   const base::string16 default_profile_name =
1046       l10n_util::GetStringUTF16(IDS_SINGLE_PROFILE_DISPLAY_NAME);
1047   const base::string16 profile_name1 = cache.ChooseNameForNewProfile(0);
1048   Profile* profile1 = AddProfileToCache(profile_manager,
1049                                         "path_1", profile_name1);
1050   EXPECT_EQ(default_profile_name,
1051             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1052
1053   // We should display custom names for local profiles.
1054   const base::string16 custom_profile_name = ASCIIToUTF16("Batman");
1055   cache.SetNameOfProfileAtIndex(0, custom_profile_name);
1056   cache.SetProfileIsUsingDefaultNameAtIndex(0, false);
1057   EXPECT_EQ(custom_profile_name, cache.GetNameOfProfileAtIndex(0));
1058   EXPECT_EQ(custom_profile_name,
1059             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1060
1061   // Multiple profiles means displaying the actual profile names.
1062   const base::string16 profile_name2 = cache.ChooseNameForNewProfile(1);
1063   Profile* profile2 = AddProfileToCache(profile_manager,
1064                                         "path_2", profile_name2);
1065   EXPECT_EQ(custom_profile_name,
1066             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1067   EXPECT_EQ(profile_name2,
1068             profiles::GetAvatarNameForProfile(profile2->GetPath()));
1069
1070   // Deleting a profile means returning to the original, custom name.
1071   profile_manager->ScheduleProfileForDeletion(profile2->GetPath(),
1072                                               ProfileManager::CreateCallback());
1073   // Spin the message loop so that all the callbacks can finish running.
1074   base::RunLoop().RunUntilIdle();
1075   EXPECT_EQ(custom_profile_name,
1076             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1077 }
1078
1079 TEST_F(ProfileManagerTest, ProfileDisplayNamePreservesSignedInName) {
1080   if (!profiles::IsMultipleProfilesEnabled())
1081     return;
1082
1083   // The command line is reset at the end of every test by the test suite.
1084   switches::EnableNewAvatarMenuForTesting(CommandLine::ForCurrentProcess());
1085
1086   ProfileManager* profile_manager = g_browser_process->profile_manager();
1087   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1088   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
1089
1090   // Only one local profile means we display IDS_SINGLE_PROFILE_DISPLAY_NAME.
1091   const base::string16 default_profile_name =
1092       l10n_util::GetStringUTF16(IDS_SINGLE_PROFILE_DISPLAY_NAME);
1093   const base::string16 profile_name1 = cache.ChooseNameForNewProfile(0);
1094   Profile* profile1 = AddProfileToCache(profile_manager,
1095                                         "path_1", profile_name1);
1096   EXPECT_EQ(default_profile_name,
1097             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1098
1099   // For a signed in profile with a default name we still display
1100   // IDS_SINGLE_PROFILE_DISPLAY_NAME.
1101   cache.SetUserNameOfProfileAtIndex(0, ASCIIToUTF16("user@gmail.com"));
1102   EXPECT_EQ(profile_name1, cache.GetNameOfProfileAtIndex(0));
1103   EXPECT_EQ(default_profile_name,
1104             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1105
1106   // For a signed in profile with a non-default Gaia given name we display the
1107   // Gaia given name.
1108   cache.SetUserNameOfProfileAtIndex(0, ASCIIToUTF16("user@gmail.com"));
1109   const base::string16 gaia_given_name(ASCIIToUTF16("given name"));
1110   cache.SetGAIAGivenNameOfProfileAtIndex(0, gaia_given_name);
1111   EXPECT_EQ(gaia_given_name, cache.GetNameOfProfileAtIndex(0));
1112   EXPECT_EQ(gaia_given_name,
1113       profiles::GetAvatarNameForProfile(profile1->GetPath()));
1114
1115   // Multiple profiles means displaying the actual profile names.
1116   const base::string16 profile_name2 = cache.ChooseNameForNewProfile(1);
1117   Profile* profile2 = AddProfileToCache(profile_manager,
1118                                         "path_2", profile_name2);
1119   EXPECT_EQ(gaia_given_name,
1120             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1121   EXPECT_EQ(profile_name2,
1122             profiles::GetAvatarNameForProfile(profile2->GetPath()));
1123
1124   // Deleting a profile means returning to the original, actual profile name.
1125   profile_manager->ScheduleProfileForDeletion(profile2->GetPath(),
1126                                               ProfileManager::CreateCallback());
1127   // Spin the message loop so that all the callbacks can finish running.
1128   base::RunLoop().RunUntilIdle();
1129   EXPECT_EQ(gaia_given_name,
1130             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1131 }
1132
1133 TEST_F(ProfileManagerTest, ProfileDisplayNameIsEmailIfDefaultName) {
1134   if (!profiles::IsMultipleProfilesEnabled())
1135     return;
1136
1137   // The command line is reset at the end of every test by the test suite.
1138   switches::EnableNewAvatarMenuForTesting(CommandLine::ForCurrentProcess());
1139
1140   ProfileManager* profile_manager = g_browser_process->profile_manager();
1141   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1142   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
1143
1144   // Create two signed in profiles, with both new and legacy default names, and
1145   // a profile with a custom name.
1146   Profile* profile1 = AddProfileToCache(
1147       profile_manager, "path_1", ASCIIToUTF16("Person 1"));
1148   Profile* profile2 = AddProfileToCache(
1149       profile_manager, "path_2", ASCIIToUTF16("Default Profile"));
1150   const base::string16 profile_name3(ASCIIToUTF16("Batman"));
1151   Profile* profile3 = AddProfileToCache(
1152       profile_manager, "path_3", profile_name3);
1153   EXPECT_EQ(3u, cache.GetNumberOfProfiles());
1154
1155   // Sign in all profiles, and make sure they do not have a Gaia name set.
1156   const base::string16 email1(ASCIIToUTF16("user1@gmail.com"));
1157   const base::string16 email2(ASCIIToUTF16("user2@gmail.com"));
1158   const base::string16 email3(ASCIIToUTF16("user3@gmail.com"));
1159
1160   int index = cache.GetIndexOfProfileWithPath(profile1->GetPath());
1161   cache.SetUserNameOfProfileAtIndex(index, email1);
1162   cache.SetGAIAGivenNameOfProfileAtIndex(index, base::string16());
1163   cache.SetGAIANameOfProfileAtIndex(index, base::string16());
1164
1165   // This may resort the cache, so be extra cautious to use the right profile.
1166   index = cache.GetIndexOfProfileWithPath(profile2->GetPath());
1167   cache.SetUserNameOfProfileAtIndex(index, email2);
1168   cache.SetGAIAGivenNameOfProfileAtIndex(index, base::string16());
1169   cache.SetGAIANameOfProfileAtIndex(index, base::string16());
1170
1171   index = cache.GetIndexOfProfileWithPath(profile3->GetPath());
1172   cache.SetUserNameOfProfileAtIndex(index, email3);
1173   cache.SetGAIAGivenNameOfProfileAtIndex(index, base::string16());
1174   cache.SetGAIANameOfProfileAtIndex(index, base::string16());
1175
1176   // The profiles with default names should display the email address.
1177   EXPECT_EQ(email1, profiles::GetAvatarNameForProfile(profile1->GetPath()));
1178   EXPECT_EQ(email2, profiles::GetAvatarNameForProfile(profile2->GetPath()));
1179
1180   // The profile with the custom name should display that.
1181   EXPECT_EQ(profile_name3,
1182             profiles::GetAvatarNameForProfile(profile3->GetPath()));
1183
1184   // Adding a Gaia name to a profile that previously had a default name should
1185   // start displaying it.
1186   const base::string16 gaia_given_name(ASCIIToUTF16("Robin"));
1187   cache.SetGAIAGivenNameOfProfileAtIndex(
1188       cache.GetIndexOfProfileWithPath(profile1->GetPath()), gaia_given_name);
1189   EXPECT_EQ(gaia_given_name,
1190             profiles::GetAvatarNameForProfile(profile1->GetPath()));
1191 }
1192 #endif  // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1193
1194 #if defined(OS_MACOSX)
1195 // These tests are for a Mac-only code path that assumes the browser
1196 // process isn't killed when all browser windows are closed.
1197 TEST_F(ProfileManagerTest, ActiveProfileDeletedNeedsToLoadNextProfile) {
1198   ProfileManager* profile_manager = g_browser_process->profile_manager();
1199   ASSERT_TRUE(profile_manager);
1200
1201   // Create and load one profile, and just create a second profile.
1202   const std::string profile_name1 = "New Profile 1";
1203   const std::string profile_name2 = "New Profile 2";
1204   base::FilePath dest_path1 = temp_dir_.path().AppendASCII(profile_name1);
1205   base::FilePath dest_path2 = temp_dir_.path().AppendASCII(profile_name2);
1206
1207   MockObserver mock_observer;
1208   EXPECT_CALL(mock_observer, OnProfileCreated(
1209       testing::NotNull(), NotFail())).Times(testing::AtLeast(2));
1210   CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
1211   base::RunLoop().RunUntilIdle();
1212
1213   // Track the profile, but don't load it.
1214   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1215   cache.AddProfileToCache(dest_path2, ASCIIToUTF16(profile_name2),
1216                           base::string16(), 0, std::string());
1217   base::RunLoop().RunUntilIdle();
1218
1219   EXPECT_EQ(1u, profile_manager->GetLoadedProfiles().size());
1220   EXPECT_EQ(2u, cache.GetNumberOfProfiles());
1221
1222   // Set the active profile.
1223   PrefService* local_state = g_browser_process->local_state();
1224   local_state->SetString(prefs::kProfileLastUsed,
1225                          dest_path1.BaseName().MaybeAsASCII());
1226
1227   // Delete the active profile. This should switch and load the unloaded
1228   // profile.
1229   profile_manager->ScheduleProfileForDeletion(dest_path1,
1230                                               ProfileManager::CreateCallback());
1231
1232   // Spin the message loop so that all the callbacks can finish running.
1233   base::RunLoop().RunUntilIdle();
1234
1235   EXPECT_EQ(dest_path2, profile_manager->GetLastUsedProfile()->GetPath());
1236   EXPECT_EQ(profile_name2, local_state->GetString(prefs::kProfileLastUsed));
1237 }
1238
1239 // This tests the recursive call in ProfileManager::OnNewActiveProfileLoaded
1240 // by simulating a scenario in which the profile that is being loaded as
1241 // the next active profile has also been marked for deletion, so the
1242 // ProfileManager needs to recursively select a different next profile.
1243 TEST_F(ProfileManagerTest, ActiveProfileDeletedNextProfileDeletedToo) {
1244   ProfileManager* profile_manager = g_browser_process->profile_manager();
1245   ASSERT_TRUE(profile_manager);
1246
1247   // Create and load one profile, and create two more profiles.
1248   const std::string profile_name1 = "New Profile 1";
1249   const std::string profile_name2 = "New Profile 2";
1250   const std::string profile_name3 = "New Profile 3";
1251   base::FilePath dest_path1 = temp_dir_.path().AppendASCII(profile_name1);
1252   base::FilePath dest_path2 = temp_dir_.path().AppendASCII(profile_name2);
1253   base::FilePath dest_path3 = temp_dir_.path().AppendASCII(profile_name3);
1254
1255   MockObserver mock_observer;
1256   EXPECT_CALL(mock_observer, OnProfileCreated(
1257       testing::NotNull(), NotFail())).Times(testing::AtLeast(2));
1258   CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
1259   base::RunLoop().RunUntilIdle();
1260
1261   // Create the other profiles, but don't load them. Assign a fake avatar icon
1262   // to ensure that profiles in the info cache are sorted by the profile name,
1263   // and not randomly by the avatar name.
1264   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
1265   cache.AddProfileToCache(dest_path2, ASCIIToUTF16(profile_name2),
1266                           ASCIIToUTF16(profile_name2), 1, std::string());
1267   cache.AddProfileToCache(dest_path3, ASCIIToUTF16(profile_name3),
1268                           ASCIIToUTF16(profile_name3), 2, std::string());
1269
1270   base::RunLoop().RunUntilIdle();
1271
1272   EXPECT_EQ(1u, profile_manager->GetLoadedProfiles().size());
1273   EXPECT_EQ(3u, cache.GetNumberOfProfiles());
1274
1275   // Set the active profile.
1276   PrefService* local_state = g_browser_process->local_state();
1277   local_state->SetString(prefs::kProfileLastUsed,
1278                          dest_path1.BaseName().MaybeAsASCII());
1279
1280   // Delete the active profile, Profile1.
1281   // This will post a CreateProfileAsync message, that tries to load Profile2,
1282   // which checks that the profile is not being deleted, and then calls back
1283   // FinishDeletingProfile for Profile1.
1284   // Try to break this flow by setting the active profile to Profile2 in the
1285   // middle (so after the first posted message), and trying to delete Profile2,
1286   // so that the ProfileManager has to look for a different profile to load.
1287   profile_manager->ScheduleProfileForDeletion(dest_path1,
1288                                               ProfileManager::CreateCallback());
1289   local_state->SetString(prefs::kProfileLastUsed,
1290                          dest_path2.BaseName().MaybeAsASCII());
1291   profile_manager->ScheduleProfileForDeletion(dest_path2,
1292                                               ProfileManager::CreateCallback());
1293   // Spin the message loop so that all the callbacks can finish running.
1294   base::RunLoop().RunUntilIdle();
1295
1296   EXPECT_EQ(dest_path3, profile_manager->GetLastUsedProfile()->GetPath());
1297   EXPECT_EQ(profile_name3, local_state->GetString(prefs::kProfileLastUsed));
1298 }
1299 #endif  // !defined(OS_MACOSX)