Util.pm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package Playwright::Util;
  2. use strict;
  3. use warnings;
  4. use v5.28;
  5. use JSON::MaybeXS();
  6. use Carp qw{confess};
  7. use Sereal::Encoder;
  8. use Sereal::Decoder;
  9. use File::Temp;
  10. use POSIX();
  11. #ABSTRACT: Common utility functions for the Playwright module
  12. no warnings 'experimental';
  13. use feature qw{signatures};
  14. =head2 request(STRING method, STRING url, INTEGER port, LWP::UserAgent ua, HASH args) = HASH
  15. De-duplicates request logic in the Playwright Modules.
  16. =cut
  17. sub request ( $method, $url, $port, $ua, %args ) {
  18. my $fullurl = "http://localhost:$port/$url";
  19. # Handle passing Playwright elements as arguments
  20. if (ref $args{args} eq 'ARRAY') {
  21. @{$args{args}} = map {
  22. my $transformed = $_;
  23. if (ref($_) eq 'Playwright::ElementHandle' ) {
  24. $transformed = { uuid => $_->{guid} }
  25. }
  26. $transformed;
  27. } @{$args{args}};
  28. }
  29. my $request = HTTP::Request->new( $method, $fullurl );
  30. $request->header( 'Content-type' => 'application/json' );
  31. $request->content( JSON::MaybeXS::encode_json( \%args ) );
  32. my $response = $ua->request($request);
  33. my $content = $response->decoded_content();
  34. my $decoded = JSON::MaybeXS::decode_json($content);
  35. my $msg = $decoded->{message};
  36. confess($msg) if $decoded->{error};
  37. return $msg;
  38. }
  39. sub arr2hash ($array,$primary_key) {
  40. my $inside_out = {};
  41. @$inside_out{map { $_->{$primary_key} } @$array} = @$array;
  42. return $inside_out;
  43. }
  44. # Serialize a subprocess because NOTHING ON CPAN DOES THIS GRRRRR
  45. sub async ($subroutine) {
  46. # The fork would result in the tmpdir getting whacked when it terminates.
  47. my (undef, $filename) = File::Temp::tempfile();
  48. my $pid = fork() // die "Could not fork";
  49. _child($filename, $subroutine) unless $pid;
  50. return { pid => $pid, file => $filename };
  51. }
  52. sub _child ($filename,$subroutine) {
  53. Sereal::Encoder->encode_to_file($filename,$subroutine->());
  54. # Prevent destructors from firing due to exiting instantly
  55. POSIX::_exit(0);
  56. }
  57. sub await ($to_wait) {
  58. waitpid($to_wait->{pid},0);
  59. confess("Timed out while waiting for event.") unless -f $to_wait->{file} && -s _;
  60. return Sereal::Decoder->decode_from_file($to_wait->{file});
  61. }
  62. 1;