App-Actions

 view release on metacpan or  search on metacpan

t/integration.t  view on Meta::CPAN


	open my $handle, '>', $path or die "cannot write $path: $!";
	print {$handle} $text;
	close $handle;

	return $path;
}

sub read_file {
	my ($path) = @_;

	return '' unless -f $path;
	open my $handle, '<', $path or die "cannot read $path: $!";
	local $/;
	my $text = <$handle>;
	close $handle;

	return defined $text ? $text : '';
}

# A daemon of its own: the state directory is what it has, and the log is
# every command it was given.
sub daemon {
	my $state = tempdir(CLEANUP => 1);

	return { state => $state, log => File::Spec->catfile($state, 'docker.log') };
}

# Runs $code against $daemon, with the fake's knobs (FAKE_*) set for it alone.
sub with_daemon {
	my ($daemon, $knobs, $code) = @_;

	local $ENV{FAKE_DOCKER_STATE} = $daemon->{state};
	local $ENV{FAKE_DOCKER_LOG} = $daemon->{log};
	local @ENV{ keys %{$knobs} } = values %{$knobs};

	return $code->();
}

# The commands the daemon was given, each as its argument list; the timing
# lines FAKE_PULL_TIMING adds are left out.
sub commands {
	my ($daemon) = @_;

	return [ map { [ split /\t/ ] } grep { !/\Apull-(?:start|end)\t/ } split /\n/, read_file($daemon->{log}) ];
}

# The containers the daemon was asked to start for jobs (docker run -d),
# rather than the probe the check runs and removes (docker run --rm).
sub job_containers {
	my ($daemon) = @_;

	return [ map { $_->[3] } grep { $_->[0] eq 'run' && $_->[1] eq '-d' } @{ commands($daemon) } ];
}

# Runs $code, capturing what it prints, and returns that with its result.
sub captured {
	my ($code) = @_;

	my $result;
	my ($stdout, $stderr) = capture { $result = $code->() };
	s/\r\n/\n/g for $stdout, $stderr;

	return { result => $result, stdout => $stdout, stderr => $stderr };
}

# The result each job had, from the run's summary.
sub summary {
	my ($stdout) = @_;

	my ($block) = $stdout =~ /^=== Workflow summary ===\n(.*?)^Workflow /ms;
	return { map { /\A {2}(.+?)\s{2,}(\S+)\z/ ? ($1, $2) : () } split /\n/, defined $block ? $block : '' };
}

# The messages a logger array collected at one level.
sub messages {
	my ($logger, $level) = @_;

	return [ map { $_->{message} } grep { $_->{level} eq $level } @{$logger} ];
}

# An App::Actions for $project on the fake daemon, with its own cache record
# and log directory unless the caller names others.
sub actions {
	my ($project, %options) = @_;

	return new_ok('App::Actions' => [
		workflow_file => $project->{workflow},
		docker_bin => $FAKE_DOCKER,
		image => $config{image},
		cache_file => File::Spec->catfile(tempdir(CLEANUP => 1), 'cache.json'),
		log_dir => File::Spec->catdir(tempdir(CLEANUP => 1), 'logs'),
		logger => [],
		%options,
	]);
}

# A Docker program that passes every command on to the fake daemon except the
# one it has been told to break, as a daemon with a bug or a proxy in the way
# would: SABOTAGE=size gives an image size that is not a number, and
# SABOTAGE=os an operating system that is not one.  It is a Perl script, which
# App::Actions::Docker runs with the current Perl, so it works on Windows too.
sub saboteur {
	my $path = File::Spec->catfile(tempdir(CLEANUP => 1), 'docker-saboteur');

	write_file($path, <<"PERL");
#!/usr/bin/env perl
my \$mode = defined \$ENV{SABOTAGE} ? \$ENV{SABOTAGE} : '';
if (\$mode eq 'size' && grep { /Size/ } \@ARGV) {
	print "$config{malformed_size}\\n";
	exit 0;
}
if (\$mode eq 'os' && \$ARGV[0] eq 'info') {
	print '$config{malformed_os}', "\\n";
	exit 0;
}
exit system(\$^X, '$FAKE_DOCKER', \@ARGV) >> 8;
PERL
	chmod 0755, $path;

	return $path;
}

