MockRemoteConnection.pm 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package MockRemoteConnection;
  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. extends 'Selenium::Remote::RemoteConnection';
  8. has 'spec' => (
  9. is => 'ro',
  10. required => 1,
  11. );
  12. has 'mock_cmds' => (
  13. is => 'ro',
  14. );
  15. has 'fake_session_id' => (
  16. is => 'lazy',
  17. builder => sub {
  18. my $id = join '',
  19. map +( 0 .. 9, 'a' .. 'z', 'A' .. 'Z' )[ rand( 10 + 26 * 2 ) ], 1 .. 50;
  20. return $id;
  21. },
  22. );
  23. has 'record' => (
  24. is => 'ro',
  25. default => sub { 0 }
  26. );
  27. has 'session_store' => (
  28. is => 'ro',
  29. default => sub { {} }
  30. );
  31. sub dump_session_store {
  32. my $self = shift;
  33. my ($file,$session_id) = @_;
  34. croak "'$file' is not a file" unless (-f $file);
  35. open my $fh, $file, '>' or croak "Opening '$file' failed";
  36. my $session_store = $self->session_store;
  37. my $dump = {};
  38. foreach my $path (keys %{$session_store->{$session_id}}) {
  39. $dump->{$path} = $session_store->{$session_id}->{$path};
  40. }
  41. my $json = JSON->new;
  42. $json->allow_blessed;
  43. my $json_session = $json->allow_nonref->utf8->encode($dump);
  44. print $fh $json_session;
  45. close ($fh);
  46. }
  47. sub request {
  48. my $self = shift;
  49. my ($resource, $params) = @_;
  50. if ($self->record) {
  51. my ($m,$u) = ($resource->{method},$resource->{url});
  52. }
  53. my $method = $resource->{method};
  54. my $url = $resource->{url};
  55. my $no_content_success = $resource->{no_content_success} // 0;
  56. my $url_params = $resource->{url_params};
  57. my $mock_cmds = $self->mock_cmds;
  58. my $spec = $self->spec;
  59. my $cmd = $mock_cmds->get_method_name_from_parameters({method => $method,url => $url});
  60. my $ret = {cmd_status => 'OK', cmd_return => 1};
  61. if (defined($spec->{$cmd})) {
  62. my $return_sub = $spec->{$cmd};
  63. if ($no_content_success) {
  64. $ret->{cmd_return} = 1;
  65. }
  66. else {
  67. my $mock_return = $return_sub->($url_params,$params);
  68. if (ref($mock_return) eq 'HASH') {
  69. $ret->{cmd_status} = $mock_return->{status};
  70. $ret->{cmd_return} = $mock_return->{return};
  71. $ret->{cmd_error} = $mock_return->{error} // ''
  72. }
  73. else {
  74. $ret = $mock_return;
  75. }
  76. }
  77. $ret->{session_id} = $self->fake_session_id if (ref($ret) eq 'HASH');
  78. }
  79. else {
  80. $ret->{sessionId} = $self->fake_session_id;
  81. }
  82. return $ret;
  83. }
  84. 1;