App-PAIA
view release on metacpan or search on metacpan
lib/App/PAIA/Tester.pm view on Meta::CPAN
use App::PAIA;
use JSON::PP qw(encode_json);
use Scalar::Util qw(reftype);
use HTTP::Tiny;
our $CWD = getcwd();
our $RESULT;
sub decode_json {
my $json = shift;
$json =~ s/^#.*$//mg;
JSON::PP::decode_json($json)
}
sub stdout_json() { decode_json($RESULT->stdout) }
sub stderr_json() { decode_json($RESULT->stderr) }
sub output_json() { decode_json($RESULT->output) }
## no critic
eval "sub $_() { \$RESULT->$_ }" for qw(stdout stderr output error exit_code);
our $HTTP_TINY_REQUEST = \&HTTP::Tiny::request;
our $DEFAULT_PSGI = [ 500, [], ["no response faked yet"] ];
our $PSGI_RESPONSE = $DEFAULT_PSGI;
our $HTTP_REQUEST = sub { $PSGI_RESPONSE };
sub mock_http {
my ($self, $method, $url, $opts) = @_;
my $psgi = $HTTP_REQUEST->(
$method, $url, $opts->{headers}, $opts->{content}
);
return {
protocol => 'HTTP/1.1',
status => $psgi->[0],
headers => { @{$psgi->[1]} },
content => join "", @{$psgi->[2]},
};
};
sub paia_live() {
no warnings;
*HTTP::Tiny::request = $HTTP_TINY_REQUEST;
}
sub new_paia_test(@) { ## no critic
chdir tempdir;
paia_live;
}
sub paia_response(@) { ## no critic
$PSGI_RESPONSE = $DEFAULT_PSGI;
if (ref $_[0] and reftype $_[0] eq 'ARRAY') {
$PSGI_RESPONSE = shift;
} else {
$PSGI_RESPONSE = $DEFAULT_PSGI;
$PSGI_RESPONSE->[0] = $_[0] =~ /^\d+/ ? shift : 200;
$PSGI_RESPONSE->[1] = shift if ref $_[0] and reftype $_[0] eq 'ARRAY' and @_ > 1;
my $content = shift;
if (reftype $content eq 'HASH') {
push @{$PSGI_RESPONSE->[1]}, 'Content-type', 'application/json; charset=UTF-8';
$PSGI_RESPONSE->[2] = [ encode_json($content) ];
} elsif (reftype $_[1] eq 'ARRAY') {
$PSGI_RESPONSE->[2] = $content;
} else {
$PSGI_RESPONSE->[2] = [$content];
}
}
no warnings;
*HTTP::Tiny::request = \&mock_http;
}
sub paia(@) { ## no critic
$RESULT = test_app('App::PAIA' => [@_]);
}
sub PAIA($) { ## no critic
my @args = split /\s+/, shift;
say join ' ', '# paia', @args;
paia(@args);
}
sub done_paia_test() {
chdir $CWD;
done_testing;
}
sub debug {
say "# $_" for split "\n", join "\n", (
"stdout: ".$RESULT->stdout,
"stderr: ".$RESULT->stderr,
"error: ".$RESULT->error // 'undef',
"exit_code: ".$RESULT->exit_code
);
}
1;
__END__
=head1 NAME
App::PAIA::Tester - facilitate PAIA testing
=head1 SYNOPSIS
use Test::More;
use App::PAIA::Tester;
new_paia_test;
# call with list
paia qw(config base http://example.org/);
# call with string and print call
PAIA "config base http://example.org/";
is error, undef;
paia qw(config);
is_deeply stdout_json, {
( run in 2.069 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )