App-FileSync

 view release on metacpan or  search on metacpan

t/regressions.t  view on Meta::CPAN

#!/usr/bin/env perl

# One subtest per bug fixed in the 0.001.1 review.  Each states the old
# behaviour, so a failure here says which regression came back.

use strict;
use warnings;

use Digest::SHA ();
use File::Path qw(make_path);
use File::Spec;
use File::Temp qw(tempdir);
use Test::Most;
use Test::Permissions qw(:revoke :guard);

use lib 't/lib';
use TestSync;
use App::FileSync::Admin;
use App::FileSync::Args;
use App::FileSync::CLI;
use App::FileSync::Client;
use App::FileSync::Config;
use App::FileSync::Delta;
use App::FileSync::I18N qw(strip_location);
use App::FileSync::Ignore;
use App::FileSync::Merge;
use App::FileSync::Process;
use App::FileSync::Protocol;
use App::FileSync::Scan;
use App::FileSync::Server;
use App::FileSync::Settings;
use App::FileSync::Store;
use App::FileSync::Transport::Local;
use App::FileSync::Transport::SSH;
use App::FileSync::Trash;
use App::FileSync::Verify;

my $T0 = 1_700_000_000;

# --- helpers ----------------------------------------------------------------

# Open a raw session as the env's client, send the client tree's manifest and
# ask for a plan.  Returns { transport, conn, plan => { path => action } }.
# The server's stderr goes to a temporary file: these sessions end abruptly
# on purpose and its "connection closed" diagnostics are expected, but when a
# call finds the server gone, call() shows what it said.
sub session {
	my ($env) = @_;

	my $log = File::Spec->catfile(tempdir(CLEANUP => 1), 'server.err');
	open my $saved, '>&', \*STDERR or die "dup stderr: $!";
	open STDERR, '>', $log or die "stderr to $log: $!";
	my $transport = App::FileSync::Transport::Local->new(root => $env->{server}, repo => 'docs', client => 'test-1');
	open STDERR, '>&', $saved or die "restore stderr: $!";

	my $conn = App::FileSync::Protocol->new(in => $transport->reader(), out => $transport->writer());
	$conn->send({
		cmd => 'hello', proto => 2, client => 'test-1', host => 'test', os => $^O,
		role => 'client', repo => 'docs', case_insensitive => 0, now => time,
	});
	my $hello = $conn->recv();
	die 'session refused' unless $hello->{ok};

	# Scan with the server's own ignore list, as the real client does.
	my $ignore = App::FileSync::Ignore->new(patterns => $hello->{policy}{ignore});
	my $manifest = App::FileSync::Scan::scan(root => $env->{client}, ignore => $ignore)->{manifest};
	$conn->send({ cmd => 'manifest', part => 0, of => 1, entries => [ map { { p => $_, %{ $manifest->{$_} } } } sort keys %{$manifest} ] });
	die 'manifest refused' unless $conn->recv()->{ok};

	$conn->send({ cmd => 'plan' });
	my $plan = $conn->recv();
	die 'no plan' unless $plan->{ok};

	return { transport => $transport, conn => $conn, log => $log, plan => { map { $_->{p} => $_ } @{ $plan->{actions} } } };
}

# Send one message (with optional data) and return the reply.  If the
# connection fails, the server's stderr is shown before the error is rethrown.
sub call {
	my ($session, $message, $bytes) = @_;

	my $reply = eval {
		defined $bytes ? $session->{conn}->send_data($message, $bytes) : $session->{conn}->send($message);
		$session->{conn}->recv();
	};
	return $reply if $reply;

	my $error = $@;
	if (open my $fh, '<', $session->{log}) {
		local $/;
		my $said = <$fh>;
		diag("the server's stderr:\n$said") if defined $said && length $said;
	}
	die $error;
}

sub sha256_hex {
	my ($bytes) = @_;
	return Digest::SHA::sha256_hex($bytes);
}

# An env whose a.txt was synced, then changed on both sides: the client's
# copy is newer, so the plan is a conflict the client wins.
sub conflict_env {
	my $env = TestSync->new_env();
	$env->write_file('client', 'a.txt', "v0\n", $T0);
	$env->sync();
	$env->write_file('server', 'a.txt', "server\n", $T0 + 10);
	$env->write_file('client', 'a.txt', "client\n", $T0 + 20);
	return $env;
}

