App-Actions
view release on metacpan or search on metacpan
t/function.t view on Meta::CPAN
subtest '_show' => sub {
is(App::Actions::Schema::_show(undef), 'null', 'null');
is(App::Actions::Schema::_show(JSON::PP::false()), 'false', 'false');
is(App::Actions::Schema::_show(12), '12', 'a number is bare');
is(App::Actions::Schema::_show('12a'), q{'12a'}, 'a string is quoted');
is(App::Actions::Schema::_show({}), 'HASH', 'a structure is named by its kind');
};
};
# ---------------------------------------------------------------------------
# App::Actions::Process
# ---------------------------------------------------------------------------
use App::Actions::Process;
# Shell exit statuses the Process tests expect, by meaning.
Readonly::Hash my %STATUS => (
ok => 0,
failed => 3, # what the test programs exit with when told to fail
interrupted => 130, # 128 + SIGINT
not_started => 255, # the program could not be run at all
not_found => 127, # a forked child that could not exec
);
# A command that runs this Perl, so the tests need nothing installed.
sub perl_command { return [ $^X, '-e', @_ ] }
subtest 'App::Actions::Process' => sub {
subtest 'exit_code' => sub {
is(App::Actions::Process::exit_code(0), $STATUS{ok}, 'success');
is(App::Actions::Process::exit_code(undef), $STATUS{ok}, 'no status is success');
is(App::Actions::Process::exit_code($STATUS{failed} << 8), $STATUS{failed}, 'an exit status');
is(App::Actions::Process::exit_code(2), $STATUS{interrupted}, 'a signal is 128 plus its number');
is(App::Actions::Process::exit_code(2 | 128), $STATUS{interrupted}, 'with or without a core dump');
is(App::Actions::Process::exit_code(-1), $STATUS{not_started}, 'a program that could not start is 255');
returns_ok(App::Actions::Process::exit_code(256), { type => 'integer', min => 0, max => 255 }, 'always a shell status');
};
subtest 'cpu_count' => sub {
my $count = App::Actions::Process::cpu_count();
returns_ok($count, { type => 'integer', min => 1 }, 'one processor or more');
{
local $^O = 'MSWin32';
local $ENV{NUMBER_OF_PROCESSORS} = '12';
is(App::Actions::Process::cpu_count(), 12, 'Windows says how many in the environment');
for my $bad ('0', '-4', 'many', '4; rm -rf /', '') {
local $ENV{NUMBER_OF_PROCESSORS} = $bad;
my $fallback = App::Actions::Process::cpu_count();
cmp_ok($fallback, '>=', 1, "a hostile NUMBER_OF_PROCESSORS ('$bad') is ignored");
}
}
};
subtest 'capture' => sub {
# binmode, so a Windows child writes the CRLF itself rather than its
# text layer turning the \n into a second one.
my ($output, $status) = App::Actions::Process::capture(perl_command('binmode STDOUT; print qq{a\r\nb}; exit 3'));
is($output, "a\nb", 'standard output is captured with CRLF made LF');
is($status, $STATUS{failed}, 'with the status');
($output) = App::Actions::Process::capture(perl_command('print STDERR q{noise}; print q{data}'), quiet_stderr => 1);
is($output, 'data', 'quiet_stderr keeps standard error out');
($output) = App::Actions::Process::capture(perl_command('$|=1; print q{1}; print STDERR q{2}; print q{3}'), merge_stderr => 1);
is($output, '123', 'merge_stderr interleaves the two streams in order');
($output, $status) = App::Actions::Process::capture([ File::Spec->catfile(tempdir(CLEANUP => 1), 'missing') ]);
is_deeply([ $output, $status ], [ '', $STATUS{not_started} ], 'a missing program is no output and 255');
# The command is a list, never a shell string: metacharacters are data.
($output) = App::Actions::Process::capture(perl_command('print join q{|}, @ARGV', 'a;echo pwned', '$(id)', '`x`'));
is($output, 'a;echo pwned|$(id)|`x`', 'shell metacharacters reach the program untouched');
for my $bad (undef, [], 'echo hi', { 0 => 'echo' }) {
throws_ok { App::Actions::Process::capture($bad) } qr/\ANo command given at /, 'refused: ' . explain($bad);
}
# A failure while the command runs must propagate, not hand back an
# empty capture that looks like a silent success.
{
my $guard = mock_scoped('App::Actions::Process::run' => sub { die "spawn failed\n" });
throws_ok { App::Actions::Process::capture(perl_command('1')) } qr/\Aspawn failed$/, 'a failure mid-flight propagates';
}
{
local $/ = 'caller separator';
App::Actions::Process::capture(perl_command('print 1'));
is($/, 'caller separator', 'the input record separator is restored');
}
};
subtest 'quote_win32' => sub {
my %cases = (
'plain' => 'plain',
'' => '""',
'two words' => '"two words"',
'say "hi"' => '"say \\"hi\\""',
'C:\\dir\\' => 'C:\\dir\\',
'C:\\my dir\\' => '"C:\\my dir\\\\"',
'a\\"b' => '"a\\\\\\"b"',
"tab\there" => "\"tab\there\"",
);
for my $argument (sort keys %cases) {
is(App::Actions::Process::quote_win32($argument), $cases{$argument}, "quoted: $argument");
}
is(App::Actions::Process::quote_win32(undef), '""', 'undef is an empty argument, kept');
keeps_topic(sub { App::Actions::Process::quote_win32('a b') }, 'quote_win32');
};
subtest '_spawn_args' => sub {
{
# Set, not assumed: on Windows itself $^O is already MSWin32.
local $^O = 'linux';
is_deeply([ App::Actions::Process::_spawn_args([ 'prog', 'a b', '' ]) ], [ 'prog', 'a b', '' ],
'elsewhere the arguments are passed as they are');
}
local $^O = 'MSWin32';
is_deeply([ App::Actions::Process::_spawn_args([ 'prog', 'a b', '' ]) ], [ 'prog', '"a b"', '""' ],
'on Windows they are quoted, the program name is not');
};
subtest '_windows_program_found' => sub {
# Windows would retry a program it cannot start through cmd.exe, so
# the program is looked for first, the way Windows looks: a bare name
# in the current directory and on PATH with a PATHEXT extension, a
# name with an extension as it is, a path where it says.
my $dir = tempdir(CLEANUP => 1);
t/function.t view on Meta::CPAN
throws_ok { App::Actions::Process::run_quiet([]) } qr/\ANo command given at /, 'an empty command is refused';
};
subtest 'stream' => sub {
{
my $guard = mock_scoped('App::Actions::Process::_system' => sub { $? = $STATUS{failed} << 8; return });
is(App::Actions::Process::stream([ 'anything' ]), $STATUS{failed}, 'the status of the child is returned');
}
{
my $guard = mock_scoped('App::Actions::Process::_system' => sub { $? = 2; return });
is(App::Actions::Process::stream([ 'anything' ]), $STATUS{interrupted}, 'an interrupt is 130');
}
throws_ok { App::Actions::Process::stream('ls -l') } qr/\ANo command given at /, 'a string is not a command';
};
subtest '_redirect_child' => sub {
# The routine is for a forked child, so it is tested in one. Windows
# emulates fork() with a thread of this process, so the child's
# redirection would take this test's own standard output and error,
# and POSIX::_exit would end the whole test; Process never forks there.
return plan(skip_all => 'Process does not fork on Windows') if $^O eq 'MSWin32';
my $dir = tempdir(CLEANUP => 1);
my $out = File::Spec->catfile($dir, 'child.out');
my $pid = fork();
die "fork: $!" unless defined $pid;
if (!$pid) {
App::Actions::Process::_redirect_child(stdout => $out);
print "redirected\n";
close STDOUT;
POSIX::_exit(0);
}
waitpid($pid, 0);
is($?, 0, 'the child ran');
open my $handle, '<', $out or die $!;
is(scalar <$handle>, "redirected\n", 'its standard output went to the file');
close $handle;
my $bad = File::Spec->catfile($dir, 'no', 'such', 'dir', 'file');
$pid = fork();
die "fork: $!" unless defined $pid;
if (!$pid) {
open STDERR, '>', File::Spec->devnull;
App::Actions::Process::_redirect_child(stdout => $bad);
POSIX::_exit(0);
}
waitpid($pid, 0);
is(App::Actions::Process::exit_code($?), $STATUS{not_found}, 'a file it cannot open ends the child with 127');
};
subtest 'run_parallel' => sub {
my $codes = App::Actions::Process::run_parallel([ perl_command('exit 3'), perl_command('exit 0'), perl_command('exit 1') ],
concurrency => 2);
returns_ok($codes, { type => 'arrayref' }, 'an array reference');
is_deeply($codes, [ 3, 0, 1 ], 'with each status in the slot of its command');
is_deeply(App::Actions::Process::run_parallel([]), [], 'no commands, no statuses');
is_deeply(App::Actions::Process::run_parallel([ perl_command('exit 3') ], concurrency => 1), [ 3 ], 'one at a time');
my $dir = tempdir(CLEANUP => 1);
my $err = File::Spec->catfile($dir, 'err');
$codes = App::Actions::Process::run_parallel([ [ File::Spec->catfile($dir, 'missing') ], perl_command('exit 0') ],
concurrency => 2, stderr => $err);
is_deeply($codes, [ $STATUS{not_found}, 0 ], 'a program that cannot run is 127, and the others still run');
open my $handle, '<', $err or die $!;
like(do { local $/; <$handle> }, qr/\AUnable to run '\Q$dir\E/, 'and says why, where it was told to');
close $handle;
# Every program writes to the same file; each must add to it, not
# replace what the others wrote, and what was there before is gone.
my $shared = write_file('shared.out', "stale\n", $dir);
for my $concurrency (1, 3) {
App::Actions::Process::run_parallel([ map { perl_command("print qq{$_\\n}") } qw(one two three) ],
concurrency => $concurrency, stdout => $shared);
open my $in, '<', $shared or die $!;
is_deeply([ sort <$in> ], [ "one\n", "three\n", "two\n" ], "concurrency $concurrency keeps every program's output");
close $in;
}
throws_ok { App::Actions::Process::run_parallel([ perl_command('1') ], stdout => File::Spec->catfile($dir, 'no', 'dir')) }
qr/\AUnable to open '/, 'a file that cannot be emptied is refused before anything runs';
throws_ok { App::Actions::Process::run_parallel('echo') } qr/\ANo commands given at /, 'a string is refused';
throws_ok { App::Actions::Process::run_parallel(undef) } qr/\ANo commands given at /, 'and so is nothing';
# An exception while waiting (an interrupt, say) must kill the
# children rather than leave them running behind the report.
my $guard = mock_scoped('App::Actions::Process::exit_code' => sub { die "interrupted\n" });
my $started = time;
throws_ok {
App::Actions::Process::run_parallel([ perl_command('exit 0'), perl_command('sleep 60') ], concurrency => 2);
} qr/\Ainterrupted$/, 'the exception propagates';
cmp_ok(time - $started, '<', 30, 'and the sleeping child was killed, not waited for');
};
subtest 'run' => sub {
my $dir = tempdir(CLEANUP => 1);
my $out = File::Spec->catfile($dir, 'out');
my $err = File::Spec->catfile($dir, 'err');
is(App::Actions::Process::run(perl_command('print q{o}; print STDERR q{e}; exit 3'), stdout => $out, stderr => $err),
$STATUS{failed}, 'the status');
open my $handle, '<', $out or die $!;
is(do { local $/; <$handle> }, 'o', 'standard output went to its file');
open $handle, '<', $err or die $!;
is(do { local $/; <$handle> }, 'e', 'standard error to its own');
close $handle;
my @warnings;
{
local $SIG{__WARN__} = sub { push @warnings, @_ };
is(App::Actions::Process::run([ File::Spec->catfile($dir, 'missing') ]), $STATUS{not_started}, 'a missing program is 255');
}
is_deeply(\@warnings, [], 'without Perl\'s "Can\'t exec" warning');
my $unwritable = File::Spec->catfile($dir, 'no', 'such', 'dir');
throws_ok { App::Actions::Process::run(perl_command('1'), stdout => $unwritable) }
qr/\AUnable to redirect command output: /, 'an output file that cannot be opened is an error';
ok(print(STDOUT ''), 'and standard output was put back after it');
App::Actions::Process::run(perl_command('print q{more}'), stdout => $out, append => 1);
open $handle, '<', $out or die $!;
is(do { local $/; <$handle> }, 'omore', 'append adds to the file');
close $handle;
throws_ok { App::Actions::Process::run([], stdout => $out) } qr/\ANo command given at /, 'an empty command is refused';
};
};
# ---------------------------------------------------------------------------
# App::Actions::Docker
# ---------------------------------------------------------------------------
use App::Actions::Docker;
subtest 'App::Actions::Docker' => sub {
# Every Docker test replaces the three Process entry points, so nothing
# is run: each call is recorded with the environment it would have had,
# and answers with what the test says the client printed.
my (@calls, @answers);
my $record = sub {
my ($kind) = @_;
return sub {
my ($command, %options) = @_;
push @calls, { kind => $kind, command => [ @{$command} ], token => $ENV{TOKEN}, options => {%options} };
my $answer = @answers ? shift @answers : [ '', 0 ];
return $kind eq 'capture' ? @{$answer} : $answer->[1];
};
};
my $fake_process = sub {
@calls = ();
@answers = @_;
return mock_scoped(
'App::Actions::Process::capture' => $record->('capture'),
'App::Actions::Process::stream' => $record->('stream'),
'App::Actions::Process::run_quiet' => $record->('run_quiet'),
);
};
my $docker = sub { App::Actions::Docker->new(bin => 'docker', @_) };
# What a block printed to standard output.
my $printed = sub {
my ($code) = @_;
t/function.t view on Meta::CPAN
subtest 'pull and pull_many' => sub {
{
my $guard = $fake_process->([ '', 0 ], [ '', 1 ]);
is($docker->(platform => 'linux/amd64')->pull('alpine'), 1, 'a pull that works');
is_deeply($calls[0]{command}, [qw(docker pull --platform linux/amd64 alpine)], 'with the platform');
throws_ok { $docker->()->pull('nope') } qr/\AFailed to pull Docker image 'nope' \(exit 1\)\n\z/,
'a failed pull is advice, with no source location';
}
{
my @commands;
my $guard = mock_scoped('App::Actions::Process::run_parallel' => sub {
my ($given, %options) = @_;
@commands = ([ @{$given} ], {%options});
return [ 0, 1 ];
});
my $results = $docker->()->pull_many([qw(a b)], concurrency => 2, quiet => 1);
is_deeply($results, { a => 0, b => 1 }, 'each image gets its own status');
is_deeply($commands[0], [ [qw(docker pull a)], [qw(docker pull b)] ], 'one pull command per image');
is($commands[1]{concurrency}, 2, 'the concurrency is passed on');
is($commands[1]{stdout}, File::Spec->devnull, 'quiet sends the output nowhere');
$docker->()->pull_many([ 'a' ]);
is($commands[1]{concurrency}, 4, 'four at a time by default');
ok(!exists $commands[1]{stdout}, 'and the output is shown when not quiet');
}
my $guard = $fake_process->();
my $text = $printed->(sub { is_deeply($docker->(dry_run => 1)->pull_many([qw(a)]), { a => 0 }, 'a dry run pulls nothing') });
is($text, "[dry-run] docker pull a\n", 'and says what it would have run');
is($printed->(sub { $docker->(dry_run => 1, explain => 1)->pull_many([qw(a)]) }), '', 'explain prints no commands');
for my $bad (undef, [], 'alpine') {
throws_ok { $docker->()->pull_many($bad) } qr/\ANo images given at /, 'refused: ' . explain($bad);
}
};
subtest 'the thin wrappers' => sub {
my $guard = $fake_process->(([ '', 0 ]) x 10);
my $object = $docker->();
$object->image_remove('img');
$object->network_create('net');
$object->network_remove('net');
$object->container_start('--name', 'c', 'img');
$object->container_exec('c', 'true');
$object->container_logs('c');
$object->container_logs('c', 5);
$object->container_remove('c');
is_deeply([ map { [ $_->{kind}, @{ $_->{command} }[ 1 .. $#{ $_->{command} } ] ] } @calls ], [
[qw(run_quiet image rm -f img)],
[qw(run_quiet network create net)],
[qw(run_quiet network rm net)],
[qw(run_quiet run -d --name c img)],
[qw(stream exec c true)],
[qw(stream logs --tail 200 c)],
[qw(stream logs --tail 5 c)],
[qw(run_quiet rm -f c)],
], 'each runs the docker command it is named for, quietly or not');
};
subtest 'container_start_captured and container_log_text' => sub {
my $guard = $fake_process->([ "id\n", 0 ], [ 'error', 125 ], [ "last lines\n", 0 ]);
is_deeply([ $docker->()->container_start_captured('img') ], [ "id\n", 0 ], 'the output and status of the start');
is_deeply([ $docker->()->container_start_captured('img') ], [ 'error', 125 ], 'a failed start says why');
ok($calls[0]{options}{merge_stderr}, 'with standard error merged in');
is($docker->()->container_log_text('c'), "last lines\n", 'the last lines of a log');
is_deeply([ @{ $calls[2]{command} }[ 1 .. 4 ] ], [qw(logs --tail 10 c)], 'ten by default');
is($docker->(dry_run => 1)->container_log_text('c'), '', 'a dry run has no logs');
};
subtest 'container state' => sub {
{
my $guard = $fake_process->([ "true\n", 0 ], [ "false\n", 0 ], [ "true\n", 1 ]);
is($docker->()->container_running('c'), 1, 'running');
is($docker->()->container_running('c'), 0, 'stopped');
is($docker->()->container_running('c'), 0, 'an inspect that fails is not running, whatever it printed');
}
{
my $guard = $fake_process->([ "3\n", 0 ], [ "-1\r\n", 0 ], [ "oops\n", 0 ], [ "3\n", 1 ]);
is($docker->()->container_exit_code('c'), 3, 'an exit code');
is($docker->()->container_exit_code('c'), -1, 'a negative one, as Docker reports some failures');
is($docker->()->container_exit_code('c'), undef, 'text is not an exit code');
is($docker->()->container_exit_code('c'), undef, 'nor is the answer of an inspect that failed');
}
{
my $guard = $fake_process->([ "exited\n", 0 ], [ "\n", 0 ], [ "running", 1 ]);
is($docker->()->container_status('c'), 'exited', 'a status');
is($docker->()->container_status('c'), undef, 'an empty status is unknown');
is($docker->()->container_status('c'), undef, 'so is one from an inspect that failed');
}
{
my $guard = $fake_process->([ "2\n", 0 ], [ "-2\n", 0 ], [ "x\n", 0 ]);
is($docker->()->container_restart_count('c'), 2, 'a restart count');
is($docker->()->container_restart_count('c'), undef, 'a negative count is not one');
is($docker->()->container_restart_count('c'), undef, 'nor is text');
}
my $guard = $fake_process->();
my $dry = $docker->(dry_run => 1);
is_deeply([ $dry->container_running('c'), $dry->container_exit_code('c'), $dry->container_status('c'),
$dry->container_restart_count('c') ], [ 1, 0, 'running', 0 ], 'a dry run\'s containers run and exit cleanly');
is(scalar @calls, 0, 'without asking the daemon');
};
subtest '_inspect_field' => sub {
my $guard = $fake_process->([ " a b \r\n", 0 ], [ 'x', 1 ]);
is($docker->()->_inspect_field('c', '{{.X}}'), 'ab', 'all white space is removed from a field');
is_deeply([ @{ $calls[0]{command} }[ 1 .. 4 ] ], [ 'inspect', '--format', '{{.X}}', 'c' ], 'the format is passed as one argument');
is($docker->()->_inspect_field('c', '{{.X}}'), undef, 'a failed inspect is undef');
};
subtest 'run, run_silent and _spawn' => sub {
my $secret = App::Actions::Docker::Variable->new('TOKEN', 's3cret');
{
delete local $ENV{TOKEN};
my $guard = $fake_process->([ '', 3 ], [ '', 0 ]);
is($docker->()->run('run', '-e', $secret, 'img'), 3, 'run returns the status');
is_deeply($calls[0]{command}, [qw(docker run -e TOKEN img)], 'a variable is passed by name only');
is($calls[0]{token}, 's3cret', 'with its value in the client\'s environment while it runs');
ok(!exists $ENV{TOKEN}, 'and gone again afterwards');
is($docker->()->run_silent('ps'), 0, 'run_silent returns the status');
is($calls[1]{kind}, 'run_quiet', 'and keeps the output quiet');
}
{
local $ENV{TOKEN} = 'the caller\'s';
my $guard = $fake_process->([ '', 0 ]);
t/function.t view on Meta::CPAN
my $guard = $fake_process->();
my $text = $printed->(sub { is($docker->(dry_run => 1)->run('rm', 'x'), 0, 'a dry run succeeds') });
is($text, "[dry-run] docker rm x\n", 'and only says what it would do');
is(scalar @calls, 0, 'having run nothing');
}
# A failure inside the client must not leave the secret behind in
# this process's environment.
{
delete local $ENV{TOKEN};
my $guard = mock_scoped('App::Actions::Process::stream' => sub { die "client crashed\n" });
throws_ok { $docker->()->run('run', '-e', $secret, 'img') } qr/\Aclient crashed$/, 'a crash propagates';
ok(!exists $ENV{TOKEN}, 'and the secret is not left in the environment');
}
};
subtest '_hide_variables' => sub {
my $var = sub { App::Actions::Docker::Variable->new(@_) };
my ($command, $hidden) = App::Actions::Docker::_hide_variables(undef, '-e', $var->('A', '1'), 'img');
is_deeply([ $command, $hidden ], [ [ '-e', 'A', 'img' ], { A => '1' } ], 'a variable moves to the environment');
for my $case (
[ 'a client variable', 'DOCKER_HOST', 'tcp://evil:2375' ],
[ 'PATH', 'PATH', '/tmp/evil' ],
[ 'a proxy', 'https_proxy', 'http://evil' ],
[ 'a name with a space', 'MY VAR', 'x' ],
[ 'a name that starts with a dash', '-X', 'x' ],
[ 'a name that starts with a digit', '1X', 'x' ],
[ 'an empty name', '', 'x' ],
[ 'a value with a NUL', 'OK', "a\0b" ],
) {
my ($what, $name, $value) = @{$case};
($command, $hidden) = App::Actions::Docker::_hide_variables(undef, '-e', $var->($name, $value));
is_deeply([ $command, $hidden ], [ [ '-e', "$name=$value" ], {} ], "$what stays on the command line");
}
# GitHub's INPUT_* names keep - and ., and an input is often a token.
($command, $hidden) = App::Actions::Docker::_hide_variables(undef, '-e', $var->('INPUT_GITHUB-TOKEN', 's3cret'), '-e', $var->('A.B', 1));
is_deeply([ $command, $hidden ], [ [ '-e', 'INPUT_GITHUB-TOKEN', '-e', 'A.B' ], { 'INPUT_GITHUB-TOKEN' => 's3cret', 'A.B' => 1 } ],
'a name with - or . after its first character is hidden');
($command, $hidden) = App::Actions::Docker::_hide_variables(undef, '-e', $var->('Path2', 'a'), '-e', $var->('PATH2', 'b'));
is_deeply($hidden, {}, 'names that differ only in case both stay on the command line');
($command) = App::Actions::Docker::_hide_variables(undef, 'NAME=value', 'plain');
is_deeply($command, [ 'NAME=value', 'plain' ], 'a plain string is never moved');
keeps_topic(sub { App::Actions::Docker::_hide_variables(undef, $var->('A', 1)) }, '_hide_variables');
};
subtest '_announce' => sub {
my $guard = $fake_process->();
is($printed->(sub { is($docker->()->_announce('ps'), 1, 'an ordinary call goes ahead') }), '', 'silently');
is($printed->(sub { $docker->(verbose => 1)->_announce('ps', '-a') }), "+ docker ps -a\n", 'verbose echoes the command');
is($printed->(sub { $docker->(verbose => 1, quiet => 1)->_announce('ps') }), '', 'quiet wins over verbose');
is($printed->(sub { is($docker->(dry_run => 1)->_announce('ps'), 0, 'a dry run does not go ahead') }),
"[dry-run] docker ps\n", 'and says so');
is($printed->(sub { $docker->(dry_run => 1, quiet => 1)->_announce('ps') }), '', 'quietly when asked');
};
subtest 'capture, capture_silent, capture_merged and _capture' => sub {
my $guard = $fake_process->(([ "out\n", 0 ]) x 3);
is_deeply([ $docker->()->capture('ps') ], [ "out\n", 0 ], 'capture returns output and status');
$docker->()->capture_silent('ps');
$docker->()->capture_merged('ps');
is_deeply([ map { [ $_->{options}{quiet_stderr}, $_->{options}{merge_stderr} ] } @calls ], [ [ 0, 0 ], [ 1, 0 ], [ 1, 1 ] ],
'each asks for its own treatment of standard error');
is_deeply([ $docker->(dry_run => 1, quiet => 1)->capture('ps') ], [ '', 0 ], 'a dry run captures nothing and succeeds');
delete local $ENV{TOKEN};
$docker->()->capture('run', '-e', App::Actions::Docker::Variable->new('TOKEN', 'v'));
is($calls[-1]{token}, 'v', 'a captured command gets its variables in the environment too');
ok(!exists $ENV{TOKEN}, 'only while it runs');
};
subtest 'redact' => sub {
my $object = $docker->(secrets => { SHORT => 'abc', LONG => 'abcdef', META => 'a.c*' });
is($object->redact('x abcdef y abc'), 'x *** y ***', 'the longest secret is replaced first');
is($object->redact('aXc a.c*'), 'aXc ***', 'a secret is text, not a pattern');
is($object->redact(undef), undef, 'undef stays undef');
is($object->redact('nothing secret'), 'nothing secret', 'other text is unchanged');
is($docker->()->redact('abc'), 'abc', 'with no secrets nothing is hidden');
my $long = 'abc' x $config{big};
my $started = time;
is(length $object->redact($long), 3 * $config{big}, 'a long text full of secrets');
cmp_ok(time - $started, '<=', $config{time_limit}, 'is redacted in linear time');
};
subtest '_display and _quote' => sub {
my $object = $docker->(secrets => { TOKEN => 's3cret' });
is($object->_display('run', '-e', 'TOKEN=anything', 'img'), q{run -e 'TOKEN=***' img}, 'a secret variable shows no value (quoted, since * is a glob)');
is($object->_display('echo', 'my s3cret!'), q{echo 'my ***!'}, 'a secret anywhere is hidden');
is($object->_display('-e', App::Actions::Docker::Variable->new('TOKEN', 'v')), q{-e 'TOKEN=***'},
'a Variable object is hidden the same way');
is($object->_display('a', undef, ''), q{a '' ''}, 'undef and empty show as empty quotes');
my @args = ('TOKEN=x');
$object->_display(@args);
is($args[0], 'TOKEN=x', 'the caller\'s arguments are not changed');
is(App::Actions::Docker::_quote('plain-word_1.2/x:y@z'), 'plain-word_1.2/x:y@z', 'a safe word is bare');
is(App::Actions::Docker::_quote("it's"), q{'it'\''s'}, 'an embedded quote is closed, escaped and reopened');
is(App::Actions::Docker::_quote('$(rm -rf /)'), q{'$(rm -rf /)'}, 'shell syntax is quoted');
is(App::Actions::Docker::_quote("a\nb"), "'a\nb'", 'a newline is quoted');
keeps_topic(sub { $object->_display('a', 'b') }, '_display');
};
};
# ---------------------------------------------------------------------------
# App::Actions::Expression
# ---------------------------------------------------------------------------
use App::Actions::Expression;
subtest 'App::Actions::Expression' => sub {
my $context = {
matrix => { os => 'ubuntu-latest', perl => '5.38', list => [qw(a b)], flag => JSON::PP::false() },
env => { Name => 'value', EMPTY => '' },
github => { event_name => 'push' },
};
my $new = sub { App::Actions::Expression->new };
my $value = sub { $new->()->evaluate(@_, $context) };
subtest 'new' => sub {
my $expression = $new->();
isa_ok($expression, 'App::Actions::Expression');
is_deeply([ @{$expression}{qw(context status)} ], [ {}, {} ], 'it starts with no context and no status');
memory_cycle_ok($expression, 'an evaluator holds no reference cycle');
};
t/function.t view on Meta::CPAN
is(App::Actions::Check->new(os => $_)->_is_windows ? 1 : 0, 0, "not Windows: $_") for qw(linux darwin);
is(App::Actions::Check::_trim(" a b \r\n"), 'a b', '_trim');
is(App::Actions::Check::_trim(undef), '', 'undef is empty');
};
};
# ---------------------------------------------------------------------------
# App::Actions::Runner::Support
# ---------------------------------------------------------------------------
use App::Actions::Expression;
use App::Actions::Runner::Support::Env;
use App::Actions::Runner::Support qw(
action_inputs boolean_value chomp_error default_logger env_args has_status_function
local_action_dir local_action_path null_logger redact resolve_env status_flags
trim_error write_container_file
);
# Stand-ins for the runner's collaborators. Each records what it was asked,
# so a test can tell whether the evaluator was consulted at all.
{
package Local::FakeExpression;
sub new { my ($class, %answer) = @_; return bless { %answer, asked => [] }, $class }
sub condition { my ($self, $text) = @_; push @{ $self->{asked} }, $text; return $self->{condition} }
sub interpolate {
my ($self, $text) = @_;
push @{ $self->{asked} }, $text;
die $self->{dies} if $self->{dies};
return $self->{interpolate} ? $self->{interpolate}->($text) : $text;
}
package Local::FakeAction;
sub new { my ($class, $inputs) = @_; return bless { inputs => $inputs }, $class }
sub inputs { return $_[0]{inputs} }
package Local::Redactor;
sub new { return bless {}, shift }
sub redact { my (undef, $text) = @_; (my $copy = $text) =~ s/hunter2/***/g; return $copy }
}
subtest 'App::Actions::Runner::Support' => sub {
subtest 'status_flags' => sub {
is_deeply(status_flags(0), { success => 1, failure => 0, cancelled => 0 }, 'a job that has not failed');
is_deeply(status_flags('yes'), { success => 0, failure => 1, cancelled => 0 }, 'any true value is a failure');
is_deeply(status_flags(undef), status_flags(0), 'undef is not a failure');
returns_ok(status_flags(1), { type => 'hashref' }, 'a hash reference');
};
subtest 'chomp_error and trim_error' => sub {
is(chomp_error("broken \n\t"), 'broken', 'trailing white space goes');
is(chomp_error(" kept"), ' kept', 'leading white space stays');
is(chomp_error(undef), '', 'undef is empty');
is(chomp_error(App::Actions::Error->new(code => 'x.y', message => 'm', location => "\n")), 'm', 'an object reads as its text');
is(trim_error("lost at lib/X.pm line 3.\n"), 'lost', 'the location is cut off');
is(trim_error(undef), undef, 'undef has no description');
is(trim_error(''), undef, 'nor has an empty error');
keeps_topic(sub { chomp_error("x\n"); trim_error("x\n") }, 'chomp_error and trim_error');
};
subtest 'default_logger and null_logger' => sub {
my $stderr = '';
{
local *STDERR;
open STDERR, '>', \$stderr or die $!;
default_logger()->warn('careful');
default_logger()->error('broken');
null_logger()->error('never seen');
}
is($stderr, "careful\nbroken\n", 'the default logger prints plain lines; the null logger prints nothing');
isa_ok(default_logger(), 'Log::Abstraction');
isnt(default_logger(), default_logger(), 'each call is a fresh logger');
};
subtest 'resolve_env' => sub {
my $expression = App::Actions::Expression->new;
my $env = resolve_env($expression, [ { A => 'a', B => 'x' }, 'not a layer', { B => '${{ env.A }}-b' } ], {});
is_deeply($env, { A => 'a', B => 'a-b' }, 'later layers win, and refer to earlier values');
# A chain longer than one pass settles whatever order keys come in.
$env = resolve_env($expression, [ { C => '${{ env.B }}c', B => '${{ env.A }}b', A => 'a' } ], {});
is($env->{C}, 'abc', 'a chain of references settles');
# B is resolved before Z (sorted), so Z is worked out in the middle of
# B's expression, which must then carry on where it was.
$env = resolve_env($expression, [ { Z => 'a', B => q{${{ env.Z == 'a' }}-${{ format('{0}+{1}', env.Z, 2) }}} } ], {});
is($env->{B}, 'true-a+2', 'a variable worked out mid-expression');
# Two variables that refer to each other, or one that refers to
# itself, have no value; they must be reported, not grown pass by pass.
throws_code(sub { resolve_env($expression, [ { A => '${{ env.B }}x', B => '${{ env.A }}y' } ], {}) }, 'runner.env_cycle',
"Environment variable 'A' refers to itself, directly or through other variables", 'a cycle is reported');
my $started = time;
throws_code(sub { resolve_env($expression, [ { A => '${{ env.A }}' x $config{big} } ], {}) }, 'runner.env_cycle',
undef, 'so is a value that repeats itself many times');
ok(time - $started <= $config{time_limit}, 'and that is found at once');
# A value is interpolated once: ${{ }} text that came from the
# context (a commit message, say) must never be evaluated.
my $hostile = { github => { event => { message => '${{ secrets.TOKEN }}' } }, secrets => { TOKEN => 'hunter2' } };
is(resolve_env($expression, [ { MSG => '${{ github.event.message }}', B => '${{ env.MSG }}' } ], $hostile)->{B},
'${{ secrets.TOKEN }}', 'expression text from the context is not expanded, even through another variable');
is(resolve_env($expression, [ { A => '${{ env.MISSING }}z' } ], {})->{A}, 'z', 'an unknown variable is empty');
# The env context holds the resolver, which holds the context: that
# loop must be broken on the way out, even when a cycle aborts the run.
my $weak;
{
# The context is copied, so watch a value it holds, not the hash.
my $context = { github => {} };
Scalar::Util::weaken($weak = $context->{github});
caught { resolve_env($expression, [ { A => '${{ env.A }}' } ], $context) };
}
ok(!defined $weak, 'a failed resolution leaves nothing behind');
is_deeply(resolve_env($expression, [], {}), {}, 'no layers, no variables');
is_deeply(resolve_env($expression, [ { N => 3, B => JSON::PP::true() } ], {}), { N => '3', B => 'true' }, 'values are strings');
my $broken = Local::FakeExpression->new(dies => "bad expression\n");
throws_code(sub { resolve_env($broken, [ { NAME => '${{ nope( }}' } ], {}) }, 'runner.env_failed',
"Unable to evaluate environment variable 'NAME': bad expression", 'an expression that fails names the variable');
my $context = { github => { x => 1 } };
resolve_env(Local::FakeExpression->new, [ { A => 'a' } ], $context);
is_deeply($context, { github => { x => 1 } }, 'the caller\'s context is not given an env');
};
# The tie behind resolve_env, driven by hand so that each path - a value
# worked out once, a cycle, a failure further down a chain - is seen
# without the evaluator in between.
subtest 'App::Actions::Runner::Support::Env' => sub {
t/function.t view on Meta::CPAN
memory_cycle_ok($outcomes, 'the outcomes hold no cycle');
# fail_fast stops jobs that have not started; with two slots the
# third waits, and the first failure stops it.
$object = $parallel->(capacity => 2, run_job => sub { return { result => 'failure' } });
$outcomes = $object->run($plans->(1 .. 3), 1);
is_deeply([ map { $_->{started} } @{$outcomes} ], [ 1, 1, 0 ], 'fail-fast leaves a waiting job unstarted');
$outcomes = $parallel->(capacity => 2, run_job => sub { return { result => 'failure' } })->run($plans->(1 .. 3), 0);
is_deeply([ map { $_->{started} } @{$outcomes} ], [ 1, 1, 1 ], 'without it, every job runs');
$outcomes = $parallel->(capacity => 2, run_job => sub { return { status => 'odd' } })->run($plans->(1 .. 3), 1);
is(scalar(grep { $_->{started} } @{$outcomes}), 3, 'a result with no verdict is not a failure');
# A job's plain print belongs in its log even when the caller has
# selected another handle for its own output.
$object = $parallel->(run_job => sub { print "to the log\n"; return { result => 'success' } });
my $leaked = $printed->(sub { $object->run($plans->(1, 2)) });
is($leaked, '', 'nothing a job printed reaches the caller\'s selected handle');
is(do { open my $h, '<', $object->logs->[0]{path} or die $!; local $/; <$h> }, "to the log\n", 'it is in the log');
# A job that dies leaves no result: the group fails, naming it. The
# default logger writes the reason to standard error, which is the log.
$object = $parallel->(logger => App::Actions::Runner::Support::default_logger(),
run_job => sub { die "exploded\n" if $_[0]{plan}{display_name} eq 'job 2'; return { result => 'success' } });
throws_ok { $object->run($plans->(1, 2)) } qr/\Ajob 'job 2' did not run$/, 'a job that dies fails the group';
like(do { open my $h, '<', $object->logs->[1]{path} or die $!; local $/; <$h> }, qr/^action-run: exploded$/m,
'and its log says why');
# A child that exits without writing anything is the same.
throws_ok { $parallel->(run_job => sub { POSIX::_exit(0) })->run($plans->(1, 2)) } qr/\Ajob 'job \d' did not run$/,
'a child that vanishes';
throws_ok { $parallel->(temp_path => File::Spec->catdir(tempdir(CLEANUP => 1), 'gone'))->run($plans->(1, 2)) }
qr/\Ajob 'job \d' did not run$/, 'a child that cannot open its log';
# Children the system reaps by itself (SIGCHLD ignored) are still
# collected, not dropped from the results.
{
local $SIG{CHLD} = 'IGNORE';
my $outcomes = $parallel->()->run($plans->(1 .. 3));
is(scalar(grep { $_->{result} } @{$outcomes}), 3, 'auto-reaped children are still collected');
}
# An error in the parent kills what is still running before it
# propagates, so no job carries on behind the report.
my $marker = File::Spec->catfile(tempdir(CLEANUP => 1), 'late');
$object = $parallel->(run_job => sub { sleep 3; open my $h, '>', $marker or die; close $h; return { result => 'success' } });
my $guard = mock_scoped('App::Actions::Runner::Parallel::_watch' => sub { die "interrupted\n" });
my $started = time;
throws_ok { $object->run($plans->(1, 2)) } qr/\Ainterrupted$/, 'an interruption propagates';
ok(time - $started < 3, 'without waiting for the jobs');
sleep 1 while time - $started < 4;
ok(!-e $marker, 'which were killed');
};
subtest '_run_here' => sub {
# fork() can fail (too many processes); the job then runs in this
# process, its output still going to its own log. fork itself is
# compiled in and cannot be mocked, so the fallback is called directly.
my $dir = tempdir(CLEANUP => 1);
my $entry = { plan => { display_name => 'here' }, log => File::Spec->catfile($dir, 'job.log'),
result_path => File::Spec->catfile($dir, 'job.json'), shown => 0, pending => '' };
my $object = $parallel->(run_job => sub { print "inline\n"; print STDERR "to stderr\n"; return { result => 'success', pid => $$ } });
my ($out_before, $err_before) = (fileno(STDOUT), fileno(STDERR));
my $text = $printed->(sub { $object->_run_here($entry) });
is($entry->{result}{pid}, $$, 'the job ran here');
is(App::Actions::Runner::Parallel::_read_from($entry->{log}, 0), "inline\nto stderr\n", 'into its log');
is_deeply([ fileno(STDOUT), fileno(STDERR) ], [ $out_before, $err_before ], 'and STDOUT and STDERR are put back');
is($text, '', 'nothing reached the caller\'s selected handle');
my $unwritable = { %{$entry}, log => File::Spec->catfile($dir, 'no', 'job.log') };
my $error = throws_code(sub { $object->_run_here($unwritable) }, 'runner.file_write_failed', undef,
'a log that cannot be opened is refused');
like($error->message, qr/\AUnable to write '\Q$unwritable->{log}\E': /, 'naming it');
is(fileno(STDOUT), $out_before, 'and STDOUT is still standard output');
};
subtest '_note_missing' => sub {
my $object = $parallel->();
my $group = { stopping => 0, error => undef };
$object->_note_missing($group, { result => { result => 'success' }, plan => { display_name => 'a' } });
is_deeply($group, { stopping => 0, error => undef }, 'a job with a result is fine');
$object->_note_missing($group, { plan => { display_name => 'b' } });
is_deeply($group, { stopping => 1, error => "job 'b' did not run\n" }, 'one without stops the group');
$object->_note_missing($group, { plan => { display_name => 'c' } });
is($group->{error}, "job 'b' did not run\n", 'the first error is kept');
};
subtest '_run_job and _write_result' => sub {
my $dir = tempdir(CLEANUP => 1);
my $entry = { plan => { display_name => 'x' }, result_path => File::Spec->catfile($dir, 'r.json') };
is($parallel->(run_job => sub { { result => 'success', b => 1, a => 2 } })->_run_job($entry), 0, 'a result written is 0');
is(App::Actions::Runner::Parallel::_read_from($entry->{result_path}, 0), '{"a":2,"b":1,"result":"success"}', 'as canonical JSON');
my $object = $parallel->(run_job => sub { die "boom\n" });
is($object->_run_job($entry), 1, 'a job that dies is 1');
is_deeply($object->{logger}{lines}, [ [ error => 'action-run: boom' ] ], 'and is logged as an error');
$object = $parallel->(run_job => sub { die "\n" });
$object->_run_job($entry);
is_deeply($object->{logger}{lines}, [ [ error => 'action-run: ' ] ], 'an empty error is still logged');
# die '' becomes "Died at ...", so the only error with nothing to say
# is one that is false: an object whose overloading makes it so.
$object = $parallel->(run_job => sub { die Local::FalseError->new });
$object->_run_job($entry);
is($object->{logger}{lines}[0][1], "action-run: job 'x' did not run", 'an error that is false names the job');
throws_code(sub { $parallel->()->_write_result(File::Spec->catfile($dir, 'no', 'r.json'), {}) }, 'runner.file_write_failed',
undef, 'a result that cannot be written');
throws_ok { $parallel->()->_write_result(File::Spec->catfile($dir, 'x.json'), { code => sub { } }) } qr/encountered CODE/,
'a result that is not data';
};
subtest '_stream and _collect' => sub {
my $dir = tempdir(CLEANUP => 1);
my $log = write_file('job.log', "one\r\n\ntwo\npart", $dir);
my $entry = { plan => { display_name => 'build' }, log => $log, shown => 0, pending => '', result_path => undef };
my $object = $parallel->(quiet => 0);
is($printed->(sub { $object->_stream($entry) }), "[build] one\n\n[build] two\n", 'whole lines, named; a blank line stays blank');
is($entry->{pending}, 'part', 'a partial line waits');
is($printed->(sub { $object->_stream($entry) }), '', 'nothing new, nothing printed');
open my $h, '>>', $log or die $!;
print {$h} "ial\n";
close $h;
is($printed->(sub { $object->_stream($entry) }), "[build] partial\n", 'and is finished when the rest arrives');
is($printed->(sub { $parallel->()->_stream({ %{$entry}, shown => 0 }) }), '', 'quiet shows nothing');
my @results;
t/function.t view on Meta::CPAN
# ---------------------------------------------------------------------------
use App::Actions;
subtest 'App::Actions' => sub {
# A repository with its workflow where GitHub keeps it, so the project
# directory can be worked out from the workflow's path.
my $repository = tempdir(CLEANUP => 1);
require File::Path;
File::Path::make_path(File::Spec->catdir($repository, '.github', 'workflows'));
my $file = write_file('ci.yml', "name: CI\non: push\njobs:\n a:\n runs-on: ubuntu-latest\n steps: [{run: echo}]\n",
File::Spec->catdir($repository, '.github', 'workflows'));
my $actions = sub { return App::Actions->new(workflow_file => $file, docker => Local::RunnerDocker->new, logger => 'NULL', @_) };
subtest 'new and the accessors' => sub {
my $object = $actions->();
is($object->project_dir, Cwd::abs_path($repository), 'the project is the repository the workflow is in');
is($object->workflow_file, Cwd::abs_path($file), 'the workflow file, absolute');
isa_ok($object->workflow, 'App::Actions::Workflow');
is_deeply($object->{jobs}, [], 'no job filter');
my $elsewhere = tempdir(CLEANUP => 1);
is($actions->(project_dir => $elsewhere)->project_dir, Cwd::abs_path($elsewhere), 'an explicit project wins');
memory_cycle_ok($object, 'no reference cycle');
throws_code(sub { App::Actions->new }, 'actions.workflow_file_required', 'workflow_file is required', 'no workflow');
my $missing = File::Spec->catfile($repository, 'none.yml');
throws_code(sub { App::Actions->new(workflow_file => $missing) }, 'actions.workflow_file_missing',
"Workflow file '$missing' does not exist", 'a workflow that is not there');
throws_code(sub { App::Actions->new(workflow_file => $repository) }, 'actions.workflow_file_missing', undef, 'a directory is not a workflow');
my $loose = write_file('loose.yml', "on: push\njobs:\n a: {runs-on: x, steps: [{run: x}]}\n");
throws_code(sub { App::Actions->new(workflow_file => $loose) }, 'actions.project_dir_required',
'project_dir is required when the workflow is not inside .github/workflows', 'a workflow elsewhere needs a project');
my $gone = File::Spec->catdir($repository, 'gone');
throws_code(sub { $actions->(project_dir => $gone) }, 'actions.project_dir_missing', "Project directory '$gone' does not exist",
'a project that is not there');
throws_ok { $actions->(colour => 1) } qr/\AInvalid arguments to App::Actions::new: Unknown parameter 'colour'/, 'an unknown option';
throws_ok { $actions->(jobs => 'a') } qr/'jobs'/, 'a job filter must be a list';
};
subtest '_project_dir' => sub {
is(App::Actions->_project_dir(undef, "$repository/.github/workflows/ci.yml"), Cwd::abs_path($repository), 'from the workflow path');
is(App::Actions->_project_dir(undef, '/.github/workflows/ci.yml'), '/', 'a repository at the root is the root, not the current directory');
is(App::Actions->_project_dir(undef, "$repository/.github/workflows/odd\nname.yml"), Cwd::abs_path($repository),
'a file name with a newline in it is still in the workflows folder');
throws_code(sub { App::Actions->_project_dir(undef, "$repository/.github/workflows/sub/ci.yml") }, 'actions.project_dir_required', undef,
'nor does one in a folder below the workflows');
throws_code(sub { App::Actions->_project_dir(undef, "$repository/github/workflows/ci.yml") }, 'actions.project_dir_required', undef,
'nor one that only looks like it');
};
subtest '_logger' => sub {
my $object = Local::Logger->new;
is(App::Actions::_logger($object), $object, 'an object is used as it is');
my @lines;
my $array = App::Actions::_logger(\@lines);
isa_ok($array, 'Log::Abstraction');
$array->warn('collected');
ok(scalar(grep { /collected/ } map { ref $_ ? $_->{message} : $_ } @lines), 'an array collects the messages');
my $null = App::Actions::_logger('NULL');
isa_ok($null, 'Log::Abstraction');
my $stderr = '';
{
local *STDERR;
open STDERR, '>', \$stderr or die $!;
$null->error('never seen');
}
is($stderr, '', 'NULL is silent');
isa_ok(App::Actions::_logger({ level => 'error' }), 'Log::Abstraction', 'a hash of options');
throws_ok { App::Actions->new(workflow_file => $file, logger => sub { }) } qr/'logger'/, 'a code reference is not one of the forms';
};
subtest 'the logger argument wins over the configuration' => sub {
my $config = tempdir(CLEANUP => 1);
write_file('app-actions.yml', "App__Actions:\n logger:\n level: debug\n", $config);
local $ENV{CONFIG_DIR} = $config;
my $mine = Local::Logger->new;
is($actions->(logger => $mine)->{logger}, $mine, 'a logger given to new is kept');
};
subtest '_overrides and _runner' => sub {
my $object = $actions->(quiet => 1, image => 'mine:1');
is_deeply($object->_overrides('run', [ verbose => 1 ]), { verbose => 1 }, 'an override');
is_deeply($object->_overrides('run', []), {}, 'none');
throws_ok { $object->_overrides('run', [ colour => 1 ]) } qr/\AInvalid arguments to App::Actions::run: Unknown parameter 'colour'/,
'an unknown override names the method';
my $runner = $object->_runner({ image => undef, verbose => 1 });
isa_ok($runner, 'App::Actions::Runner');
is_deeply([ @{$runner}{qw(image verbose quiet)} ], [ undef, 1, 1 ], 'an override replaces, even with undef; the rest are the object\'s');
is($object->_runner({ docker => undef })->{docker}, $object->{docker}, 'an undef docker keeps the object\'s');
};
subtest 'run, preflight and list_jobs' => sub {
my $object = $actions->(quiet => 1);
my %seen;
my $guard = mock_scoped('App::Actions::Runner::run' => sub { $seen{run} = $_[0]{verbose}; 0 });
is($object->run(verbose => 1), 0, 'run is the runner\'s');
is($seen{run}, 1, 'with the overrides');
undef $guard;
$guard = mock_scoped('App::Actions::Runner::preflight' => sub { my (undef, %options) = @_; $seen{preflight} = { %options }; { exit => 0 } });
$object->preflight(json => 1, schema_line => 0);
is_deeply($seen{preflight}, { json => 1, schema_line => 0 }, 'json and schema_line go to the preflight');
throws_ok { $object->preflight(loud => 1) } qr/\AInvalid arguments to App::Actions::preflight: Unknown parameter 'loud'/, 'an unknown option';
undef $guard;
$guard = mock_scoped('App::Actions::Runner::list_jobs' => sub { $seen{list} = [ @{ $_[0] }{qw(dry_run quiet)} ]; 0 });
$object = $actions->();
$object->list_jobs(dry_run => 0);
is_deeply($seen{list}, [ 1, 1 ], 'listing never runs or prints anything but the list');
};
subtest 'json_schema' => sub {
for my $name (qw(check preflight cache logs)) {
is(ref App::Actions->json_schema($name), 'HASH', "the $name schema");
}
is_deeply(App::Actions->json_schema('preflight'), App::Actions::Runner->json_schema, 'each from its own module');
throws_code(sub { App::Actions->json_schema }, 'actions.document_required', 'A document name is required', 'no name');
throws_code(sub { App::Actions->json_schema('') }, 'actions.document_required', undef, 'an empty name');
throws_code(sub { App::Actions->json_schema('Check') }, 'actions.document_unknown',
"Unknown document 'Check'; expected check, preflight, cache or logs", 'names are exact');
throws_code(sub { App::Actions->json_schema('../etc/passwd') }, 'actions.document_unknown', undef, 'a path is just an unknown name');
throws_ok { App::Actions->json_schema([]) } qr/'name'/, 'a name that is not a string';
};
};
# ---------------------------------------------------------------------------
# The cache and logs listings, and the lines a child process prints, in the
t/function.t view on Meta::CPAN
my $cache = $fresh->();
is($cache->_heading_line, "Cache file: $cache->{file}\n", 'the first line names the record');
is($cache->_nothing_selected(undef), "No images have been cached yet.\n", 'an empty record');
is($cache->_nothing_selected($DAY), "No images have been cached yet.\n",
'a threshold over an empty record still says nothing was cached, not that nothing is old');
$cache->{data}{images}{'perl:5.40'} = { pulls => 1, last_used => time };
is($cache->_nothing_selected($DAY), "No cached images are older than 1 day.\n", 'images, none old enough');
is($cache->_nothing_selected(undef), "No images have been cached yet.\n",
'without a threshold there is nothing to be too young for');
my $file = $cache->{file};
$cache->{file} = "a\nb";
is($cache->_heading_line, "Cache file: a\nb\n", 'a name is shown as it is, not interpreted');
$cache->{file} = $file;
memory_cycle_ok($cache, 'no reference cycle');
};
subtest 'Logs::_heading_line and _nothing_selected' => sub {
my $dir = tempdir(CLEANUP => 1);
my $logs = App::Actions::Logs->new(directory => $dir);
is($logs->_heading_line, "Logs directory: $dir\n", 'the first line names the directory');
is($logs->_nothing_selected(undef), "No job logs have been kept yet.\n", 'nothing kept');
is($logs->_nothing_selected($DAY), "No job logs have been kept yet.\n", 'a threshold over nothing');
my $guard = mock_scoped('App::Actions::Logs::entries' => sub { [ { name => 'run' } ] });
is($logs->_nothing_selected($DAY), "No job logs are older than 1 day.\n", 'logs, none old enough');
};
subtest 'a French listing' => sub {
local $ENV{ACTION_RUN_LANG} = 'fr';
my $cache = $fresh->();
my $now = time;
$cache->{data}{images}{'ubuntu:latest'} = { pulls => 1, last_used => $now - 2 * 3600 };
my $out = $cache->report(now => $now);
like($out, qr/\AFichier du cache : /, 'the first line is French');
like($out, qr/il y a 2 heures$/m, 'and so is the age');
unlike($out, qr/Cache file|LAST USED|\bago\b|not reachable|unknown/, 'no English is left');
# The heading row and the image row put each column at the same
# place, though "DERNIERE UTILISATION" is wider than a date.
my ($heading, $row) = grep { /\A \S/ } split /\n/, $out;
my $at = sub { my ($line, $word) = @_; return index($line, $word) };
ok($at->($heading, 'TAILLE') >= 0, 'the size heading is translated');
my @heading_starts = map { $-[0] } $heading =~ /(?<= )\S/g;
my @row_starts = map { $-[0] } $row =~ /(?<= )\S/g;
is($row_starts[0], $heading_starts[0], 'the image column starts where its heading does');
is($row_starts[-1], $heading_starts[-1], 'and so does the age column, after the widened date column');
my $empty = $fresh->();
like($empty->report, qr/^Aucune image n.a encore/m, 'an empty record says so in French');
my $json = $cache->document(now => $now);
is($json->{images}[0]{image}, 'ubuntu:latest', 'the JSON document is not translated');
};
subtest 'a French child process message' => sub {
local $ENV{ACTION_RUN_LANG} = 'fr';
my $dir = tempdir(CLEANUP => 1);
my $err = File::Spec->catfile($dir, 'err');
my $missing = File::Spec->catfile($dir, 'missing');
# Two commands at once, so each runs in a child of its own; a single
# command is run in this process, where a missing program is 255.
my $codes = App::Actions::Process::run_parallel([ [ $missing ], perl_command('exit 0') ],
concurrency => 2, stderr => $err);
is_deeply($codes, [ $STATUS{not_found}, 0 ], 'a program that cannot run is still 127');
open my $handle, '<', $err or die $!;
like(do { local $/; <$handle> }, qr/\AImpossible d.ex.cuter '\Q$missing\E' : /, 'and the child says why in French');
close $handle;
# run_parallel opens the output files before it forks, so a file the
# child cannot open is only reached by calling the child's routine in
# a child: a directory is not a file it can write.
my $pid = fork;
die "fork: $!" unless defined $pid;
if ($pid == 0) {
open STDERR, '>', $err or POSIX::_exit(2);
App::Actions::Process::_redirect_child(stdout => $dir);
POSIX::_exit(0);
}
waitpid $pid, 0;
is($? >> 8, $STATUS{not_found}, 'an output the child cannot open stops it with 127');
open $handle, '<', $err or die $!;
like(do { local $/; <$handle> }, qr/\AImpossible de rediriger stdout vers '\Q$dir\E' : /, 'and says so in French');
close $handle;
};
};
restore_all();
done_testing();
( run in 1.105 second using v1.01-cache-2.11-cpan-60884a8df76 )