01-driver.t 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. use strict;
  2. use warnings;
  3. use JSON;
  4. use Net::Ping;
  5. use HTTP::Headers;
  6. use Test::More;
  7. use Test::LWP::UserAgent;
  8. use Selenium::Remote::Driver;
  9. BEGIN {
  10. if (defined $ENV{'WD_MOCKING_RECORD'} && ($ENV{'WD_MOCKING_RECORD'}==1)) {
  11. use t::lib::MockSeleniumWebDriver;
  12. my $p = Net::Ping->new("tcp", 2);
  13. $p->port_number(4444);
  14. unless ($p->ping('localhost')) {
  15. plan skip_all => "Selenium server is not running on localhost:4444";
  16. exit;
  17. }
  18. warn "\n\nRecording...\n\n";
  19. }
  20. }
  21. my $record = (defined $ENV{'WD_MOCKING_RECORD'} && ($ENV{'WD_MOCKING_RECORD'}==1))?1:0;
  22. my $os = $^O;
  23. if ($os =~ m/(aix|freebsd|openbsd|sunos|solaris)/) {
  24. $os = 'linux';
  25. }
  26. my $mock_file = "01-driver-mock-$os.json";
  27. if (!$record && !(-e "t/mock-recordings/$mock_file")) {
  28. plan skip_all => "Mocking of tests is not been enabled for this platform";
  29. }
  30. t::lib::MockSeleniumWebDriver::register($record,"t/mock-recordings/$mock_file");
  31. my $driver = Selenium::Remote::Driver->new(browser_name => 'firefox');
  32. my $website = 'http://localhost:63636';
  33. my $ret;
  34. ERROR_MESSAGE: {
  35. my $unused_port = do {
  36. my $l = IO::Socket::INET->new(
  37. Listen => 5,
  38. LocalHost => '127.0.0.1',
  39. LocalPort => 0,
  40. Proto => 'tcp',
  41. ReuseAddr => 1,
  42. ) or die $!;
  43. $l->sockport;
  44. };
  45. eval {
  46. my $sel = Selenium::Remote::Driver->new(
  47. host => 'localhost', port => $unused_port);
  48. };
  49. unlike($@, qr/Use of uninitialized value/, "not unhelpful message");
  50. }
  51. DESIRED_CAPABILITIES: {
  52. # We're using a different test method for these because we needed
  53. # to inspect payload of the POST to /session, and the method of
  54. # recording the RES/REQ pairs doesn't provide any easy way to do
  55. # that.
  56. my $tua = Test::LWP::UserAgent->new;
  57. my $res = {
  58. cmd_return => {},
  59. cmd_status => 'OK',
  60. sessionId => '123124123'
  61. };
  62. $tua->map_response(qr{status}, HTTP::Response->new(200, 'OK'));
  63. my $requests_count = 0;
  64. my $mock_session_handler = sub {
  65. my $request = shift;
  66. $requests_count++;
  67. if ($request->method eq 'POST') {
  68. my $caps = from_json($request->decoded_content)->{desiredCapabilities};
  69. my @keys = keys %$caps;
  70. if (scalar @keys) {
  71. ok(scalar @keys == 2, 'exactly 2 keys passed in if we use desired_capabilities');
  72. my $grep = grep { 'browserName' eq $_ } @keys;
  73. ok($grep, 'and it is the right one');
  74. ok($caps->{superfluous} eq 'thing', 'and we pass through anything else');
  75. ok($caps->{browserName} eq 'firefox', 'and we override the "normal" caps');
  76. ok(!exists $caps->{platform}, 'or ignore them entirely');
  77. }
  78. else {
  79. ok(to_json($caps) eq '{}', 'an empty constructor defaults to an empty hash');
  80. }
  81. return HTTP::Response->new(204, 'OK', ['Content-Type' => 'application/json'], to_json($res));
  82. }
  83. else {
  84. # it's the DELETE when the driver calls
  85. # DESTROY. This should be the last call to /session/.
  86. return HTTP::Response->new(200, 'OK')
  87. }
  88. };
  89. $tua->map_response(qr{session}, $mock_session_handler);
  90. my $caps_driver = Selenium::Remote::Driver->new_from_caps(
  91. auto_close => 0,
  92. browser_name => 'not firefox',
  93. platform => 'WINDOWS',
  94. desired_capabilities => {
  95. 'browserName' => 'firefox',
  96. 'superfluous' => 'thing'
  97. },
  98. ua => $tua
  99. );
  100. ok($caps_driver->auto_close eq 0, 'and other properties are still set');
  101. $caps_driver = Selenium::Remote::Driver->new(
  102. auto_close => 0,
  103. browser_name => 'not firefox',
  104. platform => 'WINDOWS',
  105. desired_capabilities => {
  106. 'browserName' => 'firefox',
  107. 'superfluous' => 'thing'
  108. },
  109. ua => $tua
  110. );
  111. ok($caps_driver->auto_close eq 0, 'and other properties are set if we use the normal constructor');
  112. $caps_driver = Selenium::Remote::Driver->new_from_caps(ua => $tua);
  113. ok($requests_count == 3, 'The new_from_caps section has the correct number of requests to /session/');
  114. }
  115. GRID_STARTUP: {
  116. # Mimicking a grid server; /wd/hub/status fails, and we expect
  117. # grid/api/hub/status to be checked instead.
  118. my $tua = Test::LWP::UserAgent->new;
  119. my $not_ok = sub {
  120. return HTTP::Response->new(500, 'NOTOK');
  121. };
  122. $tua->map_response(qr{wd/hub/status}, $not_ok);
  123. my $grid_status_count = 0;
  124. my $ok = sub {
  125. my $res = {
  126. cmd_return => {},
  127. cmd_status => 'OK',
  128. sessionId => '123124123'
  129. };
  130. $grid_status_count++;
  131. return HTTP::Response->new(200, 'OK', ['Content-Type' => 'application/json'], to_json($res));
  132. };
  133. $tua->map_response(qr{(?:grid/api/hub/status|session)}, $ok);
  134. my $grid_driver = Selenium::Remote::Driver->new(ua => $tua);
  135. ok(defined $grid_driver, 'Grid: Object loaded fine using grid/api/hub/status');
  136. ok($grid_driver->isa('Selenium::Remote::Driver'), 'Grid: ...and of right type');
  137. ok($grid_status_count == 2, 'checked Grid specific status');
  138. }
  139. CHECK_DRIVER: {
  140. ok(defined $driver, 'Object loaded fine...');
  141. ok($driver->isa('Selenium::Remote::Driver'), '...and of right type');
  142. ok(defined $driver->{'session_id'}, 'Established session on remote server');
  143. $ret = $driver->get_capabilities;
  144. is($ret->{'browserName'}, 'firefox', 'Right capabilities');
  145. my $status = $driver->status;
  146. ok($status->{build}->{version},"Got status build.version");
  147. ok($status->{build}->{revision},"Got status build.revision");
  148. ok($status->{build}->{time},"Got status build.time");
  149. }
  150. IME: {
  151. SKIP: {
  152. eval {$driver->available_engines;};
  153. if ($@) {
  154. skip "ime not available on this system",3;
  155. }
  156. };
  157. }
  158. LOAD_PAGE: {
  159. $driver->get("$website/index.html");
  160. pass('Loaded home page');
  161. $ret = $driver->get_title();
  162. is($ret, 'Hello WebDriver', 'Got the title');
  163. $ret = $driver->get_current_url();
  164. ok($ret =~ m/$website/i, 'Got proper URL');
  165. }
  166. WINDOW: {
  167. $ret = $driver->get_current_window_handle();
  168. ok($ret =~ m/^{.*}$/, 'Proper window handle received');
  169. $ret = $driver->get_window_handles();
  170. is(ref $ret, 'ARRAY', 'Received all window handles');
  171. $ret = $driver->set_window_position(100,100);
  172. is($ret, 1, 'Set the window position to 100, 100');
  173. $ret = $driver->get_window_position();
  174. is ($ret->{'x'}, 100, 'Got the right X Co-ordinate');
  175. is ($ret->{'y'}, 100, 'Got the right Y Co-ordinate');
  176. $ret = $driver->set_window_size(640, 480);
  177. is($ret, 1, 'Set the window size to 640x480');
  178. $ret = $driver->get_window_size();
  179. is ($ret->{'height'}, 640, 'Got the right height');
  180. is ($ret->{'width'}, 480, 'Got the right width');
  181. $ret = $driver->get_page_source();
  182. ok($ret =~ m/^<html/i, 'Received page source');
  183. eval {$driver->set_implicit_wait_timeout(20001);};
  184. ok(!$@,"Set implicit wait timeout");
  185. eval {$driver->set_implicit_wait_timeout(0);};
  186. ok(!$@,"Reset implicit wait timeout");
  187. $ret = $driver->get("$website/frameset.html");
  188. $ret = $driver->switch_to_frame('second');
  189. }
  190. COOKIES: {
  191. $driver->get("$website/cookies.html");
  192. $ret = $driver->get_all_cookies();
  193. is(@{$ret}, 2, 'Got 2 cookies');
  194. $ret = $driver->delete_all_cookies();
  195. pass('Deleting cookies...');
  196. $ret = $driver->get_all_cookies();
  197. is(@{$ret}, 0, 'Deleted all cookies.');
  198. $ret = $driver->add_cookie('foo', 'bar', '/', 'localhost', 0);
  199. pass('Adding cookie foo...');
  200. $ret = $driver->get_all_cookies();
  201. is(@{$ret}, 1, 'foo cookie added.');
  202. is($ret->[0]{'secure'}, 0, 'foo cookie insecure.');
  203. $ret = $driver->delete_cookie_named('foo');
  204. pass('Deleting cookie foo...');
  205. $ret = $driver->get_all_cookies();
  206. is(@{$ret}, 0, 'foo cookie deleted.');
  207. $ret = $driver->delete_all_cookies();
  208. }
  209. MOVE: {
  210. $driver->get("$website/index.html");
  211. $driver->get("$website/formPage.html");
  212. $ret = $driver->go_back();
  213. pass('Clicked Back...');
  214. $ret = $driver->get_title();
  215. is($ret, 'Hello WebDriver', 'Got the right title');
  216. $ret = $driver->go_forward();
  217. pass('Clicked Forward...');
  218. $ret = $driver->get_title();
  219. is($ret, 'We Leave From Here', 'Got the right title');
  220. $ret = $driver->refresh();
  221. pass('Clicked Refresh...');
  222. $ret = $driver->get_title();
  223. is($ret, 'We Leave From Here', 'Got the right title');
  224. }
  225. FIND: {
  226. my $elem = $driver->find_element("//input[\@id='checky']");
  227. ok($elem->isa('Selenium::Remote::WebElement'), 'Got WebElement via Xpath');
  228. $elem = $driver->find_element('checky', 'id');
  229. ok($elem->isa('Selenium::Remote::WebElement'), 'Got WebElement via Id');
  230. $elem = $driver->find_element('checky', 'name');
  231. ok($elem->isa('Selenium::Remote::WebElement'), 'Got WebElement via Name');
  232. $elem = $driver->find_element('multi', 'id');
  233. $elem = $driver->find_child_element($elem, "option");
  234. ok($elem->isa('Selenium::Remote::WebElement'), 'Got child WebElement...');
  235. $ret = $elem->get_value();
  236. is($ret, 'Eggs', '...right child WebElement');
  237. $ret = $driver->find_child_elements($elem, "//option[\@selected='selected']");
  238. is(@{$ret}, 4, 'Got 4 WebElements');
  239. my $expected_err = "An element could not be located on the page using the "
  240. . "given search parameters: "
  241. . "element_that_doesnt_exist,id"
  242. # the following needs to always be right before the eval
  243. . " at " . __FILE__ . " line " . (__LINE__+1);
  244. eval { $driver->find_element("element_that_doesnt_exist","id"); };
  245. chomp $@;
  246. is($@,$expected_err.".","find_element croaks properly");
  247. my $elems = $driver->find_elements("//input[\@id='checky']");
  248. is(scalar(@$elems),1, 'Got an arrayref of WebElements');
  249. my @array_elems = $driver->find_elements("//input[\@id='checky']");
  250. is(scalar(@array_elems),1, 'Got an array of WebElements');
  251. is($elems->[0]->get_value(),$array_elems[0]->get_value(), 'and the elements returned are the same');
  252. }
  253. EXECUTE: {
  254. my $script = q{
  255. var arg1 = arguments[0];
  256. var elem = window.document.getElementById(arg1);
  257. return elem;
  258. };
  259. my $elem = $driver->execute_script($script,'checky');
  260. ok($elem->isa('Selenium::Remote::WebElement'), 'Executed script');
  261. is($elem->get_attribute('id'),'checky','Execute found proper element');
  262. $script = q{
  263. var links = window.document.links
  264. var length = links.length
  265. var results = new Array(length)
  266. while(length--) results[length] = links[length];
  267. return results;
  268. };
  269. $elem = $driver->execute_script($script);
  270. ok($elem, 'Got something back from execute_script');
  271. isa_ok($elem, 'ARRAY', 'What we got back is an ARRAY ref');
  272. ok(scalar(@$elem), 'There are elements in our array ref');
  273. foreach my $element (@$elem) {
  274. isa_ok($element, 'Selenium::Remote::WebElement', 'Element was converted to a WebElement object');
  275. }
  276. $script = q{
  277. var arg1 = arguments[0];
  278. var callback = arguments[arguments.length-1];
  279. var elem = window.document.getElementById(arg1);
  280. callback(elem);
  281. };
  282. $elem = $driver->execute_async_script($script,'multi');
  283. ok($elem->isa('Selenium::Remote::WebElement'),'Executed async script');
  284. is($elem->get_attribute('id'),'multi','Async found proper element');
  285. }
  286. ALERT: {
  287. $driver->get("$website/alerts.html");
  288. $driver->find_element("alert",'id')->click;
  289. is($driver->get_alert_text,'cheese','alert text match');
  290. eval {$driver->dismiss_alert;};
  291. ok(!$@,"dismissed alert");
  292. $driver->find_element("prompt",'id')->click;
  293. is($driver->get_alert_text,'Enter your name','prompt text match');
  294. $driver->send_keys_to_prompt("Larry Wall");
  295. eval {$driver->accept_alert;};
  296. ok(!$@,"accepted prompt");
  297. is($driver->get_alert_text,'Larry Wall','keys sent to prompt');
  298. $driver->dismiss_alert;
  299. $driver->find_element("confirm",'id')->click;
  300. is($driver->get_alert_text,"Are you sure?",'confirm text match');
  301. eval {$driver->dismiss_alert;};
  302. ok(!$@,"dismissed confirm");
  303. is($driver->get_alert_text,'false',"dismissed confirmed correct");
  304. $driver->accept_alert;
  305. $driver->find_element("confirm",'id')->click;
  306. eval {$driver->accept_alert;};
  307. ok(!$@,"accepted confirm");
  308. is($driver->get_alert_text,'true',"accept confirm correct");
  309. $driver->accept_alert;
  310. }
  311. PAUSE: {
  312. my $starttime=time();
  313. $driver->pause();
  314. my $endtime=time();
  315. ok($starttime <= $endtime-1,"starttime <= endtime+1"); # Slept at least 1 second
  316. ok($starttime >= $endtime-2,"starttime >= endtime-2"); # Slept at most 2 seconds
  317. }
  318. AUTO_CLOSE: {
  319. my $stayOpen = Selenium::Remote::Driver->new(
  320. browser_name => 'firefox',
  321. auto_close => 0
  322. );
  323. $stayOpen->DESTROY();
  324. ok(defined $stayOpen->{'session_id'}, 'auto close in init hash is respected');
  325. $stayOpen->auto_close(1);
  326. $stayOpen->DESTROY();
  327. ok(!defined $stayOpen->{'session_id'}, 'true for auto close is still respected');
  328. $driver->auto_close(0);
  329. $driver->DESTROY();
  330. ok(defined $driver->{'session_id'}, 'changing autoclose on the fly keeps the session open');
  331. $driver->auto_close(1);
  332. }
  333. BASE_URL: {
  334. {
  335. package MySeleniumRemoteDriver;
  336. use Moo;
  337. extends 'Selenium::Remote::Driver';
  338. sub _execute_command { $_[2]->{url} }
  339. 1;
  340. }
  341. my @tests = ({
  342. base_url => 'http://example.com',
  343. url => '/foo',
  344. expected => 'http://example.com/foo',
  345. },{
  346. base_url => 'http://example.com/',
  347. url => '/foo',
  348. expected => 'http://example.com/foo',
  349. },{
  350. base_url => 'http://example.com',
  351. url => 'foo',
  352. expected => 'http://example.com/foo',
  353. },{
  354. base_url => 'http://example.com/a',
  355. url => '/foo',
  356. expected => 'http://example.com/a/foo',
  357. },{
  358. base_url => 'http://example.com/a',
  359. url => 'foo',
  360. expected => 'http://example.com/a/foo',
  361. },{
  362. base_url => 'http://example.com/a',
  363. url => 'http://blog.example.com/foo',
  364. expected => 'http://blog.example.com/foo',
  365. });
  366. for my $test (@tests) {
  367. my $base_url_driver = MySeleniumRemoteDriver->new(
  368. browser_name => 'firefox',
  369. base_url => $test->{base_url},
  370. testing => 1,
  371. );
  372. my $got = $base_url_driver->get($test->{url});
  373. is $got, $test->{expected}, "base_url + $test->{url}";
  374. }
  375. }
  376. QUIT: {
  377. $ret = $driver->quit();
  378. ok((not defined $driver->{'session_id'}), 'Killed the remote session');
  379. }
  380. done_testing;