# --- Ignore -----------------------------------------------------------------

subtest 'Ignore: the caller\'s pattern list is not modified' => sub {
	# Old: new() stripped the "!" in place, so the next Ignore built from the
	# same list ignored keep.tmp - and a later sync deleted it remotely.
	my @patterns = ('*.tmp', '!keep.tmp');
	App::FileSync::Ignore->new(patterns => \@patterns);
	is_deeply(\@patterns, [ '*.tmp', '!keep.tmp' ], 'list unchanged');
	ok(!App::FileSync::Ignore->new(patterns => \@patterns)->match('keep.tmp'), 'a second object still re-includes');
};

subtest 'Ignore: anchors and trailing slashes' => sub {
	my $ignore = App::FileSync::Ignore->new(patterns => [ '/top', 'build/' ]);
	ok($ignore->match('top'), '/top matches at the root');
	ok(!$ignore->match('sub/top'), '/top does not match deeper (old: it matched anywhere)');
	ok($ignore->match('build'), 'build/ matches build');
	ok($ignore->match('src/build'), 'build/ matches at any depth');
	ok($ignore->match('src/build/x.o'), 'and everything inside it');
};

# --- Trash ------------------------------------------------------------------

subtest 'Trash: same-day versions sort numerically, past .99' => sub {
	my $root = tempdir(CLEANUP => 1);
	my $src = tempdir(CLEANUP => 1);
	my @made;
	for my $n (0 .. 101) {
		my $file = File::Spec->catfile($src, 'a.txt');
		open my $fh, '>', $file or die $!;
		print {$fh} "version $n\n";
		close $fh;
		push @made, App::FileSync::Trash::move_to_trash(src => $file, rel => 'a.txt', root => $root, epoch => $T0);
	}
	like($made[-1], qr/a\.txt\.101\z/, 'the 102nd copy is .101 (old: capped at .99)');

	my $versions = App::FileSync::Trash::versions(root => $root, rel => 'a.txt');
	is(scalar @{$versions}, 102, 'every version is listed');
	like($versions->[0], qr/\.101\z/, 'newest first');
	my ($nine) = grep { $versions->[$_] =~ /\.9\z/ } 0 .. $#{$versions};
	my ($ten)  = grep { $versions->[$_] =~ /\.10\z/ } 0 .. $#{$versions};

t/regressions.t  view on Meta::CPAN

	$env->sync();
	$env->write_file('server', 'new-there.txt', "new\n", $T0 + 10);
	$env->write_file('client', 'new-here.txt', "new\n", $T0 + 10);
	unlink $env->server_path('gone-there.txt') or die $!;
	unlink $env->client_path('gone-here.txt') or die $!;
	$env->write_file('server', 'client-wins.txt', "server\n", $T0 + 10);
	$env->write_file('client', 'client-wins.txt', "client\n", $T0 + 20);
	$env->write_file('client', 'master-wins.txt', "client\n", $T0 + 10);
	$env->write_file('server', 'master-wins.txt', "server\n", $T0 + 20);

	my %path = (
		pull              => 'new-there.txt',
		push              => 'new-here.txt',
		delete_local      => 'gone-there.txt',
		delete_remote     => 'gone-here.txt',
		'conflict:client' => 'client-wins.txt',
		'conflict:remote' => 'master-wins.txt',
	);
	my $s = session($env);
	my %planned = map {
		my $action = $s->{plan}{ $path{$_} } || {};
		($_ => ($action->{a} // '') eq 'conflict' ? "conflict:$action->{winner}" : $action->{a} // '')
	} keys %path;
	is_deeply(\%planned, { map { $_ => $_ } keys %path }, 'the plan has one path for each kind of action');
	$s->{transport}->close();

	# The request each kind of _expect gate serves, and the actions it may
	# serve.  Every other pairing must be refused at the gate, before the
	# server looks at anything else in the request.
	my %request = (
		get  => [ 'read',   qw(pull conflict:remote) ],
		put  => [ 'write',  qw(push conflict:client) ],
		sig  => [ 'delta',  qw(push) ],
		dsig => [ 'pull',   qw(pull) ],
		mkdir => [ 'mkdir', qw(push) ],
		del  => [ 'delete', qw(delete_remote) ],
		ack  => [ 'ack',    qw(pull delete_local conflict:remote) ],
	);
	for my $cmd (sort keys %request) {
		my ($kind, @may) = @{ $request{$cmd} };
		my %may = map { $_ => 1 } @may;
		for my $action (sort grep { !$may{$_} } keys %path) {
			my $session = session($env);
			my $reply = call($session, { cmd => $cmd, p => $path{$action} });
			ok(!$reply->{ok}, "$cmd ($kind) of a planned $action is refused");
			like($reply->{error}, qr/\A\S.* of '\Q$path{$action}\E' is not in the plan\z/, '... at the plan gate');
			$session->{transport}->close();
		}
	}
	ok($env->exists_in('server', 'gone-here.txt'), 'and the refused requests changed nothing on the master');
	ok(!$env->exists_in('server', 'new-here.txt'), 'nothing was created there either');
};

subtest 'Server: filesync-server exits 0 after a good session and 1 after a failed one' => sub {
	# ssh hands the server's exit status back to the client, so it must say
	# whether the session worked.  Nothing checked it, and Server::run could
	# have reported success as failure unnoticed.
	my $env = TestSync->new_env();
	my $exit = sub {
		my ($repo, @messages) = @_;
		open my $saved, '>&', \*STDERR or die "dup stderr: $!";
		open STDERR, '>', File::Spec->devnull() or die "null stderr: $!";
		my $child = App::FileSync::Process::spawn(command => [
			$^X, '-Ilib', 'bin/filesync-server',
			'--root', $env->{server}, '--repo', $repo, '--client', 'test-1', '--role', 'client',
		], stderr => fileno(STDERR));
		open STDERR, '>&', $saved or die "restore stderr: $!";

		my $conn = App::FileSync::Protocol->new(in => $child->{reader}, out => $child->{writer});
		my @replies;
		for my $message (@messages) {
			$conn->send($message);
			push @replies, $conn->recv();
			last unless $replies[-1]{ok};
		}
		close $child->{writer};
		close $child->{reader};
		return (App::FileSync::Process::reap(pid => $child->{pid})->{status}, \@replies);
	};
	my %hello = (
		cmd => 'hello', proto => 2, client => 'test-1', host => 'test', os => $^O,
		role => 'client', repo => 'docs', case_insensitive => 0, now => time,
	);

	my ($status, $replies) = $exit->('docs',
		\%hello, { cmd => 'manifest', part => 0, of => 1, entries => [] }, { cmd => 'plan' }, { cmd => 'done' });
	is(scalar(grep { $_->{ok} } @{$replies}), 4, 'a whole session is served');
	is($status, 0, 'and the server exits 0');

	($status, $replies) = $exit->('no-such-repo', { %hello, repo => 'no-such-repo' });
	ok(!$replies->[0]{ok}, 'a session for a missing repo is refused');
	is($status, 1, 'and the server exits 1');
};

subtest 'Server: ack is accepted only for actions the client applies' => sub {
	my $env = TestSync->new_env();
	$env->write_file('client', 'new.txt', "push me\n", $T0);
	my $s = session($env);
	is($s->{plan}{'new.txt'}{a}, 'push', 'new.txt is a push');

	# Old: any planned path could be acked, so a push could be marked done
	# without its content ever being sent.
	my $reply = call($s, { cmd => 'ack', p => 'new.txt', h => sha256_hex("push me\n"), s => 8, m => $T0 });
	ok(!$reply->{ok}, 'ack of a push is refused');
	like($reply->{error}, qr/not in the plan/, 'with the plan error');
	$s->{transport}->close();

	$env = TestSync->new_env();
	$env->write_file('server', 'pull.txt', "pull me\n", $T0);
	$s = session($env);
	is($s->{plan}{'pull.txt'}{a}, 'pull', 'pull.txt is a pull');
	$reply = call($s, { cmd => 'ack', p => 'pull.txt', deleted => 1 });
	ok(!$reply->{ok}, 'a "deleted" ack for a pull is refused');
	like($reply->{error}, qr/does not match its planned action/, 'with server.bad_ack');
	$s->{transport}->close();
};

subtest 'Server: get validates offset and size' => sub {
	my $env = TestSync->new_env();
	$env->write_file('server', 'pull.txt', "0123456789", $T0);

	my $s = session($env);
	my $reply = call($s, { cmd => 'get', p => 'pull.txt', off => 0, max => 4 });
	ok($reply->{ok}, 'a normal get works');
	is($s->{conn}->read_data($reply), '0123', 'and honours max');
	ok(!$reply->{eof}, 'not at the end');

t/regressions.t  view on Meta::CPAN

	}

	# Pulled: the client's x/ holds the ignored file.
	{
		my $env = TestSync->new_env();
		$env->write_file('client', 'x/y', "inside\n", $T0);
		$env->sync();
		$env->write_file('client', 'x/.DS_Store', "finder\n", $T0);
		File::Path::remove_tree($env->server_path('x'));
		$env->write_file('server', 'x', "now a file\n", $T0 + 5);
		App::FileSync::Admin->new(root => $env->{server})->reindex(repo => 'docs');

		my $result = do { local $SIG{__WARN__} = sub {}; $env->sync() };
		is($result->{exit}, 0, 'pull: the sync succeeds');
		is($env->read_file('client', 'x'), "now a file\n", 'pull: the client has the file');
		my $trash = File::Spec->catdir($env->{home}, 'trash', 'repos', 'docs');
		is(scalar @{ $ds_store->($trash) }, 1, 'pull: the ignored file is in the local trash');
		is($env->sync()->{exit}, 0, 'pull: and the next sync is clean');
	}
};

subtest 'Server: errors sent to the client name no server paths' => sub {
	# Old: the client was sent the server's absolute paths, such as "Cannot
	# replace non-empty directory /srv/filesync/master/docs/x".

	# The rewriting itself, on a server rooted at /srv/filesync.
	my $server = sub {
		App::FileSync::Server->new(root => shift, repo => 'docs', client => 'c1', role => 'client', connection => bless({}, 'Stand::In'));
	};
	my $for_client = sub { my ($root, $text) = @_; $server->($root)->_for_client($text) };
	my $master = File::Spec->catdir('/srv/filesync', 'master', 'docs');
	my $meta = File::Spec->catfile('/srv/filesync', '.filesync', 'repos', 'docs', 'master.json');
	my $elsewhere = File::Spec->catfile('/srv/filesyncdata', 'x');
	my %cases = (
		'a path in the master is relative to the repo' =>
			[ '/srv/filesync', "Cannot replace non-empty directory $master/sub/x", 'Cannot replace non-empty directory sub/x' ],
		'every one of them' =>
			[ '/srv/filesync', "Cannot move $master/.filesync-tmp-1 to $master/a.txt: denied", 'Cannot move .filesync-tmp-1 to a.txt: denied' ],
		'another server path keeps only its place under the root' =>
			[ '/srv/filesync', "Cannot write $meta: full", 'Cannot write [server root]/.filesync/repos/docs/master.json: full' ],
		'the root on its own' =>
			[ '/srv/filesync', q{No such repo 'x' under /srv/filesync (run filesync-admin repo create)}, q{No such repo 'x' under [server root] (run filesync-admin repo create)} ],
		'a root given with a trailing slash' =>
			[ '/srv/filesync/', "Cannot replace non-empty directory $master/x", 'Cannot replace non-empty directory x' ],
		'a longer name that only starts with the root is left alone' =>
			[ '/srv/filesync', "Cannot read $elsewhere", "Cannot read $elsewhere" ],
	);
	for my $case (sort keys %cases) {
		my ($root, $text, $expected) = @{ $cases{$case} };
		is($for_client->($root, $text), $expected, $case);
	}

	# Through a real session: a master directory that refuses new files stops
	# the upload's temporary file, and the error names that directory.
	my $env = TestSync->new_env();
	plan skip_all => why_not('create', $env->{server}) unless can_revoke_create($env->{server});
	$env->write_file('client', 'sub/a.txt', "one\n", $T0);
	$env->sync();
	$env->write_file('client', 'sub/b.txt', "two\n", $T0 + 5);

	# The local server shares our stderr, as an ssh server's reaches the
	# client: catch it to see the server's log line.
	my $error;
	my $log = File::Spec->catfile(tempdir(CLEANUP => 1), 'server.err');
	with_revoked(create => $env->server_path('sub'), sub {
		open my $saved, '>&', \*STDERR or die "dup stderr: $!";
		open STDERR, '>', $log or die "Cannot write $log: $!";
		eval { $env->sync(); 1 } or $error = $@;
		open STDERR, '>&', $saved or die "restore stderr: $!";
	});
	like($error, qr/Cannot create a temporary file in sub: /, 'the client is told the repo path');
	unlike($error, qr/\Q$env->{server}\E/, 'and not where the server keeps it');
	my $logged = do { open my $fh, '<', $log or die "Cannot read $log: $!"; local $/; <$fh> };
	like($logged, qr/Cannot create a temporary file in sub: /, 'the server logs the same text');
	unlike($logged, qr/\Q$env->{server}\E/, 'so its stderr carries no server path either');

	my ($event) = grep { ($_->{action} // '') eq 'session' && ($_->{result} // '') eq 'error' }
		@{ App::FileSync::Admin->new(root => $env->{server})->journal_read(repo => 'docs') };
	like($event->{error}, qr/\Q$env->{server}\E/, 'the server journal keeps the absolute path');
};

# --- Client -----------------------------------------------------------------

subtest 'Client: each repo has its own local trash' => sub {
	my $env = TestSync->new_env();
	$env->write_file('client', 'a.txt', "a\n", $T0);
	$env->sync();
	unlink $env->server_path('a.txt') or die $!;
	$env->sync();
	ok(!$env->exists_in('client', 'a.txt'), 'the remote delete reached the client');

	my $own = File::Spec->catdir($env->{home}, 'trash', 'repos', 'docs');
	ok(-d $own, 'the deleted file went to this repo\'s trash');

	# Old: every repo shared home/trash, so another repo's restore found
	# (and prune expired) this repo's files.
	my $config = App::FileSync::Config::load_client($env->{config_path});
	$config->{repos}{other} = { %{ $config->{repos}{docs} }, root => tempdir(CLEANUP => 1) };
	my $other = App::FileSync::Client->new(config => $config, name => 'other');
	my $found = $other->restore(path => 'a.txt', list => 1);
	is_deeply($found->{versions}, [], 'another repo does not see it');

	my $restored = $env->restore(path => 'a.txt');
	is($env->read_file('client', 'a.txt'), "a\n", 'this repo restores it');
};

subtest 'Client: restore still finds files in the old shared trash' => sub {
	my $env = TestSync->new_env();
	my $src = tempdir(CLEANUP => 1);
	my $file = File::Spec->catfile($src, 'legacy.txt');
	# Raw: in text mode Windows writes "legacy\r\n", and restore copies bytes.
	open my $fh, '>:raw', $file or die $!;
	print {$fh} "legacy\n";
	close $fh;
	App::FileSync::Trash::move_to_trash(src => $file, rel => 'legacy.txt', root => File::Spec->catdir($env->{home}, 'trash'));

	$env->restore(path => 'legacy.txt');
	is($env->read_file('client', 'legacy.txt'), "legacy\n", 'restored from the legacy location');
};

subtest 'Client: a repo name that is not a plain id is refused' => sub {
	my $env = TestSync->new_env();
	my $config = App::FileSync::Config::load_client($env->{config_path});
	for my $name ('../x', '', 'a/b') {
		throws_ok { App::FileSync::Client->new(config => $config, name => $name) } qr/./, "name '$name'";
	}
};

# --- I18N -------------------------------------------------------------------

subtest 'strip_location removes same-line locations' => sub {
	is(strip_location("Can't open 'x': No such file or directory at lib/X.pm line 12.\n"),
		q{Can't open 'x': No such file or directory}, 'autodie style');
	is(strip_location("Cannot read 'f'\n at lib/X.pm line 3.\n"), q{Cannot read 'f'}, 'croak style');
	is(strip_location("Path 'a at b line 3' is fine\n"), q{Path 'a at b line 3' is fine}, 'a path that merely looks like a location stays');

t/regressions.t  view on Meta::CPAN

	$env->write_file('client', 'a.txt', "alpha\n", 1_700_000_000);

	my $output = `$^X -Ilib $filesync sync --repo docs --quiet 2>&1`;
	is($?, 0, 'the first sync exits 0');
	like($output, qr/docs: pulled 0, pushed 1/, '--quiet still reports a sync that did something');

	$output = `$^X -Ilib $filesync sync --repo docs --quiet 2>&1`;
	is($?, 0, 'an idle sync exits 0');
	is($output, '', '--quiet prints nothing for an idle sync');

	$output = `$^X -Ilib $filesync sync --repo docs --quiet --dry-run 2>&1`;
	is($output, '', 'nor for an idle dry run');

	$output = `$^X -Ilib $filesync sync --repo docs 2>&1`;
	like($output, qr/docs: pulled 0, pushed 0, deleted 0, conflicts 0/, 'without --quiet an idle sync is still reported');

	$env->write_file('client', 'b.txt', "beta\n", 1_700_000_100);
	$output = `$^X -Ilib $filesync sync --repo docs --quiet --dry-run 2>&1`;
	like($output, qr/would push b\.txt/, '--quiet --dry-run still lists what it would do');
};

subtest 'json_decode: non-ASCII hash keys come back as bytes' => sub {
	# json_decode downgraded values but not hash keys, and manifests are keyed
	# by path.  A key such as "h\xc3\xa9llo.txt" kept the UTF-8 flag, so a
	# file test on it looked for a differently-encoded name: verify's random
	# sample silently skipped every non-ASCII file (sampled 1 of 2 here).
	my $root = tempdir(CLEANUP => 1);
	for my $name ("h\xc3\xa9llo.txt", 'plain.txt') {
		open my $fh, '>:raw', File::Spec->catfile($root, $name) or die "Cannot write $name: $!";
		print {$fh} "x\n";
		close $fh;
	}
	my $manifest = App::FileSync::Scan::scan(root => $root)->{manifest};
	my $entries = App::FileSync::json_decode(App::FileSync::json_encode($manifest));

	my ($key) = grep { /[^\x00-\x7f]/ } keys %{$entries};
	ok(!utf8::is_utf8($key), 'the decoded key carries no UTF-8 flag');
	ok(-e File::Spec->catfile($root, $key), 'and names the file on disk');

	my $result = App::FileSync::Verify::verify(root => $root, entries => $entries, sample => 10);
	is($result->{sampled}, 2, 'verify samples the non-ASCII file too');
};

# --- Transports: closing a session part-way ---------------------------------

subtest 'Transport::Local: closing mid-session lets the server exit by itself' => sub {
	# Old: on Windows the server inherited the client's end of its own stdin
	# pipe, so closing it never gave the server end of file, and close()
	# waited for it forever.  Every Windows CI run hung here.
	local $App::FileSync::Process::GRACE_SECONDS = 10;
	my $env = conflict_env();
	my $s = session($env);
	my $content = "client\n";
	ok(call($s, { cmd => 'put', p => 'a.txt', s => length $content, h => sha256_hex($content), m => $T0 + 20, mode => 0644 })->{ok},
		'put accepted; the server now waits for the data');
	$s->{transport}->close();
	is($s->{transport}{end}{killed}, 0, 'the server saw end of file and exited without being stopped');
};

subtest 'Process: reap stops a child that will not exit' => sub {
	my $child = App::FileSync::Process::spawn(command => [ $^X, '-e', 'sleep 300' ], stderr => fileno(STDERR));
	close $child->{writer};
	close $child->{reader};
	my $started = time;
	my $end = App::FileSync::Process::reap(pid => $child->{pid}, grace => 0.2);
	is($end->{killed}, 1, 'it was stopped');
	cmp_ok(time - $started, '<', 30, 'promptly (old: waitpid with no limit)');
	SKIP: {
		# Windows waitpid() falls back to OpenProcess() for a pid that is no
		# longer its child, so asking again can return the pid.
		skip 'waitpid on a reaped pid is not -1 on Windows', 1 if $^O eq 'MSWin32';
		is(waitpid($child->{pid}, 0), -1, 'and reaped');
	}

	$child = App::FileSync::Process::spawn(command => [ $^X, '-e', 'exit 7' ], stderr => fileno(STDERR));
	$end = App::FileSync::Process::reap(pid => $child->{pid}, grace => 10);
	is_deeply($end, { status => 7, signal => 0, killed => 0 }, 'a child that exits keeps its status');
};

subtest 'Process: a program that cannot start is named' => sub {
	my $missing = File::Spec->catfile(tempdir(CLEANUP => 1), 'no-such-program');
	if ($^O eq 'MSWin32') {
		# Perl on Windows retries a program it cannot start through cmd.exe,
		# so the start succeeds and the failure is cmd.exe's exit status.
		open my $null, '>', File::Spec->devnull() or die "null: $!";
		my $child = App::FileSync::Process::spawn(command => [ $missing ], stderr => fileno($null));
		close $child->{writer};
		close $child->{reader};
		isnt(App::FileSync::Process::reap(pid => $child->{pid}, grace => 30)->{status}, 0, 'the child reports failure');
		return;
	}
	throws_ok { App::FileSync::Process::spawn(command => [ $missing ], stderr => fileno(STDERR)) }
		qr/Cannot start '\Q$missing\E'/, 'process.spawn';
};

subtest 'Transport::SSH: an ssh that has to be stopped is a failed close' => sub {
	plan skip_all => 'the stand-in ssh is a #! script' if $^O eq 'MSWin32';
	local $App::FileSync::Process::GRACE_SECONDS = 0.2;

	my $fake = File::Spec->catfile(tempdir(CLEANUP => 1), 'stuck-ssh');
	open my $fh, '>', $fake or die "Cannot write $fake: $!";
	print {$fh} "#!$^X\nsleep 300;\n";
	close $fh;
	chmod 0755, $fake or die "chmod: $!";

	my $ssh = App::FileSync::Transport::SSH->new(server => 'host', repo => 'docs', client => 'test-1', command => $fake);
	is($ssh->close(), 0, 'close reports the failure (old: it would have waited for ssh forever)');
	ok($ssh->{killed}, 'and records that ssh was stopped');
};

# --- Settings ---------------------------------------------------------------

subtest 'Settings: an environment variable is named as the environment spells it' => sub {
	# Old: _env_key asked "exists $ENV{name}" first.  On Windows that lookup
	# ignores case, so "filesync settings" named App__FileSync__ssh_identity
	# when the environment holds APP__FILESYNC__SSH_IDENTITY.  A tied %ENV
	# whose exists() ignores case stands in for Windows here.
	{
		package CaseBlindEnv;
		require Tie::Hash;
		our @ISA = ('Tie::StdHash');
		sub EXISTS { my ($self, $key) = @_; return scalar grep { lc $_ eq lc $key } keys %{$self} }
	}
	# Keep the real variables: HARNESS_ACTIVE lets the test call a :Private sub.
	my %real = map { $_ => $ENV{$_} } grep { !/\Aapp__filesync__/i } keys %ENV;
	local *ENV;
	tie %ENV, 'CaseBlindEnv';
	%ENV = (%real, APP__FILESYNC__SSH_IDENTITY => '/tmp/id');
	is(App::FileSync::Settings::_env_key('App__FileSync__ssh_identity'), 'APP__FILESYNC__SSH_IDENTITY', 'the stored spelling');
	is(App::FileSync::Settings::_env_key('APP__FILESYNC__SSH_IDENTITY'), 'APP__FILESYNC__SSH_IDENTITY', 'an exact match');
	is(App::FileSync::Settings::_env_key('App__FileSync__log_level'), undef, 'an unset variable');
};

subtest 'Sub::Private is enforced outside the test harness' => sub {
	local $Sub::Private::config{harness_bypass} = 0;
	throws_ok { App::FileSync::CLI::_default_client_id() } qr/private/i, 'a private sub called from outside its package';
};

done_testing();



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