# The fake daemon's pull timing log, as the time each image started and

t/integration.t  view on Meta::CPAN

	is(scalar @{$runs}, 1, 'one run of logs is kept');
	my @names = map { $_->{name} } @{ $runs->[0]{logs} };
	is(scalar @names, scalar @{ $config{matrix} }, 'with a log for each instance of the matrix');
	like($run->{stdout}, qr/^\s+test \(n=\Q$config{matrix}[0]\E\)\s+\Q$names[0]\E$/m, 'the names the run printed');
	ok((grep { -s $_->{path} } @{ $runs->[0]{logs} }) == @names, 'and none of them is empty');

	is_deeply([ App::Actions::Schema::validate($listing->document, App::Actions->json_schema('logs')) ], [],
		'the listing is a valid logs document');
	my (undef, $status) = $listing->prune;
	is($status, 0, 'pruning the logs succeeds');
	is_deeply(App::Actions::Logs->new(directory => $logs)->entries, [], 'and leaves none');
};

subtest 'independent objects do not interfere with each other' => sub {
	# Two objects, each with its own workflow, daemon, image, record and
	# logger, used in turn.  Strategy: whatever one does - an override, a
	# failure, a pull - must show only in its own record, logger and daemon.
	my ($passing, $failing) = (project($PASSING), project($CASCADE =~ s{^(\s+)runs-on: ubuntu-latest\n}{$1runs-on: ubuntu-latest\n$1container: $config{other_image}\n}mgr));
	my ($passing_daemon, $failing_daemon) = (daemon(), daemon());
	my ($passing_record, $failing_record) = map { File::Spec->catfile(tempdir(CLEANUP => 1), 'cache.json') } 1 .. 2;
	my (@passing_log, @failing_log);

	my $one = actions($passing, cache_file => $passing_record, logger => \@passing_log);
	my $two = actions($failing, cache_file => $failing_record, logger => \@failing_log);
	isnt($one->workflow, $two->workflow, 'each has its own workflow');

	my $only_lint = with_daemon($passing_daemon, {}, sub { captured(sub { $one->run(jobs => [ 'lint' ]) }) });
	my $cascade = with_daemon($failing_daemon, {}, sub { captured(sub { $two->run }) });
	my $whole = with_daemon($passing_daemon, {}, sub { captured(sub { $one->run }) });

	is_deeply([ sort keys %{ summary($only_lint->{stdout}) } ], [ 'lint' ], 'an override selects jobs for one run');
	is(scalar keys %{ summary($whole->{stdout}) }, scalar @{ $config{matrix} } + 1,
		'and does not stay behind for the next run of the same object');
	is($whole->{result}, $config{exit}{success}, 'the passing workflow passes');
	is($cascade->{result}, $config{exit}{failure}, 'while the other fails');

	is_deeply(\@passing_log, [], 'the failure is not reported to the other object\'s logger');
	ok(scalar @{ messages(\@failing_log, 'error') }, 'but to its own');

	is_deeply([ map { $_->{image} } @{ App::Actions::Cache->new(file => $passing_record)->entries } ], [ $config{image} ],
		'one record holds only the image its object pulled');
	is_deeply([ map { $_->{image} } @{ App::Actions::Cache->new(file => $failing_record)->entries } ], [ $config{other_image} ],
		'and the other only its own');
	ok(!(grep { grep { $_ eq $config{other_image} } @{$_} } @{ commands($passing_daemon) }),
		'and neither daemon was asked about the other\'s image');
};

