Home | History | Annotate | Download | only in sessions
      1 // Copyright 2013 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "chrome/browser/extensions/api/sessions/sessions_api.h"
      6 
      7 #include "base/command_line.h"
      8 #include "base/path_service.h"
      9 #include "base/strings/stringprintf.h"
     10 #include "chrome/browser/extensions/api/tabs/tabs_api.h"
     11 #include "chrome/browser/extensions/extension_apitest.h"
     12 #include "chrome/browser/extensions/extension_function_test_utils.h"
     13 #include "chrome/browser/profiles/profile_manager.h"
     14 #include "chrome/browser/sync/glue/session_model_associator.h"
     15 #include "chrome/browser/sync/open_tabs_ui_delegate.h"
     16 #include "chrome/browser/sync/profile_sync_service.h"
     17 #include "chrome/browser/sync/profile_sync_service_factory.h"
     18 #include "chrome/browser/sync/profile_sync_service_mock.h"
     19 #include "chrome/common/chrome_paths.h"
     20 #include "chrome/test/base/in_process_browser_test.h"
     21 #include "chrome/test/base/test_switches.h"
     22 #include "chrome/test/base/testing_browser_process.h"
     23 
     24 namespace utils = extension_function_test_utils;
     25 
     26 namespace extensions {
     27 
     28 namespace {
     29 
     30 // If more sessions are added to session tags, num sessions should be updated.
     31 const char* kSessionTags[] = {"tag0", "tag1", "tag2", "tag3", "tag4"};
     32 const size_t kNumSessions = 5;
     33 
     34 void BuildSessionSpecifics(const std::string& tag,
     35                            sync_pb::SessionSpecifics* meta) {
     36   meta->set_session_tag(tag);
     37   sync_pb::SessionHeader* header = meta->mutable_header();
     38   header->set_device_type(sync_pb::SyncEnums_DeviceType_TYPE_LINUX);
     39   header->set_client_name(tag);
     40 }
     41 
     42 void BuildWindowSpecifics(int window_id,
     43                           const std::vector<int>& tab_list,
     44                           sync_pb::SessionSpecifics* meta) {
     45   sync_pb::SessionHeader* header = meta->mutable_header();
     46   sync_pb::SessionWindow* window = header->add_window();
     47   window->set_window_id(window_id);
     48   window->set_selected_tab_index(0);
     49   window->set_browser_type(sync_pb::SessionWindow_BrowserType_TYPE_TABBED);
     50   for (std::vector<int>::const_iterator iter = tab_list.begin();
     51        iter != tab_list.end(); ++iter) {
     52     window->add_tab(*iter);
     53   }
     54 }
     55 
     56 void BuildTabSpecifics(const std::string& tag, int window_id, int tab_id,
     57                        sync_pb::SessionSpecifics* tab_base) {
     58   tab_base->set_session_tag(tag);
     59   tab_base->set_tab_node_id(0);
     60   sync_pb::SessionTab* tab = tab_base->mutable_tab();
     61   tab->set_tab_id(tab_id);
     62   tab->set_tab_visual_index(1);
     63   tab->set_current_navigation_index(0);
     64   tab->set_pinned(true);
     65   tab->set_extension_app_id("app_id");
     66   sync_pb::TabNavigation* navigation = tab->add_navigation();
     67   navigation->set_virtual_url("http://foo/1");
     68   navigation->set_referrer("referrer");
     69   navigation->set_title("title");
     70   navigation->set_page_transition(sync_pb::SyncEnums_PageTransition_TYPED);
     71 }
     72 
     73 } // namespace
     74 
     75 class ExtensionSessionsTest : public InProcessBrowserTest {
     76  public:
     77   virtual void SetUpOnMainThread() OVERRIDE;
     78  protected:
     79   void CreateTestProfileSyncService();
     80   void CreateTestExtension();
     81   void CreateSessionModels();
     82 
     83   template <class T>
     84   scoped_refptr<T> CreateFunction(bool has_callback) {
     85     scoped_refptr<T> fn(new T());
     86     fn->set_extension(extension_.get());
     87     fn->set_has_callback(has_callback);
     88     return fn;
     89   };
     90 
     91   Browser* browser_;
     92   browser_sync::SessionModelAssociator* associator_;
     93   scoped_refptr<extensions::Extension> extension_;
     94 };
     95 
     96 void ExtensionSessionsTest::SetUpOnMainThread() {
     97   CreateTestProfileSyncService();
     98   CreateTestExtension();
     99 }
    100 
    101 void ExtensionSessionsTest::CreateTestProfileSyncService() {
    102   ProfileManager* profile_manager = g_browser_process->profile_manager();
    103   base::FilePath path;
    104   PathService::Get(chrome::DIR_USER_DATA, &path);
    105   path = path.AppendASCII("test_profile");
    106   if (!base::PathExists(path))
    107     CHECK(base::CreateDirectory(path));
    108   Profile* profile =
    109       Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS);
    110   profile_manager->RegisterTestingProfile(profile, true, false);
    111   browser_ = new Browser(Browser::CreateParams(
    112       profile, chrome::HOST_DESKTOP_TYPE_NATIVE));
    113   ProfileSyncServiceMock* service = static_cast<ProfileSyncServiceMock*>(
    114       ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
    115       profile, &ProfileSyncServiceMock::BuildMockProfileSyncService));
    116 
    117   associator_ = new browser_sync::SessionModelAssociator(
    118       static_cast<ProfileSyncService*>(service), true);
    119   syncer::ModelTypeSet preferred_types;
    120   preferred_types.Put(syncer::SESSIONS);
    121   GoogleServiceAuthError no_error(GoogleServiceAuthError::NONE);
    122 
    123   ON_CALL(*service, GetOpenTabsUIDelegate()).WillByDefault(
    124       testing::Return(associator_));
    125   ON_CALL(*service, GetPreferredDataTypes()).WillByDefault(
    126       testing::Return(preferred_types));
    127   EXPECT_CALL(*service, GetAuthError()).WillRepeatedly(
    128       testing::ReturnRef(no_error));
    129   ON_CALL(*service, GetActiveDataTypes()).WillByDefault(
    130       testing::Return(preferred_types));
    131   EXPECT_CALL(*service, AddObserver(testing::_)).Times(testing::AnyNumber());
    132   EXPECT_CALL(*service, RemoveObserver(testing::_)).Times(testing::AnyNumber());
    133 
    134   service->Initialize();
    135 }
    136 
    137 void ExtensionSessionsTest::CreateTestExtension() {
    138   scoped_ptr<base::DictionaryValue> test_extension_value(
    139       utils::ParseDictionary(
    140       "{\"name\": \"Test\", \"version\": \"1.0\", "
    141       "\"permissions\": [\"sessions\", \"tabs\"]}"));
    142   extension_ = utils::CreateExtension(test_extension_value.get());
    143 }
    144 
    145 void ExtensionSessionsTest::CreateSessionModels() {
    146   for (size_t index = 0; index < kNumSessions; ++index) {
    147     // Fill an instance of session specifics with a foreign session's data.
    148     sync_pb::SessionSpecifics meta;
    149     BuildSessionSpecifics(kSessionTags[index], &meta);
    150     SessionID::id_type tab_nums1[] = {5, 10, 13, 17};
    151     std::vector<SessionID::id_type> tab_list1(
    152         tab_nums1, tab_nums1 + arraysize(tab_nums1));
    153     BuildWindowSpecifics(index, tab_list1, &meta);
    154     std::vector<sync_pb::SessionSpecifics> tabs1;
    155     tabs1.resize(tab_list1.size());
    156     for (size_t i = 0; i < tab_list1.size(); ++i) {
    157       BuildTabSpecifics(kSessionTags[index], 0, tab_list1[i], &tabs1[i]);
    158     }
    159 
    160     associator_->SetCurrentMachineTagForTesting(kSessionTags[index]);
    161     // Update associator with the session's meta node containing one window.
    162     associator_->AssociateForeignSpecifics(meta, base::Time());
    163     // Add tabs for the window.
    164     for (std::vector<sync_pb::SessionSpecifics>::iterator iter = tabs1.begin();
    165          iter != tabs1.end(); ++iter) {
    166       associator_->AssociateForeignSpecifics(*iter, base::Time());
    167     }
    168   }
    169 }
    170 
    171 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevices) {
    172   CreateSessionModels();
    173 
    174   scoped_ptr<base::ListValue> result(utils::ToList(
    175       utils::RunFunctionAndReturnSingleResult(
    176           CreateFunction<SessionsGetDevicesFunction>(true).get(),
    177           "[{\"maxResults\": 0}]",
    178           browser_)));
    179   ASSERT_TRUE(result);
    180   ListValue* devices = result.get();
    181   EXPECT_EQ(5u, devices->GetSize());
    182   DictionaryValue* device = NULL;
    183   ListValue* sessions = NULL;
    184   for (size_t i = 0; i < devices->GetSize(); ++i) {
    185     EXPECT_TRUE(devices->GetDictionary(i, &device));
    186     EXPECT_EQ(kSessionTags[i], utils::GetString(device, "info"));
    187     EXPECT_TRUE(device->GetList("sessions", &sessions));
    188     EXPECT_EQ(0u, sessions->GetSize());
    189   }
    190 }
    191 
    192 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesMaxResults) {
    193   CreateSessionModels();
    194 
    195   scoped_ptr<base::ListValue> result(utils::ToList(
    196       utils::RunFunctionAndReturnSingleResult(
    197           CreateFunction<SessionsGetDevicesFunction>(true).get(),
    198           "[]",
    199           browser_)));
    200   ASSERT_TRUE(result);
    201   ListValue* devices = result.get();
    202   EXPECT_EQ(5u, devices->GetSize());
    203   DictionaryValue* device = NULL;
    204   ListValue* sessions = NULL;
    205   for (size_t i = 0; i < devices->GetSize(); ++i) {
    206     EXPECT_TRUE(devices->GetDictionary(i, &device));
    207     EXPECT_EQ(kSessionTags[i], utils::GetString(device, "info"));
    208     EXPECT_TRUE(device->GetList("sessions", &sessions));
    209     EXPECT_EQ(1u, sessions->GetSize());
    210   }
    211 }
    212 
    213 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesListEmpty) {
    214   scoped_ptr<base::ListValue> result(utils::ToList(
    215       utils::RunFunctionAndReturnSingleResult(
    216           CreateFunction<SessionsGetDevicesFunction>(true).get(),
    217           "[]",
    218           browser_)));
    219 
    220   ASSERT_TRUE(result);
    221   ListValue* devices = result.get();
    222   EXPECT_EQ(0u, devices->GetSize());
    223 }
    224 
    225 // Flaky timeout: http://crbug.com/278372
    226 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest,
    227                        DISABLED_RestoreForeignSessionWindow) {
    228   CreateSessionModels();
    229 
    230   scoped_ptr<base::DictionaryValue> restored_window_session(utils::ToDictionary(
    231       utils::RunFunctionAndReturnSingleResult(
    232           CreateFunction<SessionsRestoreFunction>(true).get(),
    233           "[\"tag3.3\"]",
    234           browser_,
    235           utils::INCLUDE_INCOGNITO)));
    236   ASSERT_TRUE(restored_window_session);
    237 
    238   scoped_ptr<base::ListValue> result(utils::ToList(
    239       utils::RunFunctionAndReturnSingleResult(
    240           CreateFunction<WindowsGetAllFunction>(true).get(),
    241           "[]",
    242           browser_)));
    243   ASSERT_TRUE(result);
    244 
    245   ListValue* windows = result.get();
    246   EXPECT_EQ(2u, windows->GetSize());
    247   DictionaryValue* restored_window = NULL;
    248   EXPECT_TRUE(restored_window_session->GetDictionary("window",
    249                                                      &restored_window));
    250   DictionaryValue* window = NULL;
    251   int restored_id = utils::GetInteger(restored_window, "id");
    252   for (size_t i = 0; i < windows->GetSize(); ++i) {
    253     EXPECT_TRUE(windows->GetDictionary(i, &window));
    254     if (utils::GetInteger(window, "id") == restored_id)
    255       break;
    256   }
    257   EXPECT_EQ(restored_id, utils::GetInteger(window, "id"));
    258 }
    259 
    260 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionInvalidId) {
    261   CreateSessionModels();
    262 
    263   EXPECT_TRUE(MatchPattern(utils::RunFunctionAndReturnError(
    264       CreateFunction<SessionsRestoreFunction>(true).get(),
    265       "[\"tag3.0\"]",
    266       browser_), "Invalid session id: \"tag3.0\"."));
    267 }
    268 
    269 // Flaky on ChromeOS, times out on OSX Debug http://crbug.com/251199
    270 #if defined(OS_CHROMEOS) || (defined(OS_MACOSX) && !defined(NDEBUG))
    271 #define MAYBE_SessionsApis DISABLED_SessionsApis
    272 #else
    273 #define MAYBE_SessionsApis SessionsApis
    274 #endif
    275 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_SessionsApis) {
    276 #if defined(OS_WIN) && defined(USE_ASH)
    277   // Disable this test in Metro+Ash for now (http://crbug.com/262796).
    278   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
    279     return;
    280 #endif
    281 
    282   ASSERT_TRUE(RunExtensionSubtest("sessions",
    283                                   "sessions.html")) << message_;
    284 }
    285 
    286 }  // namespace extensions
    287