App-Actions

 view release on metacpan or  search on metacpan

t/unit.t  view on Meta::CPAN

	# Leaving an eval clears $@, so what the code left is read inside it.
	my ($ok, $error, $after);
	{
		my $before = $@;
		$ok = eval { $@ = $before; $code->(); $after = $@; 1 };
		$error = $@;
		$@ = $ok ? $after : $before;
	}
	$handle->flush;
	open $handle, '>&', $keep or die "restore $stream: $!";
	die $error unless $ok;
	open my $in, '<', $file or die $!;
	local $/;
	my $text = <$in>;
	return defined $text ? $text : '';
}

subtest 'App::Actions::Process' => sub {
	# Programs run as lists, never through a shell, and every function
	# reports the same exit statuses.  The failures the POD lists that need
	# the operating system to refuse are forced through %FAIL.
	subtest 'exit statuses' => sub {
		is(App::Actions::Process::run(perl_command('exit 0')), 0, 'a program that succeeds is 0');
		settle('status Process: 0 success');
		is(App::Actions::Process::run(perl_command('exit 3')), 3, 'one that fails is the number it chose');
		is(App::Actions::Process::run(perl_command('exit 125')), 125, 'up to 125');
		settle('status Process: 1-125 program status');
		is(App::Actions::Process::run(perl_command('kill q{TERM}, $$; sleep 5')), 128 + 15, 'a signal is 128 plus its number');
		settle('status Process: 128+n signal');
		my $missing = File::Spec->catfile(tempdir(CLEANUP => 1), 'missing');
		is(App::Actions::Process::run([ $missing ]), 255, 'a program that cannot start is 255');
		settle('status Process: 255 not started');
	};

	subtest 'exit_code' => sub {
		is(App::Actions::Process::exit_code(0), 0, 'success');
		is(App::Actions::Process::exit_code(undef), 0, 'no status is success');
		is(App::Actions::Process::exit_code(3 << 8), 3, 'an exit status');
		is(App::Actions::Process::exit_code(2), 130, 'signal 2 is 130, as for Ctrl-C');
		is(App::Actions::Process::exit_code(2 | 128), 130, 'a core dump changes nothing');
		is(App::Actions::Process::exit_code(-1), 255, 'a program that did not start is 255');
		returns_ok(App::Actions::Process::exit_code(256 * 300), { type => 'integer', min => 0, max => 255 }, 'always 0 to 255');
		keeps_globals(sub { App::Actions::Process::exit_code(256) }, 'exit_code');
	};

	subtest 'cpu_count' => sub {
		returns_ok(App::Actions::Process::cpu_count(), { type => 'integer', min => 1 }, 'one processor or more');
		local $^O = 'MSWin32';
		local $ENV{NUMBER_OF_PROCESSORS} = '6';
		is(App::Actions::Process::cpu_count(), 6, 'Windows says in NUMBER_OF_PROCESSORS');
		for my $hostile ('0', '-2', 'lots', '4; rm -rf /', '') {
			local $ENV{NUMBER_OF_PROCESSORS} = $hostile;
			cmp_ok(App::Actions::Process::cpu_count(), '>=', 1, 'a NUMBER_OF_PROCESSORS of ' . shown($hostile) . ' is not believed');
		}
	};

	subtest 'capture' => sub {
		my ($output, $status) = App::Actions::Process::capture(perl_command('binmode STDOUT; print qq{a\r\nb}; exit 4'));
		is($output, "a\nb", 'the output, with CRLF made LF');
		is($status, 4, 'and the status');
		is(output_of(stderr => sub { ($output) = App::Actions::Process::capture(perl_command('print STDERR q{noise}; print q{d}')) }),
			'noise', 'the error output goes to the terminal by default');
		is($output, 'd', 'and is not in the output');
		is(output_of(stderr => sub { ($output) = App::Actions::Process::capture(perl_command('print STDERR q{x}; print q{d}'),
			quiet_stderr => 1) }), '', 'quiet_stderr throws it away');
		($output) = App::Actions::Process::capture(perl_command('$| = 1; print 1; print STDERR 2; print 3'), merge_stderr => 1);
		is($output, '123', 'merge_stderr includes it, in order');
		is_deeply([ App::Actions::Process::capture([ File::Spec->catfile(tempdir(CLEANUP => 1), 'none') ]) ], [ '', 255 ],
			'a missing program is no output and 255');
		($output) = App::Actions::Process::capture(perl_command('print join q{|}, @ARGV', 'a;echo no', '$(id)', '`x`', '*'));
		is($output, 'a;echo no|$(id)|`x`|*', 'arguments are never read by a shell');

		throws_ok { App::Actions::Process::capture($_) } qr/\ANo command given at /, 'refused: ' . shown($_)
			for undef, [], 'echo', { 0 => 'echo' };
		settle('text Process: No command given');

		{
			local $FAIL{seek} = 1;
			throws_ok { App::Actions::Process::capture(perl_command('print 1')) }
				qr/\AUnable to rewind captured output: \S/, 'a temporary file that cannot be rewound';
		}
		settle('text Process: Unable to rewind captured output');
		keeps_globals(sub { App::Actions::Process::capture(perl_command('print 1')) }, 'capture', io => 1);
	};

	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}'), stdout => $out, stderr => $err), 0, 'run');
		my $read = sub { open my $in, '<', $_[0] or die $!; local $/; my $text = <$in>; return defined $text ? $text : '' };
		is($read->($out), 'o', 'the output goes to stdout');
		is($read->($err), 'e', 'the error output to stderr');
		App::Actions::Process::run(perl_command('print q{p}'), stdout => $out, append => 1);
		is($read->($out), 'op', 'append adds to the file');
		App::Actions::Process::run(perl_command('$| = 1; print 1; print STDERR 2'), stdout => $out, stderr => $err, merge_stderr => 1);
		is($read->($out), '12', 'merge_stderr wins over stderr');
		is(output_of(stdout => sub { App::Actions::Process::run(perl_command('print q{gone}')) }), '',
			'without stdout the output is thrown away');

		throws_ok { App::Actions::Process::run(perl_command('1'), stdout => $dir) }
			qr/\AUnable to redirect command output: \S/, 'an output file that cannot be opened';
		settle('text Process: Unable to redirect command output');
		is(output_of(stdout => sub { print "still here\n" }), "still here\n", 'and STDOUT works afterwards');

		for my $stream (qw(STDOUT STDERR)) {
			my $handle = $stream eq 'STDOUT' ? \*STDOUT : \*STDERR;
			local $FAIL{open} = sub { !defined $_[0] && $_[1] eq '>&' && ref $_[2] && $_[2] == $handle };
			throws_ok { App::Actions::Process::run(perl_command('1')) } qr/\AUnable to duplicate $stream: \S/,
				"a $stream that cannot be duplicated";
		}
		settle('text Process: Unable to duplicate STDOUT/STDERR');

		for my $stream (qw(STDOUT STDERR)) {
			open my $keep, '>&', ($stream eq 'STDOUT' ? \*STDOUT : \*STDERR) or die $!;
			my $error;
			{
				local $FAIL{open} = sub { defined $_[0] && !ref $_[0] && $_[0] eq $stream && $_[1] eq '>&'
					&& ref $_[2] && $_[2] != \*STDOUT && $_[2] != \*STDERR };
				$error = caught { App::Actions::Process::run(perl_command('1')) };
			}
			open(($stream eq 'STDOUT' ? \*STDOUT : \*STDERR), '>&', $keep) or die $!;
			like($error, qr/\AUnable to restore $stream: \S/, "a $stream that cannot be restored");
		}
		settle('text Process: Unable to restore STDOUT/STDERR');
		keeps_globals(sub { App::Actions::Process::run(perl_command('exit 0')) }, 'run', io => 1);
	};

	subtest 'run_quiet and stream' => sub {
		my $quiet;
		is(output_of(stderr => sub { is(output_of(stdout => sub {
			$quiet = App::Actions::Process::run_quiet(perl_command('print q{o}; print STDERR q{e}; exit 2')) }), '', 'run_quiet: no output') }),
			'', 'and no error output');
		is($quiet, 2, 'run_quiet: the status');
		my $status;
		is(output_of(stdout => sub { $status = App::Actions::Process::stream(perl_command('print q{live}; exit 5')) }), 'live',
			'stream: the output reaches the terminal');
		is($status, 5, 'stream: the status');
		throws_ok { App::Actions::Process::stream($_) } qr/\ANo command given at /, 'stream refuses ' . shown($_) for undef, [];
		throws_ok { App::Actions::Process::run_quiet([]) } qr/\ANo command given at /, 'run_quiet refuses an empty command';
		keeps_globals(sub { App::Actions::Process::run_quiet(perl_command('1')) }, 'run_quiet', io => 1);
	};

	subtest 'run_parallel' => sub {
		my $dir = tempdir(CLEANUP => 1);
		my $out = File::Spec->catfile($dir, 'out');
		my $statuses = App::Actions::Process::run_parallel([ map { perl_command("print q{$_}; exit $_") } 0 .. 3 ],
			concurrency => 2, stdout => $out);
		returns_ok($statuses, { type => 'arrayref' }, 'an array reference');
		is_deeply($statuses, [ 0 .. 3 ], 'one status per command, in their order');
		open my $in, '<', $out or die $!;
		is(join('', sort split //, do { local $/; <$in> }), '0123', 'each program adds to the one file');
		close $in;
		write_file('out', 'old', $dir);
		App::Actions::Process::run_parallel([ perl_command('print q{new}') ], stdout => $out);
		open $in, '<', $out or die $!;
		is(do { local $/; <$in> }, 'new', 'which is emptied once, first');
		close $in;
		is_deeply(App::Actions::Process::run_parallel([]), [], 'no commands, no statuses');
		is_deeply(App::Actions::Process::run_parallel([ (perl_command('exit 1')) x 3 ]), [ 1, 1, 1 ], 'the default concurrency');

		# A program a child cannot start is 127, and the child says why.
		my $err = File::Spec->catfile($dir, 'err');
		my $missing = File::Spec->catfile($dir, 'missing');
		$statuses = App::Actions::Process::run_parallel([ [ $missing ], perl_command('exit 0') ], concurrency => 2, stderr => $err);
		is_deeply($statuses, [ 127, 0 ], 'a program a child cannot start is 127');
		settle('status Process: 127 child could not start');
		open $in, '<', $err or die $!;
		like(do { local $/; <$in> }, qr/\AUnable to run '\Q$missing\E': \S/, 'and the child says so');
		close $in;
		settle('message process.exec_failed');

		# A file the child cannot open: the parent emptied it, the child's
		# append is refused.
		my $said;
		{
			local $FAIL{open} = sub { defined $_[1] && $_[1] eq '>>' };
			$said = output_of(stderr => sub {
				$statuses = App::Actions::Process::run_parallel([ perl_command('1'), perl_command('1') ], concurrency => 2, stdout => $out);
			});
		}
		is_deeply($statuses, [ 127, 127 ], 'an output a child cannot open is 127');
		like($said, qr/^Unable to redirect stdout to '\Q$out\E': \S/m, 'and the child says so');
		settle('message process.redirect_failed');

		throws_ok { App::Actions::Process::run_parallel($_) } qr/\ANo commands given at /, 'refused: ' . shown($_)
			for undef, 'echo', {};
		settle('text Process: No commands given');
		throws_ok { App::Actions::Process::run_parallel([ perl_command('1') ], stdout => $dir) }
			qr/\AUnable to open '\Q$dir\E': \S/, 'an output file that cannot be emptied';
		settle(q{text Process: Unable to open 'F'});
		keeps_globals(sub { App::Actions::Process::run_parallel([ perl_command('1') ]) }, 'run_parallel', io => 1);
	};

	subtest 'quote_win32' => sub {
		my %quoted = (
			'plain' => 'plain',
			'' => '""',
			'two words' => '"two words"',
			'say "hi"' => '"say \\"hi\\""',
			'C:\\dir\\' => 'C:\\dir\\',
			'C:\\my dir\\' => '"C:\\my dir\\\\"',
			"tab\there" => "\"tab\there\"",
		);
		is(App::Actions::Process::quote_win32($_), $quoted{$_}, 'quoted: ' . shown($_)) for sort keys %quoted;
		is(App::Actions::Process::quote_win32(undef), '""', 'undef is the empty argument');
		returns_ok(App::Actions::Process::quote_win32('x'), { type => 'string', min => 1 }, 'never empty');
		keeps_globals(sub { App::Actions::Process::quote_win32('a b') }, 'quote_win32');
	};
};

# ---------------------------------------------------------------------------
# App::Actions::Docker
# ---------------------------------------------------------------------------

# A scripted stand-in for the docker client.  Each rule is a pattern matched
# against the arguments joined by spaces, then the status, the output and
# the error output to give; the first rule that matches wins and anything
# else succeeds silently.  Every call is logged twice: the arguments exactly
# as given (what any user of the host can read in ps), and, as "ENV NAME=VALUE"
# lines, each bare "-e NAME" the client found in its environment.  The name
# ends in .pl, so it is run with this Perl, as the POD says.
#
# The status PROBE plays App::Actions::Check's probe container: it prints the
# marker file from the folder mounted on /action-run-check, then the number
# of entries in the one on /check-project (0 when there is none), or the
# rule's output instead of that number when the rule gives one.
Readonly::Scalar my $FAKE_DOCKER => <<'FAKE';
use strict;
use warnings;

my @args = @ARGV;
if (open my $log, '>>', $ENV{UNIT_DOCKER_LOG}) {
	print {$log} join("\t", 'ARGV', @args), "\n";
	for my $index (1 .. $#args) {
		next unless $args[$index - 1] eq '-e' && exists $ENV{ $args[$index] };
		print {$log} "ENV\t$args[$index]=$ENV{ $args[$index] }\n";
	}

t/unit.t  view on Meta::CPAN

		my ($kind, @fields) = split /\t/, $line, -1;
		push @{ $log{argv} }, \@fields if $kind eq 'ARGV';
		$log{env}{$1} = $2 if $kind eq 'ENV' && $fields[0] =~ /\A([^=]+)=(.*)\z/s;
	}
	close $in;
	show_state(docker_log => \%log);
	return \%log;
}