subtest 'a failing job is reported to the logger and does not bring down the others' => sub {
	# A step that fails is a job that fails: the jobs that need it are
	# skipped, an independent job still runs, and the error goes to the
	# logger rather than to standard error.
	my @logger;
	my $actions = actions(project($CASCADE), logger => \@logger);
	my $run = with_daemon(daemon(), {}, sub { captured(sub { $actions->run }) });
	verbose_diag('cascade', $run);

	is($run->{result}, $config{exit}{failure}, 'the run reports that a job failed');
	is_deeply(summary($run->{stdout}), { build => 'failure', test => 'skipped', docs => 'success' },
		'the job that needs the failed one is skipped, and the other one still runs');
	like(messages(\@logger, 'error')->[0], qr/\b$config{step_status}\b/, 'the logger is told the status the step exited with');
	is($run->{stderr}, '', 'and nothing is printed to standard error');
};

subtest 'preflight prepares the images and returns a valid document' => sub {
	# preflight runs the check and the image preparation a run makes before
	# its first job, without starting one.  Strategy: the first preflight
	# pulls, the second finds the image present, and both documents match
	# the published schema.
	my $actions = actions(project($PASSING));
	my $daemon = daemon();
	my $schema = App::Actions->json_schema('preflight');

	for my $expected (qw(pulled present)) {
		my $outcome = with_daemon($daemon, {}, sub { captured(sub { $actions->preflight(json => 1) }) });
		my $result = $outcome->{result};
		verbose_diag("preflight ($expected)", $result);
		returns_ok($result, { type => 'hashref' }, "the preflight returns a hash ($expected)");
		is($result->{exit}, $config{exit}{success}, "it succeeds ($expected)");
		is($outcome->{stdout}, '', "prints nothing with json ($expected)");
		ok($result->{summary}{ready}, "finds the environment ready ($expected)");
		is_deeply([ map { [ $_->{image}, $_->{status} ] } @{ $result->{summary}{images} } ], [ [ $config{image}, $expected ] ],
			"and says the image was $expected");
		is_deeply([ App::Actions::Schema::validate(JSON::PP->new->decode(JSON::PP->new->encode($result->{summary})), $schema) ],
			[], "in a document that matches its schema ($expected)");
	}
	is_deeply(job_containers($daemon), [], 'no job was started');
};

