Upstream version 5.34.104.0
[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/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"
40
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"
47 #endif
48
49 using base::ASCIIToUTF16;
50 using content::BrowserThread;
51
52 namespace {
53
54 // This global variable is used to check that value returned to different
55 // observers is the same.
56 Profile* g_created_profile;
57
58 class UnittestProfileManager : public ::ProfileManagerWithoutInit {
59  public:
60   explicit UnittestProfileManager(const base::FilePath& user_data_dir)
61       : ::ProfileManagerWithoutInit(user_data_dir) {}
62
63  protected:
64   virtual Profile* CreateProfileHelper(
65       const base::FilePath& file_path) OVERRIDE {
66     if (!base::PathExists(file_path)) {
67       if (!base::CreateDirectory(file_path))
68         return NULL;
69     }
70     return new TestingProfile(file_path, NULL);
71   }
72
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));
79
80     return new TestingProfile(path, this);
81   }
82 };
83
84 }  // namespace
85
86 class ProfileManagerTest : public testing::Test {
87  protected:
88   class MockObserver {
89    public:
90     MOCK_METHOD2(OnProfileCreated,
91         void(Profile* profile, Profile::CreateStatus status));
92   };
93
94   ProfileManagerTest()
95       : local_state_(TestingBrowserProcess::GetGlobal()) {
96   }
97
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()));
103
104 #if defined(OS_CHROMEOS)
105   CommandLine* cl = CommandLine::ForCurrentProcess();
106   cl->AppendSwitch(switches::kTestType);
107 #endif
108   }
109
110   virtual void TearDown() {
111     TestingBrowserProcess::GetGlobal()->SetProfileManager(NULL);
112     base::RunLoop().RunUntilIdle();
113   }
114
115   // Helper function to create a profile with |name| for a profile |manager|.
116   void CreateProfileAsync(ProfileManager* manager,
117                           const std::string& name,
118                           bool is_managed,
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());
127   }
128
129 #if defined(OS_CHROMEOS)
130   chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
131   chromeos::ScopedTestCrosSettings test_cros_settings_;
132 #endif
133
134   // The path to temporary directory used to contain the test operations.
135   base::ScopedTempDir temp_dir_;
136   ScopedTestingLocalState local_state_;
137
138   content::TestBrowserThreadBundle thread_bundle_;
139
140 #if defined(OS_CHROMEOS)
141   chromeos::ScopedTestUserManager test_user_manager_;
142 #endif
143 };
144
145 TEST_F(ProfileManagerTest, GetProfile) {
146   base::FilePath dest_path = temp_dir_.path();
147   dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
148
149   ProfileManager* profile_manager = g_browser_process->profile_manager();
150
151   // Successfully create a profile.
152   Profile* profile = profile_manager->GetProfile(dest_path);
153   EXPECT_TRUE(profile);
154
155   // The profile already exists when we call GetProfile. Just load it.
156   EXPECT_EQ(profile, profile_manager->GetProfile(dest_path));
157 }
158
159 TEST_F(ProfileManagerTest, DefaultProfileDir) {
160   base::FilePath expected_default =
161       base::FilePath().AppendASCII(chrome::kInitialProfile);
162   EXPECT_EQ(
163       expected_default.value(),
164       g_browser_process->profile_manager()->GetInitialProfileDir().value());
165 }
166
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);
172
173   cl->AppendSwitchASCII(chromeos::switches::kLoginProfile, profile_dir);
174
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());
180
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();
193 }
194
195 #endif
196
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"));
200
201   base::FilePath dest_path2 = temp_dir_.path();
202   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
203
204   ProfileManager* profile_manager = g_browser_process->profile_manager();
205
206   // Successfully create the profiles.
207   TestingProfile* profile1 =
208       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
209   ASSERT_TRUE(profile1);
210
211   TestingProfile* profile2 =
212       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
213   ASSERT_TRUE(profile2);
214
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));
226
227   // Make sure any pending tasks run before we destroy the profiles.
228     base::RunLoop().RunUntilIdle();
229
230   TestingBrowserProcess::GetGlobal()->SetProfileManager(NULL);
231
232   // Make sure history cleans up correctly.
233   base::RunLoop().RunUntilIdle();
234 }
235
236 MATCHER(NotFail, "Profile creation failure status is not reported.") {
237   return arg == Profile::CREATE_STATUS_CREATED ||
238          arg == Profile::CREATE_STATUS_INITIALIZED;
239 }
240
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;
245 }
246
247 TEST_F(ProfileManagerTest, CreateProfileAsyncMultipleRequests) {
248   g_created_profile = NULL;
249
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));
259
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);
265
266   base::RunLoop().RunUntilIdle();
267 }
268
269 TEST_F(ProfileManagerTest, CreateProfilesAsync) {
270   const std::string profile_name1 = "New Profile 1";
271   const std::string profile_name2 = "New Profile 2";
272
273   MockObserver mock_observer;
274   EXPECT_CALL(mock_observer, OnProfileCreated(
275       testing::NotNull(), NotFail())).Times(testing::AtLeast(3));
276
277   ProfileManager* profile_manager = g_browser_process->profile_manager();
278
279   CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
280   CreateProfileAsync(profile_manager, profile_name2, false, &mock_observer);
281
282   base::RunLoop().RunUntilIdle();
283 }
284
285 TEST_F(ProfileManagerTest, CreateProfileAsyncCheckOmitted) {
286   std::string name = "Managed Profile";
287
288   MockObserver mock_observer;
289   EXPECT_CALL(mock_observer, OnProfileCreated(
290       testing::NotNull(), NotFail())).Times(testing::AtLeast(2));
291
292   ProfileManager* profile_manager = g_browser_process->profile_manager();
293   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
294   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
295
296   CreateProfileAsync(profile_manager, name, true, &mock_observer);
297   base::RunLoop().RunUntilIdle();
298
299   EXPECT_EQ(1u, cache.GetNumberOfProfiles());
300   // Managed profiles should start out omitted from the profile list.
301   EXPECT_TRUE(cache.IsOmittedProfileAtIndex(0));
302
303   name = "Regular Profile";
304   CreateProfileAsync(profile_manager, name, false, &mock_observer);
305   base::RunLoop().RunUntilIdle();
306
307   EXPECT_EQ(2u, cache.GetNumberOfProfiles());
308   // Non-managed profiles should be included in the profile list.
309   EXPECT_FALSE(cache.IsOmittedProfileAtIndex(1));
310 }
311
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());
316
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");
320
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));
325
326   const base::FilePath nonmanaged_path = temp_dir_.path().AppendASCII(
327       "Non-Managed");
328   TestingProfile* nonmanaged_profile = new TestingProfile(nonmanaged_path,
329                                                           NULL);
330   profile_manager->RegisterTestingProfile(nonmanaged_profile, true, false);
331
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));
337 }
338
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);
344 }
345
346 #if defined(OS_CHROMEOS)
347 class UnittestGuestProfileManager : public UnittestProfileManager {
348  public:
349   explicit UnittestGuestProfileManager(const base::FilePath& user_data_dir)
350       : UnittestProfileManager(user_data_dir) {}
351
352  protected:
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();
359
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>());
366
367     return testing_profile;
368   }
369 };
370
371 class ProfileManagerGuestTest : public ProfileManagerTest {
372  protected:
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()));
378
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);
384
385     chromeos::UserManager::Get()->UserLoggedIn(
386         chromeos::UserManager::kGuestUserName,
387         chromeos::UserManager::kGuestUserName,
388         false);
389   }
390 };
391
392 TEST_F(ProfileManagerGuestTest, GuestProfileIngonito) {
393   Profile* primary_profile = ProfileManager::GetPrimaryUserProfile();
394   EXPECT_TRUE(primary_profile->IsOffTheRecord());
395
396   Profile* active_profile = ProfileManager::GetActiveUserProfile();
397   EXPECT_TRUE(active_profile->IsOffTheRecord());
398
399   EXPECT_TRUE(active_profile->IsSameProfile(primary_profile));
400
401   Profile* last_used_profile = ProfileManager::GetLastUsedProfile();
402   EXPECT_TRUE(last_used_profile->IsOffTheRecord());
403
404   EXPECT_TRUE(last_used_profile->IsSameProfile(active_profile));
405 }
406 #endif
407
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));
413
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))
419     return;
420
421   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
422   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_1"),
423                           ASCIIToUTF16("name_1"), base::string16(), 0,
424                           std::string());
425   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_2"),
426                           ASCIIToUTF16("name_2"), base::string16(), 0,
427                           std::string());
428   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_3"),
429                           ASCIIToUTF16("name_3"), base::string16(), 0,
430                           std::string());
431   cache.SetBackgroundStatusOfProfileAtIndex(0, true);
432   cache.SetBackgroundStatusOfProfileAtIndex(2, true);
433   EXPECT_EQ(3u, cache.GetNumberOfProfiles());
434
435   profile_manager->AutoloadProfiles();
436
437   EXPECT_EQ(2u, profile_manager->GetLoadedProfiles().size());
438 }
439
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));
445
446   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
447   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_1"),
448                           ASCIIToUTF16("name_1"), base::string16(), 0,
449                           std::string());
450   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_2"),
451                           ASCIIToUTF16("name_2"), base::string16(), 0,
452                           std::string());
453   cache.SetBackgroundStatusOfProfileAtIndex(0, false);
454   cache.SetBackgroundStatusOfProfileAtIndex(1, true);
455   EXPECT_EQ(2u, cache.GetNumberOfProfiles());
456
457   profile_manager->AutoloadProfiles();
458
459   EXPECT_EQ(0u, profile_manager->GetLoadedProfiles().size());
460 }
461
462 TEST_F(ProfileManagerTest, InitProfileUserPrefs) {
463   base::FilePath dest_path = temp_dir_.path();
464   dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
465
466   ProfileManager* profile_manager = g_browser_process->profile_manager();
467
468   Profile* profile;
469
470   // Successfully create the profile
471   profile = profile_manager->GetProfile(dest_path);
472   ASSERT_TRUE(profile);
473
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());
478
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(
483       avatar_index));
484 }
485
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"));
491
492   ProfileManager* profile_manager = g_browser_process->profile_manager();
493   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
494
495   // Successfully create the profile
496   Profile* profile = profile_manager->GetProfile(dest_path);
497   ASSERT_TRUE(profile);
498
499   std::string profile_name =
500       profile->GetPrefs()->GetString(prefs::kProfileName);
501   size_t avatar_index =
502       profile->GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
503
504   size_t profile_index = cache.GetIndexOfProfileWithPath(dest_path);
505
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));
511 }
512
513 TEST_F(ProfileManagerTest, GetLastUsedProfileAllowedByPolicy) {
514   ProfileManager* profile_manager = g_browser_process->profile_manager();
515   ASSERT_TRUE(profile_manager);
516
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));
523
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());
533
534   IncognitoModePrefs::SetAvailability(prefs, IncognitoModePrefs::DISABLED);
535   EXPECT_FALSE(
536       profile_manager->GetLastUsedProfileAllowedByPolicy()->IsOffTheRecord());
537
538   // GetLastUsedProfileAllowedByPolicy() returns the incognito Profile when
539   // incognito mode is forced.
540   IncognitoModePrefs::SetAvailability(prefs, IncognitoModePrefs::FORCED);
541   EXPECT_TRUE(
542       profile_manager->GetLastUsedProfileAllowedByPolicy()->IsOffTheRecord());
543 }
544
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"));
550
551   base::FilePath dest_path2 = temp_dir_.path();
552   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
553
554   ProfileManager* profile_manager = g_browser_process->profile_manager();
555
556   // Successfully create the profiles.
557   TestingProfile* profile1 =
558       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
559   ASSERT_TRUE(profile1);
560
561   TestingProfile* profile2 =
562       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
563   ASSERT_TRUE(profile2);
564
565   std::vector<Profile*> last_opened_profiles =
566       profile_manager->GetLastOpenedProfiles();
567   ASSERT_EQ(0U, last_opened_profiles.size());
568
569   // Create a browser for profile1.
570   Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
571   scoped_ptr<Browser> browser1a(
572       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
573
574   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
575   ASSERT_EQ(1U, last_opened_profiles.size());
576   EXPECT_EQ(profile1, last_opened_profiles[0]);
577
578   // And for profile2.
579   Browser::CreateParams profile2_params(profile2, chrome::GetActiveDesktop());
580   scoped_ptr<Browser> browser2(
581       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
582
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]);
587
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]);
595
596   // Close the browsers.
597   browser1a.reset();
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]);
602
603   browser1b.reset();
604   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
605   ASSERT_EQ(1U, last_opened_profiles.size());
606   EXPECT_EQ(profile2, last_opened_profiles[0]);
607
608   browser2.reset();
609   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
610   ASSERT_EQ(0U, last_opened_profiles.size());
611 }
612
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"));
616
617   base::FilePath dest_path2 = temp_dir_.path();
618   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
619
620   ProfileManager* profile_manager = g_browser_process->profile_manager();
621
622   // Successfully create the profiles.
623   TestingProfile* profile1 =
624       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
625   ASSERT_TRUE(profile1);
626
627   TestingProfile* profile2 =
628       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
629   ASSERT_TRUE(profile2);
630
631   // Create a browser for profile1.
632   Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
633   scoped_ptr<Browser> browser1(
634       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
635
636   // And for profile2.
637   Browser::CreateParams profile2_params(profile2, chrome::GetActiveDesktop());
638   scoped_ptr<Browser> browser2(
639       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
640
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]);
646
647   // Simulate a shutdown.
648   content::NotificationService::current()->Notify(
649       chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
650       content::NotificationService::AllSources(),
651       content::NotificationService::NoDetails());
652
653   // Even if the browsers are destructed during shutdown, the profiles stay
654   // open.
655   browser1.reset();
656   browser2.reset();
657
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]);
662 }
663
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"));
669
670   ProfileManager* profile_manager = g_browser_process->profile_manager();
671
672   // Successfully create the profiles.
673   TestingProfile* profile1 =
674       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
675   ASSERT_TRUE(profile1);
676
677   // Incognito profiles should not be managed by the profile manager but by the
678   // original profile.
679   TestingProfile::Builder builder;
680   builder.SetIncognito();
681   scoped_ptr<TestingProfile> profile2 = builder.Build();
682   profile1->SetOffTheRecordProfile(profile2.PassAs<Profile>());
683
684   std::vector<Profile*> last_opened_profiles =
685       profile_manager->GetLastOpenedProfiles();
686   ASSERT_EQ(0U, last_opened_profiles.size());
687
688   // Create a browser for profile1.
689   Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
690   scoped_ptr<Browser> browser1(
691       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
692
693   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
694   ASSERT_EQ(1U, last_opened_profiles.size());
695   EXPECT_EQ(profile1, last_opened_profiles[0]);
696
697   // And for profile2.
698   Browser::CreateParams profile2_params(profile1->GetOffTheRecordProfile(),
699                                         chrome::GetActiveDesktop());
700   scoped_ptr<Browser> browser2a(
701       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
702
703   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
704   ASSERT_EQ(1U, last_opened_profiles.size());
705   EXPECT_EQ(profile1, last_opened_profiles[0]);
706
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]);
713
714   // Close the browsers.
715   browser2a.reset();
716   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
717   ASSERT_EQ(1U, last_opened_profiles.size());
718   EXPECT_EQ(profile1, last_opened_profiles[0]);
719
720   browser2b.reset();
721   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
722   ASSERT_EQ(1U, last_opened_profiles.size());
723   EXPECT_EQ(profile1, last_opened_profiles[0]);
724
725   browser1.reset();
726   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
727   ASSERT_EQ(0U, last_opened_profiles.size());
728 }
729 #endif  // !defined(OS_ANDROID)
730
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"));
736
737   ProfileManager* profile_manager = g_browser_process->profile_manager();
738
739   TestingProfile* profile =
740       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path));
741   ASSERT_TRUE(profile);
742   profile->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles, true);
743
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);
747
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);
754
755   // Close the browser.
756   browser.reset();
757   last_used_profile = profile_manager->GetLastUsedProfile();
758   EXPECT_NE(profile, last_used_profile);
759 }
760
761 TEST_F(ProfileManagerTest, EphemeralProfilesDontEndUpAsLastOpenedAtShutdown) {
762   base::FilePath dest_path1 = temp_dir_.path();
763   dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("Normal Profile"));
764
765   base::FilePath dest_path2 = temp_dir_.path();
766   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("Ephemeral Profile 1"));
767
768   base::FilePath dest_path3 = temp_dir_.path();
769   dest_path3 = dest_path3.Append(FILE_PATH_LITERAL("Ephemeral Profile 2"));
770
771   ProfileManager* profile_manager = g_browser_process->profile_manager();
772
773   // Successfully create the profiles.
774   TestingProfile* normal_profile =
775       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
776   ASSERT_TRUE(normal_profile);
777
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,
783                                              true);
784
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);
789
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));
795
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));
801
802   Browser::CreateParams profile3_params(ephemeral_profile2,
803                                         chrome::GetActiveDesktop());
804   scoped_ptr<Browser> browser3(
805       chrome::CreateBrowserWithTestWindowForParams(&profile3_params));
806
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]);
812
813   // Mark the second profile ephemeral.
814   ephemeral_profile2->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles,
815                                              true);
816
817   // Simulate a shutdown.
818   content::NotificationService::current()->Notify(
819       chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
820       content::NotificationService::AllSources(),
821       content::NotificationService::NoDetails());
822   browser1.reset();
823   browser2.reset();
824   browser3.reset();
825
826   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
827   ASSERT_EQ(1U, last_opened_profiles.size());
828   EXPECT_EQ(normal_profile, last_opened_profiles[0]);
829 }
830
831 TEST_F(ProfileManagerTest, ActiveProfileDeleted) {
832   ProfileManager* profile_manager = g_browser_process->profile_manager();
833   ASSERT_TRUE(profile_manager);
834
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);
842
843   MockObserver mock_observer;
844   EXPECT_CALL(mock_observer, OnProfileCreated(
845       testing::NotNull(), NotFail())).Times(testing::AtLeast(3));
846
847   CreateProfileAsync(profile_manager, profile_name1, false, &mock_observer);
848   CreateProfileAsync(profile_manager, profile_name2, false, &mock_observer);
849   base::RunLoop().RunUntilIdle();
850
851   EXPECT_EQ(2u, profile_manager->GetLoadedProfiles().size());
852   EXPECT_EQ(2u, profile_manager->GetProfileInfoCache().GetNumberOfProfiles());
853
854   // Set the active profile.
855   PrefService* local_state = g_browser_process->local_state();
856   local_state->SetString(prefs::kProfileLastUsed, profile_name1);
857
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();
863
864   EXPECT_EQ(dest_path2, profile_manager->GetLastUsedProfile()->GetPath());
865   EXPECT_EQ(profile_name2, local_state->GetString(prefs::kProfileLastUsed));
866 }
867 #endif  // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
868
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);
875
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);
883
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();
889
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();
895
896   EXPECT_EQ(1u, profile_manager->GetLoadedProfiles().size());
897   EXPECT_EQ(2u, cache.GetNumberOfProfiles());
898
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());
903
904   // Delete the active profile. This should switch and load the unloaded
905   // profile.
906   profile_manager->ScheduleProfileForDeletion(dest_path1,
907                                               ProfileManager::CreateCallback());
908
909   // Spin the message loop so that all the callbacks can finish running.
910   base::RunLoop().RunUntilIdle();
911
912   EXPECT_EQ(dest_path2, profile_manager->GetLastUsedProfile()->GetPath());
913   EXPECT_EQ(profile_name2, local_state->GetString(prefs::kProfileLastUsed));
914 }
915
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);
923
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);
934
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();
940
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());
949
950   base::RunLoop().RunUntilIdle();
951
952   EXPECT_EQ(1u, profile_manager->GetLoadedProfiles().size());
953   EXPECT_EQ(3u, cache.GetNumberOfProfiles());
954
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());
959
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();
975
976   EXPECT_EQ(dest_path3, profile_manager->GetLastUsedProfile()->GetPath());
977   EXPECT_EQ(profile_name3, local_state->GetString(prefs::kProfileLastUsed));
978 }
979 #endif  // !defined(OS_MACOSX)