RemoteConnection.pm 11 KB

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