App-FileSync

 view release on metacpan or  search on metacpan

t/function.t  view on Meta::CPAN

	my $full = File::Spec->catdir($dir, 'full');
	put_file(File::Spec->catfile($full, 'keep'), 'keep');
	error_is(sub { App::FileSync::IO::install_file(put_file(File::Spec->catfile($dir, 'tmp5'), 'x'), $full) },
		"Cannot replace non-empty directory $full", 'a non-empty directory is refused');
	is(slurp(File::Spec->catfile($full, 'keep')), 'keep', 'and its contents survive');

	my $gone = File::Spec->catfile($dir, 'never-there');
	my $error = do { eval { App::FileSync::IO::install_file($gone, $target, 1) }; $@ };
	like(strip_location($error), qr/\ACannot set the modification time of \Q$gone\E: /, 'a missing temp is refused before anything is removed');
	ok(-e $target, 'and the target survives');
};

subtest 'IO::clear_target' => sub {
	# Strategy: clear exactly one entry and never follow a link into a
	# directory; nothing there is not an error.
	my $dir = scratch();
	is(App::FileSync::IO::clear_target(File::Spec->catfile($dir, 'none')), 1, 'nothing there is fine');
	my $file = put_file(File::Spec->catfile($dir, 'f'), 'x');
	App::FileSync::IO::clear_target($file);
	ok(!-e $file, 'a file is removed');

	SKIP: {
		my $target = File::Spec->catdir($dir, 'target');
		put_file(File::Spec->catfile($target, 'keep'), 'keep');
		my $link = File::Spec->catfile($dir, 'link');
		skip 'no symlinks', 3 unless eval { symlink $target, $link };
		App::FileSync::IO::clear_target($link);
		ok(!-l $link, 'a link to a directory is unlinked');
		ok(-f File::Spec->catfile($target, 'keep'), 'and the directory it pointed at is untouched');
		my $dangling = File::Spec->catfile($dir, 'dangling');
		symlink File::Spec->catfile($dir, 'nowhere'), $dangling;
		App::FileSync::IO::clear_target($dangling);
		ok(!-l $dangling, 'a dangling link is removed too');
	}

	my $nonempty = File::Spec->catdir($dir, 'target');
	error_is(sub { App::FileSync::IO::clear_target($nonempty) }, "Cannot replace non-empty directory $nonempty", 'a non-empty directory');

	SKIP: {
		skip 'root ignores permissions', 1 if $> == 0 || $^O eq 'MSWin32';
		my $locked = File::Spec->catdir($dir, 'locked');
		my $inside = put_file(File::Spec->catfile($locked, 'f'), 'x');
		chmod oct(500), $locked;
		error_is(sub { App::FileSync::IO::clear_target($inside) }, "Cannot remove $inside: ${\ do { local $! = EACCES; qq{$!} }}",
			'a file in a read-only directory is io.remove');
		chmod oct(700), $locked;
	}
};

subtest 'IO::set_mtime' => sub {
	# Strategy: undef means "leave it", a fractional time is kept where the
	# platform allows, the whole-second fallback is used only for the
	# "unimplemented" croak, and a file that cannot be touched is an error
	# (old: a missing file silently "succeeded").
	my $dir = scratch();
	my $path = put_file(File::Spec->catfile($dir, 'f'), 'x', 1000);

	is(App::FileSync::IO::set_mtime($path, undef), 1, 'undef: nothing to do');
	is((stat $path)[9], 1000, 'and the file is unchanged');
	App::FileSync::IO::set_mtime($path, 2000.75);
	cmp_ok(abs((Time::HiRes::stat($path))[9] - 2000.75), '<', 1, 'a fractional time');

	my $missing = File::Spec->catfile($dir, 'missing');
	error_is(sub { App::FileSync::IO::set_mtime($missing, 5) },
		"Cannot set the modification time of $missing: ${\ do { local $! = ENOENT; qq{$!} }}", 'a missing file is io.utime');

	my @fallback;
	mock 'Time::HiRes::utime' => sub { die "Time::HiRes::utime(): unimplemented in this platform\n" };
	App::FileSync::IO::set_mtime($path, 3000.9);
	is((stat $path)[9], 3000, 'the fallback stores whole seconds');
	error_is(sub { App::FileSync::IO::set_mtime($missing, 5) },
		"Cannot set the modification time of $missing: ${\ do { local $! = ENOENT; qq{$!} }}", 'and reports its own failure');
	restore_all();

	mock 'Time::HiRes::utime' => sub { die "something else broke\n" };
	error_is(sub { App::FileSync::IO::set_mtime($path, 5) }, "Cannot set the modification time of $path: something else broke",
		'any other croak is not retried');
	restore_all();
};