sub docker {
	return App::Actions::Docker->new(bin => $fake_docker, @_);
}

subtest 'App::Actions::Docker' => sub {
	subtest 'new and its accessors' => sub {
		my $docker = docker();
		isa_ok($docker, 'App::Actions::Docker');
		is($docker->bin, $fake_docker, 'bin');
		for my $flag (qw(dry_run explain verbose quiet)) {
			is($docker->$flag, 0, "$flag is 0 by default");
			returns_ok(docker($flag => 'yes')->$flag, { type => 'integer', memberof => [ 1 ] }, "$flag is 1 when asked for");
		}
		{
			local $ENV{DOCKER} = '/opt/docker';
			is(App::Actions::Docker->new->bin, '/opt/docker', 'bin defaults to DOCKER');
			local $ENV{DOCKER} = '';
			is(App::Actions::Docker->new->bin, 'docker', 'then to docker');
		}
		is_deeply([ $docker->platform_args ], [], 'no platform, no platform arguments');
		is_deeply([ docker(platform => 'linux/arm64')->platform_args ], [ '--platform', 'linux/arm64' ], 'a platform');
		is_deeply([ docker(platform => '')->platform_args ], [], 'an empty platform is none');
		keeps_globals(sub { docker(secrets => { A => 'b' })->bin }, 'new');
	};

	subtest 'Perl wrappers' => sub {
		# A #! perl script without the executable bit still runs.
		my $script = write_file('docker', "#!/usr/bin/perl\nprint qq{wrapped\\n};\n");
		chmod 0644, $script;
		my ($output, $status) = App::Actions::Docker->new(bin => $script)->capture('version');
		is_deeply([ $output, $status ], [ "wrapped\n", 0 ], 'a #! perl script is run with this Perl');
	};

	subtest 'check' => sub {
		is(App::Actions::Docker->new(bin => File::Spec->catfile(tempdir(CLEANUP => 1), 'none'), dry_run => 1)->check, 1,
			'a dry run checks nothing');
		my $result;
		my $log = with_docker([], sub { $result = docker()->check });
		is($result, 1, 'a working docker is 1');
		is_deeply([ map { $_->[0] } @{ $log->{argv} } ], [ '--version', 'info' ], 'it asks for the version, then the daemon');

		my $missing = File::Spec->catfile(tempdir(CLEANUP => 1), 'none');
		throws_ok { App::Actions::Docker->new(bin => $missing)->check }
			qr/\ADocker executable '\Q$missing\E' was not found or is not usable at /, 'no docker program';
		with_docker([ [ '^--version', 1 ] ], sub {
			throws_ok { docker()->check } qr/\ADocker executable '.*' was not found or is not usable at /, 'a docker that fails';
		});
		settle("text Docker: Docker executable 'BIN' was not found or is not usable");

		my $said;
		with_docker([ [ '^info', 1, '', "daemon down\\n" ] ], sub {
			$said = output_of(stderr => sub {
				throws_ok { docker()->check }
					qr/\ACannot connect to the Docker daemon\. Is Docker running, and can this user access it\? at /,
					'no daemon';
			});
		});
		like($said, qr/daemon down/, "docker's own reason is shown");
		with_docker([ [ '^info', 1, '', "daemon down\\n" ] ], sub {
			$said = output_of(stderr => sub { eval { docker(quiet => 1)->check } });
		});
		is($said, '', 'but not when quiet');
		settle('text Docker: Cannot connect to the Docker daemon');

		with_docker([ [ '^--version', 0, "Docker version 99\\n" ] ], sub {
			is(output_of(stdout => sub { docker(verbose => 1)->check }), "+ $fake_docker --version\nDocker version 99\n"
				. "+ $fake_docker info --format '{{.ServerVersion}}'\n", 'verbose shows the commands and the version');
		});
		with_docker([], sub { keeps_globals(sub { docker()->check }, 'check', io => 1) });
	};

	subtest 'images' => sub {
		with_docker([ [ 'inspect --format \{\{\.Id\}\} there', 0 ], [ 'inspect', 1 ] ], sub {
			is(docker()->image_exists('there'), 1, 'an image that is here');
			is(docker()->image_exists('gone'), 0, 'one that is not');
		});
		is(docker(dry_run => 1)->image_exists('gone'), 1, 'a dry run says yes');

		with_docker([ [ 'Size\}\} big', 0, "1234\\r\\n" ], [ 'Size\}\} odd', 0, 'lots' ], [ 'Size', 1 ] ], sub {
			is(docker()->image_size('big'), 1234, 'the size in bytes');
			is(docker()->image_size('odd'), undef, 'undef when docker says something else');
			is(docker()->image_size('gone'), undef, 'undef for a missing image');
		});
		is(docker(dry_run => 1)->image_size('big'), undef, 'undef in a dry run');

		my $log = with_docker([ [ '^pull', 0, "pulled\\n" ] ], sub {
			is(output_of(stdout => sub { is(docker(platform => 'linux/amd64')->pull('perl:5.40'), 1, 'pull is 1') }),
				"pulled\n", "docker's progress is shown");
		});
		is_deeply($log->{argv}, [ [ 'pull', '--platform', 'linux/amd64', 'perl:5.40' ] ], 'with the platform');
		with_docker([ [ '^pull', 3 ] ], sub {
			throws_ok { docker()->pull('nope') } qr/\AFailed to pull Docker image 'nope' \(exit 3\)\n\z/,
				'a failed pull dies with advice, not a line number';
			ok($@->is('runner.image.pull_failed'), 'as runner.image.pull_failed');
		});

		my $results;
		$log = with_docker([ [ 'pull bad', 2 ] ], sub {
			$results = docker()->pull_many([ 'good', 'bad', 'fine' ], concurrency => 2);
		});
		returns_ok($results, { type => 'hashref' }, 'pull_many: a hash reference');
		is_deeply($results, { good => 0, bad => 2, fine => 0 }, 'the status of each pull');
		is(scalar @{ $log->{argv} }, 3, 'one pull each');
		with_docker([ [ 'pull', 0, "noise\\n", "more\\n" ] ], sub {
			is(output_of(stderr => sub { is(output_of(stdout => sub { docker()->pull_many([ 'a' ], quiet => 1) }), '',
				'quiet: no output') }), '', 'and no error output');
			is(output_of(stdout => sub { docker(verbose => 1)->pull_many([ 'a', 'b' ], quiet => 1) }), '', 'even when verbose');
			like(output_of(stdout => sub { docker(verbose => 1)->pull_many([ 'a', 'b' ]) }),
				qr/\A\+ \Q$fake_docker\E pull a\n\+ \Q$fake_docker\E pull b\n/, 'verbose: the commands first');
		});
		is(output_of(stdout => sub { $results = docker(dry_run => 1, platform => 'x/y')->pull_many([ 'a', 'b' ]) }),
			"[dry-run] $fake_docker pull --platform x/y a\n[dry-run] $fake_docker pull --platform x/y b\n",
			'a dry run prints the pulls');
		is_deeply($results, { a => 0, b => 0 }, 'and says they worked');
		is(output_of(stdout => sub { docker(dry_run => 1, explain => 1)->pull_many([ 'a' ]) }), '', 'unless it is explaining');
		throws_ok { docker()->pull_many($_) } qr/\ANo images given at /, 'pull_many refuses ' . shown($_)
			for undef, [], 'perl', { perl => 1 };
		settle('text Docker: No images given');

		$log = with_docker([ [ 'image rm', 1, 'out', 'err' ] ], sub {
			is(output_of(stdout => sub { is(docker()->image_remove('old'), 1, 'image_remove: the status') }), '',
				'and nothing is shown');
		});
		is_deeply($log->{argv}, [ [ qw(image rm -f old) ] ], 'it forces the removal');
		is(docker(dry_run => 1, quiet => 1)->image_remove('old'), 0, '0 in a dry run');
	};

	subtest 'networks and containers' => sub {
		my $log = with_docker([ [ '^network create', 0 ], [ '^network rm', 4 ] ], sub {
			is(docker()->network_create('net'), 0, 'network_create');
			is(docker()->network_remove('net'), 4, 'network_remove: the status');
		});
		is_deeply($log->{argv}, [ [ qw(network create net) ], [ qw(network rm net) ] ], 'the network commands');

		$log = with_docker([ [ 'run -d bad', 125, '', "port is already allocated\\n" ], [ '^run', 0, "abc123\\n" ] ], sub {
			is(output_of(stdout => sub { is(docker()->container_start('--name', 'j', 'img'), 0, 'container_start') }), '',
				'shows nothing');
			is_deeply([ docker()->container_start_captured('bad') ], [ "port is already allocated\n", 125 ],
				'container_start_captured: why it failed, and the status');
			is_deeply([ docker()->container_start_captured('img') ], [ "abc123\n", 0 ], 'and the id when it worked');
		});
		is_deeply($log->{argv}[0], [ qw(run -d --name j img) ], 'run -d');

		with_docker([ [ '^exec', 6, "from inside\\n" ] ], sub {
			my $status;
			is(output_of(stdout => sub { $status = docker()->container_exec('j', 'sh', '-c', 'exit 6') }), "from inside\n",
				'container_exec shows the output');
			is($status, 6, 'and returns the status');
		});

		with_docker([ [ 'Running\}\} up', 0, "true\\n" ], [ 'Running\}\} down', 0, "false\\n" ], [ 'Running', 1 ] ], sub {
			is(docker()->container_running('up'), 1, 'container_running: running');
			is(docker()->container_running('down'), 0, 'stopped');
			is(docker()->container_running('gone'), 0, 'gone');
		});
		is(docker(dry_run => 1, quiet => 1)->container_running('gone'), 1, 'a dry run says yes');

		$log = with_docker([ [ '^logs', 0, "line\\n", "error line\\n" ] ], sub {
			is(output_of(stdout => sub { is(docker()->container_logs('j'), 0, 'container_logs: the status') }), "line\n",
				'shows the lines');
			docker()->container_logs('j', 5);
			is(docker()->container_log_text('j'), "line\nerror line\n", 'container_log_text: both streams');
			docker()->container_log_text('j', 3);
		});
		is_deeply([ map { $_->[2] } @{ $log->{argv} } ], [ 200, 5, 10, 3 ], 'the default numbers of lines are 200 and 10');
		is(docker(dry_run => 1, quiet => 1)->container_log_text('j'), '', 'empty in a dry run');

		with_docker([
			[ 'ExitCode\}\} three', 0, "3\\r\\n" ], [ 'ExitCode\}\} negative', 0, "-1\\n" ], [ 'ExitCode\}\} odd', 0, "none\\n" ],
			[ 'Status\}\} db', 0, "restarting\\n" ], [ 'Status\}\} blank', 0, "\\n" ],
			[ 'RestartCount\}\} db', 0, "2\\n" ], [ 'RestartCount\}\} odd', 0, "-1\\n" ],
			[ 'inspect', 1 ],
		], sub {
			is(docker()->container_exit_code('three'), 3, 'container_exit_code');
			is(docker()->container_exit_code('negative'), -1, 'which may be negative');
			is(docker()->container_exit_code('odd'), undef, 'undef when it is not a number');
			is(docker()->container_exit_code('gone'), undef, 'undef when docker cannot say');
			is(docker()->container_status('db'), 'restarting', 'container_status');
			is(docker()->container_status('blank'), undef, 'undef when empty');
			is(docker()->container_status('gone'), undef, 'undef when docker cannot say');
			is(docker()->container_restart_count('db'), 2, 'container_restart_count');
			is(docker()->container_restart_count('odd'), undef, 'undef when not a count');
			is(docker()->container_restart_count('gone'), undef, 'undef when docker cannot say');
		});
		my $dry = docker(dry_run => 1, quiet => 1);
		is_deeply([ $dry->container_exit_code('x'), $dry->container_status('x'), $dry->container_restart_count('x') ],
			[ 0, 'running', 0 ], 'a dry run: exit 0, running, never restarted');

		$log = with_docker([ [ '^rm', 1 ] ], sub { is(docker()->container_remove('j'), 1, 'container_remove: the status') });
		is_deeply($log->{argv}, [ [ qw(rm -f j) ] ], 'rm -f');
	};

	subtest 'run, run_silent and the captures' => sub {
		with_docker([ [ '^ps', 0, "out\\r\\n", "err\\n" ], [ '^die', 'TERM' ] ], sub {
			my ($status, $error);
			is(output_of(stdout => sub { $error = output_of(stderr => sub { $status = docker()->run('ps') }) }), "out\r\n",
				'run shows the output as it is');
			is($error, "err\n", 'and the error output');
			is($status, 0, 'and returns the status');
			is(docker()->run('die'), 128 + 15, 'a signal is 128 plus its number');
			is(output_of(stdout => sub { $error = output_of(stderr => sub { $status = docker()->run_silent('ps') }) }), '',
				'run_silent shows nothing');
			is($error, '', 'not even errors');

			my ($output);
			$error = output_of(stderr => sub { ($output, $status) = docker()->capture('ps') });
			is_deeply([ $output, $status ], [ "out\n", 0 ], 'capture: the output, CRLF made LF, and the status');
			is($error, "err\n", 'the error output goes to the terminal');
			$error = output_of(stderr => sub { ($output) = docker()->capture_silent('ps') });
			is_deeply([ $output, $error ], [ "out\n", '' ], 'capture_silent throws the error output away');
			($output) = docker()->capture_merged('ps');
			is($output, "out\nerr\n", 'capture_merged includes it');
		});
		for my $method (qw(capture capture_silent capture_merged)) {
			is_deeply([ docker(dry_run => 1, quiet => 1)->$method('ps') ], [ '', 0 ], "$method: ('', 0) in a dry run");
		}
		is(docker(dry_run => 1, quiet => 1)->run('ps'), 0, 'run: 0 in a dry run');

		# What is printed: [dry-run] or +, quoted so it could be pasted, with
		# the secrets hidden.
		my $docker = docker(dry_run => 1, secrets => { TOKEN => 'hunter2', EMPTY => '' });
		is(output_of(stdout => sub { $docker->run('run', '-e', 'TOKEN=anything', '-e', 'X=hunter2 too', "it's", '', 'a=b') }),
			qq{[dry-run] $fake_docker run -e 'TOKEN=***' -e 'X=*** too' 'it'\\''s' '' a=b\n},
			'a dry run prints the command, quoted, with secrets hidden');
		is(output_of(stdout => sub { docker(dry_run => 1, quiet => 1)->run('ps') }), '', 'quiet prints nothing');
		is(output_of(stdout => sub { docker(dry_run => 1, explain => 1)->run('ps') }), '', 'nor does explain');
		with_docker([], sub {
			is(output_of(stdout => sub { docker(verbose => 1, secrets => { T => 'pw' })->run_silent('login', '-p', 'pw') }),
				"+ $fake_docker login -p '***'\n", 'verbose prints the command with +');
			is(output_of(stdout => sub { docker(verbose => 1, quiet => 1)->run_silent('ps') }), '', 'quiet wins over verbose');
		});
		with_docker([], sub { keeps_globals(sub { docker()->run_silent('ps') }, 'run_silent', io => 1) });
	};

	subtest 'job variables' => sub {
		# A variable after -e is kept off the command line, unless hiding it
		# would change what the command does.
		my $variable = sub { App::Actions::Docker::Variable->new(@_) };
		my $log = with_docker([], sub {
			docker()->run('run',
				'-e', $variable->('TOKEN', 's3cret'),
				'-e', $variable->('INPUT_GITHUB-TOKEN', 'dashed'),
				'-e', $variable->('DOCKER_HOST', 'tcp://x'),
				'-e', $variable->('https_proxy', 'http://p'),
				'-e', $variable->('Mixed', 'one'),
				'-e', $variable->('MIXED', 'two'),
				'-e', $variable->('NUL', "a\0b"),
				'-e', $variable->('1BAD', 'bad'),
				'-e', 'PLAIN=visible',
				'img');
		});
		is_deeply($log->{argv}, [ [ 'run',
			'-e', 'TOKEN', '-e', 'INPUT_GITHUB-TOKEN', '-e', 'DOCKER_HOST=tcp://x', '-e', 'https_proxy=http://p',
			'-e', 'Mixed=one', '-e', 'MIXED=two', '-e', 'NUL=a', '-e', '1BAD=bad', '-e', 'PLAIN=visible', 'img' ] ],
			'only the variables it is safe to hide are hidden (an argument, like an environment, ends at a NUL)');
		is_deeply($log->{env}, { TOKEN => 's3cret', 'INPUT_GITHUB-TOKEN' => 'dashed' }, 'the client reads them from its environment');
		ok(!exists $ENV{TOKEN}, 'which is put back afterwards');

		my $docker = docker(dry_run => 1, secrets => { TOKEN => 's3cret' });
		is(output_of(stdout => sub { $docker->capture('run', '-e', $variable->('TOKEN', 's3cret'), '-e', $variable->('V', 'v')) }),
			"[dry-run] $fake_docker run -e 'TOKEN=***' -e V=v\n", 'what is printed is NAME=VALUE, with secrets hidden');
	};

	subtest 'redact' => sub {
		my $docker = docker(secrets => { SHORT => 'abc', LONG => 'abcdef', EMPTY => '', NONE => undef });
		is($docker->redact('abcdef and abc'), '*** and ***', 'the longer secret first, so none of it is left');
		is($docker->redact('nothing secret'), 'nothing secret', 'other text is left alone');
		is($docker->redact(undef), undef, 'undef stays undef');
		is($docker->redact(''), '', 'an empty secret is never redacted');

t/unit.t  view on Meta::CPAN

	};

	subtest 'run: json' => sub {
		my $result = $check->([], json => 1);
		is($result->{status}, 0, 'the same status');
		my $document = JSON::PP->new->decode($result->{text});
		ok(!App::Actions::Schema::validate($document, App::Actions::Check->json_schema), 'one document that matches its schema');
		ok($document->{ready}, 'ready is a JSON boolean');
		$result = $check->([ [ 'Server', 1 ] ], json => 1, quiet => 1);
		$document = JSON::PP->new->decode($result->{text});
		is_deeply([ $result->{status}, $document->{problems}, $document->{docker}{daemon}, $document->{image} ], [ 2, 1, undef, undef ],
			'a problem: what could not be found out is null');

		{
			my $guard = Test::Mockingbird::mock_scoped('App::Actions::Check::json_schema' => sub { { type => 'array' } });
			my $error = caught { $check->([], json => 1) };
			isa_ok($error, 'App::Actions::Schema::Invalid', 'a document that does not match its schema');
			like("$error", qr/the action-run check --json document does not match App::Actions::Check->json_schema/, 'says so');
		}
		settle('text Check: the document does not match its schema');

		{
			local $FAIL{open} = sub { ref $_[2] eq 'SCALAR' };
			throws_ok { App::Actions::Check->new(docker_bin => $fake_docker)->run } qr/\AUnable to buffer the check report: \S/,
				'a report that cannot be buffered';
		}
		settle('text Check: Unable to buffer the check report');
	};
};

# ---------------------------------------------------------------------------
# App::Actions::Runner::Support and App::Actions::Runner::Support::Env
# ---------------------------------------------------------------------------

subtest 'App::Actions::Runner::Support' => sub {
	my $expression = App::Actions::Expression->new;

	subtest 'status_flags, chomp_error, trim_error and has_status_function' => sub {
		returns_ok(App::Actions::Runner::Support::status_flags(0), { type => 'hashref' }, 'status_flags');
		is_deeply(App::Actions::Runner::Support::status_flags(0), { success => 1, failure => 0, cancelled => 0 }, 'not failed');
		is_deeply(App::Actions::Runner::Support::status_flags(1), { success => 0, failure => 1, cancelled => 0 }, 'failed');

		is(App::Actions::Runner::Support::chomp_error("boom at x line 3.\n\n"), 'boom at x line 3.', 'chomp_error keeps the location');
		is(App::Actions::Runner::Support::chomp_error(undef), '', 'and undef is empty');

		is(App::Actions::Runner::Support::trim_error("boom at lib/X.pm line 3.\n"), 'boom', 'trim_error drops the location');
		my $error = caught { App::Actions::Workflow->load('') };
		is(App::Actions::Runner::Support::trim_error($error), 'No workflow file given', 'and gives an error its message');
		is(App::Actions::Runner::Support::trim_error($_), undef, 'no error is undef: ' . shown($_)) for undef, '';

		my %status = ('success()' => 1, 'always ()' => 1, '${{ failure() }}' => 1, 'cancelled()' => 1, 'github.success' => 0,
			q{'success'} => 0, '' => 0);
		is_returned(App::Actions::Runner::Support::has_status_function($_), { type => 'boolean' }, $status{$_},
			'has_status_function: ' . shown($_)) for sort keys %status;
		is(App::Actions::Runner::Support::has_status_function(undef), 0, 'undef has none');
	};

	subtest 'default_logger and null_logger' => sub {
		my $logger = App::Actions::Runner::Support::default_logger();
		returns_ok($logger, { type => 'object', isa => 'Log::Abstraction' }, 'default_logger');
		is(output_of(stderr => sub { $logger->warn('the image cache could not be written') }),
			"the image cache could not be written\n", 'prints the message as written, on standard error');
		is(output_of(stderr => sub { $logger->error("two\nlines") }), "two\nlines\n", 'several lines as they are');
		is(output_of(stderr => sub { $logger->debug('detail') }), "detail\n", 'every level');
		is(output_of(stdout => sub { $logger->warn('x') }), '', 'nothing on standard output');
		my $null = App::Actions::Runner::Support::null_logger();
		returns_ok($null, { type => 'object', isa => 'Log::Abstraction' }, 'null_logger');
		is(output_of(stderr => sub { $null->error('gone') }), '', 'throws every message away');
		keeps_globals(sub { App::Actions::Runner::Support::default_logger() }, 'default_logger');
	};

	subtest 'resolve_env' => sub {
		my $context = { matrix => { perl => '5.40' }, github => { event => { message => 'see ${{ env.SECRET }}' } } };
		my $env = App::Actions::Runner::Support::resolve_env($expression, [
			{ A => 'workflow', B => 'b-${{ env.C }}', MESSAGE => '${{ github.event.message }}', SECRET => 'hidden' },
			'not a layer',
			{ A => 'job', C => 'c-${{ env.a }}-${{ matrix.perl }}' },
			undef,
			{ N => 3, T => JSON::PP::true },
		], $context);
		returns_ok($env, { type => 'hashref' }, 'a hash reference');
		is_deeply($env, {
			A => 'job', B => 'b-c-job-5.40', C => 'c-job-5.40', MESSAGE => 'see ${{ env.SECRET }}', SECRET => 'hidden', N => '3', T => 'true',
		}, 'later layers win, values refer to each other in any order, and text from a value is not evaluated');
		ok(!exists $context->{env}, "the caller's context is not changed");

		throws_code(sub { App::Actions::Runner::Support::resolve_env($expression, [ { A => '${{ env.B }}', B => 'x${{ env.A }}' } ], {}) },
			'runner.env_cycle', q{Environment variable 'A' refers to itself, directly or through other variables},
			'variables that refer to each other');
		throws_code(sub { App::Actions::Runner::Support::resolve_env($expression, [ { SELF => '${{ env.SELF }}' } ], {}) },
			'runner.env_cycle', undef, 'one that refers to itself');
		my $error = throws_code(sub { App::Actions::Runner::Support::resolve_env($expression, [ { BAD => '${{ 1 + }}' } ], {}) },
			'runner.env_failed', undef, 'a value that does not evaluate');
		like($error->message, qr/\AUnable to evaluate environment variable 'BAD': Unexpected character '\+'/, 'says which and why');
		$error = throws_code(sub { App::Actions::Runner::Support::resolve_env($expression, [ { USES => '${{ env.BAD }}', BAD => '${{ x( }}' } ], {}) },
			'runner.env_failed', undef, 'the first failure is the one raised');
		like($error->message, qr/variable 'BAD'/, 'the variable that failed, not the one that used it');
		is_deeply(App::Actions::Runner::Support::resolve_env($expression, [], {}), {}, 'no layers, no variables');
		keeps_globals(sub { App::Actions::Runner::Support::resolve_env($expression, [ { A => '${{ env.B }}', B => 1 } ], {}) },
			'resolve_env');
	};

	subtest 'App::Actions::Runner::Support::Env' => sub {
		my %raw = (A => 'a', B => 'b');
		my (%resolved, @asked);
		my $state = tie my %env, 'App::Actions::Runner::Support::Env', \%raw, \%resolved, sub { push @asked, $_[0]; return uc $raw{ $_[0] } };
		returns_ok($state, { type => 'object', isa => 'App::Actions::Runner::Support::Env' }, 'TIEHASH');
		ok(exists $env{A} && !exists $env{Z}, 'EXISTS sees the raw names');
		is_deeply([ sort keys %env ], [ 'A', 'B' ], 'and so do keys');
		is_deeply(\@asked, [], 'without working anything out');
		ok(scalar %env, 'SCALAR');
		is($env{A}, 'A', 'FETCH works a value out');
		is($env{A}, 'A', 'once');
		is_deeply([ \@asked, \%resolved ], [ [ 'A' ], { A => 'A' } ], 'and keeps it');
		is($env{Z}, undef, 'an unknown name is undef');
		is($state->failure, undef, 'no failure');
		keeps_globals(sub { $env{B} }, 'FETCH');

		my %looping = (L => 'x');
		my ($loop, %cycle);
		$loop = tie %cycle, 'App::Actions::Runner::Support::Env', \%looping, {}, sub { return $cycle{L} };
		throws_code(sub { $cycle{L} }, 'runner.env_cycle', undef, 'a value that needs itself');
		isa_ok($loop->failure, 'App::Actions::Error', 'the failure is kept');
		is($loop->failure->code, 'runner.env_cycle', 'with its code');
		undef $loop;
		untie %cycle;

		my $failing = tie my %bad, 'App::Actions::Runner::Support::Env', { F => 'f' }, {}, sub { die "no good\n" };



( run in 1.390 second using v1.01-cache-2.11-cpan-60884a8df76 )