1
0

Driver.pm 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212
  1. package Selenium::Remote::Driver;
  2. # ABSTRACT: Perl Client for Selenium Remote Driver
  3. use Moo;
  4. use Try::Tiny;
  5. use 5.006;
  6. use v5.10.0; # Before 5.006, v5.10.0 would not be understood.
  7. # See http://perldoc.perl.org/5.10.0/functions/use.html#use-VERSION
  8. # and http://www.dagolden.com/index.php/369/version-numbers-should-be-boring/
  9. # for details.
  10. use Carp;
  11. our @CARP_NOT;
  12. use IO::Compress::Zip qw(zip $ZipError);
  13. use Scalar::Util;
  14. use Selenium::Remote::RemoteConnection;
  15. use Selenium::Remote::Commands;
  16. use Selenium::Remote::WebElement;
  17. use constant FINDERS => {
  18. class => 'class name',
  19. class_name => 'class name',
  20. css => 'css selector',
  21. id => 'id',
  22. link => 'link text',
  23. link_text => 'link text',
  24. name => 'name',
  25. partial_link_text => 'partial link text',
  26. tag_name => 'tag name',
  27. xpath => 'xpath',
  28. };
  29. =head1 SYNOPSIS
  30. use Selenium::Remote::Driver;
  31. my $driver = Selenium::Remote::Driver->new;
  32. $driver->get('http://www.google.com');
  33. print $driver->get_title();
  34. $driver->quit();
  35. =cut
  36. =head1 DESCRIPTION
  37. Selenium is a test tool that allows you to write
  38. automated web application UI tests in any programming language against
  39. any HTTP website using any mainstream JavaScript-enabled browser. This module is
  40. an implementation of the client for the Remote driver that Selenium provides.
  41. You can find bindings for other languages at this location:
  42. L<http://code.google.com/p/selenium/>
  43. This module sends commands directly to the Server using HTTP. Using this module
  44. together with the Selenium Server, you can automatically control any supported
  45. browser. To use this module, you need to have already downloaded and started
  46. the Selenium Server (Selenium Server is a Java application).
  47. =cut
  48. =head1 USAGE (read this first)
  49. =head2 Remote Driver Response
  50. Selenium::Remote::Driver uses the L<JsonWireProtocol|http://code.google.com/p/selenium/wiki/JsonWireProtocol> to communicate with the
  51. Selenium Server. If an error occurs while executing the command then the server
  52. sends back an HTTP error code with a JSON encoded reponse that indicates the
  53. precise L<Response Error Code|http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes>. The module will then croak with the error message
  54. associated with this code. If no error occurred, then the subroutine called will
  55. return the value sent back from the server (if a return value was sent).
  56. So a rule of thumb while invoking methods on the driver is if the method did not
  57. croak when called, then you can safely assume the command was successful even if
  58. nothing was returned by the method.
  59. =head2 WebElement
  60. Selenium Webdriver represents all the HTML elements as WebElement, which is
  61. in turn represented by L<Selenium::Remote::WebElement> module. So any method that
  62. deals with WebElements will return and/or expect WebElement object. The POD for
  63. that module describes all the methods that perform various actions on the
  64. WebElements like click, submit etc.
  65. To interact with any WebElement you have to first "find" it, read the POD for
  66. find_element or find_elements for further info. Once you find the required element
  67. then you can perform various actions. If you don't call find_* method first, all
  68. your further actions will fail for that element. Finally, just remember that you
  69. don't have to instantiate WebElement objects at all - they will be automatically
  70. created when you use the find_* methods.
  71. A sub-class of Selenium::Remote::WebElement may be used instead of Selenium::Remote::WebElement,
  72. by providing that class name as an option the constructor:
  73. my $driver = Selenium::Remote::Driver->new( webelement_class => ... );
  74. For example, a testing-subclass may extend the web-element object with testing methods.
  75. =head1 TESTING
  76. If are writing automated tests using this module, make sure you also see
  77. L<Test::Selenium::Remote::Driver> which is also included in this distribution.
  78. It includes convenience testing methods for many of the selenum methods
  79. available here.
  80. =head1 FUNCTIONS
  81. =head2 new
  82. Description:
  83. Constructor for Driver. It'll instantiate the object if it can communicate
  84. with the Selenium Webdriver server.
  85. Input: (all optional)
  86. Desired capabilities - HASH - Following options are accepted:
  87. Optional:
  88. 'remote_server_addr' - <string> - IP or FQDN of the Webdriver server machine
  89. 'port' - <string> - Port on which the Webdriver server is listening
  90. 'browser_name' - <string> - desired browser string: {phantomjs|firefox|internet explorer|htmlunit|iphone|chrome}
  91. 'version' - <string> - desired browser version number
  92. 'platform' - <string> - desired platform: {WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANY}
  93. 'javascript' - <boolean> - whether javascript should be supported
  94. 'accept_ssl_certs' - <boolean> - whether SSL certs should be accepted, default is true.
  95. 'firefox_profile' - Profile - Use S::R::D::Firefox::Profile to create a Firefox profile for the browser to use
  96. 'proxy' - HASH - Proxy configuration with the following keys:
  97. 'proxyType' - <string> - REQUIRED, Possible values are:
  98. direct - A direct connection - no proxy in use,
  99. manual - Manual proxy settings configured, e.g. setting a proxy for HTTP, a proxy for FTP, etc,
  100. pac - Proxy autoconfiguration from a URL,
  101. autodetect - proxy autodetection, probably with WPAD,
  102. system - Use system settings
  103. 'proxyAutoconfigUrl' - <string> - REQUIRED if proxyType is 'pac', ignored otherwise. Expected format: http://hostname.com:1234/pacfile.
  104. 'ftpProxy' - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  105. 'httpProxy' - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  106. 'sslProxy' - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  107. 'extra_capabilities' - HASH - Any other extra capabilities
  108. You can also specify some options in the constructor hash that are
  109. not part of the browser-related desired capabilities. These items
  110. are also optional.
  111. 'auto_close' - <boolean> - whether driver should end session on remote server on close.
  112. 'default_finder' - <string> - choose default finder used for find_element* {class|class_name|css|id|link|link_text|name|partial_link_text|tag_name|xpath}
  113. 'webelement_class' - <string> - sub-class of Selenium::Remote::WebElement if you wish to use an alternate WebElement class.
  114. 'ua' - LWP::UserAgent instance - if you wish to use a specific $ua, like from Test::LWP::UserAgent
  115. If no values are provided, then these defaults will be assumed:
  116. 'remote_server_addr' => 'localhost'
  117. 'port' => '4444'
  118. 'browser_name' => 'firefox'
  119. 'version' => ''
  120. 'platform' => 'ANY'
  121. 'javascript' => 1
  122. 'auto_close' => 1
  123. 'default_finder' => 'xpath'
  124. Output:
  125. Remote Driver object
  126. Usage:
  127. my $driver = Selenium::Remote::Driver->new;
  128. or
  129. my $driver = Selenium::Remote::Driver->new('browser_name' => 'firefox',
  130. 'platform' => 'MAC');
  131. or
  132. my $driver = Selenium::Remote::Driver->new('remote_server_addr' => '10.10.1.1',
  133. 'port' => '2222',
  134. 'auto_close' => 0);
  135. or
  136. my $driver = Selenium::Remote::Driver->new('browser_name' =>'chrome'
  137. 'extra_capabilities' => {
  138. 'chromeOptions' => {
  139. 'args' => [
  140. 'window-size=1260,960',
  141. 'incognito'
  142. ],
  143. 'prefs' => {
  144. 'session' => {
  145. 'restore_on_startup' => 4,
  146. 'urls_to_restore_on_startup' => [
  147. 'http://www.google.com',
  148. 'http://docs.seleniumhq.org'
  149. ]},
  150. 'first_run_tabs' => [
  151. 'http://www.google.com',
  152. 'http://docs.seleniumhq.org'
  153. ]
  154. }
  155. }
  156. });
  157. or
  158. my $driver = Selenium::Remote::Driver->new('proxy' => {'proxyType' => 'manual', 'httpProxy' => 'myproxy.com:1234'});
  159. or
  160. my $driver = Selenium::Remote::Driver->new('default_finder' => 'css');
  161. =head2 new_from_caps
  162. Description:
  163. For experienced users who want complete control over the desired
  164. capabilities, use this alternative constructor along with the
  165. C<desired_capabilities> hash key in the init hash. Unlike "new",
  166. this constructor will not assume any defaults for your desired
  167. capabilities.
  168. This alternate constructor IGNORES all other browser-related
  169. desiredCapability options; the only options that will be respected
  170. are those that are NOT part of the Capabilities JSON Object as
  171. described in the Json Wire Protocol.
  172. Input:
  173. The only respected keys in the input hash are:
  174. remote_server_addr - STRING - defaults to localhost
  175. port - INTEGER - defaults to 4444
  176. default_finder - STRING - defaults to xpath
  177. webelement_class - STRING - defaults to Selenium::Remote::WebElement
  178. auto_close - BOOLEAN - defaults to 1
  179. desired_capabilities - HASHREF - defaults to {}
  180. Except for C<desired_capabilities>, these keys perform exactly the
  181. same as listed in the regular "new" constructor.
  182. The hashref you pass in as desired_capabilities only gets json
  183. encoded before being passed to the Selenium server; no default
  184. options of any sort will be added.
  185. This means you must handle normalization and casing of the input
  186. options (like "browser_name" vs "browserName") and take care of
  187. things like encoding the firefox profile if applicable. More
  188. information about the desired capabilities object is available on
  189. the Selenium wiki:
  190. https://code.google.com/p/selenium/wiki/JsonWireProtocol#Capabilities_JSON_Object
  191. Output:
  192. Remote Driver object
  193. Usage:
  194. my $driver = Selenium::Remote::Driver->new_from_caps(
  195. 'desired_capabilities' => {'browserName' => 'firefox'}
  196. );
  197. The above would generate a POST to the webdriver server at
  198. localhost:4444 with the exact payload of '{"desiredCapabilities":
  199. {"browserName": "firefox" }}'.
  200. =cut
  201. has 'remote_server_addr' => (
  202. is => 'rw',
  203. coerce => sub { ( defined($_[0]) ? $_[0] : 'localhost' )},
  204. default => sub {'localhost'},
  205. );
  206. has 'browser_name' => (
  207. is => 'rw',
  208. coerce => sub { ( defined($_[0]) ? $_[0] : 'firefox' )},
  209. default => sub {'firefox'},
  210. );
  211. has 'platform' => (
  212. is => 'rw',
  213. coerce => sub { ( defined($_[0]) ? $_[0] : 'ANY' )},
  214. default => sub {'ANY'},
  215. );
  216. has 'port' => (
  217. is => 'rw',
  218. coerce => sub { ( defined($_[0]) ? $_[0] : '4444' )},
  219. default => sub {'4444'},
  220. );
  221. has 'version' => (
  222. is => 'rw',
  223. default => sub {''},
  224. );
  225. has 'webelement_class' => (
  226. is => 'rw',
  227. default => sub {'Selenium::Remote::WebElement'},
  228. );
  229. has 'default_finder' => (
  230. is => 'rw',
  231. coerce => sub { FINDERS->{ $_[0] } },
  232. default => sub {'xpath'},
  233. );
  234. has 'session_id' => (
  235. is => 'rw',
  236. default => sub {undef},
  237. );
  238. has 'remote_conn' => (
  239. is => 'lazy',
  240. builder => sub {
  241. my $self = shift;
  242. return Selenium::Remote::RemoteConnection->new(
  243. remote_server_addr => $self->remote_server_addr,
  244. port => $self->port,
  245. ua => $self->ua
  246. );
  247. },
  248. );
  249. has 'ua' => (
  250. is => 'lazy',
  251. builder => sub { return LWP::UserAgent->new }
  252. );
  253. has 'commands' => (
  254. is => 'lazy',
  255. builder => sub { return Selenium::Remote::Commands->new; },
  256. );
  257. has 'auto_close' => (
  258. is => 'rw',
  259. coerce => sub { ( defined($_[0]) ? $_[0] : 1 )},
  260. default => sub {1},
  261. );
  262. has 'pid' => (
  263. is => 'lazy',
  264. builder => sub { return $$ }
  265. );
  266. has 'javascript' => (
  267. is => 'rw',
  268. coerce => sub { $_[0] ? JSON::true : JSON::false },
  269. default => sub { return JSON::true }
  270. );
  271. has 'accept_ssl_certs' => (
  272. is => 'rw',
  273. coerce => sub { $_[0] ? JSON::true : JSON::false },
  274. default => sub { return JSON::true }
  275. );
  276. has 'proxy' => (
  277. is => 'rw',
  278. coerce => sub {
  279. my $proxy = $_[0];
  280. if ( $proxy->{proxyType} eq 'pac' ) {
  281. if ( not defined $proxy->{proxyAutoconfigUrl} ) {
  282. croak "proxyAutoconfigUrl not provided\n";
  283. }
  284. elsif ( not( $proxy->{proxyAutoconfigUrl} =~ /^http/g ) ) {
  285. croak "proxyAutoconfigUrl should be of format http://";
  286. }
  287. }
  288. $proxy;
  289. },
  290. );
  291. has 'extra_capabilities' => (
  292. is => 'rw',
  293. default => sub { {} }
  294. );
  295. has 'firefox_profile' => (
  296. is => 'rw',
  297. coerce => sub {
  298. my $profile = shift;
  299. unless (Scalar::Util::blessed($profile)
  300. && $profile->isa('Selenium::Remote::Driver::Firefox::Profile')) {
  301. croak "firefox_profile should be a Selenium::Remote::Driver::Firefox::Profile\n";
  302. }
  303. return $profile->_encode;
  304. },
  305. predicate => 'has_firefox_profile'
  306. );
  307. has 'desired_capabilities' => (
  308. is => 'rw',
  309. lazy => 1,
  310. predicate => 'has_desired_capabilities'
  311. );
  312. sub BUILD {
  313. my $self = shift;
  314. # Connect to remote server & establish a new session
  315. if ($self->has_desired_capabilities) {
  316. $self->new_desired_session( $self->desired_capabilities );
  317. }
  318. else {
  319. $self->new_session( $self->extra_capabilities );
  320. }
  321. if ( !( defined $self->session_id ) ) {
  322. croak "Could not establish a session with the remote server\n";
  323. }
  324. }
  325. sub new_from_caps {
  326. my ($self, %args) = @_;
  327. if (not exists $args{desired_capabilities}) {
  328. $args{desired_capabilities} = {};
  329. }
  330. return $self->new(%args);
  331. }
  332. sub DESTROY {
  333. my ($self) = @_;
  334. return if $$ != $self->pid;
  335. $self->quit() if ( $self->auto_close && defined $self->session_id );
  336. }
  337. # This is an internal method used the Driver & is not supposed to be used by
  338. # end user. This method is used by Driver to set up all the parameters
  339. # (url & JSON), send commands & receive processed response from the server.
  340. sub _execute_command {
  341. my ( $self, $res, $params ) = @_;
  342. $res->{'session_id'} = $self->session_id;
  343. my $resource = $self->commands->get_params($res);
  344. if ($resource) {
  345. my $resp =
  346. $self->remote_conn->request( $resource->{'method'},
  347. $resource->{'url'}, $params );
  348. if ( ref($resp) eq 'HASH' ) {
  349. if ( $resp->{cmd_status} && $resp->{cmd_status} eq 'OK' ) {
  350. return $resp->{cmd_return};
  351. }
  352. else {
  353. my $msg = "Error while executing command";
  354. if ( $resp->{cmd_error} ) {
  355. $msg .= ": $resp->{cmd_error}" if $resp->{cmd_error};
  356. }
  357. elsif ( $resp->{cmd_return} ) {
  358. if ( ref( $resp->{cmd_return} ) eq 'HASH' ) {
  359. $msg .= ": $resp->{cmd_return}->{error}->{msg}"
  360. if $resp->{cmd_return}->{error}->{msg};
  361. $msg .= ": $resp->{cmd_return}->{message}"
  362. if $resp->{cmd_return}->{message};
  363. }
  364. else {
  365. $msg .= ": $resp->{cmd_return}";
  366. }
  367. }
  368. croak $msg;
  369. }
  370. }
  371. return $resp;
  372. }
  373. else {
  374. croak "Couldn't retrieve command settings properly\n";
  375. }
  376. }
  377. # A method that is used by the Driver itself. It'll be called to set the
  378. # desired capabilities on the server.
  379. sub new_session {
  380. my ( $self, $extra_capabilities ) = @_;
  381. $extra_capabilities ||= {};
  382. my $args = {
  383. 'desiredCapabilities' => {
  384. 'browserName' => $self->browser_name,
  385. 'platform' => $self->platform,
  386. 'javascriptEnabled' => $self->javascript,
  387. 'version' => $self->version,
  388. 'acceptSslCerts' => $self->accept_ssl_certs,
  389. %$extra_capabilities,
  390. },
  391. };
  392. if ( defined $self->proxy ) {
  393. $args->{desiredCapabilities}->{proxy} = $self->proxy;
  394. }
  395. if ($args->{desiredCapabilities}->{browserName} =~ /firefox/i
  396. && $self->has_firefox_profile) {
  397. $args->{desiredCapabilities}->{firefox_profile} = $self->firefox_profile;
  398. }
  399. $self->_request_new_session($args);
  400. }
  401. sub new_desired_session {
  402. my ( $self, $caps ) = @_;
  403. $self->_request_new_session({
  404. desiredCapabilities => $caps
  405. });
  406. }
  407. sub _request_new_session {
  408. my ( $self, $args ) = @_;
  409. # command => 'newSession' to fool the tests of commands implemented
  410. # TODO: rewrite the testing better, this is so fragile.
  411. my $resp = $self->remote_conn->request(
  412. $self->commands->get_method('newSession'),
  413. $self->commands->get_url('newSession'), $args,
  414. );
  415. if ( ( defined $resp->{'sessionId'} ) && $resp->{'sessionId'} ne '' ) {
  416. $self->session_id( $resp->{'sessionId'} );
  417. }
  418. else {
  419. my $error = 'Could not create new session';
  420. $error .= ": $resp->{cmd_return}" if defined $resp->{cmd_return};
  421. croak $error;
  422. }
  423. }
  424. =head2 debug_on
  425. Description:
  426. Turns on debugging mode and the driver will print extra info like request
  427. and response to stdout. Useful, when you want to see what is being sent to
  428. the server & what response you are getting back.
  429. Usage:
  430. $driver->debug_on;
  431. =cut
  432. sub debug_on {
  433. my ($self) = @_;
  434. $self->remote_conn->debug(1);
  435. }
  436. =head2 debug_off
  437. Description:
  438. Turns off the debugging mode.
  439. Usage:
  440. $driver->debug_off;
  441. =cut
  442. sub debug_off {
  443. my ($self) = @_;
  444. $self->remote_conn->debug(0);
  445. }
  446. =head2 get_sessions
  447. Description:
  448. Returns a list of the currently active sessions. Each session will be
  449. returned as an array of Hashes with the following keys:
  450. 'id' : The session ID
  451. 'capabilities: An object describing session's capabilities
  452. Output:
  453. Array of Hashes
  454. Usage:
  455. print Dumper $driver->get_sessions();
  456. =cut
  457. sub get_sessions {
  458. my ($self) = @_;
  459. my $res = { 'command' => 'getSessions' };
  460. return $self->_execute_command($res);
  461. }
  462. =head2 status
  463. Description:
  464. Query the server's current status. All server implementations
  465. should return two basic objects describing the server's current
  466. platform and when the server was built.
  467. Output:
  468. Hash ref
  469. Usage:
  470. print Dumper $driver->status;
  471. =cut
  472. sub status {
  473. my ($self) = @_;
  474. my $res = { 'command' => 'status' };
  475. return $self->_execute_command($res);
  476. }
  477. =head2 get_alert_text
  478. Description:
  479. Gets the text of the currently displayed JavaScript alert(), confirm()
  480. or prompt() dialog.
  481. Example
  482. my $string = $driver->get_alert_text;
  483. =cut
  484. sub get_alert_text {
  485. my ($self) = @_;
  486. my $res = { 'command' => 'getAlertText' };
  487. return $self->_execute_command($res);
  488. }
  489. =head2 send_keys_to_active_element
  490. Description:
  491. Send a sequence of key strokes to the active element. This command is
  492. similar to the send keys command in every aspect except the implicit
  493. termination: The modifiers are not released at the end of the call.
  494. Rather, the state of the modifier keys is kept between calls, so mouse
  495. interactions can be performed while modifier keys are depressed.
  496. Input: 1
  497. Required:
  498. {ARRAY | STRING} - Array of strings or a string.
  499. Usage:
  500. $driver->send_keys_to_active_element('abcd', 'efg');
  501. $driver->send_keys_to_active_element('hijk');
  502. or
  503. # include the WDKeys module
  504. use Selenium::Remote::WDKeys;
  505. .
  506. .
  507. $driver->send_keys_to_active_element(KEYS->{'space'}, KEYS->{'enter'});
  508. =cut
  509. sub send_keys_to_active_element {
  510. my ( $self, @strings ) = @_;
  511. my $res = { 'command' => 'sendKeysToActiveElement' };
  512. my $params = {
  513. 'value' => \@strings,
  514. };
  515. return $self->_execute_command( $res, $params );
  516. }
  517. =head2 send_keys_to_alert
  518. Synonymous with send_keys_to_prompt
  519. =cut
  520. sub send_keys_to_alert {
  521. return shift->send_keys_to_prompt(@_);
  522. }
  523. =head2 send_keys_to_prompt
  524. Description:
  525. Sends keystrokes to a JavaScript prompt() dialog.
  526. Input:
  527. {string} keys to send
  528. Example:
  529. $driver->send_keys_to_prompt('hello world');
  530. or
  531. ok($driver->get_alert_text eq 'Please Input your name','prompt appears');
  532. $driver->send_keys_to_alert("Larry Wall");
  533. $driver->accept_alert;
  534. =cut
  535. sub send_keys_to_prompt {
  536. my ( $self, $keys ) = @_;
  537. my $res = { 'command' => 'sendKeysToPrompt' };
  538. my $params = { 'text' => $keys };
  539. return $self->_execute_command( $res, $params );
  540. }
  541. =head2 accept_alert
  542. Description:
  543. Accepts the currently displayed alert dialog. Usually, this is
  544. equivalent to clicking the 'OK' button in the dialog.
  545. Example:
  546. $driver->accept_alert;
  547. =cut
  548. sub accept_alert {
  549. my ($self) = @_;
  550. my $res = { 'command' => 'acceptAlert' };
  551. return $self->_execute_command($res);
  552. }
  553. =head2 dismiss_alert
  554. Description:
  555. Dismisses the currently displayed alert dialog. For comfirm()
  556. and prompt() dialogs, this is equivalent to clicking the
  557. 'Cancel' button. For alert() dialogs, this is equivalent to
  558. clicking the 'OK' button.
  559. Example:
  560. $driver->dismiss_alert;
  561. =cut
  562. sub dismiss_alert {
  563. my ($self) = @_;
  564. my $res = { 'command' => 'dismissAlert' };
  565. return $self->_execute_command($res);
  566. }
  567. =head2 mouse_move_to_location
  568. Description:
  569. Move the mouse by an offset of the specificed element. If no
  570. element is specified, the move is relative to the current mouse
  571. cursor. If an element is provided but no offset, the mouse will be
  572. moved to the center of the element. If the element is not visible,
  573. it will be scrolled into view.
  574. Output:
  575. STRING -
  576. Usage:
  577. # element - the element to move to. If not specified or is null, the offset is relative to current position of the mouse.
  578. # xoffset - X offset to move to, relative to the top-left corner of the element. If not specified, the mouse will move to the middle of the element.
  579. # yoffset - Y offset to move to, relative to the top-left corner of the element. If not specified, the mouse will move to the middle of the element.
  580. print $driver->mouse_move_to_location(element => e, xoffset => x, yoffset => y);
  581. =cut
  582. sub mouse_move_to_location {
  583. my ( $self, %params ) = @_;
  584. $params{element} = $params{element}{id} if exists $params{element};
  585. my $res = { 'command' => 'mouseMoveToLocation' };
  586. return $self->_execute_command( $res, \%params );
  587. }
  588. =head2 move_to
  589. Synonymous with mouse_move_to_location
  590. =cut
  591. sub move_to {
  592. return shift->mouse_move_to_location(@_);
  593. }
  594. =head2 get_capabilities
  595. Description:
  596. Retrieve the capabilities of the specified session.
  597. Output:
  598. HASH of all the capabilities.
  599. Usage:
  600. my $capab = $driver->get_capabilities();
  601. print Dumper($capab);
  602. =cut
  603. sub get_capabilities {
  604. my $self = shift;
  605. my $res = { 'command' => 'getCapabilities' };
  606. return $self->_execute_command($res);
  607. }
  608. =head2 set_timeout
  609. Description:
  610. Configure the amount of time that a particular type of operation can execute
  611. for before they are aborted and a |Timeout| error is returned to the client.
  612. Input:
  613. type - <STRING> - The type of operation to set the timeout for.
  614. Valid values are:
  615. "script" : for script timeouts,
  616. "implicit" : for modifying the implicit wait timeout
  617. "page load" : for setting a page load timeout.
  618. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  619. commands are permitted to run.
  620. Usage:
  621. $driver->set_timeout('script', 1000);
  622. =cut
  623. sub set_timeout {
  624. my ( $self, $type, $ms ) = @_;
  625. if ( not defined $type or not defined $ms ) {
  626. croak "Expecting type & timeout in ms";
  627. }
  628. my $res = { 'command' => 'setTimeout' };
  629. my $params = { 'type' => $type, 'ms' => $ms };
  630. return $self->_execute_command( $res, $params );
  631. }
  632. =head2 set_async_script_timeout
  633. Description:
  634. Set the amount of time, in milliseconds, that asynchronous scripts executed
  635. by execute_async_script() are permitted to run before they are
  636. aborted and a |Timeout| error is returned to the client.
  637. Input:
  638. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  639. commands are permitted to run.
  640. Usage:
  641. $driver->set_async_script_timeout(1000);
  642. =cut
  643. sub set_async_script_timeout {
  644. my ( $self, $ms ) = @_;
  645. if ( not defined $ms ) {
  646. croak "Expecting timeout in ms";
  647. }
  648. my $res = { 'command' => 'setAsyncScriptTimeout' };
  649. my $params = { 'ms' => $ms };
  650. return $self->_execute_command( $res, $params );
  651. }
  652. =head2 set_implicit_wait_timeout
  653. Description:
  654. Set the amount of time the driver should wait when searching for elements.
  655. When searching for a single element, the driver will poll the page until
  656. an element is found or the timeout expires, whichever occurs first.
  657. When searching for multiple elements, the driver should poll the page until
  658. at least one element is found or the timeout expires, at which point it
  659. will return an empty list. If this method is never called, the driver will
  660. default to an implicit wait of 0ms.
  661. Input:
  662. Time in milliseconds.
  663. Output:
  664. Server Response Hash with no data returned back from the server.
  665. Usage:
  666. $driver->set_implicit_wait_timeout(10);
  667. =cut
  668. sub set_implicit_wait_timeout {
  669. my ( $self, $ms ) = @_;
  670. my $res = { 'command' => 'setImplicitWaitTimeout' };
  671. my $params = { 'ms' => $ms };
  672. return $self->_execute_command( $res, $params );
  673. }
  674. =head2 pause
  675. Description:
  676. Pause execution for a specified interval of milliseconds.
  677. Usage:
  678. $driver->pause(10000); # 10 second delay
  679. $driver->pause(); # 1 second delay default
  680. =cut
  681. sub pause {
  682. my $self = shift;
  683. my $timeout = ( shift // 1000 ) / 1000;
  684. select( undef, undef, undef, $timeout ); # Fractional-second sleep
  685. }
  686. =head2 close
  687. Description:
  688. Close the current window.
  689. Usage:
  690. $driver->close();
  691. or
  692. #close a popup window
  693. my $handles = $driver->get_window_handles;
  694. $driver->switch_to_window($handles->[1]);
  695. $driver->close();
  696. $driver->switch_to_window($handles->[0]);
  697. =cut
  698. sub close {
  699. my $self = shift;
  700. my $res = { 'command' => 'close' };
  701. $self->_execute_command($res);
  702. }
  703. =head2 quit
  704. Description:
  705. Delete the session & close open browsers.
  706. Usage:
  707. $driver->quit();
  708. =cut
  709. sub quit {
  710. my $self = shift;
  711. my $res = { 'command' => 'quit' };
  712. $self->_execute_command($res);
  713. $self->session_id(undef);
  714. }
  715. =head2 get_current_window_handle
  716. Description:
  717. Retrieve the current window handle.
  718. Output:
  719. STRING - the window handle
  720. Usage:
  721. print $driver->get_current_window_handle();
  722. =cut
  723. sub get_current_window_handle {
  724. my $self = shift;
  725. my $res = { 'command' => 'getCurrentWindowHandle' };
  726. return $self->_execute_command($res);
  727. }
  728. =head2 get_window_handles
  729. Description:
  730. Retrieve the list of window handles used in the session.
  731. Output:
  732. ARRAY of STRING - list of the window handles
  733. Usage:
  734. print Dumper $driver->get_window_handles;
  735. or
  736. # get popup, close, then back
  737. my $handles = $driver->get_window_handles;
  738. $driver->switch_to_window($handles->[1]);
  739. $driver->close;
  740. $driver->switch_to_window($handles->[0]);
  741. =cut
  742. sub get_window_handles {
  743. my $self = shift;
  744. my $res = { 'command' => 'getWindowHandles' };
  745. return $self->_execute_command($res);
  746. }
  747. =head2 get_window_size
  748. Description:
  749. Retrieve the window size
  750. Input:
  751. STRING - <optional> - window handle (default is 'current' window)
  752. Output:
  753. HASH - containing keys 'height' & 'width'
  754. Usage:
  755. my $window_size = $driver->get_window_size();
  756. print $window_size->{'height'}, $window_size->('width');
  757. =cut
  758. sub get_window_size {
  759. my ( $self, $window ) = @_;
  760. $window = ( defined $window ) ? $window : 'current';
  761. my $res = { 'command' => 'getWindowSize', 'window_handle' => $window };
  762. return $self->_execute_command($res);
  763. }
  764. =head2 get_window_position
  765. Description:
  766. Retrieve the window position
  767. Input:
  768. STRING - <optional> - window handle (default is 'current' window)
  769. Output:
  770. HASH - containing keys 'x' & 'y'
  771. Usage:
  772. my $window_size = $driver->get_window_position();
  773. print $window_size->{'x'}, $window_size->('y');
  774. =cut
  775. sub get_window_position {
  776. my ( $self, $window ) = @_;
  777. $window = ( defined $window ) ? $window : 'current';
  778. my $res = { 'command' => 'getWindowPosition', 'window_handle' => $window };
  779. return $self->_execute_command($res);
  780. }
  781. =head2 get_current_url
  782. Description:
  783. Retrieve the url of the current page
  784. Output:
  785. STRING - url
  786. Usage:
  787. print $driver->get_current_url();
  788. =cut
  789. sub get_current_url {
  790. my $self = shift;
  791. my $res = { 'command' => 'getCurrentUrl' };
  792. return $self->_execute_command($res);
  793. }
  794. =head2 navigate
  795. Description:
  796. Navigate to a given url. This is same as get() method.
  797. Input:
  798. STRING - url
  799. Usage:
  800. $driver->navigate('http://www.google.com');
  801. =cut
  802. sub navigate {
  803. my ( $self, $url ) = @_;
  804. $self->get($url);
  805. }
  806. =head2 get
  807. Description:
  808. Navigate to a given url
  809. Input:
  810. STRING - url
  811. Usage:
  812. $driver->get('http://www.google.com');
  813. =cut
  814. sub get {
  815. my ( $self, $url ) = @_;
  816. my $res = { 'command' => 'get' };
  817. my $params = { 'url' => $url };
  818. return $self->_execute_command( $res, $params );
  819. }
  820. =head2 get_title
  821. Description:
  822. Get the current page title
  823. Output:
  824. STRING - Page title
  825. Usage:
  826. print $driver->get_title();
  827. =cut
  828. sub get_title {
  829. my $self = shift;
  830. my $res = { 'command' => 'getTitle' };
  831. return $self->_execute_command($res);
  832. }
  833. =head2 go_back
  834. Description:
  835. Equivalent to hitting the back button on the browser.
  836. Usage:
  837. $driver->go_back();
  838. =cut
  839. sub go_back {
  840. my $self = shift;
  841. my $res = { 'command' => 'goBack' };
  842. return $self->_execute_command($res);
  843. }
  844. =head2 go_forward
  845. Description:
  846. Equivalent to hitting the forward button on the browser.
  847. Usage:
  848. $driver->go_forward();
  849. =cut
  850. sub go_forward {
  851. my $self = shift;
  852. my $res = { 'command' => 'goForward' };
  853. return $self->_execute_command($res);
  854. }
  855. =head2 refresh
  856. Description:
  857. Reload the current page.
  858. Usage:
  859. $driver->refresh();
  860. =cut
  861. sub refresh {
  862. my $self = shift;
  863. my $res = { 'command' => 'refresh' };
  864. return $self->_execute_command($res);
  865. }
  866. =head2 javascript
  867. Description:
  868. returns true if javascript is enabled in the driver.
  869. Usage:
  870. if ($driver->has_javascript) { ...; }
  871. =cut
  872. sub has_javascript {
  873. my $self = shift;
  874. return $self->javascript == JSON::true;
  875. }
  876. =head2 execute_async_script
  877. Description:
  878. Inject a snippet of JavaScript into the page for execution in the context
  879. of the currently selected frame. The executed script is assumed to be
  880. asynchronous and must signal that is done by invoking the provided
  881. callback, which is always provided as the final argument to the function.
  882. The value to this callback will be returned to the client.
  883. Asynchronous script commands may not span page loads. If an unload event
  884. is fired while waiting for a script result, an error should be returned
  885. to the client.
  886. Input: 2 (1 optional)
  887. Required:
  888. STRING - Javascript to execute on the page
  889. Optional:
  890. ARRAY - list of arguments that need to be passed to the script.
  891. Output:
  892. {*} - Varied, depending on the type of result expected back from the script.
  893. Usage:
  894. my $script = q{
  895. var arg1 = arguments[0];
  896. var callback = arguments[arguments.length-1];
  897. var elem = window.document.findElementById(arg1);
  898. callback(elem);
  899. };
  900. my $elem = $driver->execute_async_script($script,'myid');
  901. $elem->click;
  902. =cut
  903. sub execute_async_script {
  904. my ( $self, $script, @args ) = @_;
  905. if ( $self->has_javascript ) {
  906. if ( not defined $script ) {
  907. croak 'No script provided';
  908. }
  909. my $res = { 'command' => 'executeAsyncScript' };
  910. # Check the args array if the elem obj is provided & replace it with
  911. # JSON representation
  912. for ( my $i = 0; $i < @args; $i++ ) {
  913. if ( Scalar::Util::blessed( $args[$i] )
  914. and $args[$i]->isa('Selenium::Remote::WebElement') )
  915. {
  916. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  917. }
  918. }
  919. my $params = { 'script' => $script, 'args' => \@args };
  920. my $ret = $self->_execute_command( $res, $params );
  921. # replace any ELEMENTS with WebElement
  922. if ( ref($ret)
  923. and ( ref($ret) eq 'HASH' )
  924. and exists $ret->{'ELEMENT'} )
  925. {
  926. $ret = $self->webelement_class->new( id => $ret->{ELEMENT},
  927. driver => $self );
  928. }
  929. return $ret;
  930. }
  931. else {
  932. croak 'Javascript is not enabled on remote driver instance.';
  933. }
  934. }
  935. =head2 execute_script
  936. Description:
  937. Inject a snippet of JavaScript into the page and return its result.
  938. WebElements that should be passed to the script as an argument should be
  939. specified in the arguments array as WebElement object. Likewise,
  940. any WebElements in the script result will be returned as WebElement object.
  941. Input: 2 (1 optional)
  942. Required:
  943. STRING - Javascript to execute on the page
  944. Optional:
  945. ARRAY - list of arguments that need to be passed to the script.
  946. Output:
  947. {*} - Varied, depending on the type of result expected back from the script.
  948. Usage:
  949. my $script = q{
  950. var arg1 = arguments[0];
  951. var elem = window.document.findElementById(arg1);
  952. return elem;
  953. };
  954. my $elem = $driver->execute_script($script,'myid');
  955. $elem->click;
  956. =cut
  957. sub execute_script {
  958. my ( $self, $script, @args ) = @_;
  959. if ( $self->has_javascript ) {
  960. if ( not defined $script ) {
  961. croak 'No script provided';
  962. }
  963. my $res = { 'command' => 'executeScript' };
  964. # Check the args array if the elem obj is provided & replace it with
  965. # JSON representation
  966. for ( my $i = 0; $i < @args; $i++ ) {
  967. if ( Scalar::Util::blessed( $args[$i] )
  968. and $args[$i]->isa('Selenium::Remote::WebElement') )
  969. {
  970. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  971. }
  972. }
  973. my $params = { 'script' => $script, 'args' => [@args] };
  974. my $ret = $self->_execute_command( $res, $params );
  975. return $self->_convert_to_webelement($ret);
  976. }
  977. else {
  978. croak 'Javascript is not enabled on remote driver instance.';
  979. }
  980. }
  981. # _convert_to_webelement
  982. # An internal method used to traverse a data structure
  983. # and convert any ELEMENTS with WebElements
  984. sub _convert_to_webelement {
  985. my ( $self, $ret ) = @_;
  986. if ( ref($ret) and ( ref($ret) eq 'HASH' ) ) {
  987. if ( ( keys %$ret == 1 ) and exists $ret->{'ELEMENT'} ) {
  988. # replace an ELEMENT with WebElement
  989. return $self->webelement_class->new( id => $ret->{ELEMENT},
  990. driver => $self );
  991. }
  992. my %hash;
  993. foreach my $key ( keys %$ret ) {
  994. $hash{$key} = $self->_convert_to_webelement( $ret->{$key} );
  995. }
  996. return \%hash;
  997. }
  998. if ( ref($ret) and ( ref($ret) eq 'ARRAY' ) ) {
  999. my @array = map { $self->_convert_to_webelement($_) } @$ret;
  1000. return \@array;
  1001. }
  1002. return $ret;
  1003. }
  1004. =head2 screenshot
  1005. Description:
  1006. Get a screenshot of the current page as a base64 encoded image.
  1007. Output:
  1008. STRING - base64 encoded image
  1009. Usage:
  1010. print $driver->screenshot();
  1011. To conveniently write the screenshot to a file, see L<capture_screenshot()>.
  1012. =cut
  1013. sub screenshot {
  1014. my ($self) = @_;
  1015. my $res = { 'command' => 'screenshot' };
  1016. return $self->_execute_command($res);
  1017. }
  1018. =head2 capture_screenshot
  1019. Description:
  1020. Capture a screenshot and save as a PNG to provided file name.
  1021. (The method is compatible with the WWW::Selenium method fo the same name)
  1022. Output:
  1023. TRUE - (Screenshot is written to file)
  1024. Usage:
  1025. $driver->capture_screenshot($filename);
  1026. =cut
  1027. sub capture_screenshot {
  1028. my ( $self, $filename ) = @_;
  1029. croak '$filename is required' unless $filename;
  1030. require MIME::Base64;
  1031. open( my $fh, '>', $filename );
  1032. binmode $fh;
  1033. print $fh MIME::Base64::decode_base64( $self->screenshot() );
  1034. CORE::close $fh;
  1035. return 1;
  1036. }
  1037. =head2 available_engines
  1038. Description:
  1039. List all available engines on the machine. To use an engine, it has to be present in this list.
  1040. Output:
  1041. {Array.<string>} A list of available engines
  1042. Usage:
  1043. print Dumper $driver->available_engines;
  1044. =cut
  1045. sub available_engines {
  1046. my ($self) = @_;
  1047. my $res = { 'command' => 'availableEngines' };
  1048. return $self->_execute_command($res);
  1049. }
  1050. =head2 switch_to_frame
  1051. Description:
  1052. Change focus to another frame on the page. If the frame ID is null, the
  1053. server will switch to the page's default content. You can also switch to a
  1054. WebElement, for e.g. you can find an iframe using find_element & then
  1055. provide that as an input to this method. Also see e.g.
  1056. Input: 1
  1057. Required:
  1058. {STRING | NUMBER | NULL | WebElement} - ID of the frame which can be one of the three
  1059. mentioned.
  1060. Usage:
  1061. $driver->switch_to_frame('frame_1');
  1062. or
  1063. $driver->switch_to_frame($driver->find_element('iframe', 'tag_name'));
  1064. =cut
  1065. sub switch_to_frame {
  1066. my ( $self, $id ) = @_;
  1067. my $json_null = JSON::null;
  1068. my $params;
  1069. $id = ( defined $id ) ? $id : $json_null;
  1070. my $res = { 'command' => 'switchToFrame' };
  1071. if ( ref $id eq $self->webelement_class ) {
  1072. $params = { 'id' => { 'ELEMENT' => $id->{'id'} } };
  1073. }
  1074. else {
  1075. $params = { 'id' => $id };
  1076. }
  1077. return $self->_execute_command( $res, $params );
  1078. }
  1079. =head2 switch_to_window
  1080. Description:
  1081. Change focus to another window. The window to change focus to may be
  1082. specified by its server assigned window handle, or by the value of its name
  1083. attribute.
  1084. Input: 1
  1085. Required:
  1086. STRING - Window handle or the Window name
  1087. Usage:
  1088. $driver->switch_to_window('MY Homepage');
  1089. or
  1090. # close a popup window and switch back
  1091. my $handles = $driver->get_window_handles;
  1092. $driver->switch_to_window($handles->[1]);
  1093. $driver->close;
  1094. $driver->switch_to_window($handles->[0]);
  1095. =cut
  1096. sub switch_to_window {
  1097. my ( $self, $name ) = @_;
  1098. if ( not defined $name ) {
  1099. return 'Window name not provided';
  1100. }
  1101. my $res = { 'command' => 'switchToWindow' };
  1102. my $params = { 'name' => $name };
  1103. return $self->_execute_command( $res, $params );
  1104. }
  1105. =head2 get_speed
  1106. Description:
  1107. Get the current user input speed. The actual input speed is still browser
  1108. specific and not covered by the Driver.
  1109. Output:
  1110. STRING - One of these: SLOW, MEDIUM, FAST
  1111. Usage:
  1112. print $driver->get_speed();
  1113. =cut
  1114. sub get_speed {
  1115. my ($self) = @_;
  1116. my $res = { 'command' => 'getSpeed' };
  1117. return $self->_execute_command($res);
  1118. }
  1119. =head2 set_speed
  1120. Description:
  1121. Set the user input speed.
  1122. Input:
  1123. STRING - One of these: SLOW, MEDIUM, FAST
  1124. Usage:
  1125. $driver->set_speed('MEDIUM');
  1126. Note: This function is a no-op in WebDriver (?). See
  1127. https://groups.google.com/d/topic/selenium-users/oX0ZnYFPuSA/discussion and
  1128. http://code.google.com/p/selenium/source/browse/trunk/java/client/src/org/openqa/selenium/WebDriverCommandProcessor.java
  1129. =cut
  1130. sub set_speed {
  1131. my ( $self, $speed ) = @_;
  1132. if ( not defined $speed ) {
  1133. return 'Speed not provided.';
  1134. }
  1135. my $res = { 'command' => 'setSpeed' };
  1136. my $params = { 'speed' => $speed };
  1137. return $self->_execute_command( $res, $params );
  1138. }
  1139. =head2 set_window_position
  1140. Description:
  1141. Set the position (on screen) where you want your browser to be displayed.
  1142. Input:
  1143. INT - x co-ordinate
  1144. INT - y co-ordinate
  1145. STRING - <optional> - window handle (default is 'current' window)
  1146. Output:
  1147. BOOLEAN - Success or failure
  1148. Usage:
  1149. $driver->set_window_position(50, 50);
  1150. =cut
  1151. sub set_window_position {
  1152. my ( $self, $x, $y, $window ) = @_;
  1153. $window = ( defined $window ) ? $window : 'current';
  1154. if ( not defined $x and not defined $y ) {
  1155. croak "X & Y co-ordinates are required";
  1156. }
  1157. my $res = { 'command' => 'setWindowPosition', 'window_handle' => $window };
  1158. my $params = { 'x' => $x, 'y' => $y };
  1159. my $ret = $self->_execute_command( $res, $params );
  1160. if ( $ret =~ m/204/g ) {
  1161. return 1;
  1162. }
  1163. else { return 0; }
  1164. }
  1165. =head2 set_window_size
  1166. Description:
  1167. Set the size of the browser window
  1168. Input:
  1169. INT - height of the window
  1170. INT - width of the window
  1171. STRING - <optional> - window handle (default is 'current' window)
  1172. Output:
  1173. BOOLEAN - Success or failure
  1174. Usage:
  1175. $driver->set_window_size(640, 480);
  1176. =cut
  1177. sub set_window_size {
  1178. my ( $self, $height, $width, $window ) = @_;
  1179. $window = ( defined $window ) ? $window : 'current';
  1180. if ( not defined $height and not defined $width ) {
  1181. croak "height & width of browser are required";
  1182. }
  1183. my $res = { 'command' => 'setWindowSize', 'window_handle' => $window };
  1184. my $params = { 'height' => $height, 'width' => $width };
  1185. my $ret = $self->_execute_command( $res, $params );
  1186. if ( $ret =~ m/204/g ) {
  1187. return 1;
  1188. }
  1189. else { return 0; }
  1190. }
  1191. =head2 get_all_cookies
  1192. Description:
  1193. Retrieve all cookies visible to the current page. Each cookie will be
  1194. returned as a HASH reference with the following keys & their value types:
  1195. 'name' - STRING
  1196. 'value' - STRING
  1197. 'path' - STRING
  1198. 'domain' - STRING
  1199. 'secure' - BOOLEAN
  1200. Output:
  1201. ARRAY of HASHES - list of all the cookie hashes
  1202. Usage:
  1203. print Dumper($driver->get_all_cookies());
  1204. =cut
  1205. sub get_all_cookies {
  1206. my ($self) = @_;
  1207. my $res = { 'command' => 'getAllCookies' };
  1208. return $self->_execute_command($res);
  1209. }
  1210. =head2 add_cookie
  1211. Description:
  1212. Set a cookie on the domain.
  1213. Input: 5 (1 optional)
  1214. Required:
  1215. 'name' - STRING
  1216. 'value' - STRING
  1217. 'path' - STRING
  1218. 'domain' - STRING
  1219. Optional:
  1220. 'secure' - BOOLEAN - default is false.
  1221. Usage:
  1222. $driver->add_cookie('foo', 'bar', '/', '.google.com', 0)
  1223. =cut
  1224. sub add_cookie {
  1225. my ( $self, $name, $value, $path, $domain, $secure ) = @_;
  1226. if ( ( not defined $name )
  1227. || ( not defined $value )
  1228. || ( not defined $path )
  1229. || ( not defined $domain ) )
  1230. {
  1231. croak "Missing parameters";
  1232. }
  1233. my $res = { 'command' => 'addCookie' };
  1234. my $json_false = JSON::false;
  1235. my $json_true = JSON::true;
  1236. $secure = ( defined $secure && $secure ) ? $json_true : $json_false;
  1237. my $params = {
  1238. 'cookie' => {
  1239. 'name' => $name,
  1240. 'value' => $value,
  1241. 'path' => $path,
  1242. 'domain' => $domain,
  1243. 'secure' => $secure,
  1244. }
  1245. };
  1246. return $self->_execute_command( $res, $params );
  1247. }
  1248. =head2 delete_all_cookies
  1249. Description:
  1250. Delete all cookies visible to the current page.
  1251. Usage:
  1252. $driver->delete_all_cookies();
  1253. =cut
  1254. sub delete_all_cookies {
  1255. my ($self) = @_;
  1256. my $res = { 'command' => 'deleteAllCookies' };
  1257. return $self->_execute_command($res);
  1258. }
  1259. =head2 delete_cookie_named
  1260. Description:
  1261. Delete the cookie with the given name. This command will be a no-op if there
  1262. is no such cookie visible to the current page.
  1263. Input: 1
  1264. Required:
  1265. STRING - name of cookie to delete
  1266. Usage:
  1267. $driver->delete_cookie_named('foo');
  1268. =cut
  1269. sub delete_cookie_named {
  1270. my ( $self, $cookie_name ) = @_;
  1271. if ( not defined $cookie_name ) {
  1272. croak "Cookie name not provided";
  1273. }
  1274. my $res = { 'command' => 'deleteCookieNamed', 'name' => $cookie_name };
  1275. return $self->_execute_command($res);
  1276. }
  1277. =head2 get_page_source
  1278. Description:
  1279. Get the current page source.
  1280. Output:
  1281. STRING - The page source.
  1282. Usage:
  1283. print $driver->get_page_source();
  1284. =cut
  1285. sub get_page_source {
  1286. my ($self) = @_;
  1287. my $res = { 'command' => 'getPageSource' };
  1288. return $self->_execute_command($res);
  1289. }
  1290. =head2 find_element
  1291. Description:
  1292. Search for an element on the page, starting from the document root. The
  1293. located element will be returned as a WebElement object.
  1294. Input: 2 (1 optional)
  1295. Required:
  1296. STRING - The search target.
  1297. Optional:
  1298. STRING - Locator scheme to use to search the element, available schemes:
  1299. {class, class_name, css, id, link, link_text, partial_link_text,
  1300. tag_name, name, xpath}
  1301. Defaults to 'xpath' if not configured global during instantiation.
  1302. Output:
  1303. Selenium::Remote::WebElement - WebElement Object
  1304. (This could be a subclass of L<Selenium::Remote::WebElement> if C<webelement_class> was set.
  1305. Usage:
  1306. $driver->find_element("//input[\@name='q']");
  1307. =cut
  1308. sub find_element {
  1309. my ( $self, $query, $method ) = @_;
  1310. if ( not defined $query ) {
  1311. croak 'Search string to find element not provided.';
  1312. }
  1313. my $using =
  1314. ( defined $method ) ? FINDERS->{$method} : $self->default_finder;
  1315. if ( defined $using ) {
  1316. my $res = { 'command' => 'findElement' };
  1317. my $params = { 'using' => $using, 'value' => $query };
  1318. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1319. if ($@) {
  1320. if ( $@
  1321. =~ /(An element could not be located on the page using the given search parameters)/
  1322. )
  1323. {
  1324. # give details on what element wasn't found
  1325. $@ = "$1: $query,$using";
  1326. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1327. croak $@;
  1328. }
  1329. else {
  1330. # re throw if the exception wasn't what we expected
  1331. die $@;
  1332. }
  1333. }
  1334. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1335. driver => $self );
  1336. }
  1337. else {
  1338. croak "Bad method, expected - class, class_name, css, id, link,
  1339. link_text, partial_link_text, name, tag_name, xpath";
  1340. }
  1341. }
  1342. =head2 find_elements
  1343. Description:
  1344. Search for multiple elements on the page, starting from the document root.
  1345. The located elements will be returned as an array of WebElement object.
  1346. Input: 2 (1 optional)
  1347. Required:
  1348. STRING - The search target.
  1349. Optional:
  1350. STRING - Locator scheme to use to search the element, available schemes:
  1351. {class, class_name, css, id, link, link_text, partial_link_text,
  1352. tag_name, name, xpath}
  1353. Defaults to 'xpath' if not configured global during instantiation.
  1354. Output:
  1355. ARRAY or ARRAYREF of WebElement Objects
  1356. Usage:
  1357. $driver->find_elements("//input");
  1358. =cut
  1359. sub find_elements {
  1360. my ( $self, $query, $method ) = @_;
  1361. if ( not defined $query ) {
  1362. croak 'Search string to find element not provided.';
  1363. }
  1364. my $using =
  1365. ( defined $method ) ? FINDERS->{$method} : $self->default_finder;
  1366. if ( defined $using ) {
  1367. my $res = { 'command' => 'findElements' };
  1368. my $params = { 'using' => $using, 'value' => $query };
  1369. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1370. if ($@) {
  1371. if ( $@
  1372. =~ /(An element could not be located on the page using the given search parameters)/
  1373. )
  1374. {
  1375. # give details on what element wasn't found
  1376. $@ = "$1: $query,$using";
  1377. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1378. croak $@;
  1379. }
  1380. else {
  1381. # re throw if the exception wasn't what we expected
  1382. die $@;
  1383. }
  1384. }
  1385. my $elem_obj_arr = [];
  1386. foreach (@$ret_data) {
  1387. push(
  1388. @$elem_obj_arr,
  1389. $self->webelement_class->new(
  1390. id => $_->{ELEMENT}, driver => $self
  1391. )
  1392. );
  1393. }
  1394. return wantarray? @{$elem_obj_arr} : $elem_obj_arr ;
  1395. }
  1396. else {
  1397. croak "Bad method, expected - class, class_name, css, id, link,
  1398. link_text, partial_link_text, name, tag_name, xpath";
  1399. }
  1400. }
  1401. =head2 find_child_element
  1402. Description:
  1403. Search for an element on the page, starting from the identified element. The
  1404. located element will be returned as a WebElement object.
  1405. Input: 3 (1 optional)
  1406. Required:
  1407. Selenium::Remote::WebElement - WebElement object from where you want to
  1408. start searching.
  1409. STRING - The search target. (Do not use a double whack('//')
  1410. in an xpath to search for a child element
  1411. ex: '//option[@id="something"]'
  1412. instead use a dot whack ('./')
  1413. ex: './option[@id="something"]')
  1414. Optional:
  1415. STRING - Locator scheme to use to search the element, available schemes:
  1416. {class, class_name, css, id, link, link_text, partial_link_text,
  1417. tag_name, name, xpath}
  1418. Defaults to 'xpath' if not configured global during instantiation.
  1419. Output:
  1420. WebElement Object
  1421. Usage:
  1422. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1423. # note the usage of ./ when searching for a child element instead of //
  1424. my $child = $driver->find_child_element($elem1, "./option[\@value='es_ar']");
  1425. =cut
  1426. sub find_child_element {
  1427. my ( $self, $elem, $query, $method ) = @_;
  1428. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1429. croak "Missing parameters";
  1430. }
  1431. my $using = ( defined $method ) ? $method : $self->default_finder;
  1432. if ( exists FINDERS->{$using} ) {
  1433. my $res = { 'command' => 'findChildElement', 'id' => $elem->{id} };
  1434. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1435. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1436. if ($@) {
  1437. if ( $@
  1438. =~ /(An element could not be located on the page using the given search parameters)/
  1439. )
  1440. {
  1441. # give details on what element wasn't found
  1442. $@ = "$1: $query,$using";
  1443. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1444. croak $@;
  1445. }
  1446. else {
  1447. # re throw if the exception wasn't what we expected
  1448. die $@;
  1449. }
  1450. }
  1451. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1452. driver => $self );
  1453. }
  1454. else {
  1455. croak "Bad method, expected - class, class_name, css, id, link,
  1456. link_text, partial_link_text, name, tag_name, xpath";
  1457. }
  1458. }
  1459. =head2 find_child_elements
  1460. Description:
  1461. Search for multiple element on the page, starting from the identified
  1462. element. The located elements will be returned as an array of WebElement
  1463. objects.
  1464. Input: 3 (1 optional)
  1465. Required:
  1466. Selenium::Remote::WebElement - WebElement object from where you want to
  1467. start searching.
  1468. STRING - The search target.
  1469. Optional:
  1470. STRING - Locator scheme to use to search the element, available schemes:
  1471. {class, class_name, css, id, link, link_text, partial_link_text,
  1472. tag_name, name, xpath}
  1473. Defaults to 'xpath' if not configured global during instantiation.
  1474. Output:
  1475. ARRAY of WebElement Objects.
  1476. Usage:
  1477. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1478. my $child = $driver->find_child_elements($elem1, "//option");
  1479. =cut
  1480. sub find_child_elements {
  1481. my ( $self, $elem, $query, $method ) = @_;
  1482. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1483. croak "Missing parameters";
  1484. }
  1485. my $using = ( defined $method ) ? $method : $self->default_finder;
  1486. if ( exists FINDERS->{$using} ) {
  1487. my $res = { 'command' => 'findChildElements', 'id' => $elem->{id} };
  1488. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1489. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1490. if ($@) {
  1491. if ( $@
  1492. =~ /(An element could not be located on the page using the given search parameters)/
  1493. )
  1494. {
  1495. # give details on what element wasn't found
  1496. $@ = "$1: $query,$using";
  1497. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1498. croak $@;
  1499. }
  1500. else {
  1501. # re throw if the exception wasn't what we expected
  1502. die $@;
  1503. }
  1504. }
  1505. my $elem_obj_arr;
  1506. my $i = 0;
  1507. foreach (@$ret_data) {
  1508. $elem_obj_arr->[$i] =
  1509. $self->webelement_class->new( id => $_->{ELEMENT},
  1510. driver => $self );
  1511. $i++;
  1512. }
  1513. return wantarray ? @{$elem_obj_arr} : $elem_obj_arr;
  1514. }
  1515. else {
  1516. croak "Bad method, expected - class, class_name, css, id, link,
  1517. link_text, partial_link_text, name, tag_name, xpath";
  1518. }
  1519. }
  1520. =head2 get_active_element
  1521. Description:
  1522. Get the element on the page that currently has focus.. The located element
  1523. will be returned as a WebElement object.
  1524. Output:
  1525. WebElement Object
  1526. Usage:
  1527. $driver->get_active_element();
  1528. =cut
  1529. sub get_active_element {
  1530. my ($self) = @_;
  1531. my $res = { 'command' => 'getActiveElement' };
  1532. my $ret_data = eval { $self->_execute_command($res) };
  1533. if ($@) {
  1534. croak $@;
  1535. }
  1536. else {
  1537. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1538. driver => $self );
  1539. }
  1540. }
  1541. =head2 send_modifier
  1542. Description:
  1543. Send an event to the active element to depress or release a modifier key.
  1544. Input: 2
  1545. Required:
  1546. value - String - The modifier key event to be sent. This key must be one 'Ctrl','Shift','Alt',' or 'Command'/'Meta' as defined by the send keys command
  1547. isdown - Boolean/String - Whether to generate a key down or key up
  1548. Usage:
  1549. $driver->send_modifier('Alt','down');
  1550. $elem->send_keys('c');
  1551. $driver->send_modifier('Alt','up');
  1552. or
  1553. $driver->send_modifier('Alt',1);
  1554. $elem->send_keys('c');
  1555. $driver->send_modifier('Alt',0);
  1556. =cut
  1557. sub send_modifier {
  1558. my ( $self, $modifier, $isdown ) = @_;
  1559. if ( $isdown =~ /(down|up)/ ) {
  1560. $isdown = $isdown =~ /down/ ? 1 : 0;
  1561. }
  1562. my $res = { 'command' => 'sendModifier' };
  1563. my $params = {
  1564. value => $modifier,
  1565. isdown => $isdown
  1566. };
  1567. return $self->_execute_command( $res, $params );
  1568. }
  1569. =head2 compare_elements
  1570. Description:
  1571. Test if two element IDs refer to the same DOM element.
  1572. Input: 2
  1573. Required:
  1574. Selenium::Remote::WebElement - WebElement Object
  1575. Selenium::Remote::WebElement - WebElement Object
  1576. Output:
  1577. BOOLEAN
  1578. Usage:
  1579. $driver->compare_elements($elem_obj1, $elem_obj2);
  1580. =cut
  1581. sub compare_elements {
  1582. my ( $self, $elem1, $elem2 ) = @_;
  1583. my $res = {
  1584. 'command' => 'elementEquals',
  1585. 'id' => $elem1->{id},
  1586. 'other' => $elem2->{id}
  1587. };
  1588. return $self->_execute_command($res);
  1589. }
  1590. =head2 click
  1591. Description:
  1592. Click any mouse button (at the coordinates set by the last moveto command).
  1593. Input:
  1594. button - any one of 'LEFT'/0 'MIDDLE'/1 'RIGHT'/2
  1595. defaults to 'LEFT'
  1596. Usage:
  1597. $driver->click('LEFT');
  1598. $driver->click(1); #MIDDLE
  1599. $driver->click('RIGHT');
  1600. $driver->click; #Defaults to left
  1601. =cut
  1602. sub click {
  1603. my ( $self, $button ) = @_;
  1604. my $button_enum = { LEFT => 0, MIDDLE => 1, RIGHT => 2 };
  1605. if ( defined $button && $button =~ /(LEFT|MIDDLE|RIGHT)/i ) {
  1606. $button = $button_enum->{ uc $1 };
  1607. }
  1608. elsif ( defined $button && $button =~ /(0|1|2)/ ) {
  1609. $button = $1;
  1610. }
  1611. else {
  1612. $button = 0;
  1613. }
  1614. my $res = { 'command' => 'click' };
  1615. my $params = { 'button' => $button };
  1616. return $self->_execute_command( $res, $params );
  1617. }
  1618. =head2 double_click
  1619. Description:
  1620. Double-clicks at the current mouse coordinates (set by moveto).
  1621. Usage:
  1622. $driver->double_click;
  1623. =cut
  1624. sub double_click {
  1625. my ($self) = @_;
  1626. my $res = { 'command' => 'doubleClick' };
  1627. return $self->_execute_command($res);
  1628. }
  1629. =head2 button_down
  1630. Description:
  1631. Click and hold the left mouse button (at the coordinates set by the
  1632. last moveto command). Note that the next mouse-related command that
  1633. should follow is buttonup . Any other mouse command (such as click
  1634. or another call to buttondown) will yield undefined behaviour.
  1635. Usage:
  1636. $self->button_down;
  1637. =cut
  1638. sub button_down {
  1639. my ($self) = @_;
  1640. my $res = { 'command' => 'buttonDown' };
  1641. return $self->_execute_command($res);
  1642. }
  1643. =head2 button_up
  1644. Description:
  1645. Releases the mouse button previously held (where the mouse is
  1646. currently at). Must be called once for every buttondown command
  1647. issued. See the note in click and buttondown about implications of
  1648. out-of-order commands.
  1649. Usage:
  1650. $self->button_up;
  1651. =cut
  1652. sub button_up {
  1653. my ($self) = @_;
  1654. my $res = { 'command' => 'buttonUp' };
  1655. return $self->_execute_command($res);
  1656. }
  1657. =head2 upload_file
  1658. Description:
  1659. Upload a file from the local machine to the selenium server
  1660. machine. That file then can be used for testing file upload on web
  1661. forms. Returns the remote-server's path to the file.
  1662. Usage:
  1663. my $remote_fname = $driver->upload_file( $fname );
  1664. my $element = $driver->find_element( '//input[@id="file"]' );
  1665. $element->send_keys( $remote_fname );
  1666. =cut
  1667. # this method duplicates upload() method in the
  1668. # org.openqa.selenium.remote.RemoteWebElement java class.
  1669. sub upload_file {
  1670. my ( $self, $filename ) = @_;
  1671. if ( not -r $filename ) { die "upload_file: no such file: $filename"; }
  1672. my $string = ""; # buffer
  1673. zip $filename => \$string
  1674. or die "zip failed: $ZipError\n"; # compress the file into string
  1675. my $res = { 'command' => 'uploadFile' }; # /session/:SessionId/file
  1676. require MIME::Base64;
  1677. my $params = {
  1678. file => encode_base64($string) # base64-encoded string
  1679. };
  1680. return $self->_execute_command( $res, $params );
  1681. }
  1682. =head2 get_text
  1683. Description:
  1684. Get the text of a particular element. Wrapper around L<find_element()>
  1685. Usage:
  1686. $text = $driver->get_text("//div[\@name='q']");
  1687. =cut
  1688. sub get_text {
  1689. my $self = shift;
  1690. return $self->find_element(@_)->get_text();
  1691. }
  1692. =head2 get_body
  1693. Description:
  1694. Get the current text for the whole body. If you want the entire raw HTML instead,
  1695. See L<get_page_source>.
  1696. Usage:
  1697. $body_text = $driver->get_body();
  1698. =cut
  1699. sub get_body {
  1700. my $self = shift;
  1701. return $self->get_text('//body');
  1702. }
  1703. =head2 get_path
  1704. Description:
  1705. Get the path part of the current browser location.
  1706. Usage:
  1707. $path = $driver->get_path();
  1708. =cut
  1709. sub get_path {
  1710. my $self = shift;
  1711. my $location = $self->get_current_url;
  1712. $location =~ s/\?.*//; # strip of query params
  1713. $location =~ s/#.*//; # strip of anchors
  1714. $location =~ s#^https?://[^/]+##; # strip off host
  1715. return $location;
  1716. }
  1717. 1;
  1718. __END__
  1719. =head1 SEE ALSO
  1720. http://code.google.com/p/selenium/
  1721. https://code.google.com/p/selenium/wiki/JsonWireProtocol#Capabilities_JSON_Object
  1722. https://github.com/gempesaw/Selenium-Remote-Driver/wiki
  1723. =cut