RemoteConnection.pm 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. package Selenium::Remote::Mock::RemoteConnection;
  2. # ABSTRACT: utility class to mock the responses from Selenium server
  3. use strict;
  4. use warnings;
  5. use Moo;
  6. use JSON;
  7. use Carp;
  8. use Try::Tiny;
  9. use HTTP::Response;
  10. use Data::Dumper;
  11. extends 'Selenium::Remote::RemoteConnection';
  12. has 'spec' => (
  13. is => 'ro',
  14. default => sub { {} },
  15. );
  16. has 'mock_cmds' => ( is => 'ro', );
  17. has 'fake_session_id' => (
  18. is => 'lazy',
  19. builder => sub {
  20. my $id = join '',
  21. map +( 0 .. 9, 'a' .. 'z', 'A' .. 'Z' )[ rand( 10 + 26 * 2 ) ],
  22. 1 .. 50;
  23. return $id;
  24. },
  25. );
  26. has 'record' => (
  27. is => 'ro',
  28. default => sub { 0 }
  29. );
  30. has 'replay' => ( is => 'ro', );
  31. has 'replay_file' => ( is => 'ro', );
  32. has 'session_store' => (
  33. is => 'rw',
  34. default => sub { {} }
  35. );
  36. has 'session_id' => (
  37. is => 'rw',
  38. default => sub { undef },
  39. );
  40. has 'remote_server_addr' => (
  41. is => 'lazy',
  42. default => sub { 'localhost' }
  43. );
  44. =for Pod::Coverage *EVERYTHING*
  45. =cut
  46. sub BUILD {
  47. my $self = shift;
  48. croak 'Cannot define replay and record attributes at the same time'
  49. if ( ( $self->replay ) && ( $self->record ) );
  50. croak 'replay_file attribute needs to be defined'
  51. if ( ( $self->replay ) && !( $self->replay_file ) );
  52. croak 'replay attribute needs to be defined'
  53. if ( !( $self->replay ) && ( $self->replay_file ) );
  54. $self->port('4444');
  55. if ( $self->replay ) {
  56. $self->load_session_store( $self->replay_file );
  57. }
  58. }
  59. sub check_status {
  60. return;
  61. }
  62. sub load_session_store {
  63. my $self = shift;
  64. my $file = shift;
  65. croak "'$file' is not a valid file" unless ( -f $file );
  66. open( my $fh, '<', $file ) or croak "Opening '$file' failed";
  67. # here we use a fake session id since we have no way of figuring out
  68. # which session is good or not
  69. local $/ = undef;
  70. my $json = JSON->new;
  71. $json->allow_blessed;
  72. my $decoded_json = $json->allow_nonref(1)->utf8(1)->decode(<$fh>);
  73. close($fh);
  74. $self->session_store($decoded_json);
  75. }
  76. sub dump_session_store {
  77. my $self = shift;
  78. my ($file) = @_;
  79. open( my $fh, '>', $file ) or croak "Opening '$file' failed";
  80. my $session_store = $self->session_store;
  81. my $dump = {};
  82. foreach my $path ( keys %{$session_store} ) {
  83. $dump->{$path} = $session_store->{$path};
  84. }
  85. my $json = JSON->new;
  86. $json->allow_blessed;
  87. my $json_session = $json->allow_nonref->utf8->pretty->encode($dump);
  88. print $fh $json_session;
  89. close($fh);
  90. }
  91. sub request {
  92. my $self = shift;
  93. my ( $resource, $params ) = @_;
  94. my $method = $resource->{method};
  95. my $url = $resource->{url};
  96. my $no_content_success = $resource->{no_content_success} // 0;
  97. my $content = '';
  98. my $json = JSON->new;
  99. $json->allow_blessed;
  100. if ($params) {
  101. $content = $json->allow_nonref->utf8->canonical(1)->encode($params);
  102. }
  103. my $url_params = $resource->{url_params};
  104. print "REQ: $method, $url, $content\n" if $self->debug;
  105. if ( $self->record ) {
  106. my $response = $self->SUPER::request( $resource, $params, 1 );
  107. push @{ $self->session_store->{"$method $url $content"} },
  108. $response->as_string;
  109. return $self->_process_response( $response, $no_content_success );
  110. }
  111. if ( $self->replay ) {
  112. my $resp;
  113. my $arr_of_resps = $self->session_store->{"$method $url $content"}
  114. // [];
  115. if ( scalar(@$arr_of_resps) ) {
  116. $resp = shift @$arr_of_resps;
  117. $resp = HTTP::Response->parse($resp);
  118. }
  119. else {
  120. $resp = HTTP::Response->new( '501', "Failed to find a response" );
  121. }
  122. return $self->_process_response( $resp, $no_content_success );
  123. }
  124. my $mock_cmds = $self->mock_cmds;
  125. my $spec = $self->spec;
  126. my $cmd = $mock_cmds->get_method_name_from_parameters(
  127. { method => $method, url => $url } );
  128. my $ret = { cmd_status => 'OK', cmd_return => 1 };
  129. if ( defined( $spec->{$cmd} ) ) {
  130. my $return_sub = $spec->{$cmd};
  131. my $mock_return = $return_sub->( $url_params, $params );
  132. if ( ref($mock_return) eq 'HASH' ) {
  133. $ret->{cmd_status} = $mock_return->{status};
  134. $ret->{cmd_return} = $mock_return->{return};
  135. $ret->{cmd_error} = $mock_return->{error} // '';
  136. }
  137. else {
  138. $ret = $mock_return;
  139. }
  140. $ret->{session_id} = $self->fake_session_id if ( ref($ret) eq 'HASH' );
  141. }
  142. else {
  143. $ret->{sessionId} = $self->fake_session_id;
  144. }
  145. return $ret;
  146. }
  147. 1;
  148. __END__
  149. =pod
  150. =head1 DESCRIPTION
  151. Selenium::Remote::Mock::RemoteConnection is a class to act as a short-circuit or a pass through to the connection to a Selenium Server.
  152. Using this class in place of L<Selenium::Remote::RemoteConnection> allows to:
  153. =over
  154. =item *
  155. record interactions with the Selenium Server into a JSON file
  156. =item *
  157. replay recorded interactions from a JSON file to mock answers from the Selenium Server
  158. =item *
  159. mock responses to specific functions
  160. =back
  161. =head1 SYNOPSIS
  162. =head2 Record interactions
  163. use strict;
  164. use warnings;
  165. use Selenium::Remote::Driver;
  166. use Selenium::Remote::Mock::RemoteConnection;
  167. # create a new Mock object to record the interactions with Selenium
  168. # Server
  169. my $mock_connection = Selenium::Remote::Mock::RemoteConnection->new( record => 1 );
  170. # the Mock object is passed to the driver in place of what would be
  171. # a regular Selenium::Remote::RemoteConnection object
  172. my $driver = Selenium::Remote::Driver->new( remote_conn => $mock_connection );
  173. # always store the session id, as it will become undef once
  174. # $driver->quit is called
  175. my $session_id = $driver->session_id;
  176. # do all the selenium things and quit
  177. $driver->get('http://www.google.com');
  178. $driver->get('http://www.wikipedia.com');
  179. $driver->quit;
  180. # dump the session to a file
  181. $mock_connection->dump_session_store( 'my_record.json' );
  182. This code, above doing some basic Selenium interactions, will end up generating a JSON file containing all the requests and their responses for your Selenium session.
  183. The JSON file looks like this :
  184. '{
  185. "HTTP_REQUEST_URL {request_parameters}":[response1,response2,...],
  186. ...
  187. }'
  188. The reason why we store array of responses is that the exact same request can be made more than once during a session, so we have to store every response to the same requests.
  189. =head2 Replay interactions
  190. #!perl
  191. use strict;
  192. use warnings;
  193. use Test::More;
  194. use Test::Selenium::Remote::Driver;
  195. use Selenium::Remote::Mock::RemoteConnection;
  196. my $mock_connection_2 =
  197. Selenium::Remote::Mock::RemoteConnection->new( replay => 1,
  198. replay_file => 'my_record.json' );
  199. # javascript + version parameters added or else it will not work
  200. my $driver =
  201. Test::Selenium::Remote::Driver->new( remote_conn => $mock_connection_2, javascript => 1, version => '' );
  202. $driver->get_ok('http://www.google.com');
  203. $driver->get_ok('http://www.wikipedia.com');
  204. $driver->quit;
  205. done_testing;
  206. Using the file generated with the recording snippet from the section before, we are able to mock the responses.
  207. Note that there is one small limitation (that I hope to remove in future versions), is that a record generated with L<Selenium::Remote::Driver> is not directly useable with L<Test::Selenium::Remote::Driver>.
  208. This is mainly because the way the two instances are created are a bit different, which leads to different requests made, for creating a session for instance.
  209. For now, what works for sure is recording and replaying from the same class.
  210. =head2 Mock responses
  211. #!perl
  212. use Test::More;
  213. use Test::Selenium::Remote::Driver;
  214. use Selenium::Remote::WebElement;
  215. use Selenium::Remote::Mock::Commands;
  216. use Selenium::Remote::Mock::RemoteConnection;
  217. my $spec = {
  218. findElement => sub {
  219. my (undef,$searched_item) = @_;
  220. return { status => 'OK', return => { ELEMENT => '123456' } }
  221. if ( $searched_item->{value} eq 'q' );
  222. return { status => 'NOK', return => 0, error => 'element not found' };
  223. },
  224. getPageSource => sub { return 'this output matches regex'},
  225. };
  226. my $mock_commands = Selenium::Remote::Mock::Commands->new;
  227. my $successful_driver =
  228. Test::Selenium::Remote::Driver->new(
  229. remote_conn => Selenium::Remote::Mock::RemoteConnection->new( spec => $spec, mock_cmds => $mock_commands ),
  230. commands => $mock_commands,
  231. );
  232. $successful_driver->find_element_ok('q','find_element_ok works');
  233. dies_ok { $successful_driver->find_element_ok('notq') } 'find_element_ok dies if element not found';
  234. $successful_driver->find_no_element_ok('notq','find_no_element_ok works');
  235. $successful_driver->content_like( qr/matches/, 'content_like works');
  236. $successful_driver->content_unlike( qr/nomatch/, 'content_unlike works');
  237. done_testing();
  238. Mocking responses by hand requires a more advanced knowledge of the underlying implementation of L<Selenium::Remote::Driver>.
  239. What we mock here is the processed response that will be returned by L<Selenium::Remote::RemoteConnection> to '_execute_command' call.
  240. To accomplish this we need :
  241. =over
  242. =item *
  243. a spec: a HASHREF which keys are the name of the methods we want to mock. Note that those keys should also be valid keys from the _cmds attribute in L<Selenium::Remote::Commands>.
  244. The value of each key is a sub which will be given two parameters:
  245. =over
  246. =item *
  247. $url_params : the values that should have been replaced in the URL
  248. For instance, on the example above, it would have been:
  249. { session_id => 'some_session_id'}
  250. =item *
  251. $params : the original parameters of the request.
  252. On the example above it would have been:
  253. { value => 'q', using => 'xpath'}
  254. =back
  255. The sub used as a value in the spec is not expected to return anything, so you have to craft very carefully what you return so that it will produce the expected result.
  256. =item *
  257. a mock_cmd: a L<Selenium::Remote::Mock::Commands> object. This is used mainly to hijack the normal commands so that placeholders do not get replaced in the URLs.
  258. =back
  259. =head1 BUGS
  260. This code is really early alpha, so its API might change. Use with caution !
  261. =cut