subtest 'IO::sha256_file' => sub {
	# Strategy: known digests, and undef (never a digest of nothing) for
	# anything that is not a readable regular file.
	my $dir = scratch();
	is(App::FileSync::IO::sha256_file(put_file(File::Spec->catfile($dir, 'abc'), 'abc')),
		'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad', 'the digest of "abc"');
	is(App::FileSync::IO::sha256_file(put_file(File::Spec->catfile($dir, 'e'), '')),
		'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'the digest of an empty file');
	is(App::FileSync::IO::sha256_file($dir), undef, 'a directory has none');
	is(App::FileSync::IO::sha256_file(File::Spec->catfile($dir, 'missing')), undef, 'a missing file has none');
	mock 'Digest::SHA::addfile' => sub { die "read error\n" };
	is(App::FileSync::IO::sha256_file(File::Spec->catfile($dir, 'abc')), undef, 'a read failure part-way has none');
	restore_all();
};

subtest 'IO::list_dir' => sub {
	# Strategy: sorted, without . and .., hidden names kept, and undef with
	# $! set for a directory that cannot be opened.
	my $dir = scratch();
	put_file(File::Spec->catfile($dir, $_), '') for qw(b a .hidden);
	is_deeply(App::FileSync::IO::list_dir($dir), [qw(.hidden a b)], 'sorted names');
	is_deeply(App::FileSync::IO::list_dir(scratch()), [], 'an empty directory');
	my $missing = File::Spec->catdir($dir, 'missing');
	is(App::FileSync::IO::list_dir($missing), undef, 'a missing directory');
	is($! + 0, ENOENT, 'with $! saying why');
	is(App::FileSync::IO::list_dir(File::Spec->catfile($dir, 'a')), undef, 'a file is not a directory');
};

subtest 'IO::copy_preserving' => sub {
	# Strategy: content, mode and mtime all survive; the destination's
	# directory is made; a given stat is used instead of a fresh one.
	my $dir = scratch();
	my $src = put_file(File::Spec->catfile($dir, 's'), 'data', 1234);
	chmod oct(640), $src;
	my $dst = File::Spec->catfile($dir, 'deep', 'er', 'd');
	is(App::FileSync::IO::copy_preserving($src, $dst), 1, 'returns 1');
	is(slurp($dst), 'data', 'the content');
	is((stat $dst)[9], 1234, 'the mtime');
	SKIP: {
		skip 'no POSIX modes on Windows', 2 if $^O eq 'MSWin32';
		is((stat $dst)[2] & oct(777), oct(640), 'the mode');

t/function.t  view on Meta::CPAN

	error_is(sub { $server->_manifest({ entries => [ { p => 'f', h => $hash, s => undef } ] }) }, "Bad manifest field 's' for f", 'a missing size');
};

subtest 'Server::_expect and _unique_loser_names' => sub {
	# Strategy: each kind of request serves only the planned actions %MAY
	# lists; a conflict is labelled by which side won.
	my ($server) = new_server(plan => [
		{ p => 'pull', a => 'pull' }, { p => 'push', a => 'push' }, { p => 'gone', a => 'delete_remote' },
		{ p => 'cr', a => 'conflict', winner => 'remote' }, { p => 'cc', a => 'conflict', winner => 'client' },
		{ p => 'odd', a => 'conflict' },
	]);
	my %allowed = (
		read   => [qw(pull cr)],
		write  => [qw(push cc)],
		delta  => [qw(push)],
		pull   => [qw(pull)],
		mkdir  => [qw(push)],
		delete => [qw(gone)],
		ack    => [qw(pull cr)],
	);
	my %what = (read => 'Read', write => 'Write', delta => 'Delta write', pull => 'Signature upload', mkdir => 'Directory creation', delete => 'Deletion', ack => 'Ack');
	for my $kind (sort keys %allowed) {
		my %yes = map { $_ => 1 } @{ $allowed{$kind} };
		for my $path (qw(pull push gone cr cc odd)) {
			if ($yes{$path}) {
				is($server->_expect($kind, $path)->{p}, $path, "$kind may serve $path");
			} else {
				error_is(sub { $server->_expect($kind, $path) }, "$what{$kind} of '$path' is not in the plan", "$kind may not serve $path");
			}
		}
	}
	error_is(sub { $server->_expect('read', 'other') }, "Read of unplanned path 'other'", 'an unplanned path');
	error_is(sub { $server->_expect('read', undef) }, "Read of unplanned path ''", 'no path');

	$server->{index} = { 'a (conflict).txt' => {} };
	my @actions = ({ a => 'conflict', loser_name => 'a (conflict).txt' }, { a => 'conflict', loser_name => 'a (conflict).txt' }, { a => 'push', loser_name => 'x' });
	$server->_unique_loser_names(\@actions);
	isnt($actions[0]{loser_name}, 'a (conflict).txt', 'a loser name taken in the master is changed');
	isnt($actions[0]{loser_name}, $actions[1]{loser_name}, 'two conflicts get different names');
	is($actions[2]{loser_name}, 'x', 'non-conflicts are left alone');
};

subtest 'Server::_get and _file_stat' => sub {
	my ($server, $conn) = new_server(plan => [ { p => 'f', a => 'pull' }, { p => 'd', a => 'pull' }, { p => 'gone', a => 'pull' } ]);
	master_file($server, 'f', 'abcdef');
	make_path(master_file($server, 'd'));
	$server->_get({ p => 'f', off => 2, max => 3 });
	is($conn->last_reply()->{_bytes}, 'cde', 'a range');
	is($conn->last_reply()->{eof}, 0, 'not the end');
	$server->_get({ p => 'f', off => 6 });
	is_deeply([ @{ $conn->last_reply() }{qw(_bytes eof s)} ], [ '', 1, 6 ], 'an offset at the end is an empty last chunk');
	error_is(sub { $server->_get({ p => 'f', off => 7 }) }, "Bad 'off' for 'f'", 'past the end');
	error_is(sub { $server->_get({ p => 'f', off => -1 }) }, "Bad 'off' for 'f'", 'a negative offset');
	error_is(sub { $server->_get({ p => 'f', max => '1.5' }) }, "Bad 'max' for 'f'", 'a fractional max');
	mock 'App::FileSync::Delta::read_exact' => sub { return 'x' x $_[1] };
	$server->_get({ p => 'f', max => 10**12 });
	restore_all();
	is(length $conn->last_reply()->{_bytes}, 6, 'a huge max is clamped, never trusted');
	error_is(sub { $server->_get({ p => 'd' }) }, "Cannot send 'd': not a regular file", 'a directory');
	error_is(sub { $server->_get({ p => 'gone' }) }, "Cannot stat gone: ${\ do { local $! = ENOENT; qq{$!} }}", 'a vanished file');
	is_deeply($server->_file_stat(master_file($server, 'f'), 'f')->{s}, 6, '_file_stat');
	SKIP: {
		skip 'no symlinks', 1 unless eval { symlink '/etc/passwd', master_file($server, 'evil') };
		# Scan never lists a symlink, but the master can change between the
		# plan and the read: a link put there must not be followed out of it.
		$server->{plan}{evil} = { p => 'evil', a => 'pull' };
		error_is(sub { $server->_get({ p => 'evil' }) }, "Cannot send 'evil': not a regular file", 'a symlink is never followed (old: sent its target)');
	}
};

subtest 'Server::_put, _chunk, _chunk_end and the upload helpers' => sub {
	# Strategy: a whole-file push is verified against its announced size
	# and hash before it replaces anything; every failure removes the temp.
	my ($server, $conn) = new_server(plan => [ { p => 'new.txt', a => 'push' }, { p => 'b', a => 'push' } ]);
	my $content = 'hello world';
	my %file = (p => 'new.txt', s => length $content, h => Digest::SHA::sha256_hex($content), m => 1000, mode => oct(600));
	$server->_put({ %file });
	is_deeply($conn->last_reply(), { ok => 1, off => 0 }, 'put opens the upload');
	my $temp = $server->{uploads}{'new.txt'}{temp};
	ok(-e $temp, 'with a temporary file');
	error_is(sub { $server->_put({ %file }) }, "Already receiving 'new.txt'", 'a second put of the same path');
	$conn->{queue} = [];
	$conn->{pending} = 'hello ';
	$server->_chunk({ p => 'new.txt', len => 6 });
	is_deeply($conn->last_reply(), { ok => 1, off => 6 }, 'a chunk');
	$conn->{pending} = 'world';
	$server->_chunk({ p => 'new.txt', len => 5 });
	$server->_chunk_end({ p => 'new.txt' });
	my $abs = master_file($server, 'new.txt');
	is(slurp($abs), $content, 'installed');
	is((stat $abs)[9], 1000, 'with its mtime');
	is($server->{index}{'new.txt'}{h}, $file{h}, 'indexed');
	ok($server->{applied}{'new.txt'}, 'and applied');
	ok(!-e $temp, 'the temp is gone');

	# A client that sends more than it announced cannot fill the disk.
	$server->_put({ p => 'b', s => 2, h => $file{h} });
	$temp = $server->{uploads}{b}{temp};
	$conn->{pending} = 'abc';
	error_is(sub { $server->_chunk({ p => 'b', len => 3 }) }, "Upload of 'b' is larger than announced", 'an overflow');
	ok(!-e $temp && !$server->{uploads}{b}, 'discards the upload');

	$server->_put({ p => 'b', s => 3, h => Digest::SHA::sha256_hex('xyz') });
	$temp = $server->{uploads}{b}{temp};
	$conn->{pending} = 'abc';
	$server->_chunk({ p => 'b', len => 3 });
	error_is(sub { $server->_chunk_end({ p => 'b' }) }, "Hash mismatch for 'b': expected ${\ Digest::SHA::sha256_hex('xyz') }, got ${\ Digest::SHA::sha256_hex('abc') }", 'a hash mismatch');
	ok(!-e $temp, 'removes the temp');
	ok(!-e master_file($server, 'b'), 'and installs nothing');

	$server->_put({ p => 'b', s => 5, h => Digest::SHA::sha256_hex('abc') });
	$conn->{pending} = 'abc';
	$server->_chunk({ p => 'b', len => 3 });
	error_is(sub { $server->_chunk_end({ p => 'b' }) }, "Size mismatch for 'b': expected 5, got 3", 'a short upload');

	error_is(sub { $server->_chunk({ p => 'b', len => $App::FileSync::Constants::MAX_CHUNK_BYTES + 1 }) }, "Data for 'b' without a put", 'a chunk with no put');
	$server->_put({ p => 'b', s => 1, h => $file{h} });
	error_is(sub { $server->_chunk({ p => 'b', len => $App::FileSync::Constants::MAX_CHUNK_BYTES + 1 }) }, "Chunk for 'b' is too large", 'an oversized chunk');
	error_is(sub { $server->_chunk({ p => 'b', len => 'lots' }) }, "Bad 'len' for 'b'", 'a junk length');
	error_is(sub { $server->_chunk_end({}) }, "Data for '' without a put", 'chunk_end with no path');
	$server->_discard_uploads();



( run in 3.097 seconds using v1.01-cache-2.11-cpan-eb134014566 )