subtest 'a run degrades cleanly when its directories refuse access' => sub {
	# The record and the logs are a convenience: a run that cannot write them
	# must still run its jobs, succeed, and say why (the record only when
	# verbose, as Runner::Images documents).  Reading them back from a
	# directory that cannot be searched gives nothing rather than an error.
	my $locked = tempdir(CLEANUP => 1);

	SKIP: {
		skip(why_not('create', $locked), 3) unless can_revoke_create($locked);

		my @logger;
		my $actions = actions(project($PASSING), cache_file => File::Spec->catfile($locked, 'cache.json'),
			logger => \@logger, verbose => 1);
		my $run = with_revoked(create => $locked, sub { with_daemon(daemon(), {}, sub { captured(sub { $actions->run }) }) });
		verbose_diag('cache unwritable', \@logger);
		is($run->{result}, $config{exit}{success}, 'a run whose record cannot be created still succeeds');
		ok((grep { /could not update the image cache/ } @{ messages(\@logger, 'warn') }), 'and warns that the record was not kept');
		is_deeply(App::Actions::Cache->new(file => File::Spec->catfile($locked, 'cache.json'))->entries, [],
			'which then has no images');
	}

	SKIP: {
		skip(why_not('search', $locked), 4) unless can_revoke_search($locked);

		my $record = File::Spec->catfile($locked, 'kept.json');
		App::Actions::Cache->new(file => $record)->remember($config{other_image});
		my @logger;
		my $actions = actions(project($PASSING), cache_file => $record, logger => \@logger, verbose => 1);

		my ($run, $entries, $logs) = with_revoked(search => $locked, sub {
			my $outcome = with_daemon(daemon(), {}, sub { captured(sub { $actions->run }) });
			my $listing = App::Actions::Logs->new(directory => File::Spec->catdir($locked, 'logs'));
			return ($outcome, App::Actions::Cache->new(file => $record)->entries, $listing->entries);

t/integration.t  view on Meta::CPAN

		verbose_diag('prune', $pruned);
		is($status, 0, 'pruning succeeds');
		is_deeply([ @{$pruned}{qw(removed forgotten freed)} ], [ 1, 0, 0 ], 'by removing the image, which frees no known size');
		ok(!$docker->image_exists($config{image}), 'and the daemon no longer has it');
	});

	my @logger;
	my $confused = actions(project($PASSING), docker_bin => $saboteur, logger => \@logger);
	my $fresh = daemon();
	my $run = with_daemon($fresh, { SABOTAGE => 'os' }, sub { captured(sub { $confused->run }) });
	is($run->{result}, $config{exit}{infrastructure}, 'a daemon that names no real operating system is not used');
	like($run->{stdout}, qr/\Q$config{malformed_os}\E' containers/, 'the report quotes what it said');
	is_deeply(job_containers($fresh), [], 'and no job container was started');
};

subtest 'malformed files are survived or refused, as documented' => sub {
	# A record that is not JSON counts as empty (Cache POD) and is replaced by
	# the next run; a workflow that is not YAML is refused by new() with a
	# coded error, before anything else happens.
	my $record = write_file(File::Spec->catfile(tempdir(CLEANUP => 1), 'cache.json'), $config{malformed_record});
	is_deeply(App::Actions::Cache->new(file => $record)->entries, [], 'a broken record reads as empty');

	my $run = with_daemon(daemon(), {}, sub { captured(sub { actions(project($PASSING), cache_file => $record)->run }) });
	is($run->{result}, $config{exit}{success}, 'a run with a broken record succeeds');
	my $rewritten = eval { JSON::PP->new->decode(read_file($record)) };
	ok($rewritten, 'and leaves a record that is JSON again');
	is_deeply([ keys %{ $rewritten->{images} || {} } ], [ $config{image} ], 'holding the image the run pulled');

	my $broken = project("name: [\n");
	my $error;
	throws_ok { App::Actions->new(workflow_file => $broken->{workflow}, logger => 'NULL') } 'App::Actions::Error',
		'a workflow that is not YAML is refused';
	$error = $@;
	ok($error->is('workflow.parse_failed'), 'with the code that says why');
	# new() names the workflow by its absolute path, which on Windows is
	# written with forward slashes.
	like($error->message, qr/\Q@{[ Cwd::abs_path($broken->{workflow}) ]}\E/, 'naming the file');
};

subtest 'no optional module is needed, and none changes the outcome' => sub {
	# App::Actions declares no optional dependencies: JSON::PP and YAML::PP
	# are used directly.  Strategy: hide every combination of the faster
	# modules other distributions often pick up when present, in a fresh
	# Perl each time, and check that a run and a schema lookup behave alike.
	my @optional = @{ $config{optional_modules} };
	my $project = project($PASSING);
	# A script file, not perl -e: Windows rebuilds a command line from the
	# arguments, and a program of several lines does not survive that.
	my $program = write_file(File::Spec->catfile(tempdir(CLEANUP => 1), 'optional.pl'), <<'PERL');
use App::Actions;
my ($workflow, $docker) = @ARGV;
my $schema = App::Actions->json_schema('check');
my $exit = App::Actions->new(workflow_file => $workflow, docker_bin => $docker, dry_run => 1, quiet => 1, logger => 'NULL')->run;
print "$exit $schema->{title}\n";
PERL

	my %seen;
	for my $mask (0 .. 2**@optional - 1) {
		my @hidden = map { $optional[$_] } grep { $mask & (1 << $_) } 0 .. $#optional;
		my @switches = @hidden ? ('-MTest::Without::Module=' . join(',', @hidden)) : ();
		my ($stdout, $stderr, $status) = capture {
			system($^X, "-I$LIB", @switches, $program, $project->{workflow}, $FAKE_DOCKER);
		};
		my $label = @hidden ? 'without ' . join(', ', @hidden) : 'with everything installed';
		is($status, 0, "a run $label works") or diag($stderr);
		$seen{$stdout}++;
	}
	is(scalar keys %seen, 1, 'and every combination gives the same answer');
	verbose_diag('outcomes', \%seen);
};

done_testing();



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