MockRemoteConnection.pm 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package MockRemoteConnection;
  2. # ABSTRACT: utility class to mock the responses from Selenium server
  3. use Moo;
  4. use JSON;
  5. use Try::Tiny;
  6. extends 'Selenium::Remote::RemoteConnection';
  7. has 'spec' => (
  8. is => 'ro',
  9. required => 1,
  10. );
  11. has 'mock_cmds' => (
  12. is => 'ro',
  13. );
  14. has 'fake_session_id' => (
  15. is => 'lazy',
  16. builder => sub {
  17. my $id = join '',
  18. map +( 0 .. 9, 'a' .. 'z', 'A' .. 'Z' )[ rand( 10 + 26 * 2 ) ], 1 .. 50;
  19. return $id;
  20. },
  21. );
  22. sub request {
  23. my $self = shift;
  24. my ($resource, $params) = @_;
  25. my $method = $resource->{method};
  26. my $url = $resource->{url};
  27. my $no_content_success = $resource->{no_content_success} // 0;
  28. my $url_params = $resource->{url_params};
  29. my $mock_cmds = $self->mock_cmds;
  30. my $spec = $self->spec;
  31. my $cmd = $mock_cmds->get_method_name_from_parameters({method => $method,url => $url});
  32. my $ret = {cmd_status => 'OK', cmd_return => 1};
  33. if (defined($spec->{$cmd})) {
  34. my $return_sub = $spec->{$cmd};
  35. if ($no_content_success) {
  36. $ret->{cmd_return} = 1;
  37. }
  38. else {
  39. my $mock_return = $return_sub->($url_params,$params);
  40. if (ref($mock_return) eq 'HASH') {
  41. $ret->{cmd_status} = $mock_return->{status};
  42. $ret->{cmd_return} = $mock_return->{return};
  43. $ret->{cmd_error} = $mock_return->{error} // ''
  44. }
  45. else {
  46. $ret = $mock_return;
  47. }
  48. }
  49. $ret->{session_id} = $self->fake_session_id if (ref($ret) eq 'HASH');
  50. }
  51. else {
  52. $ret->{sessionId} = $self->fake_session_id;
  53. }
  54. return $ret;
  55. }
  56. 1;