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.
5 #include "chrome/browser/extensions/api/sessions/sessions_api.h"
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/local_device_info_provider_mock.h"
15 #include "chrome/browser/sync/open_tabs_ui_delegate.h"
16 #include "chrome/browser/sync/profile_sync_components_factory_mock.h"
17 #include "chrome/browser/sync/profile_sync_service.h"
18 #include "chrome/browser/sync/profile_sync_service_factory.h"
19 #include "chrome/browser/sync/profile_sync_service_mock.h"
20 #include "chrome/common/chrome_paths.h"
21 #include "chrome/common/chrome_switches.h"
22 #include "chrome/test/base/in_process_browser_test.h"
23 #include "chrome/test/base/test_switches.h"
24 #include "chrome/test/base/testing_browser_process.h"
25 #include "sync/api/attachments/attachment_id.h"
26 #include "sync/api/fake_sync_change_processor.h"
27 #include "sync/api/sync_error_factory_mock.h"
28 #include "sync/internal_api/public/attachments/attachment_service_proxy_for_test.h"
30 #if defined(OS_CHROMEOS)
31 #include "chromeos/chromeos_switches.h"
34 namespace utils = extension_function_test_utils;
36 namespace extensions {
40 // If more sessions are added to session tags, num sessions should be updated.
41 const char* kSessionTags[] = {"tag0", "tag1", "tag2", "tag3", "tag4"};
42 const size_t kNumSessions = 5;
44 void BuildSessionSpecifics(const std::string& tag,
45 sync_pb::SessionSpecifics* meta) {
46 meta->set_session_tag(tag);
47 sync_pb::SessionHeader* header = meta->mutable_header();
48 header->set_device_type(sync_pb::SyncEnums_DeviceType_TYPE_LINUX);
49 header->set_client_name(tag);
52 void BuildWindowSpecifics(int window_id,
53 const std::vector<int>& tab_list,
54 sync_pb::SessionSpecifics* meta) {
55 sync_pb::SessionHeader* header = meta->mutable_header();
56 sync_pb::SessionWindow* window = header->add_window();
57 window->set_window_id(window_id);
58 window->set_selected_tab_index(0);
59 window->set_browser_type(sync_pb::SessionWindow_BrowserType_TYPE_TABBED);
60 for (std::vector<int>::const_iterator iter = tab_list.begin();
61 iter != tab_list.end(); ++iter) {
62 window->add_tab(*iter);
66 void BuildTabSpecifics(const std::string& tag, int window_id, int tab_id,
67 sync_pb::SessionSpecifics* tab_base) {
68 tab_base->set_session_tag(tag);
69 tab_base->set_tab_node_id(0);
70 sync_pb::SessionTab* tab = tab_base->mutable_tab();
71 tab->set_tab_id(tab_id);
72 tab->set_tab_visual_index(1);
73 tab->set_current_navigation_index(0);
74 tab->set_pinned(true);
75 tab->set_extension_app_id("app_id");
76 sync_pb::TabNavigation* navigation = tab->add_navigation();
77 navigation->set_virtual_url("http://foo/1");
78 navigation->set_referrer("referrer");
79 navigation->set_title("title");
80 navigation->set_page_transition(sync_pb::SyncEnums_PageTransition_TYPED);
85 class ExtensionSessionsTest : public InProcessBrowserTest {
87 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE;
88 virtual void SetUpOnMainThread() OVERRIDE;
90 static KeyedService* BuildProfileSyncService(
91 content::BrowserContext* profile);
93 void CreateTestProfileSyncService();
94 void CreateTestExtension();
95 void CreateSessionModels();
98 scoped_refptr<T> CreateFunction(bool has_callback) {
99 scoped_refptr<T> fn(new T());
100 fn->set_extension(extension_.get());
101 fn->set_has_callback(has_callback);
106 scoped_refptr<extensions::Extension> extension_;
109 void ExtensionSessionsTest::SetUpCommandLine(CommandLine* command_line) {
110 #if defined(OS_CHROMEOS)
111 command_line->AppendSwitch(
112 chromeos::switches::kIgnoreUserProfileMappingForTests);
116 void ExtensionSessionsTest::SetUpOnMainThread() {
117 CreateTestProfileSyncService();
118 CreateTestExtension();
121 KeyedService* ExtensionSessionsTest::BuildProfileSyncService(
122 content::BrowserContext* profile) {
124 ProfileSyncComponentsFactoryMock* factory =
125 new ProfileSyncComponentsFactoryMock();
127 factory->SetLocalDeviceInfoProvider(
128 scoped_ptr<sync_driver::LocalDeviceInfoProvider>(
129 new browser_sync::LocalDeviceInfoProviderMock(
134 sync_pb::SyncEnums_DeviceType_TYPE_LINUX,
137 return new ProfileSyncServiceMock(
138 scoped_ptr<ProfileSyncComponentsFactory>(factory),
139 static_cast<Profile*>(profile));
142 void ExtensionSessionsTest::CreateTestProfileSyncService() {
143 ProfileManager* profile_manager = g_browser_process->profile_manager();
145 PathService::Get(chrome::DIR_USER_DATA, &path);
146 path = path.AppendASCII("test_profile");
147 if (!base::PathExists(path))
148 CHECK(base::CreateDirectory(path));
150 Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS);
151 profile_manager->RegisterTestingProfile(profile, true, false);
152 ProfileSyncServiceMock* service = static_cast<ProfileSyncServiceMock*>(
153 ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
154 profile, &ExtensionSessionsTest::BuildProfileSyncService));
155 browser_ = new Browser(Browser::CreateParams(
156 profile, chrome::HOST_DESKTOP_TYPE_NATIVE));
158 syncer::ModelTypeSet preferred_types;
159 preferred_types.Put(syncer::SESSIONS);
160 GoogleServiceAuthError no_error(GoogleServiceAuthError::NONE);
161 ON_CALL(*service, IsDataTypeControllerRunning(syncer::SESSIONS))
162 .WillByDefault(testing::Return(true));
163 ON_CALL(*service, GetRegisteredDataTypes())
164 .WillByDefault(testing::Return(syncer::UserTypes()));
165 ON_CALL(*service, GetPreferredDataTypes()).WillByDefault(
166 testing::Return(preferred_types));
167 EXPECT_CALL(*service, GetAuthError()).WillRepeatedly(
168 testing::ReturnRef(no_error));
169 ON_CALL(*service, GetActiveDataTypes()).WillByDefault(
170 testing::Return(preferred_types));
172 EXPECT_CALL(*service, AddObserver(testing::_)).Times(testing::AnyNumber());
173 EXPECT_CALL(*service, RemoveObserver(testing::_)).Times(testing::AnyNumber());
175 service->Initialize();
178 void ExtensionSessionsTest::CreateTestExtension() {
179 scoped_ptr<base::DictionaryValue> test_extension_value(
180 utils::ParseDictionary(
181 "{\"name\": \"Test\", \"version\": \"1.0\", "
182 "\"permissions\": [\"sessions\", \"tabs\"]}"));
183 extension_ = utils::CreateExtension(test_extension_value.get());
186 void ExtensionSessionsTest::CreateSessionModels() {
187 syncer::SyncDataList initial_data;
188 for (size_t index = 0; index < kNumSessions; ++index) {
189 // Fill an instance of session specifics with a foreign session's data.
190 sync_pb::SessionSpecifics meta;
191 BuildSessionSpecifics(kSessionTags[index], &meta);
192 SessionID::id_type tab_nums1[] = {5, 10, 13, 17};
193 std::vector<SessionID::id_type> tab_list1(
194 tab_nums1, tab_nums1 + arraysize(tab_nums1));
195 BuildWindowSpecifics(index, tab_list1, &meta);
196 std::vector<sync_pb::SessionSpecifics> tabs1;
197 tabs1.resize(tab_list1.size());
198 for (size_t i = 0; i < tab_list1.size(); ++i) {
199 BuildTabSpecifics(kSessionTags[index], 0, tab_list1[i], &tabs1[i]);
202 sync_pb::EntitySpecifics entity;
203 entity.mutable_session()->CopyFrom(meta);
204 initial_data.push_back(syncer::SyncData::CreateRemoteData(
208 syncer::AttachmentIdList(),
209 syncer::AttachmentServiceProxyForTest::Create()));
210 for (size_t i = 0; i < tabs1.size(); i++) {
211 sync_pb::EntitySpecifics entity;
212 entity.mutable_session()->CopyFrom(tabs1[i]);
213 initial_data.push_back(syncer::SyncData::CreateRemoteData(
217 syncer::AttachmentIdList(),
218 syncer::AttachmentServiceProxyForTest::Create()));
222 ProfileSyncServiceFactory::GetForProfile(browser_->profile())->
223 GetSessionsSyncableService()->
224 MergeDataAndStartSyncing(syncer::SESSIONS, initial_data,
225 scoped_ptr<syncer::SyncChangeProcessor>(
226 new syncer::FakeSyncChangeProcessor()),
227 scoped_ptr<syncer::SyncErrorFactory>(
228 new syncer::SyncErrorFactoryMock()));
231 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevices) {
232 CreateSessionModels();
234 scoped_ptr<base::ListValue> result(utils::ToList(
235 utils::RunFunctionAndReturnSingleResult(
236 CreateFunction<SessionsGetDevicesFunction>(true).get(),
237 "[{\"maxResults\": 0}]",
240 base::ListValue* devices = result.get();
241 EXPECT_EQ(5u, devices->GetSize());
242 base::DictionaryValue* device = NULL;
243 base::ListValue* sessions = NULL;
244 for (size_t i = 0; i < devices->GetSize(); ++i) {
245 EXPECT_TRUE(devices->GetDictionary(i, &device));
246 EXPECT_EQ(kSessionTags[i], utils::GetString(device, "info"));
247 EXPECT_EQ(kSessionTags[i], utils::GetString(device, "deviceName"));
248 EXPECT_TRUE(device->GetList("sessions", &sessions));
249 EXPECT_EQ(0u, sessions->GetSize());
253 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesMaxResults) {
254 CreateSessionModels();
256 scoped_ptr<base::ListValue> result(utils::ToList(
257 utils::RunFunctionAndReturnSingleResult(
258 CreateFunction<SessionsGetDevicesFunction>(true).get(),
262 base::ListValue* devices = result.get();
263 EXPECT_EQ(5u, devices->GetSize());
264 base::DictionaryValue* device = NULL;
265 base::ListValue* sessions = NULL;
266 for (size_t i = 0; i < devices->GetSize(); ++i) {
267 EXPECT_TRUE(devices->GetDictionary(i, &device));
268 EXPECT_EQ(kSessionTags[i], utils::GetString(device, "info"));
269 EXPECT_EQ(kSessionTags[i], utils::GetString(device, "deviceName"));
270 EXPECT_TRUE(device->GetList("sessions", &sessions));
271 EXPECT_EQ(1u, sessions->GetSize());
275 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesListEmpty) {
276 scoped_ptr<base::ListValue> result(utils::ToList(
277 utils::RunFunctionAndReturnSingleResult(
278 CreateFunction<SessionsGetDevicesFunction>(true).get(),
283 base::ListValue* devices = result.get();
284 EXPECT_EQ(0u, devices->GetSize());
287 // Flaky timeout: http://crbug.com/278372
288 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest,
289 DISABLED_RestoreForeignSessionWindow) {
290 CreateSessionModels();
292 scoped_ptr<base::DictionaryValue> restored_window_session(utils::ToDictionary(
293 utils::RunFunctionAndReturnSingleResult(
294 CreateFunction<SessionsRestoreFunction>(true).get(),
297 utils::INCLUDE_INCOGNITO)));
298 ASSERT_TRUE(restored_window_session);
300 scoped_ptr<base::ListValue> result(utils::ToList(
301 utils::RunFunctionAndReturnSingleResult(
302 CreateFunction<WindowsGetAllFunction>(true).get(),
307 base::ListValue* windows = result.get();
308 EXPECT_EQ(2u, windows->GetSize());
309 base::DictionaryValue* restored_window = NULL;
310 EXPECT_TRUE(restored_window_session->GetDictionary("window",
312 base::DictionaryValue* window = NULL;
313 int restored_id = utils::GetInteger(restored_window, "id");
314 for (size_t i = 0; i < windows->GetSize(); ++i) {
315 EXPECT_TRUE(windows->GetDictionary(i, &window));
316 if (utils::GetInteger(window, "id") == restored_id)
319 EXPECT_EQ(restored_id, utils::GetInteger(window, "id"));
322 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionInvalidId) {
323 CreateSessionModels();
325 EXPECT_TRUE(MatchPattern(utils::RunFunctionAndReturnError(
326 CreateFunction<SessionsRestoreFunction>(true).get(),
328 browser_), "Invalid session id: \"tag3.0\"."));
331 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreInIncognito) {
332 CreateSessionModels();
334 EXPECT_TRUE(MatchPattern(utils::RunFunctionAndReturnError(
335 CreateFunction<SessionsRestoreFunction>(true).get(),
337 CreateIncognitoBrowser()),
338 "Can not restore sessions in incognito mode."));
341 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetRecentlyClosedIncognito) {
342 scoped_ptr<base::ListValue> result(utils::ToList(
343 utils::RunFunctionAndReturnSingleResult(
344 CreateFunction<SessionsGetRecentlyClosedFunction>(true).get(),
346 CreateIncognitoBrowser())));
348 base::ListValue* sessions = result.get();
349 EXPECT_EQ(0u, sessions->GetSize());
352 // Flaky on ChromeOS, times out on OSX Debug http://crbug.com/251199
353 #if defined(OS_CHROMEOS) || (defined(OS_MACOSX) && !defined(NDEBUG))
354 #define MAYBE_SessionsApis DISABLED_SessionsApis
356 #define MAYBE_SessionsApis SessionsApis
358 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_SessionsApis) {
359 #if defined(OS_WIN) && defined(USE_ASH)
360 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
361 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
365 ASSERT_TRUE(RunExtensionSubtest("sessions",
366 "sessions.html")) << message_;
369 } // namespace extensions