RemoteConnection.pm 10 KB

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