1 // Copyright (c) 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/test/chromedriver/session_commands.h"
10 #include "base/callback.h"
11 #include "base/files/file_util.h"
12 #include "base/logging.h" // For CHECK macros.
13 #include "base/memory/ref_counted.h"
14 #include "base/synchronization/lock.h"
15 #include "base/synchronization/waitable_event.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/values.h"
18 #include "chrome/test/chromedriver/basic_types.h"
19 #include "chrome/test/chromedriver/capabilities.h"
20 #include "chrome/test/chromedriver/chrome/automation_extension.h"
21 #include "chrome/test/chromedriver/chrome/browser_info.h"
22 #include "chrome/test/chromedriver/chrome/chrome.h"
23 #include "chrome/test/chromedriver/chrome/chrome_android_impl.h"
24 #include "chrome/test/chromedriver/chrome/chrome_desktop_impl.h"
25 #include "chrome/test/chromedriver/chrome/device_manager.h"
26 #include "chrome/test/chromedriver/chrome/devtools_event_listener.h"
27 #include "chrome/test/chromedriver/chrome/geoposition.h"
28 #include "chrome/test/chromedriver/chrome/status.h"
29 #include "chrome/test/chromedriver/chrome/web_view.h"
30 #include "chrome/test/chromedriver/chrome_launcher.h"
31 #include "chrome/test/chromedriver/command_listener.h"
32 #include "chrome/test/chromedriver/logging.h"
33 #include "chrome/test/chromedriver/net/url_request_context_getter.h"
34 #include "chrome/test/chromedriver/session.h"
35 #include "chrome/test/chromedriver/util.h"
36 #include "chrome/test/chromedriver/version.h"
40 const char kWindowHandlePrefix
[] = "CDwindow-";
42 std::string
WebViewIdToWindowHandle(const std::string
& web_view_id
) {
43 return kWindowHandlePrefix
+ web_view_id
;
46 bool WindowHandleToWebViewId(const std::string
& window_handle
,
47 std::string
* web_view_id
) {
48 if (window_handle
.find(kWindowHandlePrefix
) != 0u)
50 *web_view_id
= window_handle
.substr(
51 std::string(kWindowHandlePrefix
).length());
57 InitSessionParams::InitSessionParams(
58 scoped_refptr
<URLRequestContextGetter
> context_getter
,
59 const SyncWebSocketFactory
& socket_factory
,
60 DeviceManager
* device_manager
,
61 PortServer
* port_server
,
62 PortManager
* port_manager
)
63 : context_getter(context_getter
),
64 socket_factory(socket_factory
),
65 device_manager(device_manager
),
66 port_server(port_server
),
67 port_manager(port_manager
) {}
69 InitSessionParams::~InitSessionParams() {}
73 scoped_ptr
<base::DictionaryValue
> CreateCapabilities(Chrome
* chrome
) {
74 scoped_ptr
<base::DictionaryValue
> caps(new base::DictionaryValue());
75 caps
->SetString("browserName", "chrome");
76 caps
->SetString("version", chrome
->GetBrowserInfo()->browser_version
);
77 caps
->SetString("chrome.chromedriverVersion", kChromeDriverVersion
);
78 caps
->SetString("platform", chrome
->GetOperatingSystemName());
79 caps
->SetBoolean("javascriptEnabled", true);
80 caps
->SetBoolean("takesScreenshot", true);
81 caps
->SetBoolean("takesHeapSnapshot", true);
82 caps
->SetBoolean("handlesAlerts", true);
83 caps
->SetBoolean("databaseEnabled", false);
84 caps
->SetBoolean("locationContextEnabled", true);
85 caps
->SetBoolean("mobileEmulationEnabled",
86 chrome
->IsMobileEmulationEnabled());
87 caps
->SetBoolean("applicationCacheEnabled", false);
88 caps
->SetBoolean("browserConnectionEnabled", false);
89 caps
->SetBoolean("cssSelectorsEnabled", true);
90 caps
->SetBoolean("webStorageEnabled", true);
91 caps
->SetBoolean("rotatable", false);
92 caps
->SetBoolean("acceptSslCerts", true);
93 caps
->SetBoolean("nativeEvents", true);
94 caps
->SetBoolean("hasTouchScreen", chrome
->HasTouchScreen());
95 scoped_ptr
<base::DictionaryValue
> chrome_caps(new base::DictionaryValue());
97 ChromeDesktopImpl
* desktop
= NULL
;
98 Status status
= chrome
->GetAsDesktop(&desktop
);
100 chrome_caps
->SetString(
102 desktop
->command().GetSwitchValueNative("user-data-dir"));
105 caps
->Set("chrome", chrome_caps
.release());
109 Status
CheckSessionCreated(Session
* session
) {
110 WebView
* web_view
= NULL
;
111 Status status
= session
->GetTargetWindow(&web_view
);
112 if (status
.IsError())
113 return Status(kSessionNotCreatedException
, status
);
115 status
= web_view
->ConnectIfNecessary();
116 if (status
.IsError())
117 return Status(kSessionNotCreatedException
, status
);
119 base::ListValue args
;
120 scoped_ptr
<base::Value
> result(new base::FundamentalValue(0));
121 status
= web_view
->CallFunction(session
->GetCurrentFrameId(),
122 "function(s) { return 1; }", args
, &result
);
123 if (status
.IsError())
124 return Status(kSessionNotCreatedException
, status
);
127 if (!result
->GetAsInteger(&response
) || response
!= 1) {
128 return Status(kSessionNotCreatedException
,
129 "unexpected response from browser");
135 Status
InitSessionHelper(
136 const InitSessionParams
& bound_params
,
138 const base::DictionaryValue
& params
,
139 scoped_ptr
<base::Value
>* value
) {
140 session
->driver_log
.reset(
141 new WebDriverLog(WebDriverLog::kDriverType
, Log::kAll
));
142 const base::DictionaryValue
* desired_caps
;
143 if (!params
.GetDictionary("desiredCapabilities", &desired_caps
))
144 return Status(kUnknownError
, "cannot find dict 'desiredCapabilities'");
146 Capabilities capabilities
;
147 Status status
= capabilities
.Parse(*desired_caps
);
148 if (status
.IsError())
151 Log::Level driver_level
= Log::kWarning
;
152 if (capabilities
.logging_prefs
.count(WebDriverLog::kDriverType
))
153 driver_level
= capabilities
.logging_prefs
[WebDriverLog::kDriverType
];
154 session
->driver_log
->set_min_level(driver_level
);
156 // Create Log's and DevToolsEventListener's for ones that are DevTools-based.
157 // Session will own the Log's, Chrome will own the listeners.
158 // Also create |CommandListener|s for the appropriate logs.
159 ScopedVector
<DevToolsEventListener
> devtools_event_listeners
;
160 ScopedVector
<CommandListener
> command_listeners
;
161 status
= CreateLogs(capabilities
,
163 &session
->devtools_logs
,
164 &devtools_event_listeners
,
166 if (status
.IsError())
169 // |session| will own the |CommandListener|s.
170 session
->command_listeners
.swap(command_listeners
);
172 status
= LaunchChrome(bound_params
.context_getter
.get(),
173 bound_params
.socket_factory
,
174 bound_params
.device_manager
,
175 bound_params
.port_server
,
176 bound_params
.port_manager
,
178 &devtools_event_listeners
,
180 if (status
.IsError())
183 std::list
<std::string
> web_view_ids
;
184 status
= session
->chrome
->GetWebViewIds(&web_view_ids
);
185 if (status
.IsError() || web_view_ids
.empty()) {
186 return status
.IsError() ? status
:
187 Status(kUnknownError
, "unable to discover open window in chrome");
190 session
->window
= web_view_ids
.front();
191 session
->detach
= capabilities
.detach
;
192 session
->force_devtools_screenshot
= capabilities
.force_devtools_screenshot
;
193 session
->capabilities
= CreateCapabilities(session
->chrome
.get());
194 value
->reset(session
->capabilities
->DeepCopy());
195 return CheckSessionCreated(session
);
200 Status
ExecuteInitSession(
201 const InitSessionParams
& bound_params
,
203 const base::DictionaryValue
& params
,
204 scoped_ptr
<base::Value
>* value
) {
205 Status status
= InitSessionHelper(bound_params
, session
, params
, value
);
206 if (status
.IsError()) {
207 session
->quit
= true;
208 if (session
->chrome
!= NULL
)
209 session
->chrome
->Quit();
217 const base::DictionaryValue
& params
,
218 scoped_ptr
<base::Value
>* value
) {
219 session
->quit
= true;
220 if (allow_detach
&& session
->detach
)
223 return session
->chrome
->Quit();
226 Status
ExecuteGetSessionCapabilities(
228 const base::DictionaryValue
& params
,
229 scoped_ptr
<base::Value
>* value
) {
230 value
->reset(session
->capabilities
->DeepCopy());
234 Status
ExecuteGetCurrentWindowHandle(
236 const base::DictionaryValue
& params
,
237 scoped_ptr
<base::Value
>* value
) {
238 WebView
* web_view
= NULL
;
239 Status status
= session
->GetTargetWindow(&web_view
);
240 if (status
.IsError())
244 new base::StringValue(WebViewIdToWindowHandle(web_view
->GetId())));
248 Status
ExecuteLaunchApp(
250 const base::DictionaryValue
& params
,
251 scoped_ptr
<base::Value
>* value
) {
253 if (!params
.GetString("id", &id
))
254 return Status(kUnknownError
, "'id' must be a string");
256 ChromeDesktopImpl
* desktop
= NULL
;
257 Status status
= session
->chrome
->GetAsDesktop(&desktop
);
258 if (status
.IsError())
261 AutomationExtension
* extension
= NULL
;
262 status
= desktop
->GetAutomationExtension(&extension
);
263 if (status
.IsError())
266 return extension
->LaunchApp(id
);
271 const base::DictionaryValue
& params
,
272 scoped_ptr
<base::Value
>* value
) {
273 std::list
<std::string
> web_view_ids
;
274 Status status
= session
->chrome
->GetWebViewIds(&web_view_ids
);
275 if (status
.IsError())
277 bool is_last_web_view
= web_view_ids
.size() == 1u;
278 web_view_ids
.clear();
280 WebView
* web_view
= NULL
;
281 status
= session
->GetTargetWindow(&web_view
);
282 if (status
.IsError())
285 status
= session
->chrome
->CloseWebView(web_view
->GetId());
286 if (status
.IsError())
289 status
= session
->chrome
->GetWebViewIds(&web_view_ids
);
290 if ((status
.code() == kChromeNotReachable
&& is_last_web_view
) ||
291 (status
.IsOk() && web_view_ids
.empty())) {
292 // If no window is open, close is the equivalent of calling "quit".
293 session
->quit
= true;
294 return session
->chrome
->Quit();
300 Status
ExecuteGetWindowHandles(
302 const base::DictionaryValue
& params
,
303 scoped_ptr
<base::Value
>* value
) {
304 std::list
<std::string
> web_view_ids
;
305 Status status
= session
->chrome
->GetWebViewIds(&web_view_ids
);
306 if (status
.IsError())
308 scoped_ptr
<base::ListValue
> window_ids(new base::ListValue());
309 for (std::list
<std::string
>::const_iterator it
= web_view_ids
.begin();
310 it
!= web_view_ids
.end(); ++it
) {
311 window_ids
->AppendString(WebViewIdToWindowHandle(*it
));
313 value
->reset(window_ids
.release());
317 Status
ExecuteSwitchToWindow(
319 const base::DictionaryValue
& params
,
320 scoped_ptr
<base::Value
>* value
) {
322 if (!params
.GetString("name", &name
) || name
.empty())
323 return Status(kUnknownError
, "'name' must be a nonempty string");
325 std::list
<std::string
> web_view_ids
;
326 Status status
= session
->chrome
->GetWebViewIds(&web_view_ids
);
327 if (status
.IsError())
330 std::string web_view_id
;
332 if (WindowHandleToWebViewId(name
, &web_view_id
)) {
333 // Check if any web_view matches |web_view_id|.
334 for (std::list
<std::string
>::const_iterator it
= web_view_ids
.begin();
335 it
!= web_view_ids
.end(); ++it
) {
336 if (*it
== web_view_id
) {
342 // Check if any of the tab window names match |name|.
343 const char* kGetWindowNameScript
= "function() { return window.name; }";
344 base::ListValue args
;
345 for (std::list
<std::string
>::const_iterator it
= web_view_ids
.begin();
346 it
!= web_view_ids
.end(); ++it
) {
347 scoped_ptr
<base::Value
> result
;
349 status
= session
->chrome
->GetWebViewById(*it
, &web_view
);
350 if (status
.IsError())
352 status
= web_view
->ConnectIfNecessary();
353 if (status
.IsError())
355 status
= web_view
->CallFunction(
356 std::string(), kGetWindowNameScript
, args
, &result
);
357 if (status
.IsError())
359 std::string window_name
;
360 if (!result
->GetAsString(&window_name
))
361 return Status(kUnknownError
, "failed to get window name");
362 if (window_name
== name
) {
371 return Status(kNoSuchWindow
);
373 if (session
->overridden_geoposition
) {
375 Status status
= session
->chrome
->GetWebViewById(web_view_id
, &web_view
);
376 if (status
.IsError())
378 status
= web_view
->ConnectIfNecessary();
379 if (status
.IsError())
381 status
= web_view
->OverrideGeolocation(*session
->overridden_geoposition
);
382 if (status
.IsError())
386 if (session
->overridden_network_conditions
) {
388 Status status
= session
->chrome
->GetWebViewById(web_view_id
, &web_view
);
389 if (status
.IsError())
391 status
= web_view
->ConnectIfNecessary();
392 if (status
.IsError())
394 status
= web_view
->OverrideNetworkConditions(
395 *session
->overridden_network_conditions
);
396 if (status
.IsError())
400 session
->window
= web_view_id
;
401 session
->SwitchToTopFrame();
402 session
->mouse_position
= WebPoint(0, 0);
406 Status
ExecuteSetTimeout(
408 const base::DictionaryValue
& params
,
409 scoped_ptr
<base::Value
>* value
) {
411 if (!params
.GetDouble("ms", &ms_double
))
412 return Status(kUnknownError
, "'ms' must be a double");
414 if (!params
.GetString("type", &type
))
415 return Status(kUnknownError
, "'type' must be a string");
417 base::TimeDelta timeout
=
418 base::TimeDelta::FromMilliseconds(static_cast<int>(ms_double
));
419 // TODO(frankf): implicit and script timeout should be cleared
420 // if negative timeout is specified.
421 if (type
== "implicit") {
422 session
->implicit_wait
= timeout
;
423 } else if (type
== "script") {
424 session
->script_timeout
= timeout
;
425 } else if (type
== "page load") {
426 session
->page_load_timeout
=
427 ((timeout
< base::TimeDelta()) ? Session::kDefaultPageLoadTimeout
430 return Status(kUnknownError
, "unknown type of timeout:" + type
);
435 Status
ExecuteSetScriptTimeout(
437 const base::DictionaryValue
& params
,
438 scoped_ptr
<base::Value
>* value
) {
440 if (!params
.GetDouble("ms", &ms
) || ms
< 0)
441 return Status(kUnknownError
, "'ms' must be a non-negative number");
442 session
->script_timeout
=
443 base::TimeDelta::FromMilliseconds(static_cast<int>(ms
));
447 Status
ExecuteImplicitlyWait(
449 const base::DictionaryValue
& params
,
450 scoped_ptr
<base::Value
>* value
) {
452 if (!params
.GetDouble("ms", &ms
) || ms
< 0)
453 return Status(kUnknownError
, "'ms' must be a non-negative number");
454 session
->implicit_wait
=
455 base::TimeDelta::FromMilliseconds(static_cast<int>(ms
));
459 Status
ExecuteIsLoading(
461 const base::DictionaryValue
& params
,
462 scoped_ptr
<base::Value
>* value
) {
463 WebView
* web_view
= NULL
;
464 Status status
= session
->GetTargetWindow(&web_view
);
465 if (status
.IsError())
468 status
= web_view
->ConnectIfNecessary();
469 if (status
.IsError())
473 status
= web_view
->IsPendingNavigation(
474 session
->GetCurrentFrameId(), &is_pending
);
475 if (status
.IsError())
477 value
->reset(new base::FundamentalValue(is_pending
));
481 Status
ExecuteGetLocation(
483 const base::DictionaryValue
& params
,
484 scoped_ptr
<base::Value
>* value
) {
485 if (!session
->overridden_geoposition
) {
486 return Status(kUnknownError
,
487 "Location must be set before it can be retrieved");
489 base::DictionaryValue location
;
490 location
.SetDouble("latitude", session
->overridden_geoposition
->latitude
);
491 location
.SetDouble("longitude", session
->overridden_geoposition
->longitude
);
492 location
.SetDouble("accuracy", session
->overridden_geoposition
->accuracy
);
493 // Set a dummy altitude to make WebDriver clients happy.
494 // https://code.google.com/p/chromedriver/issues/detail?id=281
495 location
.SetDouble("altitude", 0);
496 value
->reset(location
.DeepCopy());
500 Status
ExecuteGetNetworkConditions(
502 const base::DictionaryValue
& params
,
503 scoped_ptr
<base::Value
>* value
) {
504 if (!session
->overridden_network_conditions
) {
505 return Status(kUnknownError
,
506 "network conditions must be set before it can be retrieved");
508 base::DictionaryValue conditions
;
509 conditions
.SetBoolean("offline",
510 session
->overridden_network_conditions
->offline
);
511 conditions
.SetInteger("latency",
512 session
->overridden_network_conditions
->latency
);
513 conditions
.SetInteger(
514 "download_throughput",
515 session
->overridden_network_conditions
->download_throughput
);
516 conditions
.SetInteger(
518 session
->overridden_network_conditions
->upload_throughput
);
519 value
->reset(conditions
.DeepCopy());
523 Status
ExecuteGetWindowPosition(
525 const base::DictionaryValue
& params
,
526 scoped_ptr
<base::Value
>* value
) {
527 ChromeDesktopImpl
* desktop
= NULL
;
528 Status status
= session
->chrome
->GetAsDesktop(&desktop
);
529 if (status
.IsError())
532 AutomationExtension
* extension
= NULL
;
533 status
= desktop
->GetAutomationExtension(&extension
);
534 if (status
.IsError())
538 status
= extension
->GetWindowPosition(&x
, &y
);
539 if (status
.IsError())
542 base::DictionaryValue position
;
543 position
.SetInteger("x", x
);
544 position
.SetInteger("y", y
);
545 value
->reset(position
.DeepCopy());
549 Status
ExecuteSetWindowPosition(
551 const base::DictionaryValue
& params
,
552 scoped_ptr
<base::Value
>* value
) {
555 if (!params
.GetDouble("x", &x
) || !params
.GetDouble("y", &y
))
556 return Status(kUnknownError
, "missing or invalid 'x' or 'y'");
558 ChromeDesktopImpl
* desktop
= NULL
;
559 Status status
= session
->chrome
->GetAsDesktop(&desktop
);
560 if (status
.IsError())
563 AutomationExtension
* extension
= NULL
;
564 status
= desktop
->GetAutomationExtension(&extension
);
565 if (status
.IsError())
568 return extension
->SetWindowPosition(static_cast<int>(x
), static_cast<int>(y
));
571 Status
ExecuteGetWindowSize(
573 const base::DictionaryValue
& params
,
574 scoped_ptr
<base::Value
>* value
) {
575 ChromeDesktopImpl
* desktop
= NULL
;
576 Status status
= session
->chrome
->GetAsDesktop(&desktop
);
577 if (status
.IsError())
580 AutomationExtension
* extension
= NULL
;
581 status
= desktop
->GetAutomationExtension(&extension
);
582 if (status
.IsError())
586 status
= extension
->GetWindowSize(&width
, &height
);
587 if (status
.IsError())
590 base::DictionaryValue size
;
591 size
.SetInteger("width", width
);
592 size
.SetInteger("height", height
);
593 value
->reset(size
.DeepCopy());
597 Status
ExecuteSetWindowSize(
599 const base::DictionaryValue
& params
,
600 scoped_ptr
<base::Value
>* value
) {
603 if (!params
.GetDouble("width", &width
) ||
604 !params
.GetDouble("height", &height
))
605 return Status(kUnknownError
, "missing or invalid 'width' or 'height'");
607 ChromeDesktopImpl
* desktop
= NULL
;
608 Status status
= session
->chrome
->GetAsDesktop(&desktop
);
609 if (status
.IsError())
612 AutomationExtension
* extension
= NULL
;
613 status
= desktop
->GetAutomationExtension(&extension
);
614 if (status
.IsError())
617 return extension
->SetWindowSize(
618 static_cast<int>(width
), static_cast<int>(height
));
621 Status
ExecuteMaximizeWindow(
623 const base::DictionaryValue
& params
,
624 scoped_ptr
<base::Value
>* value
) {
625 ChromeDesktopImpl
* desktop
= NULL
;
626 Status status
= session
->chrome
->GetAsDesktop(&desktop
);
627 if (status
.IsError())
630 AutomationExtension
* extension
= NULL
;
631 status
= desktop
->GetAutomationExtension(&extension
);
632 if (status
.IsError())
635 return extension
->MaximizeWindow();
638 Status
ExecuteGetAvailableLogTypes(
640 const base::DictionaryValue
& params
,
641 scoped_ptr
<base::Value
>* value
) {
642 scoped_ptr
<base::ListValue
> types(new base::ListValue());
643 std::vector
<WebDriverLog
*> logs
= session
->GetAllLogs();
644 for (std::vector
<WebDriverLog
*>::const_iterator log
= logs
.begin();
647 types
->AppendString((*log
)->type());
649 *value
= types
.Pass();
653 Status
ExecuteGetLog(
655 const base::DictionaryValue
& params
,
656 scoped_ptr
<base::Value
>* value
) {
657 std::string log_type
;
658 if (!params
.GetString("type", &log_type
)) {
659 return Status(kUnknownError
, "missing or invalid 'type'");
661 std::vector
<WebDriverLog
*> logs
= session
->GetAllLogs();
662 for (std::vector
<WebDriverLog
*>::const_iterator log
= logs
.begin();
665 if (log_type
== (*log
)->type()) {
666 *value
= (*log
)->GetAndClearEntries();
670 return Status(kUnknownError
, "log type '" + log_type
+ "' not found");
673 Status
ExecuteUploadFile(
675 const base::DictionaryValue
& params
,
676 scoped_ptr
<base::Value
>* value
) {
677 std::string base64_zip_data
;
678 if (!params
.GetString("file", &base64_zip_data
))
679 return Status(kUnknownError
, "missing or invalid 'file'");
680 std::string zip_data
;
681 if (!Base64Decode(base64_zip_data
, &zip_data
))
682 return Status(kUnknownError
, "unable to decode 'file'");
684 if (!session
->temp_dir
.IsValid()) {
685 if (!session
->temp_dir
.CreateUniqueTempDir())
686 return Status(kUnknownError
, "unable to create temp dir");
688 base::FilePath upload_dir
;
689 if (!base::CreateTemporaryDirInDir(session
->temp_dir
.path(),
690 FILE_PATH_LITERAL("upload"),
692 return Status(kUnknownError
, "unable to create temp dir");
694 std::string error_msg
;
695 base::FilePath upload
;
696 Status status
= UnzipSoleFile(upload_dir
, zip_data
, &upload
);
697 if (status
.IsError())
698 return Status(kUnknownError
, "unable to unzip 'file'", status
);
700 value
->reset(new base::StringValue(upload
.value()));
704 Status
ExecuteIsAutoReporting(
706 const base::DictionaryValue
& params
,
707 scoped_ptr
<base::Value
>* value
) {
708 value
->reset(new base::FundamentalValue(session
->auto_reporting_enabled
));
712 Status
ExecuteSetAutoReporting(
714 const base::DictionaryValue
& params
,
715 scoped_ptr
<base::Value
>* value
) {
717 if (!params
.GetBoolean("enabled", &enabled
))
718 return Status(kUnknownError
, "missing parameter 'enabled'");
719 session
->auto_reporting_enabled
= enabled
;