1
0

RemoteConnection.pm 11 KB

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