- add sources.
[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 content::BrowserThread;
50
51 namespace {
52
53 // This global variable is used to check that value returned to different
54 // observers is the same.
55 Profile* g_created_profile;
56
57 class UnittestProfileManager : public ::ProfileManagerWithoutInit {
58  public:
59   explicit UnittestProfileManager(const base::FilePath& user_data_dir)
60       : ::ProfileManagerWithoutInit(user_data_dir) {}
61
62  protected:
63   virtual Profile* CreateProfileHelper(
64       const base::FilePath& file_path) OVERRIDE {
65     if (!base::PathExists(file_path)) {
66       if (!file_util::CreateDirectory(file_path))
67         return NULL;
68     }
69     return new TestingProfile(file_path, NULL);
70   }
71
72   virtual Profile* CreateProfileAsyncHelper(const base::FilePath& path,
73                                             Delegate* delegate) OVERRIDE {
74     // This is safe while all file operations are done on the FILE thread.
75     BrowserThread::PostTask(
76         BrowserThread::FILE, FROM_HERE,
77         base::Bind(base::IgnoreResult(&file_util::CreateDirectory), path));
78
79     return new TestingProfile(path, this);
80   }
81 };
82
83 }  // namespace
84
85 class ProfileManagerTest : public testing::Test {
86  protected:
87   class MockObserver {
88    public:
89     MOCK_METHOD2(OnProfileCreated,
90         void(Profile* profile, Profile::CreateStatus status));
91   };
92
93   ProfileManagerTest()
94       : local_state_(TestingBrowserProcess::GetGlobal()) {
95   }
96
97   virtual void SetUp() {
98     // Create a new temporary directory, and store the path
99     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
100     TestingBrowserProcess::GetGlobal()->SetProfileManager(
101         new UnittestProfileManager(temp_dir_.path()));
102
103 #if defined(OS_CHROMEOS)
104   CommandLine* cl = CommandLine::ForCurrentProcess();
105   cl->AppendSwitch(switches::kTestType);
106 #endif
107   }
108
109   virtual void TearDown() {
110     TestingBrowserProcess::GetGlobal()->SetProfileManager(NULL);
111     base::RunLoop().RunUntilIdle();
112   }
113
114   // Helper function to create a profile with |name| for a profile |manager|.
115   void CreateProfileAsync(ProfileManager* manager,
116                           const std::string& name,
117                           MockObserver* mock_observer) {
118     manager->CreateProfileAsync(
119         temp_dir_.path().AppendASCII(name),
120         base::Bind(&MockObserver::OnProfileCreated,
121                    base::Unretained(mock_observer)),
122         UTF8ToUTF16(name),
123         string16(),
124         std::string());
125   }
126
127 #if defined(OS_CHROMEOS)
128   chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
129   chromeos::ScopedTestCrosSettings test_cros_settings_;
130 #endif
131
132   // The path to temporary directory used to contain the test operations.
133   base::ScopedTempDir temp_dir_;
134   ScopedTestingLocalState local_state_;
135
136   content::TestBrowserThreadBundle thread_bundle_;
137
138 #if defined(OS_CHROMEOS)
139   chromeos::ScopedTestUserManager test_user_manager_;
140 #endif
141 };
142
143 TEST_F(ProfileManagerTest, GetProfile) {
144   base::FilePath dest_path = temp_dir_.path();
145   dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
146
147   ProfileManager* profile_manager = g_browser_process->profile_manager();
148
149   // Successfully create a profile.
150   Profile* profile = profile_manager->GetProfile(dest_path);
151   EXPECT_TRUE(profile);
152
153   // The profile already exists when we call GetProfile. Just load it.
154   EXPECT_EQ(profile, profile_manager->GetProfile(dest_path));
155 }
156
157 TEST_F(ProfileManagerTest, DefaultProfileDir) {
158   base::FilePath expected_default =
159       base::FilePath().AppendASCII(chrome::kInitialProfile);
160   EXPECT_EQ(
161       expected_default.value(),
162       g_browser_process->profile_manager()->GetInitialProfileDir().value());
163 }
164
165 #if defined(OS_CHROMEOS)
166 // This functionality only exists on Chrome OS.
167 TEST_F(ProfileManagerTest, LoggedInProfileDir) {
168   CommandLine *cl = CommandLine::ForCurrentProcess();
169   std::string profile_dir(chrome::kTestUserProfileDir);
170
171   cl->AppendSwitchASCII(chromeos::switches::kLoginProfile, profile_dir);
172
173   base::FilePath expected_default =
174       base::FilePath().AppendASCII(chrome::kInitialProfile);
175   ProfileManager* profile_manager = g_browser_process->profile_manager();
176   EXPECT_EQ(expected_default.value(),
177             profile_manager->GetInitialProfileDir().value());
178
179   scoped_ptr<chromeos::MockUserManager> mock_user_manager;
180   mock_user_manager.reset(new chromeos::MockUserManager());
181   mock_user_manager->SetActiveUser("user@gmail.com");
182   chromeos::User* active_user = mock_user_manager->GetActiveUser();
183   profile_manager->Observe(chrome::NOTIFICATION_LOGIN_USER_CHANGED,
184                            content::NotificationService::AllSources(),
185                            content::Details<const chromeos::User>(active_user));
186   base::FilePath expected_logged_in(profile_dir);
187   EXPECT_EQ(expected_logged_in.value(),
188             profile_manager->GetInitialProfileDir().value());
189   VLOG(1) << temp_dir_.path().Append(
190       profile_manager->GetInitialProfileDir()).value();
191 }
192
193 #endif
194
195 TEST_F(ProfileManagerTest, CreateAndUseTwoProfiles) {
196   base::FilePath dest_path1 = temp_dir_.path();
197   dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
198
199   base::FilePath dest_path2 = temp_dir_.path();
200   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
201
202   ProfileManager* profile_manager = g_browser_process->profile_manager();
203
204   // Successfully create the profiles.
205   TestingProfile* profile1 =
206       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
207   ASSERT_TRUE(profile1);
208
209   TestingProfile* profile2 =
210       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
211   ASSERT_TRUE(profile2);
212
213   // Force lazy-init of some profile services to simulate use.
214   ASSERT_TRUE(profile1->CreateHistoryService(true, false));
215   EXPECT_TRUE(HistoryServiceFactory::GetForProfile(profile1,
216                                                    Profile::EXPLICIT_ACCESS));
217   profile1->CreateBookmarkModel(true);
218   EXPECT_TRUE(BookmarkModelFactory::GetForProfile(profile1));
219   profile2->CreateBookmarkModel(true);
220   EXPECT_TRUE(BookmarkModelFactory::GetForProfile(profile2));
221   ASSERT_TRUE(profile2->CreateHistoryService(true, false));
222   EXPECT_TRUE(HistoryServiceFactory::GetForProfile(profile2,
223                                                    Profile::EXPLICIT_ACCESS));
224
225   // Make sure any pending tasks run before we destroy the profiles.
226     base::RunLoop().RunUntilIdle();
227
228   TestingBrowserProcess::GetGlobal()->SetProfileManager(NULL);
229
230   // Make sure history cleans up correctly.
231   base::RunLoop().RunUntilIdle();
232 }
233
234 MATCHER(NotFail, "Profile creation failure status is not reported.") {
235   return arg == Profile::CREATE_STATUS_CREATED ||
236          arg == Profile::CREATE_STATUS_INITIALIZED;
237 }
238
239 // Tests asynchronous profile creation mechanism.
240 // Crashes: http://crbug.com/89421
241 TEST_F(ProfileManagerTest, DISABLED_CreateProfileAsync) {
242   MockObserver mock_observer;
243   EXPECT_CALL(mock_observer, OnProfileCreated(
244       testing::NotNull(), NotFail())).Times(testing::AtLeast(1));
245
246   CreateProfileAsync(g_browser_process->profile_manager(),
247                      "New Profile", &mock_observer);
248
249   base::RunLoop().RunUntilIdle();
250 }
251
252 MATCHER(SameNotNull, "The same non-NULL value for all calls.") {
253   if (!g_created_profile)
254     g_created_profile = arg;
255   return arg != NULL && arg == g_created_profile;
256 }
257
258 TEST_F(ProfileManagerTest, CreateProfileAsyncMultipleRequests) {
259   g_created_profile = NULL;
260
261   MockObserver mock_observer1;
262   EXPECT_CALL(mock_observer1, OnProfileCreated(
263       SameNotNull(), NotFail())).Times(testing::AtLeast(1));
264   MockObserver mock_observer2;
265   EXPECT_CALL(mock_observer2, OnProfileCreated(
266       SameNotNull(), NotFail())).Times(testing::AtLeast(1));
267   MockObserver mock_observer3;
268   EXPECT_CALL(mock_observer3, OnProfileCreated(
269       SameNotNull(), NotFail())).Times(testing::AtLeast(1));
270
271   ProfileManager* profile_manager = g_browser_process->profile_manager();
272   const std::string profile_name = "New Profile";
273   CreateProfileAsync(profile_manager, profile_name, &mock_observer1);
274   CreateProfileAsync(profile_manager, profile_name, &mock_observer2);
275   CreateProfileAsync(profile_manager, profile_name, &mock_observer3);
276
277   base::RunLoop().RunUntilIdle();
278 }
279
280 TEST_F(ProfileManagerTest, CreateProfilesAsync) {
281   const std::string profile_name1 = "New Profile 1";
282   const std::string profile_name2 = "New Profile 2";
283
284   MockObserver mock_observer;
285   EXPECT_CALL(mock_observer, OnProfileCreated(
286       testing::NotNull(), NotFail())).Times(testing::AtLeast(3));
287
288   ProfileManager* profile_manager = g_browser_process->profile_manager();
289
290   CreateProfileAsync(profile_manager, profile_name1, &mock_observer);
291   CreateProfileAsync(profile_manager, profile_name2, &mock_observer);
292
293   base::RunLoop().RunUntilIdle();
294 }
295
296 TEST_F(ProfileManagerTest, GetGuestProfilePath) {
297   base::FilePath guest_path = ProfileManager::GetGuestProfilePath();
298   base::FilePath expected_path = temp_dir_.path();
299   expected_path = expected_path.Append(chrome::kGuestProfileDir);
300   EXPECT_EQ(expected_path, guest_path);
301 }
302
303 TEST_F(ProfileManagerTest, AutoloadProfilesWithBackgroundApps) {
304   ProfileManager* profile_manager = g_browser_process->profile_manager();
305   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
306   local_state_.Get()->SetUserPref(prefs::kBackgroundModeEnabled,
307                                   Value::CreateBooleanValue(true));
308
309   // Setting a pref which is not applicable to a system (i.e., Android in this
310   // case) does not necessarily create it. Don't bother continuing with the
311   // test if this pref doesn't exist because it will not load the profiles if
312   // it cannot verify that the pref for background mode is enabled.
313   if (!local_state_.Get()->HasPrefPath(prefs::kBackgroundModeEnabled))
314     return;
315
316   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
317   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_1"),
318                           ASCIIToUTF16("name_1"), string16(), 0, std::string());
319   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_2"),
320                           ASCIIToUTF16("name_2"), string16(), 0, std::string());
321   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_3"),
322                           ASCIIToUTF16("name_3"), string16(), 0, std::string());
323   cache.SetBackgroundStatusOfProfileAtIndex(0, true);
324   cache.SetBackgroundStatusOfProfileAtIndex(2, true);
325   EXPECT_EQ(3u, cache.GetNumberOfProfiles());
326
327   profile_manager->AutoloadProfiles();
328
329   EXPECT_EQ(2u, profile_manager->GetLoadedProfiles().size());
330 }
331
332 TEST_F(ProfileManagerTest, DoNotAutoloadProfilesIfBackgroundModeOff) {
333   ProfileManager* profile_manager = g_browser_process->profile_manager();
334   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
335   local_state_.Get()->SetUserPref(prefs::kBackgroundModeEnabled,
336                                   Value::CreateBooleanValue(false));
337
338   EXPECT_EQ(0u, cache.GetNumberOfProfiles());
339   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_1"),
340                           ASCIIToUTF16("name_1"), string16(), 0, std::string());
341   cache.AddProfileToCache(cache.GetUserDataDir().AppendASCII("path_2"),
342                           ASCIIToUTF16("name_2"), string16(), 0, std::string());
343   cache.SetBackgroundStatusOfProfileAtIndex(0, false);
344   cache.SetBackgroundStatusOfProfileAtIndex(1, true);
345   EXPECT_EQ(2u, cache.GetNumberOfProfiles());
346
347   profile_manager->AutoloadProfiles();
348
349   EXPECT_EQ(0u, profile_manager->GetLoadedProfiles().size());
350 }
351
352 TEST_F(ProfileManagerTest, InitProfileUserPrefs) {
353   base::FilePath dest_path = temp_dir_.path();
354   dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
355
356   ProfileManager* profile_manager = g_browser_process->profile_manager();
357
358   Profile* profile;
359
360   // Successfully create the profile
361   profile = profile_manager->GetProfile(dest_path);
362   ASSERT_TRUE(profile);
363
364   // Check that the profile name is non empty
365   std::string profile_name =
366       profile->GetPrefs()->GetString(prefs::kProfileName);
367   EXPECT_FALSE(profile_name.empty());
368
369   // Check that the profile avatar index is valid
370   size_t avatar_index =
371       profile->GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
372   EXPECT_TRUE(profile_manager->GetProfileInfoCache().IsDefaultAvatarIconIndex(
373       avatar_index));
374 }
375
376 // Tests that a new profile's entry in the profile info cache is setup with the
377 // same values that are in the profile prefs.
378 TEST_F(ProfileManagerTest, InitProfileInfoCacheForAProfile) {
379   base::FilePath dest_path = temp_dir_.path();
380   dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
381
382   ProfileManager* profile_manager = g_browser_process->profile_manager();
383   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
384
385   // Successfully create the profile
386   Profile* profile = profile_manager->GetProfile(dest_path);
387   ASSERT_TRUE(profile);
388
389   std::string profile_name =
390       profile->GetPrefs()->GetString(prefs::kProfileName);
391   size_t avatar_index =
392       profile->GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
393
394   size_t profile_index = cache.GetIndexOfProfileWithPath(dest_path);
395
396   // Check if the profile prefs are the same as the cache prefs
397   EXPECT_EQ(profile_name,
398             UTF16ToUTF8(cache.GetNameOfProfileAtIndex(profile_index)));
399   EXPECT_EQ(avatar_index,
400             cache.GetAvatarIconIndexOfProfileAtIndex(profile_index));
401 }
402
403 TEST_F(ProfileManagerTest, GetLastUsedProfileAllowedByPolicy) {
404   ProfileManager* profile_manager = g_browser_process->profile_manager();
405   ASSERT_TRUE(profile_manager);
406
407   Profile* profile = profile_manager->GetLastUsedProfileAllowedByPolicy();
408   ASSERT_TRUE(profile);
409   EXPECT_FALSE(profile->IsOffTheRecord());
410   PrefService* prefs = profile->GetPrefs();
411   EXPECT_EQ(IncognitoModePrefs::ENABLED,
412             IncognitoModePrefs::GetAvailability(prefs));
413
414   // Attach an incognito Profile to the TestingProfile.
415   ASSERT_FALSE(profile->GetOffTheRecordProfile());
416   TestingProfile::Builder builder;
417   builder.SetIncognito();
418   scoped_ptr<TestingProfile> incognito_profile = builder.Build();
419   EXPECT_TRUE(incognito_profile->IsOffTheRecord());
420   TestingProfile* testing_profile = static_cast<TestingProfile*>(profile);
421   testing_profile->SetOffTheRecordProfile(incognito_profile.PassAs<Profile>());
422   ASSERT_TRUE(profile->GetOffTheRecordProfile());
423
424   IncognitoModePrefs::SetAvailability(prefs, IncognitoModePrefs::DISABLED);
425   EXPECT_FALSE(
426       profile_manager->GetLastUsedProfileAllowedByPolicy()->IsOffTheRecord());
427
428   // GetLastUsedProfileAllowedByPolicy() returns the incognito Profile when
429   // incognito mode is forced.
430   IncognitoModePrefs::SetAvailability(prefs, IncognitoModePrefs::FORCED);
431   EXPECT_TRUE(
432       profile_manager->GetLastUsedProfileAllowedByPolicy()->IsOffTheRecord());
433 }
434
435 #if !defined(OS_ANDROID)
436 // There's no Browser object on Android.
437 TEST_F(ProfileManagerTest, LastOpenedProfiles) {
438   base::FilePath dest_path1 = temp_dir_.path();
439   dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
440
441   base::FilePath dest_path2 = temp_dir_.path();
442   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
443
444   ProfileManager* profile_manager = g_browser_process->profile_manager();
445
446   // Successfully create the profiles.
447   TestingProfile* profile1 =
448       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
449   ASSERT_TRUE(profile1);
450
451   TestingProfile* profile2 =
452       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
453   ASSERT_TRUE(profile2);
454
455   std::vector<Profile*> last_opened_profiles =
456       profile_manager->GetLastOpenedProfiles();
457   ASSERT_EQ(0U, last_opened_profiles.size());
458
459   // Create a browser for profile1.
460   Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
461   scoped_ptr<Browser> browser1a(
462       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
463
464   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
465   ASSERT_EQ(1U, last_opened_profiles.size());
466   EXPECT_EQ(profile1, last_opened_profiles[0]);
467
468   // And for profile2.
469   Browser::CreateParams profile2_params(profile2, chrome::GetActiveDesktop());
470   scoped_ptr<Browser> browser2(
471       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
472
473   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
474   ASSERT_EQ(2U, last_opened_profiles.size());
475   EXPECT_EQ(profile1, last_opened_profiles[0]);
476   EXPECT_EQ(profile2, last_opened_profiles[1]);
477
478   // Adding more browsers doesn't change anything.
479   scoped_ptr<Browser> browser1b(
480       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
481   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
482   ASSERT_EQ(2U, last_opened_profiles.size());
483   EXPECT_EQ(profile1, last_opened_profiles[0]);
484   EXPECT_EQ(profile2, last_opened_profiles[1]);
485
486   // Close the browsers.
487   browser1a.reset();
488   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
489   ASSERT_EQ(2U, last_opened_profiles.size());
490   EXPECT_EQ(profile1, last_opened_profiles[0]);
491   EXPECT_EQ(profile2, last_opened_profiles[1]);
492
493   browser1b.reset();
494   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
495   ASSERT_EQ(1U, last_opened_profiles.size());
496   EXPECT_EQ(profile2, last_opened_profiles[0]);
497
498   browser2.reset();
499   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
500   ASSERT_EQ(0U, last_opened_profiles.size());
501 }
502
503 TEST_F(ProfileManagerTest, LastOpenedProfilesAtShutdown) {
504   base::FilePath dest_path1 = temp_dir_.path();
505   dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
506
507   base::FilePath dest_path2 = temp_dir_.path();
508   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
509
510   ProfileManager* profile_manager = g_browser_process->profile_manager();
511
512   // Successfully create the profiles.
513   TestingProfile* profile1 =
514       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
515   ASSERT_TRUE(profile1);
516
517   TestingProfile* profile2 =
518       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
519   ASSERT_TRUE(profile2);
520
521   // Create a browser for profile1.
522   Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
523   scoped_ptr<Browser> browser1(
524       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
525
526   // And for profile2.
527   Browser::CreateParams profile2_params(profile2, chrome::GetActiveDesktop());
528   scoped_ptr<Browser> browser2(
529       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
530
531   std::vector<Profile*> last_opened_profiles =
532       profile_manager->GetLastOpenedProfiles();
533   ASSERT_EQ(2U, last_opened_profiles.size());
534   EXPECT_EQ(profile1, last_opened_profiles[0]);
535   EXPECT_EQ(profile2, last_opened_profiles[1]);
536
537   // Simulate a shutdown.
538   content::NotificationService::current()->Notify(
539       chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
540       content::NotificationService::AllSources(),
541       content::NotificationService::NoDetails());
542
543   // Even if the browsers are destructed during shutdown, the profiles stay
544   // open.
545   browser1.reset();
546   browser2.reset();
547
548   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
549   ASSERT_EQ(2U, last_opened_profiles.size());
550   EXPECT_EQ(profile1, last_opened_profiles[0]);
551   EXPECT_EQ(profile2, last_opened_profiles[1]);
552 }
553
554 TEST_F(ProfileManagerTest, LastOpenedProfilesDoesNotContainIncognito) {
555   base::FilePath dest_path1 = temp_dir_.path();
556   dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
557   base::FilePath dest_path2 = temp_dir_.path();
558   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
559
560   ProfileManager* profile_manager = g_browser_process->profile_manager();
561
562   // Successfully create the profiles.
563   TestingProfile* profile1 =
564       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
565   ASSERT_TRUE(profile1);
566
567   // incognito profiles should not be managed by the profile manager but by the
568   // original profile.
569   TestingProfile::Builder builder;
570   builder.SetIncognito();
571   scoped_ptr<TestingProfile> profile2 = builder.Build();
572   profile1->SetOffTheRecordProfile(profile2.PassAs<Profile>());
573
574   std::vector<Profile*> last_opened_profiles =
575       profile_manager->GetLastOpenedProfiles();
576   ASSERT_EQ(0U, last_opened_profiles.size());
577
578   // Create a browser for profile1.
579   Browser::CreateParams profile1_params(profile1, chrome::GetActiveDesktop());
580   scoped_ptr<Browser> browser1(
581       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
582
583   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
584   ASSERT_EQ(1U, last_opened_profiles.size());
585   EXPECT_EQ(profile1, last_opened_profiles[0]);
586
587   // And for profile2.
588   Browser::CreateParams profile2_params(profile1->GetOffTheRecordProfile(),
589                                         chrome::GetActiveDesktop());
590   scoped_ptr<Browser> browser2a(
591       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
592
593   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
594   ASSERT_EQ(1U, last_opened_profiles.size());
595   EXPECT_EQ(profile1, last_opened_profiles[0]);
596
597   // Adding more browsers doesn't change anything.
598   scoped_ptr<Browser> browser2b(
599       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
600   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
601   ASSERT_EQ(1U, last_opened_profiles.size());
602   EXPECT_EQ(profile1, last_opened_profiles[0]);
603
604   // Close the browsers.
605   browser2a.reset();
606   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
607   ASSERT_EQ(1U, last_opened_profiles.size());
608   EXPECT_EQ(profile1, last_opened_profiles[0]);
609
610   browser2b.reset();
611   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
612   ASSERT_EQ(1U, last_opened_profiles.size());
613   EXPECT_EQ(profile1, last_opened_profiles[0]);
614
615   browser1.reset();
616   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
617   ASSERT_EQ(0U, last_opened_profiles.size());
618 }
619 #endif  // !defined(OS_ANDROID)
620
621 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
622 // There's no Browser object on Android and there's no multi-profiles on Chrome.
623 TEST_F(ProfileManagerTest, EphemeralProfilesDontEndUpAsLastProfile) {
624   base::FilePath dest_path = temp_dir_.path();
625   dest_path = dest_path.Append(FILE_PATH_LITERAL("Ephemeral Profile"));
626
627   ProfileManager* profile_manager = g_browser_process->profile_manager();
628
629   TestingProfile* profile =
630       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path));
631   ASSERT_TRUE(profile);
632   profile->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles, true);
633
634   // Here the last used profile is still the "Default" profile.
635   Profile* last_used_profile = profile_manager->GetLastUsedProfile();
636   EXPECT_NE(profile, last_used_profile);
637
638   // Create a browser for the profile.
639   Browser::CreateParams profile_params(profile, chrome::GetActiveDesktop());
640   scoped_ptr<Browser> browser(
641       chrome::CreateBrowserWithTestWindowForParams(&profile_params));
642   last_used_profile = profile_manager->GetLastUsedProfile();
643   EXPECT_NE(profile, last_used_profile);
644
645   // Close the browser.
646   browser.reset();
647   last_used_profile = profile_manager->GetLastUsedProfile();
648   EXPECT_NE(profile, last_used_profile);
649 }
650
651 TEST_F(ProfileManagerTest, EphemeralProfilesDontEndUpAsLastOpenedAtShutdown) {
652   base::FilePath dest_path1 = temp_dir_.path();
653   dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("Normal Profile"));
654
655   base::FilePath dest_path2 = temp_dir_.path();
656   dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("Ephemeral Profile 1"));
657
658   base::FilePath dest_path3 = temp_dir_.path();
659   dest_path3 = dest_path3.Append(FILE_PATH_LITERAL("Ephemeral Profile 2"));
660
661   ProfileManager* profile_manager = g_browser_process->profile_manager();
662
663   // Successfully create the profiles.
664   TestingProfile* normal_profile =
665       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path1));
666   ASSERT_TRUE(normal_profile);
667
668   // Add one ephemeral profile which should not end up in this list.
669   TestingProfile* ephemeral_profile1 =
670       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path2));
671   ASSERT_TRUE(ephemeral_profile1);
672   ephemeral_profile1->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles,
673                                              true);
674
675   // Add second ephemeral profile but don't mark it as such yet.
676   TestingProfile* ephemeral_profile2 =
677       static_cast<TestingProfile*>(profile_manager->GetProfile(dest_path3));
678   ASSERT_TRUE(ephemeral_profile2);
679
680   // Create a browser for profile1.
681   Browser::CreateParams profile1_params(normal_profile,
682                                         chrome::GetActiveDesktop());
683   scoped_ptr<Browser> browser1(
684       chrome::CreateBrowserWithTestWindowForParams(&profile1_params));
685
686   // Create browsers for the ephemeral profile.
687   Browser::CreateParams profile2_params(ephemeral_profile1,
688                                         chrome::GetActiveDesktop());
689   scoped_ptr<Browser> browser2(
690       chrome::CreateBrowserWithTestWindowForParams(&profile2_params));
691
692   Browser::CreateParams profile3_params(ephemeral_profile2,
693                                         chrome::GetActiveDesktop());
694   scoped_ptr<Browser> browser3(
695       chrome::CreateBrowserWithTestWindowForParams(&profile3_params));
696
697   std::vector<Profile*> last_opened_profiles =
698       profile_manager->GetLastOpenedProfiles();
699   ASSERT_EQ(2U, last_opened_profiles.size());
700   EXPECT_EQ(normal_profile, last_opened_profiles[0]);
701   EXPECT_EQ(ephemeral_profile2, last_opened_profiles[1]);
702
703   // Mark the second profile ephemeral.
704   ephemeral_profile2->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles,
705                                              true);
706
707   // Simulate a shutdown.
708   content::NotificationService::current()->Notify(
709       chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
710       content::NotificationService::AllSources(),
711       content::NotificationService::NoDetails());
712   browser1.reset();
713   browser2.reset();
714   browser3.reset();
715
716   last_opened_profiles = profile_manager->GetLastOpenedProfiles();
717   ASSERT_EQ(1U, last_opened_profiles.size());
718   EXPECT_EQ(normal_profile, last_opened_profiles[0]);
719 }
720
721 TEST_F(ProfileManagerTest, ActiveProfileDeleted) {
722   ProfileManager* profile_manager = g_browser_process->profile_manager();
723   ASSERT_TRUE(profile_manager);
724
725   // Create and load two profiles.
726   const std::string profile_name1 = "New Profile 1";
727   const std::string profile_name2 = "New Profile 2";
728   base::FilePath dest_path1 =
729       temp_dir_.path().AppendASCII(profile_name1);
730   base::FilePath dest_path2 =
731       temp_dir_.path().AppendASCII(profile_name2);
732
733   MockObserver mock_observer;
734   EXPECT_CALL(mock_observer, OnProfileCreated(
735       testing::NotNull(), NotFail())).Times(testing::AtLeast(3));
736
737   CreateProfileAsync(profile_manager, profile_name1, &mock_observer);
738   CreateProfileAsync(profile_manager, profile_name2, &mock_observer);
739   base::RunLoop().RunUntilIdle();
740
741   EXPECT_EQ(2u, profile_manager->GetLoadedProfiles().size());
742   EXPECT_EQ(2u, profile_manager->GetProfileInfoCache().GetNumberOfProfiles());
743
744   // Set the active profile.
745   PrefService* local_state = g_browser_process->local_state();
746   local_state->SetString(prefs::kProfileLastUsed, profile_name1);
747
748   // Delete the active profile.
749   profile_manager->ScheduleProfileForDeletion(dest_path1,
750                                               ProfileManager::CreateCallback());
751   // Spin the message loop so that all the callbacks can finish running.
752   base::RunLoop().RunUntilIdle();
753
754   EXPECT_EQ(dest_path2, profile_manager->GetLastUsedProfile()->GetPath());
755   EXPECT_EQ(profile_name2, local_state->GetString(prefs::kProfileLastUsed));
756 }
757 #endif  // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
758
759 #if defined(OS_MACOSX)
760 // These tests are for a Mac-only code path that assumes the browser
761 // process isn't killed when all browser windows are closed.
762 TEST_F(ProfileManagerTest, ActiveProfileDeletedNeedsToLoadNextProfile) {
763   ProfileManager* profile_manager = g_browser_process->profile_manager();
764   ASSERT_TRUE(profile_manager);
765
766   // Create and load one profile, and just create a second profile.
767   const std::string profile_name1 = "New Profile 1";
768   const std::string profile_name2 = "New Profile 2";
769   base::FilePath dest_path1 =
770       temp_dir_.path().AppendASCII(profile_name1);
771   base::FilePath dest_path2 =
772       temp_dir_.path().AppendASCII(profile_name2);
773
774   MockObserver mock_observer;
775   EXPECT_CALL(mock_observer, OnProfileCreated(
776       testing::NotNull(), NotFail())).Times(testing::AtLeast(2));
777   CreateProfileAsync(profile_manager, profile_name1, &mock_observer);
778   base::RunLoop().RunUntilIdle();
779
780   // Track the profile, but don't load it.
781   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
782   cache.AddProfileToCache(dest_path2, ASCIIToUTF16(profile_name2),
783                           string16(), 0, std::string());
784   base::RunLoop().RunUntilIdle();
785
786   EXPECT_EQ(1u, profile_manager->GetLoadedProfiles().size());
787   EXPECT_EQ(2u, cache.GetNumberOfProfiles());
788
789   // Set the active profile.
790   PrefService* local_state = g_browser_process->local_state();
791   local_state->SetString(prefs::kProfileLastUsed,
792                          dest_path1.BaseName().MaybeAsASCII());
793
794   // Delete the active profile. This should switch and load the unloaded
795   // profile.
796   profile_manager->ScheduleProfileForDeletion(dest_path1,
797                                               ProfileManager::CreateCallback());
798
799   // Spin the message loop so that all the callbacks can finish running.
800   base::RunLoop().RunUntilIdle();
801
802   EXPECT_EQ(dest_path2, profile_manager->GetLastUsedProfile()->GetPath());
803   EXPECT_EQ(profile_name2, local_state->GetString(prefs::kProfileLastUsed));
804 }
805
806 // This tests the recursive call in ProfileManager::OnNewActiveProfileLoaded
807 // by simulating a scenario in which the profile that is being loaded as
808 // the next active profile has also been marked for deletion, so the
809 // ProfileManager needs to recursively select a different next profile.
810 TEST_F(ProfileManagerTest, ActiveProfileDeletedNextProfileDeletedToo) {
811   ProfileManager* profile_manager = g_browser_process->profile_manager();
812   ASSERT_TRUE(profile_manager);
813
814   // Create and load one profile, and create two more profiles.
815   const std::string profile_name1 = "New Profile 1";
816   const std::string profile_name2 = "New Profile 2";
817   const std::string profile_name3 = "New Profile 3";
818   base::FilePath dest_path1 =
819       temp_dir_.path().AppendASCII(profile_name1);
820   base::FilePath dest_path2 =
821       temp_dir_.path().AppendASCII(profile_name2);
822   base::FilePath dest_path3 =
823       temp_dir_.path().AppendASCII(profile_name3);
824
825   MockObserver mock_observer;
826   EXPECT_CALL(mock_observer, OnProfileCreated(
827       testing::NotNull(), NotFail())).Times(testing::AtLeast(2));
828   CreateProfileAsync(profile_manager, profile_name1, &mock_observer);
829   base::RunLoop().RunUntilIdle();
830
831   // Create the other profiles, but don't load them. Assign a fake avatar icon
832   // to ensure that profiles in the info cache are sorted by the profile name,
833   // and not randomly by the avatar name.
834   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
835   cache.AddProfileToCache(dest_path2, ASCIIToUTF16(profile_name2),
836                           ASCIIToUTF16(profile_name2), 1, std::string());
837   cache.AddProfileToCache(dest_path3, ASCIIToUTF16(profile_name3),
838                           ASCIIToUTF16(profile_name3), 2, std::string());
839
840   base::RunLoop().RunUntilIdle();
841
842   EXPECT_EQ(1u, profile_manager->GetLoadedProfiles().size());
843   EXPECT_EQ(3u, cache.GetNumberOfProfiles());
844
845   // Set the active profile.
846   PrefService* local_state = g_browser_process->local_state();
847   local_state->SetString(prefs::kProfileLastUsed,
848                          dest_path1.BaseName().MaybeAsASCII());
849
850   // Delete the active profile, Profile1.
851   // This will post a CreateProfileAsync message, that tries to load Profile2,
852   // which checks that the profile is not being deleted, and then calls back
853   // FinishDeletingProfile for Profile1.
854   // Try to break this flow by setting the active profile to Profile2 in the
855   // middle (so after the first posted message), and trying to delete Profile2,
856   // so that the ProfileManager has to look for a different profile to load.
857   profile_manager->ScheduleProfileForDeletion(dest_path1,
858                                               ProfileManager::CreateCallback());
859   local_state->SetString(prefs::kProfileLastUsed,
860                          dest_path2.BaseName().MaybeAsASCII());
861   profile_manager->ScheduleProfileForDeletion(dest_path2,
862                                               ProfileManager::CreateCallback());
863   // Spin the message loop so that all the callbacks can finish running.
864   base::RunLoop().RunUntilIdle();
865
866   EXPECT_EQ(dest_path3, profile_manager->GetLastUsedProfile()->GetPath());
867   EXPECT_EQ(profile_name3, local_state->GetString(prefs::kProfileLastUsed));
868 }
869 #endif  // !defined(OS_MACOSX)