App-Access2CSV

 view release on metacpan or  search on metacpan

lib/App/Access2CSV/Exporter.pm  view on Meta::CPAN

	# taint mode requires): PATH keeps only absolute directory, and variables
	# that can change how a program is started are removed
	# (File::Spec->path and path_sep, not ":": Windows separates PATH with
	# ";" and its paths contain ":", as in C:\\)
	local $ENV{PATH} = join($Config{path_sep}, map { _untaint($_) } grep { length && File::Spec->file_name_is_absolute($_) } File::Spec->path());
	local @ENV{@UNSAFE_ENV};
	delete @ENV{@UNSAFE_ENV};

	# A list (not a string) is passed, so no shell ever sees the file or
	# table name and quoting cannot be abused
	my $stderr = '';
	run3([$self->{programs}{$name}, @{$args}], \undef, $stdout, \$stderr);

	# Distinguish "never started" (-1) and a signal from an ordinary
	# non-zero exit status; $! only means something in the first case
	my ($status, $reason) = ($?, "$!");
	chomp $stderr;
	if($status == -1) {
		$self->_croak_i18n('program_not_run', { params => [$name, $reason] });
	}
	if($status & 127) {
		# While system() waits, Perl ignores INT and QUIT in this process,
		# so Ctrl-C shows up only as the child dying of SIGINT.  Treat
		# that as the user stopping the whole run, not as a bad table.
		my $signal = (split ' ', $Config{sig_name})[$status & 127] // '';
		if($signal eq 'INT' || $signal eq 'QUIT') {
			$self->{interrupted} = $signal;
			$self->_croak_i18n('interrupted', { params => [$signal] });
		}
		$self->_croak_i18n('program_signalled', { params => [$name, $status & 127] });
	}
	if($status) {
		$self->_croak_i18n('program_failed', { params => [$name, $status >> 8, $stderr] });
	}
	return $self;
}

# _csv_filename
# Purpose:        Turn a table name into a safe, unique CSV file name.
# Entry Criteria: $table is a table name (possibly empty).
# Exit Status:    Returns a file name (no directory) ending in ".csv".
# Side Effects:   Records the name in $self->{used_names}.
#

t/app.t  view on Meta::CPAN

use File::Temp qw(tempdir);
use FindBin qw($Bin);
use lib File::Spec->catdir($Bin, 'lib');

use App::Access2CSV;
use FakeMDB qw(install_fake_mdbtools make_database fake_path);

local $ENV{PATH} = fake_path();
local @ENV{qw(LANGUAGE LC_ALL LC_MESSAGES LANG)} = (undef) x 4;

# cli(@argv): run the program and return (status, stdout, stderr)
sub cli {
	my @argv = @_;
	my $status;
	my ($stdout, $stderr) = capture { $status = App::Access2CSV->run(@argv) };
	return ($status, $stdout, $stderr);
}

my $dir = tempdir(CLEANUP => 1);
my $db = make_database($dir, qw(Customers Orders));
my $log = File::Spec->catfile($dir, 'test.log');

subtest 'help and manual' => sub {
	my ($status, $stdout) = cli('--help');
	is($status, 0, '--help exits 0');
	like($stdout, qr/--output-dir/, 'lists options');

	($status, $stdout) = cli('-h');
	is($status, 0, '-h is an alias');

	($status, $stdout) = cli('--man');
	is($status, 0, '--man exits 0');
	like($stdout, qr/EXIT STATUS/, 'full manual');
};

subtest 'usage errors' => sub {
	my ($status, undef, $stderr) = cli();
	is($status, 2, 'no database');
	like($stderr, qr/Missing database filename/, 'says why');

	($status, undef, $stderr) = cli('a.accdb', 'b.accdb');
	is($status, 2, 'two databases');

	($status, undef, $stderr) = cli('--bogus', $db);
	is($status, 2, 'unknown option is no longer ignored');
	like($stderr, qr/Unknown option: bogus/, 'says why');

	($status, undef, $stderr) = cli('--output-dir');
	is($status, 2, 'option missing its value');
};

subtest 'fatal errors' => sub {
	my ($status, undef, $stderr) = cli('--no-log', File::Spec->catfile($dir, 'nope.accdb'));
	is($status, 3, 'missing database');
	like($stderr, qr/\Aaccess2csv: Cannot read database .*nope\.accdb: [^\n]+\n\z/, 'one clean line');
	unlike($stderr, qr/ line \d+\.$/m, 'no Perl file/line without --verbose');

	($status, undef, $stderr) = cli('--no-log', '--verbose', File::Spec->catfile($dir, 'nope.accdb'));
	like($stderr, qr/ at \S+ line \d+/, 'file/line with --verbose');

	($status, undef, $stderr) = cli('--no-log', '--encoding', 'ebcdic', $db);
	is($status, 2, 'bad encoding: a command-line mistake (usage error)');
	like($stderr, qr/^Invalid setting: Parameter 'encoding' \(ebcdic\) must be one of utf8, utf8-bom, cp1252$/m, 'says why, in plain words');
	unlike($stderr, qr/Params::Validate::Strict|validate_strict| line \d+/, 'no module internals or Perl location');

	($status, undef, $stderr) = cli('--log', File::Spec->catfile($dir, 'no', 'such', 'dir.log'), $db);
	is($status, 3, 'log cannot be opened');
	like($stderr, qr/Cannot open log file .*dir\.log: /, 'says why');
};

subtest 'successful export with a log' => sub {
	my $out = File::Spec->catdir($dir, 'out');
	my ($status, $stdout, $stderr) = cli('--output-dir', $out, '--log', $log, '--show-counts', $db);

	is($status, 0, 'exit 0');
	is($stdout, '', 'nothing on STDOUT');
	like($stderr, qr/\[1\/2\] Customers\n\[2\/2\] Orders\n/, 'progress on STDERR');
	ok(-f File::Spec->catfile($out, 'Customers.csv'), 'file written');

	open my $fh, '<', $log or die "$log: $!";
	my $text = do { local $/; <$fh> };
	like($text, qr/Exported Orders => .*Orders\.csv \(1 row\)/, 'export logged');
	like($text, qr/Processed 2 tables, 0 failed/, 'summary logged');

	($status) = cli('--output-dir', $out, '--no-log', '--no-progress', $db);
	is($status, 1, 'files exist: exit 1');
	($status) = cli('--output-dir', $out, '--no-log', '--no-progress', '--overwrite', $db);

t/app.t  view on Meta::CPAN

	mkdir File::Spec->catdir($work, 'sub') or die "$work/sub: $!";
	my %names = (
		'parent directory' => File::Spec->catfile($work, 'sub', File::Spec->updir(), 'up.log'),
		'dollar'        => File::Spec->catfile($work, 'cost$.log'),
		'exclamation'   => File::Spec->catfile($work, 'done!.log'),
		'semicolon'     => File::Spec->catfile($work, 'a;b.log'),
	);
	foreach my $case (sort keys %names) {
		my $file = $names{$case};
		my $out = File::Spec->catdir($work, "out-$case");
		my ($status, undef, $stderr) = cli('--no-progress', '--log', $file, '--output-dir', $out, $db);
		is($status, 0, "$case: exit 0");
		unlike($stderr, qr/Cannot write to the log/, "$case: no logging failure");

		open my $fh, '<', $file or die "$file: $!";
		my $text = do { local $/; <$fh> };
		close $fh;
		like($text, qr/Exported Customers => /, "$case: export logged");
		like($text, qr/Processed 2 tables, 0 failed/, "$case: summary logged");
	}
};

subtest 'regression: the log is closed when the run ends' => sub {

t/app.t  view on Meta::CPAN

	my @argv = ('--no-log', '--dry-run', $db);
	cli(@argv);
	is_deeply(\@argv, ['--no-log', '--dry-run', $db], 'unchanged');
};

subtest 'bin/access2csv' => sub {
	my $script = File::Spec->catfile($Bin, File::Spec->updir(), 'bin', 'access2csv');
	my $lib = File::Spec->catdir($Bin, File::Spec->updir(), 'lib');
	# Standard error is shown if the status is wrong, so a failure (for
	# example a module the child cannot load) says why
	my ($stdout, $stderr) = capture { system($^X, "-I$lib", $script, '--help') };
	is($? >> 8, 0, 'exit status passed through') or diag("child stderr: $stderr");
	like($stdout, qr/--output-dir/, 'help printed');

	(undef, $stderr) = capture { system($^X, "-I$lib", $script) };
	is($? >> 8, 2, 'usage error status passed through') or diag("child stderr: $stderr");
};

done_testing();

t/data-flow.t  view on Meta::CPAN

	around('File::Temp::new', sub {
		my ($orig, @args) = @_;
		my $temp = $orig->(@args);
		push @names, $temp->filename();
		push @weak, $temp;
		weaken($weak[-1]);
		return $temp;
	});

	my $fds_before = open_fds();
	my ($stdout, $stderr, @result) = capture { $code->() };
	my $fds_after = open_fds();
	unmock('File::Temp::new');

	return {
		created   => scalar(@names),
		alive     => scalar(grep { defined } @weak),
		leftovers => [grep { -e $_ } @names],
		fds       => [$fds_before, $fds_after],
		stdout    => $stdout,
		stderr    => $stderr,
		result    => \@result,
	};
}

# Standard lifecycle checks on the result of track_temp_files
sub lifecycle_ok {
	my ($track, $name) = @_;
	verbose_diag("$name lifecycle", { map { $_ => $track->{$_} } qw(created alive leftovers fds) });
	ok($track->{created} > 0, "$name: temporary files were used");
	is($track->{alive}, 0, "$name: every temporary file object destroyed (handles closed)");

t/data-flow.t  view on Meta::CPAN

	# data during conversion, truncated data, file already there.  In
	# every case the temporary files must be closed and deleted.
	my ($dir, $db) = new_database(qw(Broken Killed Japanese Truncated Orders));
	my $out = "$dir/out";
	mkdir $out or die $!;
	open my $fh, '>', "$out/Orders.csv" or die $!;
	close $fh;

	my $e = $CONFIG{exporter}->new(output_dir => $out, progress => 0, encoding => 'cp1252');
	my $track = track_temp_files(sub { $e->run($db) });
	verbose_diag('stderr', $track->{stderr});
	is($track->{result}[0], $CONFIG{exit_failure}, 'every table failed');
	is(scalar(() = $track->{stderr} =~ /^FAILED: /mg), 5, 'five failures reported');
	lifecycle_ok($track, 'failures');
	is_deeply(dir_entries($out), ['Orders.csv'], 'only the file that was there before');
};

subtest 'lifecycle: exceptions thrown inside the external call' => sub {
	# run3 dies after mdb-export has written part of the data (e.g. a pipe
	# error).  The exception passes through our code; the handle and the
	# temporary file must still be released.
	my ($dir, $db) = new_database(qw(Orders));
	around("$CONFIG{exporter}::run3", sub {
		my ($orig, $cmd, @rest) = @_;
		return $orig->($cmd, @rest) unless $cmd->[0] =~ /mdb-export\z/;
		print {$rest[1]} "partial";
		die "run3(): broken pipe\n";
	});

	foreach my $encoding (qw(utf8 cp1252)) {
		my $e = $CONFIG{exporter}->new(output_dir => "$dir/$encoding", progress => 0, encoding => $encoding);
		my $track = track_temp_files(sub { $e->run($db) });
		like($track->{stderr}, qr/FAILED: Orders: run3\(\): broken pipe/, "$encoding: failure reported");
		lifecycle_ok($track, "$encoding with a dying run3");
		is_deeply(dir_entries("$dir/$encoding"), [], "$encoding: no partial file");
	}
	unmock("$CONFIG{exporter}::run3");
};

subtest 'lifecycle: rename fails at the very end' => sub {
	# The data is complete but cannot be moved into place (a directory is in
	# the way).  The finished temporary file must not be left behind.
	my ($dir, $db) = new_database(qw(Orders));
	my $out = "$dir/out";
	mkdir $out or die $!;
	mkdir "$out/Orders.csv" or die $!;
	open my $fh, '>', "$out/Orders.csv/keep" or die $!;
	close $fh;

	my $e = $CONFIG{exporter}->new(output_dir => $out, progress => 0, overwrite => 1);
	my $track = track_temp_files(sub { $e->run($db) });
	like($track->{stderr}, qr/FAILED: Orders: Cannot write /, 'reported');
	lifecycle_ok($track, 'failed rename');
	is_deeply(dir_entries($out), ['Orders.csv'], 'only the directory that was in the way');
};

subtest 'lifecycle: the log file probe' => sub {
	# App::Access2CSV opens the log once to prove it is writable, then
	# closes it.  Neither success nor failure may leave it open.
	my ($dir, $db) = new_database(qw(Orders));

	my $before = open_fds();

t/domain.t  view on Meta::CPAN

}

sub slurp {
	my $path = shift;
	open my $fh, '<:raw', $path or die "$path: $!";
	local $/;
	return scalar <$fh>;
}

# export(\@tables, %settings): run a quiet exporter over a database of
# @tables; returns (status, stderr, output dir)
sub export {
	my ($tables, %settings) = @_;
	my ($dir, $db) = new_database(@{$tables});
	my $out = "$dir/out";
	my $status;
	my (undef, $stderr) = capture {
		$status = eval { $CONFIG{exporter}->new(output_dir => $out, progress => 0, %settings)->run($db) };
	};
	return ($status, $stderr, $out);
}

#######################################################################
# App::Access2CSV::I18N::i18n
#######################################################################

subtest 'i18n key: known | unknown | empty | undef | reference' => sub {
	my $i18n = $CONFIG{i18n};

	is($i18n->i18n('dry_run_title'), 'DRY RUN', 'valid: known key');

t/domain.t  view on Meta::CPAN

	# (a damaged or hostile database) are shortened to 64.  0.001.0 did
	# not shorten, so names over 251 bytes failed with "File name too
	# long" (see the cpantesters report in t/stdin.t)
	my $max = $CONFIG{access_max};
	my %names = (
		one      => 'a',
		at_max   => 'b' x $max,
		over_max => 'c' x ($max + 1),
		os_max   => 'd' x $CONFIG{name_max},
	);
	my ($status, $stderr, $out) = export([values %names]);
	verbose_diag('files', dir_entries($out));
	is($status, $CONFIG{exit_ok}, 'every table exported');
	ok(-f "$out/$names{$_}$CONFIG{csv_suffix}", "$_: kept as it is") foreach qw(one at_max);
	ok(-f "$out/" . ('c' x $max) . $CONFIG{csv_suffix}, 'over_max: shortened to 64');
	ok(-f "$out/" . ('d' x $max) . $CONFIG{csv_suffix}, 'longer than the OS allows: shortened, not failed');
	is(scalar(@{ dir_entries($out) }), scalar(keys %names), 'one file each, no temporary files');
};

subtest 'table name length: shortened names that collide are numbered' => sub {
	my $max = $CONFIG{access_max};

t/domain.t  view on Meta::CPAN

		'u-umlaut: 1 character, 2 bytes'              => "\x{fc}",
		'emoji: 1 character, 4 bytes'                 => $TEXT{emoji},
		'joined emoji: 5 characters, 18 bytes'        => $TEXT{family},
		'e and combining acute: 2 characters, 3 bytes' => "e\x{301}",
	);
	foreach my $case (sort keys %units) {
		my $unit = bytes($units{$case});
		my $by_chars = int($CONFIG{access_max} / length($units{$case}));
		my $by_bytes = int($CONFIG{max_name_bytes} / length($unit));
		my $fits = ($by_chars < $by_bytes) ? $by_chars : $by_bytes;
		my ($status, $stderr, $out) = export([$unit x ($fits + 1)]);
		is($status, $CONFIG{exit_ok}, "$case: exported");
		is_deeply(dir_entries($out), [($unit x $fits) . $CONFIG{csv_suffix}], "$case: $fits whole ones kept");
	}
};

subtest 'table name bytes that are not UTF-8 become "_"' => sub {
	# macOS refuses file names that are not valid UTF-8 ("Illegal byte
	# sequence"), so 0.001.0 failed these tables there.  Each bad byte is
	# replaced, on every system, so the name is the same everywhere.
	my %names = (
		'Latin-1 e-acute'          => ["Caf\xE9", 'Caf_'],
		'cut-off UTF-8 character'  => ["Tea\xC3", 'Tea_'],
		'UTF-16 surrogate'         => ["a\xED\xA0\x80b", 'a_b'],
		'valid UTF-8 kept'         => [bytes("Cr\x{e8}me"), bytes("Cr\x{e8}me")],
	);
	my ($status, $stderr, $out) = export([map { $_->[0] } values %names]);
	is($status, $CONFIG{exit_ok}, 'every table exported') or diag($stderr);
	is_deeply(dir_entries($out), [sort map { $_->[1] . $CONFIG{csv_suffix} } values %names], 'bad bytes replaced, valid UTF-8 kept');

	# Then shortened like any other name
	($status, undef, $out) = export(["\xE9" x $CONFIG{name_max}]);
	is($status, $CONFIG{exit_ok}, 'long Latin-1 name: exported');
	is_deeply(dir_entries($out), [('_' x $CONFIG{access_max}) . $CONFIG{csv_suffix}], 'long Latin-1 name: replaced, then shortened to 64');
};

subtest 'table name characters: German, emoji, Zalgo, RTL text' => sub {
	# Kept exactly, byte for byte, in the file name and in the data
	my @names = map { bytes($TEXT{$_}) } qw(german emoji family zalgo arabic);
	my ($status, $stderr, $out) = export(\@names);
	is($status, $CONFIG{exit_ok}, 'all exported');
	is_deeply(dir_entries($out), [sort map { "$_.csv" } @names], 'file names byte-identical to the table names');
	like(slurp("$out/" . bytes($TEXT{family}) . '.csv'), qr/\Q${\ bytes($TEXT{family}) }\E/, 'joined emoji intact in the data');
};

subtest 'table name characters: invisible direction overrides are unsafe' => sub {
	# A right-to-left override makes "report<RLO>vsc.exe.csv" display as
	# "reportexe.csv.csv"-like text: a classic file-name spoofing trick.
	# Direction controls must be treated like other control characters.
	my @overrides = ("\x{202E}", "\x{202D}", "\x{2066}", "\x{2069}", "\x{200F}");

t/domain.t  view on Meta::CPAN

				my ($cmd, $in, $out, $err) = @_;
				return $real->(@_) unless $cmd->[0] =~ /mdb-export\z/;
				print {$out} bytes($chars) . "\n";
				$out->flush();
				${$err} = '';
				$? = 0;
				return 1;
			});
		};
		my $status;
		my (undef, $stderr) = capture {
			$status = $CONFIG{exporter}->new(output_dir => "$dir/out", progress => 0, encoding => 'cp1252')->run($db);
		};
		if(defined $expected) {
			is($status, $CONFIG{exit_ok}, "$case: converted");
			is(slurp("$dir/out/T.csv"), "$expected\n", "$case: right byte");
		} else {
			is($status, $CONFIG{exit_failure}, "$case: refused");
			like($stderr, qr/line 1: cannot be represented in cp1252/, "$case: reported");
		}
	}
};

subtest 'row counts: 0 | 1 | 2' => sub {
	# The plural edge in the log message
	require Test::Mockingbird;
	foreach my $rows (0, 1, 2) {
		my $real = \&App::Access2CSV::Exporter::run3;
		my $guard = Test::Mockingbird::mock_scoped('App::Access2CSV::Exporter::run3' => sub {

t/domain.t  view on Meta::CPAN

	}
};

#######################################################################
# App::Access2CSV::run
#######################################################################

sub cli {
	my @argv = @_;
	my $status;
	my ($stdout, $stderr) = capture { $status = $CONFIG{app}->run(@argv) };
	return ($status, $stdout, $stderr);
}

subtest 'argv: 0 | 1 | 2 database names' => sub {
	my ($dir, $db) = new_database('T');
	my @common = ('--no-log', '--dry-run');
	my ($status, undef, $stderr) = cli(@common);
	is($status, $CONFIG{exit_usage}, '0 (below the only valid count)');
	like($stderr, qr/^Missing database filename$/m, 'message');
	($status) = cli(@common, $db);
	is($status, $CONFIG{exit_ok}, 'exactly one (the only valid count)');
	($status, undef, $stderr) = cli(@common, $db, $db);
	is($status, $CONFIG{exit_usage}, '2 (above)');
	like($stderr, qr/^Missing database filename$/m, 'message');
};

subtest 'argv --encoding: valid names | invalid' => sub {
	my ($dir, $db) = new_database('T');
	foreach my $value (qw(utf8 utf8-bom cp1252)) {
		my ($status) = cli('--no-log', '--dry-run', '--encoding', $value, $db);
		is($status, $CONFIG{exit_ok}, "valid: $value");
	}
	my ($status, undef, $stderr) = cli('--no-log', '--encoding', 'latin1', $db);
	is($status, $CONFIG{exit_usage}, 'invalid: latin1 (usage error)');
	like($stderr, qr/^Invalid setting: Parameter 'encoding' \(latin1\) must be one of utf8, utf8-bom, cp1252$/m, 'message');
};

subtest 'argv --table: 0 | 1 | many | non-ASCII' => sub {
	my $german = bytes($TEXT{german});
	my ($dir, $db) = new_database('A', 'B', $german);
	my %cases = (
		0    => [[], 3],
		1    => [['A'], 1],
		many => [['A', 'B', $german], 3],
		utf8 => [[$german], 1],

t/edge_cases.t  view on Meta::CPAN

}

sub new_database {
	my $dir = tempdir(CLEANUP => 1);
	return ($dir, make_database($dir, @_));
}

sub cli {
	my @argv = @_;
	my $status;
	my ($stdout, $stderr) = capture { $status = $CONFIG{app}->run(@argv) };
	return ($status, $stdout, $stderr);
}

# Run a quiet exporter; return (status, stdout, stderr, exception)
sub export {
	my ($db, %args) = @_;
	my ($status, $error);
	my ($stdout, $stderr) = capture {
		$status = eval { $CONFIG{exporter}->new(progress => 0, %args)->run($db) };
		$error = $@;
	};
	return ($status, $stdout, $stderr, $error);
}

sub slurp {
	my $path = shift;
	open my $fh, '<:raw', $path or die "$path: $!";
	local $/;
	return scalar <$fh>;
}

sub dir_entries {

t/edge_cases.t  view on Meta::CPAN

# controlled ways.  Keys: which => coderef, run3 => coderef.  Returns a guard.
sub upstream {
	my %behaviour = @_;
	return mock_scoped(
		"$CONFIG{exporter}::which" => $behaviour{which} || sub { "$CONFIG{fake_bin}/$_[0]" },
		"$CONFIG{exporter}::run3"  => $behaviour{run3},
	);
}

# A run3 double: mdb-tables lists @tables, everything else writes one
# line; $hook->($program, $cmd, $stdout, $stderr) may override
sub fake_run3 {
	my ($tables, $hook) = @_;
	return sub {
		my ($cmd, $stdin, $stdout, $stderr) = @_;
		(my $program = $cmd->[0]) =~ s{.*/}{};
		${$stderr} = '';
		$? = 0;
		return 1 if $hook && $hook->($program, $cmd, $stdout, $stderr);
		if($program eq 'mdb-tables') {
			${$stdout} = join('', map { "$_\n" } @{$tables});
		} elsif(ref($stdout) eq 'SCALAR') {
			${$stdout} = "1\n";
		} else {
			print {$stdout} "a\n";
			$stdout->flush();
		}
		return 1;
	};

t/edge_cases.t  view on Meta::CPAN

	# The stand-in mdb-tables prints the file back, so these model
	# "no tables", "one blank line" and "one CRLF line"
	foreach my $case (['0-byte', ''], ['single LF', "\n"], ['single CRLF', "\r\n"], ['only system tables', "MSysObjects\n~TMP\n"]) {
		my ($name, $content) = @{$case};
		my $dir = tempdir(CLEANUP => 1);
		my $db = "$dir/db.accdb";
		open my $fh, '>:raw', $db or die $!;
		print {$fh} $content;
		close $fh;

		my ($status, undef, $stderr, $error) = export($db, output_dir => "$dir/out");
		is($error, '', "$name: no exception");
		is($status, $CONFIG{exit_ok}, "$name: nothing to do is success");
		is_deeply(dir_entries("$dir/out"), [], "$name: no files");
	}
};

subtest 'security: shell metacharacters reach mdbtools as plain data' => sub {
	# Table and file names full of shell syntax.  If any of these went
	# through a shell, the marker file would be created.
	my $dir = tempdir(CLEANUP => 1);

t/edge_cases.t  view on Meta::CPAN

		"quote\"s and 'single'",
		' leading and trailing ',
		"tab\there",
	);
	my $db = make_database($dir, @hostile);

	# Database path with spaces, newline and metacharacters as well
	my $hostile_db = "$dir/my db; rm -rf ~ |\n.accdb";
	rename($db, $hostile_db) or die "rename: $!";

	my ($status, undef, $stderr, $error) = export($hostile_db, output_dir => "$dir/out");
	verbose_diag('files', dir_entries("$dir/out"));
	is($error, '', 'no exception');
	is($status, $CONFIG{exit_ok}, 'every table exported');
	ok(!-e $marker, 'no command was executed');
	is(scalar(@{ dir_entries("$dir/out") }), scalar(@hostile), 'one file per table, none lost to collisions');
	ok(!grep({ m{[/<>:"\\|?*\t\n]} } @{ dir_entries("$dir/out") }), 'no unsafe characters in file names');
	like(slurp("$dir/out/leading and trailing.csv"), qr/" leading and trailing "/, 'exact table name was passed to mdb-export');
};

subtest 'security: names starting with "-" are not mdbtools options' => sub {

t/edge_cases.t  view on Meta::CPAN

	# "-I" would turn the CSV into SQL.  Names must be protected by "--".
	my $dir = tempdir(CLEANUP => 1);
	my $argv_log = "$dir/argv.log";
	local $ENV{FAKE_MDB_ARGV_LOG} = $argv_log;
	my $db = make_database($dir, '-H', '-I', '--help', '-');

	# A database path that itself starts with "-", relative to the cwd
	my $cwd = File::Spec->rel2abs(File::Spec->curdir());
	chdir $dir or die $!;
	rename('test.accdb', '-db.accdb') or die $!;
	my ($status, undef, $stderr, $error) = export('-db.accdb', output_dir => 'out', show_counts => 1);
	my $files = dir_entries('out');
	chdir $cwd or die $!;

	verbose_diag('argv seen by mdbtools', slurp($argv_log));
	is($error, '', 'no exception') or diag($error);
	is($status, $CONFIG{exit_ok}, 'all four tables exported');
	is_deeply($files, [sort '-.csv', '--help.csv', '-H.csv', '-I.csv'], 'files named after the tables');
	unlike($stderr, qr/option parsing failed/, 'no name was parsed as an option');
};

subtest 'security: hostile table names cannot escape the output directory' => sub {
	# Path traversal through table names: every file must land inside
	# the output directory, and nothing may be written to its parent
	my $dir = tempdir(CLEANUP => 1);
	my @evil = ('../../escaped', '..', '.', '/etc/passwd', '..\\..\\win', "sub/../../up");
	my $db = make_database($dir, @evil);

	my ($status) = export($db, output_dir => "$dir/out/inner");

t/edge_cases.t  view on Meta::CPAN

	my $db = make_database($dir, 'Orders', 'Customers');
	my $out = "$dir/out";
	mkdir $out or die $!;
	my $victim = "$dir/victim.txt";
	open my $fh, '>', $victim or die $!;
	print {$fh} "precious\n";
	close $fh;
	symlink($victim, "$out/Orders.csv") or die $!;
	symlink("$dir/nowhere", "$out/Customers.csv") or die $!;

	my ($status, undef, $stderr) = export($db, output_dir => $out);
	is($status, $CONFIG{exit_failure}, 'both refused without --overwrite');
	like($stderr, qr/FAILED: Customers: Output file already exists: /, 'dangling symlink counts as existing');
	like($stderr, qr/FAILED: Orders: Output file already exists: /, 'symlink to a file counts as existing');
	ok(!-e "$dir/nowhere", 'dangling target not created');

	($status) = export($db, output_dir => $out, overwrite => 1);
	is($status, $CONFIG{exit_ok}, 'replaced with --overwrite');
	ok(!-l "$out/Orders.csv", 'the link was replaced by a real file');
	is(slurp($victim), "precious\n", 'the link target was not written through');
	ok(!-e "$dir/nowhere", 'still not created');
};

subtest 'filesystem: unusable output directories' => sub {

t/edge_cases.t  view on Meta::CPAN

	like($error, qr/\ACannot create output directory \/dev\/null: /, '/dev/null as a directory');

	symlink("$dir/loop", "$dir/loop") or die $!;
	(undef, undef, undef, $error) = export($db, output_dir => "$dir/loop/sub");
	like($error, qr/\ACannot create output directory /, 'symlink loop');

	SKIP: {
		skip('root can write anywhere', 3) if $> == 0;
		mkdir "$dir/ro" or die $!;
		chmod oct(555), "$dir/ro";
		my ($status, undef, $stderr) = export($db, output_dir => "$dir/ro");
		chmod oct(755), "$dir/ro";
		is($status, $CONFIG{exit_failure}, 'read-only directory: the table fails');
		like($stderr, qr/FAILED: Orders: .*\Q$OS{EACCES}\E/, 'with the OS reason');
		is_deeply(dir_entries("$dir/ro"), [], 'no temporary files left');
	}
};

subtest 'filesystem: table name longer than the OS allows' => sub {
	# 0.001.0 did not shorten names, so this table failed with "File name
	# too long".  A hostile or corrupt database can give any length (a
	# NetBSD tester saw a 500-byte one); it is now shortened and exported
	my ($dir, $db) = new_database('x' x $CONFIG{long_name}, 'Orders');
	my ($status, undef, $stderr) = export($db, output_dir => "$dir/out");
	is($status, $CONFIG{exit_ok}, 'both tables exported');
	unlike($stderr, qr/\Q$OS{ENAMETOOLONG}\E/, 'no "File name too long"');
	is_deeply(dir_entries("$dir/out"), ['Orders.csv', ('x' x $CONFIG{max_name_chars}) . '.csv'], 'shortened to 64 characters, no temporary files left');
};

subtest 'filesystem: truncated output from mdb-export' => sub {
	# mdb-export dies mid-character (unexpected EOF): utf8 copies bytes as
	# documented; cp1252 must refuse rather than guess
	my ($dir, $db) = new_database('Truncated');

	my ($status) = export($db, output_dir => "$dir/utf8");
	is($status, $CONFIG{exit_ok}, 'utf8: bytes copied as they are');

	my $stderr;
	($status, undef, $stderr) = export($db, output_dir => "$dir/cp1252", encoding => 'cp1252');
	is($status, $CONFIG{exit_failure}, 'cp1252: table fails');
	like($stderr, qr/Table Truncated, line 2: output of mdb-export is not valid UTF-8/, 'reported with the line');
	is_deeply(dir_entries("$dir/cp1252"), [], 'no partial file');
};

subtest 'scale: many colliding names' => sub {
	# Upper/lower-case variants of one name, many times over: every table
	# must still get its own file
	my @tables = map { my $n = $_; join('', map { ($n >> $_) & 1 ? 'A' : 'a' } 0 .. 9) } 0 .. $CONFIG{many_tables} - 1;
	my $guard = upstream(run3 => fake_run3(\@tables));
	my ($dir, $db) = new_database('placeholder');

t/edge_cases.t  view on Meta::CPAN

subtest 'upstream: run3 leaves no output at all' => sub {
	# A program that "succeeds" but leaves the output variable undef must be
	# treated as empty output: no warnings, no crash
	my ($dir, $db) = new_database('Orders');
	my $guard = upstream(run3 => fake_run3([], sub {
		my ($program, $cmd, $stdout) = @_;
		${$stdout} = undef if ref($stdout) eq 'SCALAR';
		return 1;
	}));

	my ($status, $stdout, $stderr, $error) = export($db, output_dir => "$dir/out", dry_run => 1, show_counts => 1);
	is($error, '', 'no exception');
	is($status, $CONFIG{exit_ok}, 'no tables is success');
	unlike($stderr, qr/uninitialized/, 'no warnings');
};

subtest 'upstream: mdb-count returns nonsense' => sub {
	# Garbage, negatives and huge numbers from mdb-count must neither crash
	# the dry run nor the export log
	my ($dir, $db) = new_database('Orders');
	foreach my $answer ('', "garbage\n", "-5\n", "$CONFIG{huge_count}\n") {
		my $guard = upstream(run3 => fake_run3(['Orders'], sub {
			my ($program, $cmd, $stdout) = @_;
			return 0 unless $program eq 'mdb-count';
			${$stdout} = $answer;
			return 1;
		}));
		my $out = "$dir/" . length($answer);
		my ($status, undef, $stderr, $error) = export($db, output_dir => $out, show_counts => 1);
		is($error, '', "mdb-count '" . ($answer =~ s/\n//r) . "': no exception");
		is($status, $CONFIG{exit_ok}, 'export succeeded');
		unlike($stderr, qr/FAILED/, 'the table is not blamed for a bad count');
	}
};

subtest 'upstream: a program that cannot be started' => sub {
	# $? == -1 means the program never ran.  That is not "killed by
	# signal 127" and must not be reported as such.
	my ($dir, $db) = new_database('Orders');
	my $guard = upstream(run3 => sub { $! = ENOENT; $? = -1; return 1 });

	my (undef, undef, undef, $error) = export($db, output_dir => "$dir/out");

t/edge_cases.t  view on Meta::CPAN

	# spooling).  For mdb-export that must fail one table, cleanly.
	my ($dir, $db) = new_database('Orders', 'Customers');
	my $guard = upstream(run3 => fake_run3(['Customers', 'Orders'], sub {
		my ($program, $cmd, $stdout) = @_;
		return 0 unless $program eq 'mdb-export' && $cmd->[-1] eq 'Orders';
		print {$stdout} "partial";
		$! = ENOSPC;
		die "run3(): $!\n";
	}));

	my ($status, undef, $stderr) = export($db, output_dir => "$dir/out");
	is($status, $CONFIG{exit_failure}, 'one table fails');
	like($stderr, qr/FAILED: Orders: run3\(\): \Q$OS{ENOSPC}\E/, 'reason passed on');
	is_deeply(dir_entries("$dir/out"), ['Customers.csv'], 'no partial Orders.csv, no temporary file');
};

subtest 'upstream: disk full while writing the byte order mark' => sub {
	# The BOM is written by Perl and flushed before mdb-export starts.
	# If that flush fails, the table must fail, not be written without it.
	my ($dir, $db) = new_database('Orders');
	# File::Temp inherits flush from IO::Handle.  Mock it there (mocking a
	# method a package only inherits leaves a stub behind on restore that
	# breaks later method calls), and fail only for temporary files.
	my $real_flush = \&IO::Handle::flush;
	my $guard = mock_scoped('IO::Handle::flush' => sub {
		return $real_flush->(@_) unless ref($_[0]) && $_[0]->isa('File::Temp');
		$! = ENOSPC;
		return;
	});

	my ($status, undef, $stderr) = export($db, output_dir => "$dir/out", encoding => 'utf8-bom');
	is($status, $CONFIG{exit_failure}, 'table fails');
	like($stderr, qr/FAILED: Orders: Cannot write .*Orders\.csv: \Q$OS{ENOSPC}\E/, 'disk full reported');
	is_deeply(dir_entries("$dir/out"), [], 'nothing left behind');
};

subtest 'upstream: the logger fails mid-run' => sub {
	# Logging is secondary.  A logger that dies (e.g. its disk is full)
	# must not turn successful exports into failures; it is reported once.
	{
		package Local::DyingLogger;
		sub new { return bless {}, shift }
		sub debug { die "log disk full\n" }
		sub info { die "log disk full\n" }
		sub warn { die "log disk full\n" }
	}
	my ($dir, $db) = new_database('Orders', 'Customers');

	my ($status, undef, $stderr, $error) = export($db, output_dir => "$dir/out", logger => Local::DyingLogger->new());
	verbose_diag('stderr', $stderr);
	is($error, '', 'no exception');
	is($status, $CONFIG{exit_ok}, 'exports still succeed');
	is_deeply(dir_entries("$dir/out"), ['Customers.csv', 'Orders.csv'], 'both written');
	is(scalar(() = $stderr =~ /Cannot write to the log: log disk full/g), 1, 'reported once');
	unlike($stderr, qr/FAILED/, 'no table blamed');
};

subtest 'context: $_ and list context' => sub {
	my ($dir, $db) = new_database('Orders');
	my $e = $CONFIG{exporter}->new(progress => 0, output_dir => "$dir/out", dry_run => 1);

	my @list;
	capture { @list = $e->run($db) };
	is(scalar(@list), 1, 'list context: exactly one status');

t/edge_cases.t  view on Meta::CPAN

	is_deeply(\@dbs, [$db, $db], 'aliased $_ not modified');
};

#######################################################################
# 3. App::Access2CSV::run
#######################################################################

subtest 'app: hostile command lines' => sub {
	my ($dir, $db) = new_database('Orders');

	my ($status, undef, $stderr) = cli(undef);
	is($status, $CONFIG{exit_usage}, 'undef database: usage error');
	like($stderr, qr/^Missing database filename$/m, 'says so');

	($status, undef, $stderr) = cli('');
	is($status, $CONFIG{exit_usage}, 'empty database: usage error');

	# "-" means standard input, even after "--" (as for cat and friends);
	# here standard input is empty, which is reported as such
	{
		open my $saved, '<&', \*STDIN or die $!;
		open STDIN, '<', File::Spec->devnull() or die $!;
		($status, undef, $stderr) = cli('--no-log', '--', '-');
		open STDIN, '<&', $saved or die $!;
	}
	is($status, $CONFIG{exit_fatal}, '"-" after "--" reads standard input');
	like($stderr, qr/Standard input is empty/, '... which is empty here');

	($status, undef, $stderr) = cli('--no-log', '--output-dir', '', $db);
	is($status, $CONFIG{exit_usage}, 'empty --output-dir is refused (usage error)');
	like($stderr, qr/^Invalid setting: .*'output_dir'/m, 'says which setting');

	($status) = cli('--no-log', '--dry-run', ('--table', 'Orders') x $CONFIG{many_tables}, $db);
	is($status, $CONFIG{exit_ok}, 'a thousand repeated --table options');

	($status, undef, $stderr) = cli('--log', $dir, $db);
	is($status, $CONFIG{exit_fatal}, 'log file is a directory');
	like($stderr, qr/\Aaccess2csv: Cannot open log file \Q$dir\E: \Q$OS{EISDIR}\E\n\z/, 'with the OS reason');

	my @list;
	capture { @list = $CONFIG{app}->run('--help') };
	is(scalar(@list), 1, 'list context: exactly one status');
};

subtest 'app: a logger constructor that returns nothing' => sub {
	# Upstream returns undef instead of a logger.  The user asked for a
	# log, so continuing silently without one would break the POD promise.
	my ($dir, $db) = new_database('Orders');
	my $log = "$dir/x.log";
	my $guard = mock_scoped('Log::Abstraction::new' => sub { return });

	my ($status, undef, $stderr) = cli('--log', $log, '--output-dir', "$dir/out", $db);
	is($status, $CONFIG{exit_fatal}, 'fatal');
	like($stderr, qr/\Aaccess2csv: Cannot open log file \Q$log\E: /, 'says why');
	ok(!-e "$dir/out", 'nothing exported without the promised log');
};

#######################################################################
# Regressions: bugs found in earlier reviews must never return
#######################################################################

subtest 'regression: earlier bugs stay fixed' => sub {
	my ($dir, $db) = new_database('A/B', 'A:B', 'A_B_2', 'Orders', 'ORDERS');

	# 1. "A_B_2" overwrote the collision file A_B_2.csv; Orders/ORDERS clashed
	my ($status, undef, $stderr, $error) = export($db, output_dir => "$dir/out");
	verbose_diag('regression export', { status => $status, stderr => $stderr, error => $error });
	is(scalar(@{ dir_entries("$dir/out") }), 5, 'five tables, five files');

	# 2. unknown options were ignored and the export went ahead
	($status) = cli('--no-log', '--bogus', '--output-dir', "$dir/bogus", $db);
	is($status, $CONFIG{exit_usage}, 'unknown option is a usage error');
	ok(!-e "$dir/bogus", 'and nothing was exported');

	# 3. --dry-run created the output directory
	export($db, output_dir => "$dir/dry", dry_run => 1);
	ok(!-e "$dir/dry", 'dry run creates nothing');

t/exporter.t  view on Meta::CPAN


# slurp($path): raw file contents
sub slurp {
	my $path = shift;
	open my $fh, '<:raw', $path or die "$path: $!";
	local $/;
	return scalar <$fh>;
}

# export(%args): run an exporter over @tables in a fresh directory and
# return (status, output dir, stdout, stderr, logger)
sub export {
	my ($tables, %args) = @_;

	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, @{$tables});
	my $out = File::Spec->catdir($dir, 'out');
	my $logger = Local::Logger->new();

	my $e = App::Access2CSV::Exporter->new(output_dir => $out, progress => 0, logger => $logger, %args);
	my $status;
	my ($stdout, $stderr) = capture { $status = $e->run($db) };
	return ($status, $out, $stdout, $stderr, $logger, $e, $db);
}

subtest 'constructor validation' => sub {
	isa_ok(App::Access2CSV::Exporter->new(), 'App::Access2CSV::Exporter');
	isa_ok(App::Access2CSV::Exporter->new({ encoding => 'cp1252' }), 'App::Access2CSV::Exporter', 'hashref form');
	lives_ok { App::Access2CSV::Exporter->new(tables => undef) } 'undef means default';
	throws_ok { App::Access2CSV::Exporter->new(encoding => 'latin1') } qr/encoding/, 'bad encoding';
	throws_ok { App::Access2CSV::Exporter->new(bogus => 1) } qr/Unknown parameter 'bogus'/, 'unknown setting';
	throws_ok { App::Access2CSV::Exporter->new(logger => 'file.log') } qr/logger/, 'logger must be an object';
	throws_ok { App::Access2CSV::Exporter->new(logger => bless({}, 'Local::NoMethods')) } qr/logger.*debug/, 'logger must have debug/info/warn';
	throws_ok { App::Access2CSV::Exporter->new(tables => [['nested']]) } qr/'?tables'? can only contain strings/, 'tables must be strings';

	my @tables = ('A');
	my $e = App::Access2CSV::Exporter->new(tables => \@tables);
	push @tables, 'B';
	is_deeply($e->{tables}, ['A'], 'table list is copied');
};

subtest 'exports user tables and skips system tables' => sub {
	my ($status, $out, $stdout, $stderr, $logger) = export([qw(Orders Customers MSysObjects USysRibbons ~TMPCLP1)]);

	is($status, 0, 'success');
	ok(-f File::Spec->catfile($out, 'Customers.csv'), 'Customers.csv');
	ok(-f File::Spec->catfile($out, 'Orders.csv'), 'Orders.csv');
	ok(!-e File::Spec->catfile($out, 'MSysObjects.csv'), 'MSys* skipped');
	ok(!-e File::Spec->catfile($out, 'USysRibbons.csv'), 'USys* skipped');
	is(slurp(File::Spec->catfile($out, 'Orders.csv')), qq{"id","name"\n1,"Orders"\n}, 'content');

	opendir(my $dh, $out);
	is_deeply([sort grep { !/^\.\.?$/ } readdir $dh], ['Customers.csv', 'Orders.csv'], 'no temporary files left');
	is($stderr, '', 'no warnings');
	like($logger->{lines}[-1], qr/INFO Processed 2 tables, 0 failed/, 'summary logged');
	like($logger->{lines}[0], qr/INFO Exported Customers => /, 'export logged');
};

subtest 'new files get normal permissions, not File::Temp 0600' => sub {
	plan(skip_all => 'Windows has no Unix permission bits') if $^O eq 'MSWin32';
	my $old = umask(022);
	my (undef, $out) = export(['Orders']);
	umask($old);
	is((stat(File::Spec->catfile($out, 'Orders.csv')))[2] & oct(777), oct(644), 'mode 0644 under umask 022');
};

subtest 'progress goes to STDERR' => sub {
	my ($status, undef, $stdout, $stderr) = export([qw(A B)], progress => 1);
	is($stdout, '', 'nothing on STDOUT');
	like($stderr, qr/^\[1\/2\] A\n\[2\/2\] B\n\z/, 'numbered progress');
};

subtest 'encodings' => sub {
	my (undef, $out) = export(['Unicode'], encoding => 'utf8');
	is(slurp("$out/Unicode.csv"), qq{"id","name"\n1,"Caf\xC3\xA9 \xE2\x82\xAC"\n}, 'utf8 is passed through');

	(undef, $out) = export(['Unicode'], encoding => 'utf8-bom');
	is(slurp("$out/Unicode.csv"), qq{\xEF\xBB\xBF"id","name"\n1,"Caf\xC3\xA9 \xE2\x82\xAC"\n}, 'utf8-bom adds a BOM, once');

	(undef, $out) = export(['Unicode'], encoding => 'cp1252');
	is(slurp("$out/Unicode.csv"), qq{"id","name"\n1,"Caf\xE9 \x80"\n}, 'cp1252 is converted');
};

subtest 'cp1252 refuses characters it cannot represent' => sub {
	my ($status, $out, undef, $stderr, $logger) = export([qw(Japanese Orders)], encoding => 'cp1252');
	is($status, 1, 'failure status');
	like($stderr, qr/FAILED: Japanese: Table Japanese, line 2: cannot be represented in cp1252/, 'warned');
	ok(!-e "$out/Japanese.csv", 'no partial file');
	ok(-e "$out/Orders.csv", 'other tables still exported');
	ok((grep { /^WARN FAILED: Japanese/ } @{ $logger->{lines} }), 'failure logged');
};

subtest 'cp1252 reports invalid UTF-8 from mdb-export' => sub {
	my ($status, undef, undef, $stderr) = export(['Latin1'], encoding => 'cp1252');
	is($status, 1, 'failure status');
	like($stderr, qr/Table Latin1, line 2: output of mdb-export is not valid UTF-8/, 'warned');
};

subtest 'mdb-export failures are per table' => sub {
	# "Killed" kills itself with a signal, which only Unix has
	my @tables = $^O eq 'MSWin32' ? qw(Broken Orders) : qw(Broken Killed Orders);
	my ($status, $out, undef, $stderr, $logger) = export(\@tables);
	is($status, 1, 'failure status');
	like($stderr, qr/FAILED: Broken: mdb-export failed with exit status 1: corrupt table/, 'exit status');
	SKIP: {
		skip('Windows has no signals', 1) if $^O eq 'MSWin32';
		like($stderr, qr/FAILED: Killed: mdb-export was killed by signal \d+/, 'signal');
	}
	ok(!-e "$out/Broken.csv", 'no partial file');
	ok(-e "$out/Orders.csv", 'good table exported');
	my ($total, $failed) = (scalar(@tables), scalar(@tables) - 1);
	like($logger->{lines}[-1], qr/Processed $total tables, $failed failed/, 'summary');
};

subtest 'existing files' => sub {
	my ($status, $out, undef, undef, undef, $e, $db) = export(['Orders']);
	is($status, 0, 'first run');

	my $stderr;
	(undef, $stderr) = capture { $status = $e->run($db) };
	is($status, 1, 'second run fails without --overwrite');
	like($stderr, qr/Output file already exists: .*Orders\.csv \(use --overwrite/, 'explains why');

	$e->{overwrite} = 1;
	(undef, $stderr) = capture { $status = $e->run($db) };
	is($status, 0, 'succeeds with overwrite');
	ok(-f "$out/Orders.csv", 'file is still there');
};

subtest 'names are the same on every run' => sub {
	my ($status, $out, undef, undef, undef, $e, $db) = export(['A/B', 'A:B'], overwrite => 1);
	capture { $status = $e->run($db) };
	is($status, 0, 'second run');
	opendir(my $dh, $out);
	is_deeply([sort grep { /\.csv$/ } readdir $dh], ['A_B.csv', 'A_B_2.csv'], 'no A_B_3.csv on the second run');
};

subtest 'table filter' => sub {
	my ($status, $out, undef, $stderr, $logger) = export([qw(A B C)], tables => [qw(C A Nope Nada)]);
	is($status, 0, 'success');
	ok(-e "$out/A.csv" && -e "$out/C.csv" && !-e "$out/B.csv", 'only the wanted tables');
	like($stderr, qr/Tables not found in database: Nada, Nope/, 'unknown tables reported (plural)');

	(undef, undef, undef, $stderr) = export([qw(A)], tables => [qw(Zed)]);
	like($stderr, qr/Table not found in database: Zed/, 'singular form');
};

subtest 'an empty table list exports nothing (documented pitfall)' => sub {
	my ($status, $out, undef, undef, $logger) = export([qw(A B)], tables => []);
	is($status, 0, 'success');
	ok(!-e "$out/A.csv" && !-e "$out/B.csv", 'no files');
	like($logger->{lines}[-1], qr/Processed 0 tables, 0 failed/, 'summary');
};

subtest 'undef settings mean "use the default"' => sub {

t/exporter.t  view on Meta::CPAN

	like($stdout, qr/^TABLE\s+ROWS\s+OUTPUT FILE$/m, 'ROWS column');
	like($stdout, qr/^Orders\s+1\s+Orders\.csv$/m, 'count shown');

	my $logger;
	($status, $out, undef, undef, $logger) = export(['Orders'], show_counts => 1);
	ok((grep { /Exported Orders => .* \(1 row\)/ } @{ $logger->{lines} }), 'count logged, singular');
};

subtest 'missing mdb-count is not fatal' => sub {
	local $ENV{PATH} = fake_path(qw(mdb-tables mdb-export));
	my ($status, undef, $stdout, $stderr) = export(['Orders'], dry_run => 1, show_counts => 1);
	is($status, 0, 'still succeeds');
	like($stderr, qr/mdb-count not found in PATH; row counts are unavailable/, 'warned');
	unlike($stdout, qr/ROWS/, 'no ROWS column');
};

subtest 'verbose logs where programs were found' => sub {
	my (undef, undef, undef, undef, $logger) = export(['Orders'], verbose => 1);
	ok((grep { /^DEBUG Found mdb-export at / } @{ $logger->{lines} }), 'debug message');
};

subtest 'fatal errors' => sub {
	my $e = App::Access2CSV::Exporter->new(progress => 0);

t/function.t  view on Meta::CPAN

# Set TEST_VERBOSE=1 to see the internal state behind each check.

use strict;
use warnings;

use Test::Most;
use Test::Memory::Cycle;
use Test::Mockingbird;
use Test::Returns;

use Capture::Tiny qw(capture capture_stderr capture_stdout);
use Errno qw(ENOENT);
use File::Spec;
use File::Temp qw(tempdir);
use Readonly;

# Loading the application loads all three modules, at compile time, so
# the access-control wrappers of Sub::Private/Sub::Protected are in place
use App::Access2CSV;

# These are white-box tests, so private and protected methods may be called

t/function.t  view on Meta::CPAN

subtest 'Exporter::_export_all carries on past failures and counts them' => sub {
	my (@exported, @warned, @logged);
	my $guard = mock_scoped($CONFIG{exporter},
		_export_table => sub { push @exported, $_[2]; die "kaput\n" if $_[2] eq 'Bad'; $_[0] },
		_warn         => sub { shift; push @warned, [@_]; return },
		_log          => sub { shift; push @logged, [@_]; return },
	);

	my $e = new_exporter(progress => 1);
	my $failed;
	my $stderr = capture_stderr { $failed = $e->_export_all($CONFIG{database}, ['A', 'Bad', 'C']) };
	verbose_diag('progress', $stderr);

	is($failed, 1, 'one failure');
	returns_ok($failed, { type => 'integer', min => 0 }, 'a count');
	is_deeply(\@exported, ['A', 'Bad', 'C'], 'every table attempted');
	is($stderr, "[1/3] A\n[2/3] Bad\n[3/3] C\n", 'progress lines');
	is_deeply(\@warned, [['export_failed', { params => ['Bad', 'kaput'] }]], 'failure warned without newline');
	is_deeply(\@logged, [['info', 'summary', { params => [3, 1], count => 3 }]], 'summary logged');

	my $quiet;
	$stderr = capture_stderr { $quiet = new_exporter()->_export_all($CONFIG{database}, []) };
	is($quiet, 0, 'empty list: no failures');
	is($stderr, '', 'no progress when switched off');
};

subtest 'Exporter::_export_all exports every table even if the list was partly iterated' => sub {
	# A caller may have used each() on the same array; that must not
	# make the export skip tables
	my @exported;
	my $guard = mock_scoped($CONFIG{exporter},
		_export_table => sub { push @exported, $_[2]; $_[0] },
		_log          => sub { $_[0] },
	);

t/function.t  view on Meta::CPAN

	is_deeply(\@calls, [[$CONFIG{mdb_count}, ['--', $CONFIG{database}, $CONFIG{table}]]], 'mdb-count arguments, options ended by --');

	# Anything that is not just a number is reported, never taken as 0
	$output = '';
	throws_ok { new_exporter()->_count_rows($CONFIG{database}, $CONFIG{table}) } qr/\Amdb-count printed no number: "" at /, 'no output: reported';
	$output = "count: 12 rows\n";
	throws_ok { new_exporter()->_count_rows($CONFIG{database}, $CONFIG{table}) } qr/\Amdb-count printed no number: "count: 12 rows\\x0A" at /, 'extra text: reported';
};

# Replaces run3 with a double that records its arguments, writes to
# stderr and sets the child status
sub mock_run3 {
	my ($status, $stderr_text, $calls) = @_;
	return ("$CONFIG{exporter}::run3" => sub {
		my ($cmd, $stdin, $stdout, $stderr) = @_;
		push @{$calls}, [$cmd, $stdin, $stdout] if $calls;
		${$stderr} = $stderr_text;
		$? = $status;
		return 1;
	});
}

subtest 'Exporter::_run_program runs the program with a list, not a shell string' => sub {
	my @calls;
	my $guard = mock_scoped(mock_run3(0, '', \@calls));

	my $e = new_exporter();

t/function.t  view on Meta::CPAN

	is($calls[0][2], \$stdout, 'stdout passed through');
};

subtest 'Exporter::_run_program croaks on exit status and signals' => sub {
	my $e = new_exporter();
	$e->{programs} = { $CONFIG{mdb_export} => program_path($CONFIG{mdb_export}) };

	{
		my $guard = mock_scoped(mock_run3($CONFIG{child_status} << 8, "corrupt table\n"));
		throws_ok { $e->_run_program($CONFIG{mdb_export}, [], \my $out) }
			qr/\A$CONFIG{mdb_export} failed with exit status $CONFIG{child_status}: corrupt table at /, 'exit status, stderr chomped';
	}
	{
		my $guard = mock_scoped(mock_run3($CONFIG{signal}, ''));
		throws_ok { $e->_run_program($CONFIG{mdb_export}, [], \my $out) }
			qr/\A$CONFIG{mdb_export} was killed by signal $CONFIG{signal} at /, 'signal';
	}
};

subtest 'Exporter::_run_program leaves the caller\'s $? alone' => sub {
	my $e = new_exporter();

t/function.t  view on Meta::CPAN

	$CONFIG{app}->_make_logger({ log => $file, verbose => 1 });
	is($created[1]{level}, 'debug', 'verbose: debug level');
};

subtest 'App::_make_logger croaks when the log cannot be written' => sub {
	my $file = File::Spec->catfile(tempdir(CLEANUP => 1), 'no', 'such', 'x.log');
	throws_ok { $CONFIG{app}->_make_logger({ log => $file }) } qr/\ACannot open log file \Q$file\E: \Q$ENOENT_TEXT\E at /, 'exact message';
};

subtest 'App::_report_fatal prints one clean line' => sub {
	my ($status, $stderr);
	$stderr = capture_stderr { $status = $CONFIG{app}->_report_fatal("boom at lib/X.pm line 3.\n", 0) };
	is($stderr, "access2csv: boom\n", 'location removed');
	is($status, $CONFIG{exit_fatal}, 'fatal status');

	$stderr = capture_stderr { $CONFIG{app}->_report_fatal("boom at lib/X.pm line 3.\n", 1) };
	is($stderr, "access2csv: boom at lib/X.pm line 3.\n", 'verbose keeps the location');

	$stderr = capture_stderr { $CONFIG{app}->_report_fatal("boom at /home/me/My Libs/X.pm line 3.\n", 0) };
	is($stderr, "access2csv: boom\n", 'location removed even when the path contains spaces');

	$stderr = capture_stderr { $CONFIG{app}->_report_fatal("Cannot read database /d/meet at noon.accdb: gone at /l/X.pm line 3.\n", 0) };
	is($stderr, "access2csv: Cannot read database /d/meet at noon.accdb: gone\n", 'an " at " inside the message is kept');

	$stderr = capture_stderr { $CONFIG{app}->_report_fatal(undef, 0) };
	is($stderr, "access2csv: Unknown error\n", 'no error text');
};

restore_all();

done_testing();

t/integration.t  view on Meta::CPAN

	diag("$label: ", Test::More::explain($data)) if $ENV{TEST_VERBOSE};
	return;
}

# A database listing @tables, in a new directory; returns (dir, db)
sub new_database {
	my $dir = tempdir(CLEANUP => 1);
	return ($dir, make_database($dir, @_));
}

# Run the program in-process; returns (status, stdout, stderr)
sub cli {
	my @argv = @_;
	my $status;
	my ($stdout, $stderr) = capture { $status = $CONFIG{app}->run(@argv) };
	return ($status, $stdout, $stderr);
}

sub slurp {
	my $path = shift;
	open my $fh, '<:raw', $path or die "$path: $!";
	local $/;
	return scalar <$fh>;
}

# CSV file names in a directory, sorted

t/integration.t  view on Meta::CPAN


subtest 'workflow: the installed script exports a database end to end' => sub {
	# bin/access2csv -> App::Access2CSV::run -> Exporter -> I18N -> real
	# Log::Abstraction, in a separate process, as a user would run it
	my ($dir, $db) = new_database(qw(Customers Orders MSysObjects));
	my $out = File::Spec->catdir($dir, 'out');
	my $log = File::Spec->catfile($dir, $CONFIG{log_name});
	my $script = File::Spec->catfile($Bin, File::Spec->updir(), 'bin', 'access2csv');
	my $lib = File::Spec->catdir($Bin, File::Spec->updir(), 'lib');

	my ($stdout, $stderr) = capture { system($^X, "-I$lib", $script, '--output-dir', $out, '--log', $log, '--show-counts', $db) };
	my $status = $? >> 8;
	verbose_diag('script stderr', $stderr);

	is($status, $CONFIG{exit_ok}, 'exit status 0');
	is_deeply(csv_files($out), ['Customers.csv', 'Orders.csv'], 'one file per user table');
	is(slurp("$out/Orders.csv"), qq{"id","name"\n1,"Orders"\n}, 'content from mdb-export');
	is($stdout, '', 'nothing on STDOUT');
	like($stderr, qr/\A\[1\/2\] Customers\n\[2\/2\] Orders\n\z/, 'progress on STDERR');

	my $text = slurp($log);
	verbose_diag('log', $text);
	like($text, qr/Exported Orders => \Q$out\E.Orders\.csv \($CONFIG{fake_rows} row\)/, 'export and row count logged');
	like($text, qr/Processed 2 tables, 0 failed/, 'summary logged');
};

subtest 'workflow: dry run, export, repeat, overwrite' => sub {
	# The state that links the runs is the file system and the names
	# chosen for colliding tables; each step must agree with the last

t/integration.t  view on Meta::CPAN

	is($status, $CONFIG{exit_ok}, 'dry run: 0');
	ok(!-e $out, 'dry run created nothing');
	my @planned = sort map { (split)[-1] } grep { /\.csv$/ } split /\n/, $stdout;
	verbose_diag('planned', \@planned);

	($status) = cli(@common, $db);
	is($status, $CONFIG{exit_ok}, 'export: 0');
	is_deeply(csv_files($out), \@planned, 'files are exactly the dry-run plan');
	is_deeply(csv_files($out), [sort qw(A_B.csv A_B_2.csv A_B_2_2.csv Orders.csv)], 'collisions resolved, nothing overwritten');

	my $stderr;
	($status, undef, $stderr) = cli(@common, $db);
	is($status, $CONFIG{exit_failure}, 'repeat without --overwrite: 1');
	is(scalar(() = $stderr =~ /Output file already exists/g), 4, 'every table refused');

	($status) = cli(@common, '--overwrite', $db);
	is($status, $CONFIG{exit_ok}, 'repeat with --overwrite: 0');
	is_deeply(csv_files($out), \@planned, 'same names again');
};

subtest 'workflow: failures are isolated and recoverable' => sub {
	# Some tables fail; the rest are exported; a later run with a working
	# encoding completes the job without disturbing the good files
	my ($dir, $db) = new_database(qw(Broken Japanese Orders));
	my $out = File::Spec->catdir($dir, 'out');

	my ($status, undef, $stderr) = cli('--no-log', '--no-progress', '--encoding', 'cp1252', '--output-dir', $out, $db);
	verbose_diag('first run', $stderr);
	is($status, $CONFIG{exit_failure}, 'partial failure: 1');
	returns_ok($status, { type => 'integer', min => 0, max => 3 }, 'documented status range');
	is_deeply(csv_files($out), ['Orders.csv'], 'only the good table written, no partial files');
	like($stderr, qr/FAILED: Broken: mdb-export failed with exit status 1: corrupt table/, 'Broken reported');
	like($stderr, qr/FAILED: Japanese: Table Japanese, line 2: cannot be represented in cp1252/, 'Japanese reported');

	my $orders = slurp("$out/Orders.csv");
	($status) = cli('--no-log', '--no-progress', '--table', 'Japanese', '--output-dir', $out, $db);
	is($status, $CONFIG{exit_ok}, 'retry of one table in UTF-8: 0');
	is_deeply(csv_files($out), ['Japanese.csv', 'Orders.csv'], 'now exported');
	is(slurp("$out/Orders.csv"), $orders, 'earlier file untouched');
};

subtest 'workflow: encodings through the whole stack' => sub {
	my ($dir, $db) = new_database('Unicode');

t/integration.t  view on Meta::CPAN

		my @present = map { $PROGRAMS[$_] } grep { $mask & (1 << $_) } 0 .. $#PROGRAMS;
		my %have = map { $_ => 1 } @present;
		my $label = @present ? join('+', @present) : 'none';

		# Only the chosen stand-ins, and nothing else, are in PATH
		local $ENV{PATH} = @present ? install_fake_mdbtools(@present) : tempdir(CLEANUP => 1);

		foreach my $counts (0, 1) {
			my $out = File::Spec->catdir($dir, "$mask-$counts");
			my @args = ('--no-log', '--no-progress', '--output-dir', $out, ($counts ? '--show-counts' : ()), $db);
			my ($status, undef, $stderr) = cli(@args);
			verbose_diag("$label counts=$counts", { status => $status, stderr => $stderr });

			my @missing = grep { !$have{$_} } @REQUIRED;
			if(@missing) {
				is($status, $CONFIG{exit_fatal}, "$label, counts=$counts: fatal");
				like($stderr, qr/\Aaccess2csv: Required program not found in PATH: $missing[0]\n\z/, "$label: names the missing program");
				ok(!-e $out, "$label: nothing created");
			} else {
				is($status, $CONFIG{exit_ok}, "$label, counts=$counts: success");
				ok(-e "$out/Orders.csv", "$label: exported");
				my $warned = $stderr =~ /mdb-count not found in PATH; row counts are unavailable/ ? 1 : 0;
				is($warned, ($counts && !$have{'mdb-count'}) ? 1 : 0, "$label, counts=$counts: warning only when counts are wanted but unavailable");
			}
		}
	}
};

subtest 'optional dependency: a missing required module fails loudly' => sub {
	# Every CPAN module is required.  Hiding one must stop the program
	# from loading with a clear error, not produce a half-working tool.
	# Each case runs in a child process, since the modules are loaded here.
	my $lib = File::Spec->catdir($Bin, File::Spec->updir(), 'lib');

	foreach my $module (@REQUIRED_MODULES) {
		my ($stdout, $stderr) = capture {
			system($^X, "-I$lib", "-MTest::Without::Module=$module", '-e', 'require App::Access2CSV; print "loaded\n"');
		};
		my $status = $? >> 8;
		verbose_diag("without $module", $stderr);
		isnt($status, 0, "without $module: loading fails");
		is($stdout, '', "without $module: never reports success");
		(my $file = "$module.pm") =~ s{::}{/}g;
		like($stderr, qr/\Q$file\E/, "without $module: the error names it");
	}

	# And with all of them available, the same command succeeds
	my ($stdout) = capture { system($^X, "-I$lib", '-e', 'require App::Access2CSV; print "loaded\n"') };
	is($stdout, "loaded\n", 'all modules available: loads');
};

subtest 'concurrency: independent exporters do not interfere' => sub {
	# Two objects, created together and run in interleaved order, with
	# different settings.  Each must keep its own names, settings and

t/integration.t  view on Meta::CPAN

	my ($dir, $db) = new_database(qw(Orders));
	my $log = File::Spec->catfile($dir, $CONFIG{log_name});
	local $App::Access2CSV::I18N::MESSAGES{de} = {
		fatal          => 'access2csv: FEHLER: %s',
		progress       => '[%d von %d] %s',
		unknown_tables => { one => 'Tabelle fehlt: %s', other => 'Tabellen fehlen: %s' },
		summary        => { one => '%d Tabelle, %d Fehler', other => '%d Tabellen, %d Fehler' },
	};
	local $ENV{LANG} = 'de_DE.UTF-8';

	my ($status, undef, $stderr) = cli('--log', $log, '--output-dir', "$dir/out", '--table', 'Orders', '--table', 'Nope', $db);
	verbose_diag('German run', $stderr);
	is($status, $CONFIG{exit_ok}, 'export: 0');
	like($stderr, qr/^\[1 von 1\] Orders$/m, 'Exporter progress translated');
	like($stderr, qr/^Tabelle fehlt: Nope at /m, 'Exporter warning translated (singular)');
	like(slurp($log), qr/1 Tabelle, 0 Fehler/, 'log entry translated');

	($status, undef, $stderr) = cli('--no-log', File::Spec->catfile($dir, 'missing.accdb'));
	is($status, $CONFIG{exit_fatal}, 'fatal: 3');
	like($stderr, qr/\Aaccess2csv: FEHLER: Cannot read database /, 'App wrapper translated; untranslated key falls back to English');
};

subtest 'cross-module: a logger object is shared, not copied' => sub {
	# One Log::Abstraction object passed to two exporters collects both
	# runs, in order, in one file
	my ($dir, $db) = new_database(qw(Orders));
	my $log = File::Spec->catfile($dir, $CONFIG{log_name});
	my $logger = Log::Abstraction->new(logger => $log, level => 'info');

	foreach my $name (qw(one two)) {

t/lib/FakeMDB.pm  view on Meta::CPAN

package FakeMDB;

# Test helper: installs stand-in mdb-tables, mdb-export and mdb-count
# scripts in a temporary directory, so that the exporter can be tested
# without mdbtools or a real Access database.
#
# The "database" is a text file listing one table name per line; the
# fake mdb-tables prints it back.  A first line of "FAIL" makes
# mdb-tables fail.  mdb-export's behaviour depends on the table name:
#   Broken   - exits 1 with "corrupt table" on stderr
#   Killed   - kills itself with SIGTERM (Unix only: Windows has no signals)
#   Unicode  - UTF-8 text that cp1252 can represent ("Cafe" with e-acute, Euro)
#   Japanese - UTF-8 text that cp1252 cannot represent
#   Latin1   - bytes that are not valid UTF-8
#   Truncated - output that stops in the middle of a UTF-8 character
#   Slow     - writes part of the table, then waits 30 seconds (for
#              interrupting an export half-way)
#   anything else - a two-line CSV naming the table

use strict;

t/locales.t  view on Meta::CPAN

			}

			# The OS text for "no such file", straight from Perl's $!
			my $enoent = do { local $! = ENOENT; "$!" };
			ok(length($enoent), "ENOENT text: $enoent");

			my $e = App::Access2CSV::Exporter->new(progress => 0);
			throws_ok { $e->run($missing) } qr/\QCannot read database $missing: $enoent\E/, 'missing database';

			my $status;
			my $stderr = do {
				local *STDERR;
				open STDERR, '>', \my $buffer or die $!;
				$status = App::Access2CSV->run('--log', $bad_log, $missing);
				$buffer;
			};
			is($status, 3, 'unopenable log is fatal');
			like($stderr, qr/\QCannot open log file $bad_log: $enoent\E/, 'log error carries the OS text');
		};
	}

	setlocale(LC_ALL, $original);
};

done_testing();

t/logic-proofs.t  view on Meta::CPAN

}

sub new_database {
	my $dir = tempdir(CLEANUP => 1);
	return ($dir, make_database($dir, @_));
}

sub cli {
	my @argv = @_;
	my $status;
	my ($stdout, $stderr) = capture { $status = $CONFIG{app}->run(@argv) };
	return ($status, $stderr);
}

# Number of calls recorded by a Test::Mockingbird spy whose first argument matches
sub calls_matching {
	my ($spy, $pattern) = @_;
	return scalar grep { my @call = @{$_}; grep({ defined && !ref && /$pattern/ } @call[1 .. $#call]) } $spy->();
}

#######################################################################
# App::Access2CSV: the command-line gates, in order

t/logic-proofs.t  view on Meta::CPAN

subtest '"exists" includes symbolic links, even broken ones' => sub {
	# Premise: -e follows links, so a broken link is not -e; -l catches it.
	# Conclusion: "-e OR -l" refuses both kinds of link.
	my ($dir, $db) = new_database('Good', 'Broken_link');
	mkdir "$dir/out" or die $!;
	symlink("$dir/target", "$dir/out/Good.csv") or die $!;
	open my $fh, '>', "$dir/target" or die $!;
	close $fh;
	symlink("$dir/nowhere", "$dir/out/Broken_link.csv") or die $!;

	my ($status, $stderr);
	(undef, $stderr) = capture { $status = $CONFIG{exporter}->new(output_dir => "$dir/out", progress => 0)->run($db) };
	is($status, $CONFIG{exit_failure}, 'refused');
	is(scalar(() = $stderr =~ /Output file already exists/g), 2, 'both links counted as existing');
};

#######################################################################
# i18n: the narrowing gates
#######################################################################

subtest 'i18n narrowing: context gate, then plural gate' => sub {
	# Premise 1: a matching context is chosen first; plural forms are
	# chosen from whatever is left.  Premise 2: this template has plural
	# forms both inside a context and at the top level.

t/logic.t  view on Meta::CPAN


use strict;
use warnings;

use Test::Most;

BEGIN {
	plan(skip_all => 'uses symbolic links and Unix stand-in programs') if $^O eq 'MSWin32';
}

use Capture::Tiny qw(capture capture_stderr);
use Errno qw(ENOENT);
use File::Spec;
use File::Temp qw(tempdir);
use FindBin qw($Bin);
use Readonly;
use Test::Mockingbird;

use lib File::Spec->catdir($Bin, 'lib');
use FakeMDB qw(install_fake_mdbtools make_database);

t/logic.t  view on Meta::CPAN

		my %present = ('mdb-tables' => $tables, 'mdb-export' => $export, 'mdb-count' => $count);
		my $guard = mock_scoped("$CONFIG{exporter}::which" => sub { $present{ $_[0] } ? "$CONFIG{fake_bin}/$_[0]" : undef });
		my $e = exporter(show_counts => $show);
		my $name = row_name([qw(tables export count show_counts)], $row);

		if(!$tables || !$export) {
			my $first = $tables ? 'mdb-export' : 'mdb-tables';
			throws_ok { $e->_verify_dependencies() } qr/\ARequired program not found in PATH: $first at /, "$name: fatal, names $first";
			next;
		}
		my $stderr = capture_stderr { $e->_verify_dependencies() };
		my $counting = $show && $count;
		is($e->{show_counts}, $counting ? 1 : 0, "$name: show_counts ends " . ($counting ? 'on' : 'off'));
		is(exists($e->{programs}{'mdb-count'}) ? 1 : 0, $counting ? 1 : 0, "$name: mdb-count stored only when used");
		is(($stderr =~ /mdb-count not found/) ? 1 : 0, ($show && !$count) ? 1 : 0, "$name: warning only when wanted but missing");
	}
};

subtest '_find_program: log debug = found AND verbose' => sub {
	foreach my $row (@{ truth_table(2) }) {
		my ($found, $verbose) = @{$row};
		my $guard = mock_scoped("$CONFIG{exporter}::which" => sub { $found ? "$CONFIG{fake_bin}/x" : undef });
		my $logger = Local::Logger->new();
		exporter(verbose => $verbose, logger => $logger)->_find_program('x');
		is(scalar(@{ $logger->{lines} }), ($found && $verbose) ? 1 : 0, row_name([qw(found verbose)], $row));

t/logic.t  view on Meta::CPAN

subtest '_select_tables: filter given x some names missing' => sub {
	my @all = ('A', 'B');
	my %cases = (
		'filter=0'            => [undef, [qw(A B)], 0],   # no filter, so nothing can be missing
		'filter=1, missing=0' => [['B'], ['B'], 0],
		'filter=1, missing=1' => [['B', 'Z'], ['B'], 1],
	);
	foreach my $case (sort keys %cases) {
		my ($filter, $expected, $warns) = @{ $cases{$case} };
		my $picked;
		my $stderr = capture_stderr { $picked = exporter(tables => $filter)->_select_tables([@all]) };
		is_deeply($picked, $expected, "$case: selection");
		is(($stderr =~ /not found in database/) ? 1 : 0, $warns, "$case: warning");
	}
};

subtest '_make_output_dir: failed = errors reported OR director still missing' => sub {
	# 2 inputs, 4 rows, forced through a mocked make_path
	foreach my $row (@{ truth_table(2) }) {
		my ($errors, $made) = @{$row};
		my $dir = File::Spec->catdir(tempdir(CLEANUP => 1), 'out');
		my $guard = mock_scoped("$CONFIG{exporter}::make_path" => sub {
			my ($path, $opts) = @_;

t/logic.t  view on Meta::CPAN

		sub debug { } sub warn { }
	}
	my %cases = (
		'logger=0'         => [undef, 0, 0],
		'logger=1, dies=0' => [Local::Logger->new(), 0, 1],
		'logger=1, dies=1' => [Local::Dying->new(), 1, 0],
	);
	foreach my $case (sort keys %cases) {
		my ($logger, $warns, $kept) = @{ $cases{$case} };
		my $e = exporter($logger ? (logger => $logger) : ());
		my $stderr = capture_stderr { $e->_log(info => 'dry_run_title') };
		is(($stderr =~ /Cannot write to the log/) ? 1 : 0, $warns, "$case: warning");
		is($e->{logger} ? 1 : 0, $kept, "$case: logger kept");
	}
};

subtest '_os_error: is a blessed object x can errno' => sub {
	# The error may be a plain string, an object with errno (autodie), an
	# object without it, or an UNBLESSED reference.  A reference must not
	# be asked ->can(): that would die and hide the real error.
	{
		package Local::WithErrno;

t/logic.t  view on Meta::CPAN

		} else {
			isa_ok($CONFIG{app}->_make_logger($opt), 'Local::Logger', "$case: logger");
		}
	}
};

subtest '_report_fatal: has text x verbose' => sub {
	foreach my $row (@{ truth_table(2) }) {
		my ($text, $verbose) = @{$row};
		my $error = $text ? "boom at x.pm line 1.\n" : undef;
		my $stderr = capture_stderr { $CONFIG{app}->_report_fatal($error, $verbose) };
		my $expected = !$text ? 'Unknown error' : $verbose ? 'boom at x.pm line 1.' : 'boom';
		is($stderr, "access2csv: $expected\n", row_name([qw(text verbose)], $row));
	}
};

subtest '_usage: help goes to STDOUT exactly when the status is 0' => sub {
	my @calls;
	my $guard = mock_scoped("$CONFIG{app}::pod2usage" => sub { push @calls, {@_}; return });
	$CONFIG{app}->_usage($CONFIG{exit_ok}, 1);
	$CONFIG{app}->_usage($CONFIG{exit_usage}, 0, 'why');
	is($calls[0]{-output}, \*STDOUT, 'status 0: STDOUT');
	is($calls[1]{-output}, \*STDERR, 'status 2: STDERR');

t/path.t  view on Meta::CPAN


use strict;
use warnings;

use Test::Most;

BEGIN {
	plan(skip_all => 'uses Unix stand-in programs and permissions') if $^O eq 'MSWin32';
}

use Capture::Tiny qw(capture capture_stderr capture_stdout);
use Errno qw(ENOENT ENOSPC);
use File::Spec;
use File::Temp qw(tempdir);
use FindBin qw($Bin);
use Params::Get qw(get_params);
use Readonly;
use Test::Mockingbird;
use Test::Returns;

use lib File::Spec->catdir($Bin, 'lib');

t/path.t  view on Meta::CPAN


subtest '_verify_dependencies paths' => sub {
	my %present;
	my $guard = mock_scoped("$CONFIG{exporter}::which" => sub { $present{ $_[0] } ? "$CONFIG{fake_bin}/$_[0]" : undef });
	throws_ok { exporter()->_verify_dependencies() } qr/PATH: mdb-tables at /, 'V1'; took('V1');
	%present = ('mdb-tables' => 1);
	throws_ok { exporter()->_verify_dependencies() } qr/PATH: mdb-export at /, 'V2'; took('V2');
	%present = ('mdb-tables' => 1, 'mdb-export' => 1);
	is_deeply([sort keys %{ exporter()->_verify_dependencies()->{programs} }], ['mdb-export', 'mdb-tables'], 'V3'); took('V3');
	my $e = exporter(show_counts => 1);
	capture_stderr { $e->_verify_dependencies() };
	is($e->{show_counts}, 0, 'V5'); took('V5');
	$present{'mdb-count'} = 1;
	ok(exporter(show_counts => 1)->_verify_dependencies()->{programs}{'mdb-count'}, 'V4'); took('V4');
};

subtest '_find_program, _reset_names paths' => sub {
	my $found = 1;
	my $guard = mock_scoped("$CONFIG{exporter}::which" => sub { $found ? "$CONFIG{fake_bin}/p" : undef });
	my $logger = Local::Logger->new();
	exporter(verbose => 1, logger => $logger)->_find_program('p');

t/path.t  view on Meta::CPAN

	$output = undef;
	is_deeply(exporter()->_get_tables('db'), [], 'G2'); took('G2');
	is(exporter()->_is_system_table('MSysX'), 1, 'S1'); took('S1');
	is(exporter()->_is_system_table('Orders'), 0, 'S2'); took('S2');
};

subtest '_select_tables paths' => sub {
	my $all = ['A', 'B'];
	is(exporter()->_select_tables($all), $all, 'T1'); took('T1');
	is_deeply(exporter(tables => ['B'])->_select_tables($all), ['B'], 'T2'); took('T2');
	my $stderr = capture_stderr { exporter(tables => ['Z'])->_select_tables($all) };
	like($stderr, qr/Table not found in database: Z/, 'T3'); took('T3');
};

subtest '_make_output_dir paths' => sub {
	my $dir = tempdir(CLEANUP => 1);
	is(exporter(output_dir => $dir)->_make_output_dir()->{output_dir}, $dir, 'M1'); took('M1');
	exporter(output_dir => "$dir/new")->_make_output_dir();
	ok(-d "$dir/new", 'M2'); took('M2');

	my $target = "$dir/fails";
	my @errors;

t/path.t  view on Meta::CPAN

	throws_ok { exporter(output_dir => $target)->_make_output_dir() } qr/: \Q$ENOENT_TEXT\E at /, 'M5'; took('M5');
};

subtest '_export_all paths' => sub {
	my %fail;
	my $guard = mock_scoped($CONFIG{exporter},
		_export_table => sub { my $why = $fail{ $_[2] }; die $why if defined $why; $_[0] },
		_log          => sub { $_[0] },
	);
	is(exporter()->_export_all('db', []), 0, 'A1: 0 iterations'); took('A1');
	my $stderr = capture_stderr { exporter(progress => 1)->_export_all('db', ['T']) };
	is($stderr, "[1/1] T\n", 'A2: 1 iteration with progress'); took('A2');

	%fail = (B => "broken\n");
	my $failed;
	$stderr = capture_stderr { $failed = exporter()->_export_all('db', ['A', 'B', 'C']) };
	is($failed, 1, 'A3: many iterations, one failure');
	like($stderr, qr/FAILED: B: broken/, 'A3: warned'); took('A3');
	unlike($stderr, qr/^\[/m, 'A5: no progress when off'); took('A5');

	# An exception that is false (an object whose truth value is false)
	{
		package Local::FalseError;
		use overload 'bool' => sub { 0 }, '""' => sub { '' }, fallback => 1;
	}
	%fail = (A => bless({}, 'Local::FalseError'));
	$stderr = capture_stderr { exporter()->_export_all('db', ['A']) };
	like($stderr, qr/FAILED: A: Unknown error/, 'A4'); took('A4');
};

subtest '_export_table paths' => sub {
	my $dir = tempdir(CLEANUP => 1);
	my (@ran, %installed, @logged, @transcoded);
	my $flush_ok = 1;
	my $count_fails = 0;
	my $real_flush = \&IO::Handle::flush;
	my $guard = mock_scoped(
		"$CONFIG{exporter}::_run_program" => sub { push @ran, 1; print { $_[3] } "d\n"; $_[3]->flush(); $_[0] },

t/path.t  view on Meta::CPAN

	throws_ok { exporter(output_dir => $dir, overwrite => 1, encoding => 'utf8-bom')->_export_table('db', 'T') } qr/\ACannot write .*: \Q$ENOSPC_TEXT\E at /, 'X4'; took('X4');
	$flush_ok = 1;

	exporter(output_dir => $dir, overwrite => 1, encoding => 'cp1252')->_export_table('db', 'T');
	is(scalar(@transcoded), 1, 'X5'); took('X5');

	exporter(output_dir => $dir, overwrite => 1, show_counts => 1)->_export_table('db', 'T');
	is($logged[-1], 'exported_rows', 'X6'); took('X6');

	$count_fails = 1;
	my $stderr = capture_stderr { exporter(output_dir => $dir, overwrite => 1, show_counts => 1)->_export_table('db', 'T') };
	is($logged[-1], 'exported', 'X8: logged as exported, without a count');
	like($stderr, qr/Cannot count the rows of T: count broke/, 'X8: warning'); took('X8');
};

subtest '_export_transcoded paths' => sub {
	my $output = '';
	my $guard = mock_scoped("$CONFIG{exporter}::_run_program" => sub { print { $_[3] } $output; $_[3]->flush(); $_[0] });
	my $e = exporter(output_dir => tempdir(CLEANUP => 1));
	my $run = sub { open my $out, '>:raw', \my $buffer or die $!; $e->_export_transcoded('db', 'T', $out); close $out; return $buffer // '' };

	is($run->(), '', 'Y1: 0 iterations'); took('Y1');
	$output = "Caf\xC3\xA9\n";

t/path.t  view on Meta::CPAN


subtest '_dry_run paths' => sub {
	my $guard = mock_scoped("$CONFIG{exporter}::_count_rows" => sub { $CONFIG{rows} });
	my $stdout = capture_stdout { exporter()->_dry_run('db', []) };
	unlike($stdout, qr/ROWS|\.csv/, 'DR1: no counts, 0 iterations'); took('DR1');
	$stdout = capture_stdout { exporter(show_counts => 1)->_dry_run('db', ['A', 'B']) };
	is(scalar(() = $stdout =~ /^\w\s+$CONFIG{rows}\s+\w\.csv$/mg), 2, 'DR2: counts, 2 iterations'); took('DR2');
	restore_all();

	my $failing = mock_scoped("$CONFIG{exporter}::_count_rows" => sub { die "count broke\n" });
	my $stderr;
	($stdout, $stderr) = capture { exporter(show_counts => 1)->_dry_run('db', ['A']) };
	like($stdout, qr/^A\s+\?\s+A\.csv$/m, 'DR3: "?" shown');
	like($stderr, qr/Cannot count the rows of A/, 'DR3: warning'); took('DR3');
};

subtest '_try_count_rows paths' => sub {
	my $behaviour = 'ok';
	my $guard = mock_scoped("$CONFIG{exporter}::_count_rows" => sub {
		die "count broke\n" if $behaviour eq 'fail';
		if($behaviour eq 'interrupt') { $_[0]{interrupted} = 'INT'; die "Interrupted\n" }
		return $CONFIG{rows};
	});
	is(exporter()->_try_count_rows('db', 'T'), $CONFIG{rows}, 'TC1'); took('TC1');

	$behaviour = 'fail';
	my $got = 'not called';
	my $stderr = capture_stderr { $got = exporter()->_try_count_rows('db', 'T') };
	is($got, undef, 'TC2: undef');
	like($stderr, qr/Cannot count the rows of T: count broke/, 'TC2: warning'); took('TC2');

	$behaviour = 'interrupt';
	throws_ok { exporter()->_try_count_rows('db', 'T') } qr/\AInterrupted/, 'TC3'; took('TC3');
};

subtest '_warn, _log, _os_error paths' => sub {
	my $logger = Local::Logger->new();
	my $e = exporter(logger => $logger);
	my $stderr = capture_stderr { $e->_warn('dry_run_title') };
	ok($stderr =~ /DRY RUN/ && $logger->{lines}[-1][0] eq 'warn', 'W1'); took('W1');

	is(exporter()->_log(info => 'dry_run_title')->{logger}, undef, 'LG1'); took('LG1');
	$e->_log(info => 'dry_run_title');
	is($logger->{lines}[-1][1], 'DRY RUN', 'LG2'); took('LG2');
	{
		package Local::DyingLogger;
		sub new { bless {}, shift }
		sub info { die "gone\n" }
		sub debug { } sub warn { }
	}
	my $dying = exporter(logger => Local::DyingLogger->new());
	$stderr = capture_stderr { $dying->_log(info => 'dry_run_title') };
	ok($stderr =~ /Cannot write to the log: gone/ && !$dying->{logger}, 'LG3'); took('LG3');

	eval { use autodie qw(open); open my $fh, '<', '/nonexistent/x' };
	is(App::Access2CSV::Exporter::_os_error($@), $ENOENT_TEXT, 'O1'); took('O1');
	is(App::Access2CSV::Exporter::_os_error("plain\n"), 'plain', 'O2'); took('O2');
};

#######################################################################
# App::Access2CSV
#######################################################################

t/path.t  view on Meta::CPAN

	$creates = 1;
	isa_ok($CONFIG{app}->_make_logger({ log => "$dir/b.log" }), 'Local::Logger', 'ML4'); took('ML4');

	my %cases = (
		RF1 => [undef, 0, 'Unknown error'],
		RF2 => ["boom at x line 1.\n", 0, 'boom'],
		RF3 => ["boom at x line 1.\n", 1, 'boom at x line 1.'],
	);
	foreach my $id (sort keys %cases) {
		my ($error, $verbose, $text) = @{ $cases{$id} };
		my $stderr = capture_stderr { $CONFIG{app}->_report_fatal($error, $verbose) };
		is($stderr, "access2csv: $text\n", $id);
		took($id);
	}
};

#######################################################################

subtest 'every path was taken' => sub {
	my @missed = sort grep { !$taken{$_} } keys %PATHS;
	fail("path never taken: $_ ($PATHS{$_})") foreach @missed;
	pass(scalar(keys %PATHS) . ' paths, all taken') unless @missed;

t/real-mdbtools.t  view on Meta::CPAN

sub slurp {
	my $path = shift;
	open my $fh, '<:raw', $path or return;
	local $/;
	return scalar <$fh>;
}

# mdbtools(@command): run a real mdbtools program; returns its raw stdout
sub mdbtools {
	my @command = @_;
	my ($stdout, $stderr) = ('', '');
	run3([@command], \undef, \$stdout, \$stderr);
	die "@command failed: $stderr" if $?;
	return $stdout;
}

# The user tables of a database, according to mdb-tables itself
sub user_tables {
	my $db = shift;
	return [ sort grep { length && !/$CONFIG{system_table}/ } split /\r?\n/, mdbtools('mdb-tables', '-1', '--', $db) ];
}

# The file name the exporter gives each table (same rules as a real run)
sub file_names {
	my $tables = shift;
	local $Sub::Protected::BYPASS = 1;
	my $e = App::Access2CSV::Exporter->new(progress => 0);
	return { map { $_ => $e->_csv_filename($_) } @{$tables} };
}

# export(%settings): run a quiet export; returns (status, stdout, stderr)
sub export {
	my ($db, %settings) = @_;
	my $status;
	my ($stdout, $stderr) = capture { $status = App::Access2CSV::Exporter->new(progress => 0, %settings)->run($db) };
	return ($status, $stdout, $stderr);
}

foreach my $db (@DATABASES) {
	my $name = (File::Spec->splitpath($db))[2];
	my $tables = user_tables($db);
	my $files = file_names($tables);
	verbose_diag("$name tables", $tables);

	subtest "$name: every table, byte for byte what mdb-export prints" => sub {
		my $out = tempdir(CLEANUP => 1);
		my ($status, undef, $stderr) = export($db, output_dir => $out);
		is($status, $CONFIG{exit_ok}, 'exit 0') or diag($stderr);
		foreach my $table (@{$tables}) {
			is(slurp("$out/$files->{$table}"), mdbtools('mdb-export', '--', $db, $table), "$table");
		}
		my @made = map { (File::Spec->splitpath($_))[2] } glob("$out/*");
		is(scalar(@made), scalar(@{$tables}), 'one file per user table, nothing else');
	};

	subtest "$name: row counts are mdb-count's" => sub {
		my ($status, $stdout) = export($db, dry_run => 1, show_counts => 1);
		is($status, $CONFIG{exit_ok}, 'dry run exit 0');

t/real-mdbtools.t  view on Meta::CPAN

		foreach my $table (@{$tables}) {
			is(slurp("$out/$files->{$table}"), $CONFIG{utf8_bom} . mdbtools('mdb-export', '--', $db, $table), "$table");
		}
	};

	subtest "$name: cp1252 converts what can be converted, refuses the rest cleanly" => sub {
		# The test converts mdb-export's output itself to know what to
		# expect: text tables convert; tables with binary or non-Western
		# data cannot, and must fail without leaving a file
		my $out = tempdir(CLEANUP => 1);
		my ($status, undef, $stderr) = export($db, output_dir => $out, encoding => 'cp1252');
		my $failures = 0;
		foreach my $table (@{$tables}) {
			my $utf8 = mdbtools('mdb-export', '--', $db, $table);
			my $expected = eval { Encode::encode('cp1252', Encode::decode('UTF-8', $utf8, FB_CROAK), FB_CROAK) };
			if(defined $expected) {
				is(slurp("$out/$files->{$table}"), $expected, "$table: converted");
			} else {
				$failures++;
				ok(!-e "$out/$files->{$table}", "$table: cannot be converted, so no file");
				like($stderr, qr/^FAILED: \Q$table\E: Table \Q$table\E, line \d+: /m, "$table: reported with a line number");
			}
		}
		is($status, $failures ? $CONFIG{exit_failure} : $CONFIG{exit_ok}, 'status follows the failures');
	};

	subtest "$name: piped in on standard input, the same files" => sub {
		my ($direct, $piped) = (tempdir(CLEANUP => 1), tempdir(CLEANUP => 1));
		export($db, output_dir => $direct);
		my $script = File::Spec->catfile('bin', 'access2csv');
		my ($stdout, $stderr) = ('', '');
		run3([$^X, '-Ilib', $script, '--no-log', '--no-progress', '--output-dir', $piped, '-'], $db, \$stdout, \$stderr);
		is($? >> 8, $CONFIG{exit_ok}, 'exit 0') or diag($stderr);
		foreach my $table (@{$tables}) {
			is(slurp("$piped/$files->{$table}"), slurp("$direct/$files->{$table}"), "$table");
		}
	};
}

done_testing();

t/security.t  view on Meta::CPAN


sub verbose_diag {
	my ($label, $data) = @_;
	diag("$label: ", Test::More::explain($data)) if $ENV{TEST_VERBOSE};
	return;
}

sub cli {
	my @argv = @_;
	my $status;
	my ($stdout, $stderr) = capture { $status = $CONFIG{app}->run(@argv) };
	return ($status, $stdout, $stderr);
}

sub slurp {
	my $path = shift;
	open my $fh, '<:raw', $path or return '';
	local $/;
	return scalar <$fh>;
}

# Visible form of a string, for test names

t/security.t  view on Meta::CPAN

	foreach my $path (".:$CLEAN_PATH", "bin:$CLEAN_PATH", "$CLEAN_PATH:.") {
		local %ENV = (%ENV, PATH => $path);
		my ($status) = cli('--no-log', '--output-dir', tempdir(CLEANUP => 1), $db);
		is($status, $CONFIG{exit_ok}, "PATH=$path: exported with the real programs");
		ok(!-e $marker, "PATH=$path: planted program not run");
	}

	# Only relative entries: nothing trustworthy is found at all
	{
		local %ENV = (%ENV, PATH => '.:bin');
		my ($status, undef, $stderr) = cli('--no-log', $db);
		is($status, $CONFIG{exit_fatal}, 'PATH with only relative entries: refused');
		like($stderr, qr/\Aaccess2csv: Required program not found in PATH: mdb-tables\n\z/, 'as "not found"');
		ok(!-e $marker, 'and nothing was run');
	}
	chdir $cwd or die $!;
};

subtest 'PATH entries containing shell syntax are never interpreted' => sub {
	# Exploit: a PATH directory named with shell syntax; if the program
	# were ever started through a shell, the name would run a command
	# The name has no "/", so it is one directory; run from $root, where an
	# executed "touch" would create the marker

t/security.t  view on Meta::CPAN

	chdir $cwd or die $!;
};

subtest 'locale variables carrying payloads' => sub {
	# Exploit: attacker-influenced locale variables (e.g. passed through
	# ssh or a wrapper) used as file names, format strings or output
	my @payloads = ('../../../../etc/passwd', '%n%n%s%s', "\e]0;PWNED\a", "de\x00DE", 'x' x $CONFIG{huge}, "\$(touch /tmp/$CONFIG{marker})");
	my $db = make_database(tempdir(CLEANUP => 1), 'T');
	foreach my $payload (@payloads) {
		local %ENV = (%ENV, PATH => $CLEAN_PATH, map { $_ => $payload } qw(LANGUAGE LC_ALL LC_MESSAGES LANG));
		my ($status, undef, $stderr) = cli('--no-log', '/nonexistent/db.accdb');
		my $name = length($payload) > 40 ? 'huge value' : shown($payload);
		is($status, $CONFIG{exit_fatal}, "$name: normal fatal exit");
		like($stderr, qr/\Aaccess2csv: Cannot read database /, "$name: plain English message");
		# Newlines that end lines are ours; only look inside lines
		ok(!grep({ /$RAW_CONTROL_RE/ } map { s/\n\z//r } split /^/, $stderr), "$name: nothing raw on the terminal");
	}
};

#######################################################################
# Hostile database content
#######################################################################

subtest 'terminal escape injection through table names' => sub {
	# Exploit: table names containing terminal control sequences.  Printed
	# raw, they retitle or clear the victim's terminal, hide text, or
	# overwrite a line with a fake message.  Every channel must escape them.
	my $dir = tempdir(CLEANUP => 1);
	my @names = values %TERMINAL_ATTACKS;
	my $db = make_database($dir, @names);
	my $log = "$dir/run.log";
	local %ENV = (%ENV, PATH => $CLEAN_PATH);

	my (undef, undef, $stderr) = cli('--log', $log, '--show-counts', '--output-dir', "$dir/out", $db);
	my (undef, $dry) = cli('--no-log', '--dry-run', '--show-counts', $db);
	my (undef, undef, $warned) = cli('--no-log', '--dry-run', '--table', $TERMINAL_ATTACKS{'OSC set window title'}, '--table', "\e[2Jmissing", $db);
	my (undef, undef, $fatal) = cli('--no-log', "/nonexistent/\e]0;PWNED\a.accdb");
	verbose_diag('escaped stderr', $stderr);

	my %channels = (
		'progress (STDERR)'        => $stderr,
		'dry-run listing (STDOUT)' => $dry,
		'warnings (STDERR)'        => $warned,
		'fatal message (STDERR)'   => $fatal,
		'log file'                 => slurp($log),
	);
	foreach my $channel (sort keys %channels) {
		my $text = $channels{$channel};
		ok(length($text), "$channel: produced output");
		# Newlines that end lines are ours; only look inside lines
		my @raw = grep { /$RAW_CONTROL_RE/ } map { s/\n\z//r } split /^/, $text;
		is_deeply(\@raw, [], "$channel: no raw control characters");
	}
	like($stderr, qr/\\x1B\]0;PWNED\\x07/, 'the attack is shown, harmlessly, as escapes');
	is(scalar(@{ [ glob("$dir/out/*.csv") ] }), scalar(@names), 'and every table was still exported');
};

subtest 'log forging with a carriage return' => sub {
	# Exploit: "\r" in a name makes a log viewer overwrite the start of the
	# line, so an entry can be made to look like something else
	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, "x\rINFO> all tables verified");
	local %ENV = (%ENV, PATH => $CLEAN_PATH);
	cli('--log', "$dir/run.log", '--output-dir', "$dir/out", $db);

t/security.t  view on Meta::CPAN

	my $db = make_database($dir, 'T');
	local %ENV = (%ENV, PATH => $CLEAN_PATH);
	my $real = \&App::Access2CSV::Exporter::run3;
	my $guard = mock_scoped("$CONFIG{exporter}::run3" => sub {
		my ($cmd, $in, $out, $err) = @_;
		return $real->(@_) unless $cmd->[0] =~ /mdb-export\z/;
		${$err} = "\e[2J\e]0;PWNED\acorrupt";
		$? = 1 << 8;
		return 1;
	});
	my ($status, undef, $stderr) = cli('--no-log', '--output-dir', "$dir/out", $db);
	is($status, $CONFIG{exit_failure}, 'the table fails');
	like($stderr, qr/FAILED: T: mdb-export failed with exit status 1: \\x1B\[2J\\x1B\]0;PWNED\\x07corrupt/, 'error shown escaped');
	unlike($stderr, qr/\e/, 'no raw escape reached the terminal');
};

subtest 'command and option injection through names' => sub {
	# Exploit: shell syntax, or a leading "-", in a table name or path.
	# (Covered in depth by t/edge_cases.t; repeated here as a pen-test.)
	# Commands use a bare marker name (a file name may not contain "/"),
	# and the test runs in $dir, where an executed "touch" would create it
	my $dir = tempdir(CLEANUP => 1);
	my $marker = "$dir/$CONFIG{marker}";
	my $touch = "touch $CONFIG{marker}";
	my $db = make_database($dir, "; $touch", "\$($touch)", "`$touch`", '| sh', '-I', '--help');
	my $hostile_db = "-x; $touch.accdb";
	rename($db, "$dir/$hostile_db") or die $!;
	local %ENV = (%ENV, PATH => $CLEAN_PATH);
	my $cwd = getcwd();
	chdir $dir or die $!;
	my ($status, undef, $stderr) = cli('--no-log', '--output-dir', 'out', '--', $hostile_db);
	chdir $cwd or die $!;
	is($status, $CONFIG{exit_ok}, 'all exported');
	ok(!-e $marker, 'no command ran');
	unlike($stderr, qr/option parsing failed/, 'no name was read as an mdbtools option');
};

subtest 'path traversal and NUL bytes' => sub {
	# Exploit 1: table names that climb out of the output directory.
	# Exploit 2: a NUL byte that a C library would treat as the end of the
	# path, so "safe.accdb\0../../secret" could open "safe.accdb".
	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, '../../../../tmp/escaped', "..\\..\\win", "a\x00b");
	local %ENV = (%ENV, PATH => $CLEAN_PATH);

	my ($status) = cli('--no-log', '--output-dir', "$dir/out/in", $db);
	is($status, $CONFIG{exit_ok}, 'exported');
	opendir my $dh, "$dir/out" or die $!;
	is_deeply([grep { !/\A\.\.?\z/ } readdir $dh], ['in'], 'nothing written outside the output directory');
	ok(!grep({ m{/|\x00} } map { (File::Spec->splitpath($_))[2] } glob("$dir/out/in/*")), 'no slash or NUL in any file name');

	($status, undef, my $stderr) = cli('--no-log', '--output-dir', "$dir/nul", "$db\x00../../etc/passwd");
	is($status, $CONFIG{exit_fatal}, 'database path with NUL: refused');
	ok(!-e "$dir/nul", 'the part before the NUL was not opened and exported');
	unlike($stderr, qr/\x00/, 'and no NUL was echoed');
};

#######################################################################
# Where the program writes
#######################################################################

subtest 'symbolic-link attack on the log file' => sub {
	# Exploit: in a shared directory such as /tmp, another user plants
	# "access2csv.log" as a link to a file of the victim's (~/.profile).
	# Appending the log to it would corrupt, or inject into, that file.

t/security.t  view on Meta::CPAN

	my $victim = "$shared/victim";
	open my $fh, '>', $victim or die $!;
	print {$fh} "precious\n";
	close $fh;
	my $db = make_database(tempdir(CLEANUP => 1), 'T');
	local %ENV = (%ENV, PATH => $CLEAN_PATH);
	my $cwd = getcwd();
	chdir $shared or die $!;

	symlink($victim, 'access2csv.log') or die $!;
	my ($status, undef, $stderr) = cli('--output-dir', "$shared/out", $db);
	is($status, $CONFIG{exit_fatal}, 'default log is a link: refused');
	is($stderr, "access2csv: Cannot open log file access2csv.log: it is a symbolic link\n", 'exact message');
	is(slurp($victim), "precious\n", 'victim file untouched');
	ok(!-e "$shared/out", 'nothing exported without a safe log');

	symlink("$shared/created-by-us", "$shared/dangling.log") or die $!;
	($status) = cli('--log', "$shared/dangling.log", '--output-dir', "$shared/out", $db);
	is($status, $CONFIG{exit_fatal}, 'dangling link: refused');
	ok(!-e "$shared/created-by-us", 'its target was not created');

	chdir $cwd or die $!;
};

t/stdin.t  view on Meta::CPAN

	my ($dir, $glob) = @_;
	return [ map { (File::Spec->splitpath($_))[2] } glob("$dir/" . ($glob // '*')) ];
}

# piped(\$input, @argv): run bin/access2csv with $input on standard input
# and TMPDIR set to a fresh directory; returns a hashref of the outcome
sub piped {
	my ($input, @argv) = @_;
	my $tmp = tempdir(CLEANUP => 1);
	local $ENV{TMPDIR} = $tmp;
	my ($stdout, $stderr) = ('', '');
	run3([$^X, "-I$LIB", $SCRIPT, @argv], $input, \$stdout, \$stderr);
	return { status => $? >> 8, stdout => $stdout, stderr => $stderr, left => list_dir($tmp, $CONFIG{copy_glob}) };
}

subtest 'a piped database is exported, and its copy removed' => sub {
	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, 'Orders', 'Customers');
	my $result = piped(\slurp($db), '--no-log', '--no-progress', '--output-dir', "$dir/out", '-');
	verbose_diag('result', $result);
	is($result->{status}, $CONFIG{exit_ok}, 'exit 0');
	is_deeply([sort @{ list_dir("$dir/out") }], ['Customers.csv', 'Orders.csv'], 'both tables exported');
	is(slurp("$dir/out/Orders.csv"), qq{"id","name"\n1,"Orders"\n}, 'content');

t/stdin.t  view on Meta::CPAN

	verbose_diag('copy', \%seen);
	is($status, $CONFIG{exit_ok}, 'exit 0');
	like($seen{path}, qr/access2csv-stdin-/, 'the exporter read the copy');
	is($seen{mode}, $CONFIG{private_mode}, 'readable by the owner only');
	ok(!-e $seen{path}, 'and it is gone afterwards');
};

subtest 'empty standard input is an error, not a confusing mdbtools failure' => sub {
	my $result = piped(\'', '--no-log', '-');
	is($result->{status}, $CONFIG{exit_fatal}, 'exit 3');
	is($result->{stderr}, "access2csv: Standard input is empty: no database was piped in\n", 'exact message');
	is_deeply($result->{left}, [], 'copy deleted');
};

subtest 'a read error gives the real reason' => sub {
	# A directory as standard input: open succeeds, read fails (EISDIR)
	my $directory = tempdir(CLEANUP => 1);
	my $eisdir = do { local $! = Errno::EISDIR(); "$!" };
	my $tmp = tempdir(CLEANUP => 1);
	local $ENV{TMPDIR} = $tmp;
	my ($stdout, $stderr);
	run3([$^X, "-I$LIB", $SCRIPT, '--no-log', '-'], $directory, \$stdout, \$stderr);
	is($? >> 8, $CONFIG{exit_fatal}, 'exit 3');
	is($stderr, "access2csv: Cannot read standard input: $eisdir\n", 'exact message');
	is_deeply(list_dir($tmp, $CONFIG{copy_glob}), [], 'copy deleted');
};

subtest 'regression: a directory is refused before anything is read' => sub {
	# On NetBSD (and FreeBSD before 13) reading a directory does not fail
	# with EISDIR: it returns the directory's raw entries, which 0.001.0
	# copied and exported as if they were a database (exit 1, a 500-byte
	# "table name").  The directory must be refused before the copy is even
	# started, so this fails on any system if the check is lost.
	# https://www.cpantesters.org/cpan/report/e9759fca-bda8-11f1-b0a1-a794297aa253

t/stdin.t  view on Meta::CPAN

	my $real = \&File::Temp::new;
	my $guard = mock_scoped('File::Temp::new' => sub {
		my (undef, %args) = @_;
		$copies++ if ($args{TEMPLATE} // '') =~ /\Aaccess2csv-stdin-/;
		return $real->(@_);
	});

	open my $saved, '<&', \*STDIN or die $!;
	open STDIN, '<', $directory or die "$directory: $!";
	my $status;
	my (undef, $stderr) = capture { $status = App::Access2CSV->run('--no-log', '-') };
	open STDIN, '<&', $saved or die $!;
	undef $guard;

	is($status, $CONFIG{exit_fatal}, 'exit 3');
	is($stderr, "access2csv: Cannot read standard input: $eisdir\n", 'exact message, the same on every system');
	is($copies, 0, 'no copy of standard input was started');
	is_deeply(list_dir($ENV{TMPDIR}, $CONFIG{copy_glob}), [], 'nothing left in the temporary directory');
};

subtest 'a terminal on standard input is refused' => sub {
	# Reading a database from a keyboard would just wait forever
	eval { require IO::Pty; 1 } or plan(skip_all => 'IO::Pty is needed to provide a terminal');
	my $pty = IO::Pty->new();
	my $tmp = tempdir(CLEANUP => 1);
	my $pid = fork // die "fork: $!";
	if(!$pid) {
		$ENV{TMPDIR} = $tmp;
		open STDIN, '<&', $pty->slave() or die $!;
		open STDERR, '>', "$tmp/stderr" or die $!;
		open STDOUT, '>', File::Spec->devnull() or die $!;
		exec($^X, "-I$LIB", $SCRIPT, '--no-log', '-') or die "exec: $!";
	}
	# The parent keeps the terminal's master side open while the child runs
	$pty->close_slave();
	waitpid($pid, 0);
	is($? >> 8, $CONFIG{exit_usage}, 'exit 2 (usage), without reading anything');
	like(slurp("$tmp/stderr"), qr/\AStandard input is a terminal: pipe the database in, or give its file name\n/, 'says why');
	is_deeply(list_dir($tmp, $CONFIG{copy_glob}), [], 'no copy made');
};

subtest 'interrupted while waiting for input: stopped, copy removed' => sub {
	# A slow pipe: part of the data arrives, then the writer stalls.
	# Ctrl-C (INT to the process group) or SIGTERM must stop the program
	# and must not leave the partial copy in the temporary directory.
	foreach my $case (['INT', 1], ['TERM', 0]) {
		my ($signal, $group) = @{$case};
		my $tmp = tempdir(CLEANUP => 1);
		pipe(my $reader, my $writer) or die "pipe: $!";
		my $pid = fork // die "fork: $!";
		if(!$pid) {
			setpgrp(0, 0);
			close $writer;
			$ENV{TMPDIR} = $tmp;
			open STDIN, '<&', $reader or die $!;
			open STDERR, '>', "$tmp/stderr" or die $!;
			exec($^X, "-I$LIB", $SCRIPT, '--no-log', '-') or die "exec: $!";
		}
		close $reader;
		syswrite($writer, "Orders\n");
		for (1 .. $CONFIG{wait_steps}) {
			last if @{ list_dir($tmp, $CONFIG{copy_glob}) };
			sleep $CONFIG{wait_step};
		}
		ok(scalar(@{ list_dir($tmp, $CONFIG{copy_glob}) }), "$signal: the copy was being written");
		kill $signal, $group ? -$pid : $pid;
		waitpid($pid, 0);
		close $writer;
		is($? >> 8, $CONFIG{exit_fatal}, "$signal: stopped with exit 3");
		like(slurp("$tmp/stderr"), qr/\Aaccess2csv: Interrupted by SIG$signal while reading the database from standard input\n\z/, "$signal: says so");
		is_deeply(list_dir($tmp, $CONFIG{copy_glob}), [], "$signal: partial copy deleted");
	}
};

subtest '"./-" is still a file called "-"; the exporter API is unchanged' => sub {
	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, 'Orders');
	rename($db, "$dir/-") or die $!;
	my $result = do {
		my $cwd = File::Spec->rel2abs(File::Spec->curdir());

t/stdin.t  view on Meta::CPAN

	like($result->{stdout}, qr/Orders/, 'listed');

	# "-" is a command-line convention; the module takes names literally
	throws_ok { App::Access2CSV::Exporter->new(progress => 0)->run('-') } qr/\ACannot read database -: /, 'Exporter->run("-") looks for a file called "-"';
};

subtest 'taint mode: piped input works under perl -T' => sub {
	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, 'Orders');
	my @inc = map { "-I$_" } ($LIB, grep { !ref } @INC);
	my ($stdout, $stderr) = ('', '');
	local $ENV{PATH} = "$FAKE_BIN:/usr/bin:/bin";
	run3([$^X, '-T', @inc, $SCRIPT, '--no-log', '--no-progress', '--output-dir', "$dir/out", '-'], \slurp($db), \$stdout, \$stderr);
	is($? >> 8, $CONFIG{exit_ok}, 'exit 0') or diag($stderr);
	ok(-e "$dir/out/Orders.csv", 'exported');
};

done_testing();

t/taint.t  view on Meta::CPAN


my $FAKE_BIN = install_fake_mdbtools();

sub verbose_diag {
	my ($label, $data) = @_;
	diag("$label: ", Test::More::explain($data)) if $ENV{TEST_VERBOSE};
	return;
}

# tainted(%env, @argv): run bin/access2csv under perl -T in a child;
# returns (exit status, stdout, stderr)
sub tainted {
	my ($path, @argv) = @_;
	local %ENV = (%ENV, PATH => $path);
	delete @ENV{qw(LANGUAGE LC_ALL LC_MESSAGES LANG)};
	my ($stdout, $stderr, $status) = capture { system($^X, '-T', @INC_FLAGS, $SCRIPT, @argv); $? >> 8 };
	return ($status, $stdout, $stderr);
}

sub slurp {
	my $path = shift;
	open my $fh, '<:raw', $path or return;
	local $/;
	return scalar <$fh>;
}

Readonly::Scalar my $SAFE_PATH => "$FAKE_BIN:/usr/bin:/bin";

subtest 'help and dry run work under -T' => sub {
	my $db = make_database(tempdir(CLEANUP => 1), 'Orders', 'Customers');
	my ($status, $stdout, $stderr) = tainted($SAFE_PATH, '--help');
	is($status, $CONFIG{exit_ok}, '--help');
	like($stdout, qr/--output-dir/, 'help text');

	($status, $stdout, $stderr) = tainted($SAFE_PATH, '--no-log', '--dry-run', '--show-counts', $db);
	verbose_diag('dry run', { stdout => $stdout, stderr => $stderr });
	is($status, $CONFIG{exit_ok}, 'dry run');
	like($stdout, qr/^Orders\s+1\s+Orders\.csv$/m, 'tables listed with counts');
	unlike($stderr, qr/Insecure/, 'no taint failure');
};

subtest 'exports in every encoding, with a log, under -T' => sub {
	# Same bytes as without -T: untainting changes nothing but permission
	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, 'Unicode');
	my %expected = (
		'utf8'     => qq{"id","name"\n1,"Caf\xC3\xA9 \xE2\x82\xAC"\n},
		'utf8-bom' => qq{$CONFIG{utf8_bom}"id","name"\n1,"Caf\xC3\xA9 \xE2\x82\xAC"\n},
		'cp1252'   => qq{"id","name"\n1,"Caf\xE9 \x80"\n},
	);
	foreach my $encoding (sort keys %expected) {
		my ($status, undef, $stderr) = tainted($SAFE_PATH, '--log', "$dir/$encoding.log", '--encoding', $encoding, '--show-counts', '--output-dir', "$dir/$encoding", $db);
		is($status, $CONFIG{exit_ok}, "$encoding: exit 0") or diag($stderr);
		is(slurp("$dir/$encoding/Unicode.csv"), $expected{$encoding}, "$encoding: exact bytes");
		like(slurp("$dir/$encoding.log") // '', qr/Exported Unicode => .* \(1 row\)/, "$encoding: logged");
	}
};

subtest 'hostile table names still work (validated, then untainted)' => sub {
	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, '-I', '; touch RAN', 'a/b', "tab\there");
	my ($status, undef, $stderr) = tainted($SAFE_PATH, '--no-log', '--no-progress', '--output-dir', "$dir/out", $db);
	is($status, $CONFIG{exit_ok}, 'exported') or diag($stderr);
	opendir my $dh, "$dir/out" or die $!;
	is(scalar(grep { /\.csv\z/ } readdir $dh), 4, 'one file per table');
	ok(!-e "$dir/$CONFIG{marker}" && !-e $CONFIG{marker}, 'nothing executed');
};

subtest 'failures give the true reason, not a taint or stale error' => sub {
	# Before the fix, a failed log open under -T was reported with a
	# leftover $! ("No such file or directory") instead of the real cause
	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, 'T');

	my ($status, undef, $stderr) = tainted($SAFE_PATH, '--no-log', "$dir/missing.accdb");
	is($status, $CONFIG{exit_fatal}, 'missing database: fatal');
	is($stderr, "access2csv: Cannot read database $dir/missing.accdb: $ENOENT_TEXT\n", 'true reason');

	($status, undef, $stderr) = tainted($SAFE_PATH, '--log', "$dir/no/such/x.log", $db);
	is($status, $CONFIG{exit_fatal}, 'log in a missing directory: fatal');
	is($stderr, "access2csv: Cannot open log file $dir/no/such/x.log: $ENOENT_TEXT\n", 'true reason');
	unlike($stderr, qr/Insecure/, 'not a taint failure');
};

subtest 'taint protection: programs in a directory anyone can write to are not run' => sub {
	# Taint mode refuses to start programs while PATH contains a directory
	# that other users can write to (they could replace the program).  The
	# refusal must be a clean fatal error, and the planted program must
	# not run.
	my $shared = tempdir(CLEANUP => 1);
	chmod $CONFIG{world_writable}, $shared or die $!;
	my $marker = "$shared/$CONFIG{marker}";
	foreach my $program (qw(mdb-tables mdb-export mdb-count)) {
		open my $fh, '>', "$shared/$program" or die $!;
		print {$fh} "#!/bin/sh\ntouch '$marker'\n";
		close $fh;
		chmod oct(755), "$shared/$program";
	}
	my $db = make_database(tempdir(CLEANUP => 1), 'T');
	my ($status, undef, $stderr) = tainted("$shared:$SAFE_PATH", '--no-log', '--dry-run', $db);
	verbose_diag('stderr', $stderr);
	is($status, $CONFIG{exit_fatal}, 'fatal');
	like($stderr, qr/\Aaccess2csv: Insecure directory in \$ENV\{PATH\}/, 'says why');
	ok(!-e $marker, 'the program was not run');
};

subtest 'mdbtools run in a clean environment (with or without -T)' => sub {
	# perlsec: IFS, CDPATH, ENV and BASH_ENV can change how programs start,
	# and relative PATH entries point at the current directory.  None of them
	# may reach the mdbtools processes.
	my %seen;
	my $real = \&App::Access2CSV::Exporter::run3;
	my $guard = mock_scoped('App::Access2CSV::Exporter::run3' => sub {

t/transaction.t  view on Meta::CPAN

	return [sort { $a <=> $b } grep { /\A\d+\z/ } readdir $dh];
}

# export(%settings): one quiet run over $settings{db}; returns a hashref
# describing the outcome, including open descriptors before and after
sub export {
	my (%args) = @_;
	my $db = delete $args{db};
	my $fds = open_fds();
	my ($status, $error);
	my ($stdout, $stderr) = capture {
		$status = eval { $CONFIG{exporter}->new(progress => 0, %args)->run($db) };
		$error = $@;
	};
	return { status => $status, error => $error, stdout => $stdout, stderr => $stderr, fds => [$fds, open_fds()] };
}

# A run3 double that behaves like mdb-export but lets a test decide what
# happens: $script->($cmd, $out, $err) prints and sets $?
sub fake_export {
	my $script = shift;
	my $real = \&App::Access2CSV::Exporter::run3;
	return mock_scoped("$CONFIG{exporter}::run3" => sub {
		my ($cmd, $in, $out, $err) = @_;
		return $real->(@_) unless $cmd->[0] =~ /mdb-export\z/;

t/transaction.t  view on Meta::CPAN

		my $dir = tempdir(CLEANUP => 1);
		my $db = make_database($dir, 'Orders');
		my $out = "$dir/out";
		mkdir $out or die $!;
		spit("$out/Orders.csv", $CONFIG{old_content});

		my $result = do {
			my $guard = $inject->();
			export(db => $db, output_dir => $out, overwrite => 1, %{$settings});
		};
		verbose_diag($fault, $result->{stderr});
		is($result->{status}, $CONFIG{exit_failure}, "$fault: the table failed");
		like($result->{stderr}, qr/FAILED: Orders: /, "$fault: reported");
		is(slurp("$out/Orders.csv"), $CONFIG{old_content}, "$fault: old file byte for byte intact");
		is_deeply(temp_files($out), [], "$fault: temporary file rolled back");
		is_deeply($result->{fds}[1], $result->{fds}[0], "$fault: no file handle left open") if $HAS_PROC_FD;
	}
};

subtest 'Phase: the commit itself fails -> rollback' => sub {
	# The rename cannot happen (a non-empty directory has the final name).
	# Whatever was there before must stay exactly as it was.
	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, 'Orders');
	my $out = "$dir/out";
	mkdir "$out" or die $!;
	mkdir "$out/Orders.csv" or die $!;
	spit("$out/Orders.csv/keep", $CONFIG{old_content});

	my $result = export(db => $db, output_dir => $out, overwrite => 1);
	is($result->{status}, $CONFIG{exit_failure}, 'failed');
	like($result->{stderr}, qr/FAILED: Orders: Cannot write /, 'reported');
	is(slurp("$out/Orders.csv/keep"), $CONFIG{old_content}, 'what was there is intact');
	is_deeply(temp_files($out), [], 'temporary file rolled back');
};

#######################################################################
# Phase 3: after the commit
#######################################################################

subtest 'Phase: after the commit -> a later failure cannot un-commit' => sub {
	# Row counting runs after the rename.  If it fails, the committed file

t/transaction.t  view on Meta::CPAN

	my $guard = mock_scoped("$CONFIG{exporter}::run3" => sub {
		return $real->(@_) unless $_[0][0] =~ /mdb-count\z/;
		${ $_[3] } = 'count failed';
		$? = 1 << 8;
		return 1;
	});
	my $result = export(db => $db, output_dir => "$dir/out", show_counts => 1);
	is(slurp("$dir/out/Orders.csv"), qq{"id","name"\n1,"Orders"\n}, 'committed file complete and correct');
	is_deeply(temp_files("$dir/out"), [], 'no temporary file');
	is($result->{status}, $CONFIG{exit_ok}, 'the table still counts as exported');
	like($result->{stderr}, qr/Cannot count the rows of Orders/, 'the count failure is a warning');
};

#######################################################################
# Phase 4: the run as a whole
#######################################################################

subtest 'Phase: run with a failing table -> other tables stay committed' => sub {
	# Each table is its own transaction (documented): a failure in the
	# middle neither rolls back the tables before it nor stops those after
	my $dir = tempdir(CLEANUP => 1);

t/transaction.t  view on Meta::CPAN

sub interrupt {
	my ($signal, $to_group) = @_;
	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, 'Slow', 'Zebra');
	my $out = "$dir/out";
	mkdir $out or die $!;
	spit("$out/Slow.csv", $CONFIG{old_content});
	my $pid = fork // die "fork: $!";
	if(!$pid) {
		setpgrp(0, 0);
		open STDERR, '>', "$dir/stderr" or die $!;
		open STDOUT, '>', File::Spec->devnull() or die $!;
		exec($^X, "-I$LIB", $SCRIPT, '--no-log', '--overwrite', '--output-dir', $out, $db) or die "exec: $!";
	}
	for (1 .. $CONFIG{wait_steps}) {
		last if @{ temp_files($out) };
		sleep $CONFIG{wait_step};
	}
	kill $signal, $to_group ? -$pid : $pid;
	waitpid($pid, 0);
	my $status = $? >> 8;
	kill 'KILL', -$pid;   # tidy away the stand-in mdb-export if it lingers
	return { status => $status, stderr => slurp("$dir/stderr") // '', out => $out };
}

subtest 'Phase: interrupted mid-transaction -> rollback and stop' => sub {
	# Ctrl-C reaches the whole process group; kill/service managers send
	# TERM to the program.  Either way the table in flight is rolled back
	# and no further table is started.
	foreach my $case (['INT', 1, 'Ctrl-C (SIGINT to the group)'], ['TERM', 0, 'SIGTERM to the program']) {
		my ($signal, $group, $name) = @{$case};
		my $result = interrupt($signal, $group);
		verbose_diag($name, $result);
		is($result->{status}, $CONFIG{exit_fatal}, "$name: stopped (exit 3)");
		like($result->{stderr}, qr/access2csv: Interrupted by SIG$signal: stopped, and the table being exported was discarded/, "$name: says so");
		is(slurp("$result->{out}/Slow.csv"), $CONFIG{old_content}, "$name: old file intact");
		is_deeply(temp_files($result->{out}), [], "$name: temporary file rolled back");
		ok(!-e "$result->{out}/Zebra.csv", "$name: the next table was not started");
	}
};

subtest 'Phase: a caller\'s own signal handlers are respected' => sub {
	# The exporter only takes over signals nobody else is handling, and
	# gives them back afterwards
	my $dir = tempdir(CLEANUP => 1);

t/transaction.t  view on Meta::CPAN

	# must not damage what the first run committed, however often it runs.
	my $dir = tempdir(CLEANUP => 1);
	my $db = make_database($dir, 'A', 'B');
	my $first = export(db => $db, output_dir => "$dir/out");
	is($first->{status}, $CONFIG{exit_ok}, 'first run commits');
	my %committed = map { $_ => [slurp("$dir/out/$_"), (stat("$dir/out/$_"))[9]] } qw(A.csv B.csv);

	foreach my $repeat (1 .. 2) {
		my $again = export(db => $db, output_dir => "$dir/out");
		is($again->{status}, $CONFIG{exit_failure}, "repeat $repeat: refused");
		is(scalar(() = $again->{stderr} =~ /Output file already exists/g), 2, "repeat $repeat: both tables refused");
		foreach my $file (sort keys %committed) {
			is(slurp("$dir/out/$file"), $committed{$file}[0], "repeat $repeat: $file content unchanged");
			is((stat("$dir/out/$file"))[9], $committed{$file}[1], "repeat $repeat: $file not even rewritten");
		}
		is_deeply(temp_files("$dir/out"), [], "repeat $repeat: no temporary files");
	}
};

subtest 'Phase: repeat with --overwrite -> the same result every time' => sub {
	# With overwrite the transaction is idempotent: same names (even for

t/transition.t  view on Meta::CPAN


# A logger that keeps the info messages, to check what was logged
{
	package Local::Recorder;
	sub new { return bless { info => [] }, shift }
	sub info { push @{ $_[0]{info} }, $_[1]; return }
	sub debug { return }
	sub warn { return }
}

# Run an exporter; returns (status or undef, error, stdout, stderr)
sub run_exporter {
	my ($e, $db) = @_;
	my ($status, $error);
	my ($stdout, $stderr) = capture { $status = eval { $e->run($db) }; $error = $@ };
	return ($status, $error, $stdout, $stderr);
}

sub cli {
	my @argv = @_;
	my $status;
	my ($stdout, $stderr) = capture { local $SIG{__WARN__} = sub { }; $status = $CONFIG{app}->run(@argv) };
	return ($status, $stdout, $stderr);
}

sub new_database {
	my $dir = tempdir(CLEANUP => 1);
	return ($dir, make_database($dir, @_));
}

#######################################################################
# App::Access2CSV::run
#######################################################################

subtest 'State: PARSING -> Trigger: --help / --man -> State: HELP -> return 0' => sub {
	foreach my $option ('--help', '--man') {
		trace_app();
		my ($status, $stdout, $stderr) = cli($option);
		is_deeply(\@TRACE, [$S{parsing}, $S{help}], "$option: path");
		is($status, $CONFIG{exit_ok}, "$option: return 0");
		ok(length($stdout) && !length($stderr), "$option: action - documentation to STDOUT");
		restore_all();
	}
};

subtest 'State: PARSING -> Trigger: bad option / missing value / not one database -> State: USAGE ERROR -> return 2' => sub {
	my %triggers = ('bad option' => ['--bogus', 'db'], 'missing value' => ['--log'], 'no database' => [], 'two databases' => ['a', 'b']);
	foreach my $trigger (sort keys %triggers) {
		trace_app();
		my ($status, $stdout, $stderr) = cli(@{ $triggers{$trigger} });
		is_deeply(\@TRACE, [$S{parsing}, $S{usage}], "$trigger: path (never opens the log)");
		is($status, $CONFIG{exit_usage}, "$trigger: return 2");
		ok(!length($stdout) && length($stderr), "$trigger: action - usage to STDERR");
		restore_all();
	}
};

subtest 'State: PARSING -> CHECKING SETTINGS -> Trigger: valid -> State: OPENING LOG -> Trigger: log writable -> State: EXPORTING -> return 0' => sub {
	my ($dir, $db) = new_database('T');
	trace_app();
	my ($status) = cli('--log', "$dir/x.log", '--output-dir', "$dir/out", $db);
	verbose_diag('trace', \@TRACE);
	is_deeply(\@TRACE, [$S{parsing}, $S{settings}, $S{open_log}, $S{exporting}], 'path');

t/transition.t  view on Meta::CPAN

	trace_app();
	my ($status) = cli('--no-log', '--no-progress', '--output-dir', "$dir/out", $db);
	is_deeply(\@TRACE, [$S{parsing}, $S{settings}, $S{exporting}], 'path');
	is($status, $CONFIG{exit_failure}, 'return 1');
	restore_all();
};

subtest 'State: OPENING LOG -> Trigger: log cannot be opened -> State: FATAL -> return 3' => sub {
	my ($dir, $db) = new_database('T');
	trace_app();
	my ($status, undef, $stderr) = cli('--log', "$dir/no/such/x.log", $db);
	is_deeply(\@TRACE, [$S{parsing}, $S{settings}, $S{open_log}, $S{fatal}], 'path (EXPORTING never entered)');
	is($status, $CONFIG{exit_fatal}, 'return 3');
	like($stderr, qr/\Aaccess2csv: /, 'action - "access2csv: <reason>" to STDERR');
	restore_all();
};

subtest 'State: EXPORTING -> Trigger: fatal error -> State: FATAL -> return 3' => sub {
	my ($dir) = new_database('T');
	trace_app();
	my ($status) = cli('--no-log', "$dir/missing.accdb");
	is_deeply(\@TRACE, [$S{parsing}, $S{settings}, $S{exporting}, $S{fatal}], 'path');
	is($status, $CONFIG{exit_fatal}, 'return 3');
	restore_all();
};

subtest 'State: CHECKING SETTINGS -> Trigger: invalid value -> State: USAGE ERROR -> return 2 (nothing created)' => sub {
	# A bad option value is a command-line mistake.  Settings are checked
	# before anything with a side effect: no copy of standard input is
	# made and no log file is created
	my ($dir, $db) = new_database('T');
	trace_app();
	my ($status, undef, $stderr) = cli('--log', "$dir/x.log", '--encoding', 'latin1', $db);
	is_deeply(\@TRACE, [$S{parsing}, $S{settings}, $S{usage}], 'path: CHECKING SETTINGS -> USAGE ERROR');
	is($status, $CONFIG{exit_usage}, 'return 2');
	like($stderr, qr/^Invalid setting: Parameter 'encoding' \(latin1\)/m, 'says why');
	ok(!-e "$dir/x.log", 'the log file was never created');
	restore_all();
};

# with_stdin($source, @argv): run the program with STDIN read from $source
sub with_stdin {
	my ($source, @argv) = @_;
	open my $saved, '<&', \*STDIN or die $!;
	open STDIN, '<', $source or die "$source: $!";
	my @result = cli(@argv);

t/transition.t  view on Meta::CPAN

	my ($status) = with_stdin($db, '--log', "$dir/x.log", '--output-dir', "$dir/out", '-');
	is_deeply(\@TRACE, [$S{parsing}, $S{settings}, $S{stdin}, $S{open_log}, $S{exporting}], 'path');
	is($status, $CONFIG{exit_ok}, 'return 0');
	ok(-e "$dir/out/T.csv", 'exported from the piped copy');
	restore_all();
};

subtest 'State: READING STDIN -> Trigger: empty input -> State: FATAL (log never opened)' => sub {
	my ($dir) = new_database('T');
	trace_app();
	my ($status, undef, $stderr) = with_stdin(File::Spec->devnull(), '--log', "$dir/x.log", '-');
	is_deeply(\@TRACE, [$S{parsing}, $S{settings}, $S{stdin}, $S{fatal}], 'path');
	is($status, $CONFIG{exit_fatal}, 'return 3');
	ok(!-e "$dir/x.log", 'the log file was never created');
	restore_all();
};

#######################################################################
# App::Access2CSV::Exporter
#######################################################################

t/transition.t  view on Meta::CPAN

	($status) = run_exporter($e, $db);
	is($TRACE[0], $S{checking}, 'READY again: a second run starts at CHECKING');
	is($status, $CONFIG{exit_ok}, 'and succeeds');
	restore_all();
};

subtest 'State: EXPORTING -> Trigger: table failure -> EXPORTING (next table) -> SUMMARY -> return 1' => sub {
	my ($dir, $db) = new_database('A', 'Broken', 'C');
	my $e = $CONFIG{exporter}->new(output_dir => "$dir/out", progress => 0, logger => bless({}, 'Local::Quiet'));
	trace_exporter();
	my ($status, undef, undef, $stderr) = run_exporter($e, $db);
	is_deeply(\@TRACE, [$S{checking}, $S{listing}, $S{preparing}, ($S{table}) x 3, $S{summary}], 'the loop continues after a failure');
	is($status, $CONFIG{exit_failure}, 'return 1');
	like($stderr, qr/FAILED: Broken/, 'action - carp');
	ok(!-e "$dir/out/Broken.csv", 'action - no file for the failed table');
	opendir my $dh, "$dir/out" or die $!;
	ok(!grep({ /\A\.access2csv-/ } readdir $dh), 'action - temporary file deleted');
	restore_all();
};

subtest 'State: LISTING -> Trigger: dry_run -> State: DRY RUN -> return 0 -> READY' => sub {
	my ($dir, $db) = new_database('A');
	my $e = $CONFIG{exporter}->new(output_dir => "$dir/out", progress => 0, dry_run => 1);
	trace_exporter();

t/transition.t  view on Meta::CPAN

	ok(!-e "$dir/out", 'no file or directory written');
	($status) = run_exporter($e, $db);
	is($status, $CONFIG{exit_ok}, 'FATAL -> READY: the object still works');
};

subtest 'State: CHECKING -> Trigger: mdb-count missing -> action: warn, switch show_counts off -> LISTING' => sub {
	my ($dir, $db) = new_database('A');
	local $ENV{PATH} = install_fake_mdbtools(qw(mdb-tables mdb-export));
	my $e = $CONFIG{exporter}->new(output_dir => "$dir/out", progress => 0, show_counts => 1, dry_run => 1);
	trace_exporter();
	my ($status, undef, undef, $stderr) = run_exporter($e, $db);
	is_deeply(\@TRACE, [$S{checking}, $S{listing}, $S{dry_run}], 'the run goes on');
	like($stderr, qr/mdb-count not found/, 'action - warning');
	is($e->{show_counts}, 0, 'action - show_counts switched off');
	restore_all();
};

subtest 'State: LISTING -> Trigger: mdb-tables fails -> State: FATAL' => sub {
	my ($dir, $db) = new_database('FAIL');
	trace_exporter();
	my ($status, $error) = run_exporter($CONFIG{exporter}->new(output_dir => "$dir/out", progress => 0), $db);
	is_deeply(\@TRACE, [$S{checking}, $S{listing}], 'stops in LISTING');
	like($error, qr/\Amdb-tables failed /, 'action - croak');

t/transition.t  view on Meta::CPAN

	});
}

subtest 'State: EXPORTING -> Trigger: success, then row count fails -> warning only -> SUMMARY -> return 0' => sub {
	# The file is in place, so the success edge has been taken; a count
	# is an optional extra and cannot turn it into a failure
	my ($dir, $db) = new_database('A');
	my $guard = failing_count();
	my $logger = Local::Recorder->new();
	trace_exporter();
	my ($status, undef, undef, $stderr) = run_exporter($CONFIG{exporter}->new(output_dir => "$dir/out", progress => 0, show_counts => 1, logger => $logger), $db);
	is_deeply(\@TRACE, [$S{checking}, $S{listing}, $S{preparing}, $S{table}, $S{summary}], 'path');
	is($status, $CONFIG{exit_ok}, 'return 0');
	ok(-e "$dir/out/A.csv", 'the file is in place');
	like($stderr, qr/^Cannot count the rows of A: mdb-count failed/m, 'action - warning');
	unlike($stderr, qr/FAILED/, 'not reported as a failed table');
	ok((grep { /\AExported A => .*A\.csv\z/ } @{ $logger->{info} }), 'logged as exported, without a count');
	ok((grep { /\AProcessed 1 table, 0 failed\z/ } @{ $logger->{info} }), 'summary: no failures');
	restore_all();
};

subtest 'State: DRY RUN -> Trigger: row count fails -> warning, "?" shown -> return 0' => sub {
	my ($dir, $db) = new_database('A');
	my $guard = failing_count();
	trace_exporter();
	my ($status, $error, $stdout, $stderr) = run_exporter($CONFIG{exporter}->new(progress => 0, show_counts => 1, dry_run => 1), $db);
	is_deeply(\@TRACE, [$S{checking}, $S{listing}, $S{dry_run}], 'path');
	is($status, $CONFIG{exit_ok}, 'return 0');
	is($error, '', 'no exception');
	like($stdout, qr/^A\s+\?\s+A\.csv$/m, 'count shown as "?"');
	like($stderr, qr/^Cannot count the rows of A: /m, 'action - warning');
	restore_all();
};

subtest 'State: LISTING -> Trigger: no tables selected -> State: SUMMARY (no PREPARING) -> return 0' => sub {
	# Nothing to export: no output directory is made, and the summary says so
	my ($dir, $db) = new_database('A');
	my $logger = Local::Recorder->new();
	my $e = $CONFIG{exporter}->new(output_dir => "$dir/out", progress => 0, tables => [], logger => $logger);
	trace_exporter();
	my ($status) = run_exporter($e, $db);
	is_deeply(\@TRACE, [$S{checking}, $S{listing}, $S{summary}], 'path: LISTING -> SUMMARY');
	is($status, $CONFIG{exit_ok}, 'return 0');
	ok(!-e "$dir/out", 'no output directory made');
	ok((grep { /\AProcessed 0 tables, 0 failed\z/ } @{ $logger->{info} }), 'action - summary logged');
	restore_all();
};

subtest 'State: LISTING -> Trigger: only unknown names selected -> SUMMARY, with a warning' => sub {
	my ($dir, $db) = new_database('A');
	trace_exporter();
	my ($status, undef, undef, $stderr) = run_exporter($CONFIG{exporter}->new(output_dir => "$dir/out", progress => 0, tables => ['Nope']), $db);
	is_deeply(\@TRACE, [$S{checking}, $S{listing}, $S{summary}], 'path');
	like($stderr, qr/Table not found in database: Nope/, 'action - warning');
	ok(!-e "$dir/out", 'no output directory made');
	restore_all();
};

#######################################################################
# Illegal transitions
#######################################################################

subtest 'Illegal: run without new (no READY state) is refused at once' => sub {
	my ($dir, $db) = new_database('A');

t/unit.t  view on Meta::CPAN

#	kill        => { table => signal that kills mdb-export }
sub mdbtools_scenario {
	my %scenario = @_;
	my %missing = map { $_ => 1 } @{ $scenario{missing} || [] };

	return mock_scoped(
		"$CONFIG{exporter}::which" => sub {
			return $missing{ $_[0] } ? undef : "$CONFIG{fake_bin}/$_[0]";
		},
		"$CONFIG{exporter}::run3" => sub {
			my ($cmd, $stdin, $stdout, $stderr) = @_;
			my ($program, @args) = @{$cmd};
			$program =~ s{\A\Q$CONFIG{fake_bin}\E/}{};
			# Like mdbtools, treat everything after "--" as a file or table
			@args = grep { $_ ne '--' } @args;
			${$stderr} = '';
			$? = 0;

			if($program eq $CONFIG{mdb_tables}) {
				${$stdout} = join('', map { "$_\n" } @{ $scenario{tables} || [] });
				${$stderr} = "not an Access file\n" if $scenario{tables_exit};
				$? = ($scenario{tables_exit} || 0) << 8 | ($scenario{tables_kill} || 0);
			} elsif($program eq $CONFIG{mdb_export}) {
				my $table = $args[-1];
				print {$stdout} exists $scenario{data}{$table} ? $scenario{data}{$table} : $CONFIG{csv_body};
				$stdout->flush();
				${$stderr} = "corrupt table\n" if $scenario{exit}{$table};
				$? = ($scenario{exit}{$table} || 0) << 8 | ($scenario{kill}{$table} || 0);
			} elsif($program eq $CONFIG{mdb_count}) {
				${$stdout} = "$CONFIG{row_count}\n";
			}
			return 1;
		},
	);
}

# A fresh directory with an empty "database" file in it
sub workspace {
	my $dir = tempdir(CLEANUP => 1);
	my $db = File::Spec->catfile($dir, 'shop.accdb');
	open my $fh, '>', $db or die "$db: $!";
	close $fh;
	return ($dir, $db, File::Spec->catdir($dir, 'out'));
}

# Run an exporter; return (status, stdout, stderr, exception)
sub export {
	my ($db, %args) = @_;
	my ($status, $error);
	my ($stdout, $stderr) = capture {
		$status = eval { $CONFIG{exporter}->new(progress => 0, %args)->run($db) };
		$error = $@;
	};
	return ($status, $stdout, $stderr, $error);
}

# check_globals($name, $code)
# Runs $code with known values in $@, $!, $_ and $? and an alarm pending,
# and checks that all of them survive.  The values are set and read back
# inside the code block, because Capture::Tiny itself changes $!.
sub check_globals {
	my ($name, $code) = @_;

	local $SIG{ALRM} = sub { die "alarm fired\n" };
	alarm($CONFIG{alarm_secs});
	my %after;
	my ($stdout, $stderr) = capture {
		local $_ = $CONFIG{sentinel};
		local $@ = $CONFIG{sentinel};
		local $? = $CONFIG{bad_status} << 8;
		$! = ENOENT;
		$code->();
		# Copy into lexicals before testing: Test::More must not see aliases
		%after = (underscore => $_, eval_error => $@, errno => $! + 0, child => $? >> 8);
	};
	my $remaining = alarm(0);
	verbose_diag("$name globals", \%after);

t/unit.t  view on Meta::CPAN

	throws_ok { $class->new(tables => 'Orders') } qr/Parameter 'tables' must be/, 'tables not an array';
	throws_ok { $class->new(tables => [['x']]) } qr/'?tables'? can only contain strings/, 'tables of non-strings';
	ticked('new: tables must be');
};

subtest 'run: exports every user table and returns 0' => sub {
	my ($dir, $db, $out) = workspace();
	my $guard = mdbtools_scenario(tables => ['Orders', 'Customers', 'MSysObjects', 'USysRibbons', '~TMP']);
	my $logger = Local::Logger->new();

	my ($status, $stdout, $stderr, $error) = export($db, output_dir => $out, logger => $logger, progress => 1);
	verbose_diag('log', $logger->{lines});
	is($error, '', 'no exception');
	is($status, $CONFIG{exit_ok}, 'status 0');
	returns_ok($status, { type => 'integer', min => 0, max => 1 }, 'Output schema');
	ticked('run: returns 0');

	is(slurp("$out/Orders.csv"), $CONFIG{csv_body}, 'data written unchanged (utf8)');
	ok(-e "$out/Customers.csv", 'second table');
	ok(!-e "$out/MSysObjects.csv" && !-e "$out/USysRibbons.csv", 'system tables skipped');
	is($stdout, '', 'nothing on STDOUT');
	is($stderr, "[1/2] Customers\n[2/2] Orders\n", 'progress to STDERR, sorted');
	like($logger->{lines}[-1][1], qr/\AProcessed 2 tables, 0 failed\z/, 'summary logged');

	opendir my $dh, $out or die $!;
	is_deeply([sort grep { !/\A\.\.?\z/ } readdir $dh], ['Customers.csv', 'Orders.csv'], 'no temporary files left');
};

subtest 'run: encodings' => sub {
	# POD ENCODING: utf8 copied exactly, utf8-bom adds 3 bytes, cp1252 converted
	my $data = "\"n\"\n\"Caf\xC3\xA9 \xE2\x82\xAC \xF0\x9F\x98\x80\"\n";
	my ($dir, $db, $out) = workspace();

t/unit.t  view on Meta::CPAN

subtest 'run: per-table failures return 1 and leave no partial files' => sub {
	my ($dir, $db, $out) = workspace();
	my $guard = mdbtools_scenario(
		tables => ['Bad', 'Emoji', 'Good', 'Killed', 'Latin1'],
		data   => { Emoji => "a\n\xF0\x9F\x98\x80\n", Latin1 => "a\nb\nCaf\xE9\n" },
		exit   => { Bad => $CONFIG{bad_status} },
		kill   => { Killed => $CONFIG{signal} },
	);
	my $logger = Local::Logger->new();

	my ($status, undef, $stderr) = export($db, output_dir => $out, encoding => 'cp1252', logger => $logger);
	verbose_diag('warnings', $stderr);
	is($status, $CONFIG{exit_failure}, 'status 1');
	returns_ok($status, { type => 'integer', min => 0, max => 1 }, 'Output schema');
	ticked('run: returns 1');

	like($stderr, qr/^FAILED: Bad: mdb-export failed with exit status $CONFIG{bad_status}: corrupt table at /m, 'exit status');
	ticked('run: FAILED');
	ticked('run: mdb-export failed with exit status');

	like($stderr, qr/^FAILED: Killed: mdb-export was killed by signal $CONFIG{signal} at /m, 'signal');
	ticked('run: killed by signal (per table)');

	like($stderr, qr/^FAILED: Emoji: Table Emoji, line 2: cannot be represented in cp1252 at /m, 'unmappable');
	ticked('run: cannot be represented in cp1252');

	like($stderr, qr/^FAILED: Latin1: Table Latin1, line 3: output of mdb-export is not valid UTF-8 at /m, 'invalid UTF-8');
	ticked('run: output of mdb-export is not valid UTF-8');

	ok(-e "$out/Good.csv", 'good table exported');
	ok(!-e "$out/$_.csv", "no partial $_.csv") foreach qw(Bad Emoji Killed Latin1);
	is(scalar(grep { $_->[0] eq 'warn' && $_->[1] =~ /\AFAILED: / } @{ $logger->{lines} }), 4, 'failures logged');
	like($logger->{lines}[-1][1], qr/\AProcessed 5 tables, 4 failed\z/, 'summary');
};

subtest 'run: existing files' => sub {
	my ($dir, $db, $out) = workspace();
	my $guard = mdbtools_scenario(tables => ['Orders']);
	export($db, output_dir => $out);

	my ($status, undef, $stderr) = export($db, output_dir => $out);
	is($status, $CONFIG{exit_failure}, 'fails without overwrite');
	like($stderr, qr/^FAILED: Orders: Output file already exists: \Q$out\E.Orders\.csv \(use --overwrite to replace it\) at /m, 'message');
	ticked('run: Output file already exists');

	($status) = export($db, output_dir => $out, overwrite => 1);
	is($status, $CONFIG{exit_ok}, 'overwrite replaces');

	# A directory where the file should go cannot be replaced by rename
	mkdir "$out/Blocked.csv" or die $!;
	open my $fh, '>', "$out/Blocked.csv/keep" or die $!;
	close $fh;
	my $guard2 = mdbtools_scenario(tables => ['Blocked']);
	($status, undef, $stderr) = export($db, output_dir => $out, overwrite => 1);
	is($status, $CONFIG{exit_failure}, 'rename failure');
	# The operating system's own reason: "Is a directory" on Unix,
	# "Permission denied" on Windows
	like($stderr, qr/^FAILED: Blocked: Cannot write \Q$out\E.Blocked\.csv: (?:\Q$OS{eisdir}\E|\Q$OS{eacces}\E) at /m, 'message with OS text');
	ticked('run: Cannot write');
};

subtest 'run: a program that cannot be started' => sub {
	# $? == -1 from run3: the program was found but never ran
	my ($dir, $db, $out) = workspace();
	my $guard = mock_scoped(
		"$CONFIG{exporter}::which" => sub { "$CONFIG{fake_bin}/$_[0]" },
		"$CONFIG{exporter}::run3"  => sub { $! = ENOENT; $? = -1; return 1 },
	);

t/unit.t  view on Meta::CPAN

	# POD pitfall: the export carries on, with one warning
	{
		package Local::BrokenLogger;
		sub new { return bless {}, shift }
		sub debug { die "log device gone\n" }
		sub info { die "log device gone\n" }
		sub warn { die "log device gone\n" }
	}
	my ($dir, $db, $out) = workspace();
	my $guard = mdbtools_scenario(tables => ['A', 'B']);
	my ($status, undef, $stderr) = export($db, output_dir => $out, logger => Local::BrokenLogger->new());
	is($status, $CONFIG{exit_ok}, 'exports unaffected');
	is(scalar(() = $stderr =~ /^Cannot write to the log: log device gone at /mg), 1, 'warned once');
	ticked('run: Cannot write to the log');
};

subtest 'run: table filter' => sub {
	my ($dir, $db, $out) = workspace();
	my $guard = mdbtools_scenario(tables => ['A', 'B', 'C']);

	my ($status, undef, $stderr) = export($db, output_dir => "$out/1", tables => ['C', 'A', 'nope', 'b']);
	is($status, $CONFIG{exit_ok}, 'unknown names are only a warning');
	ok(-e "$out/1/A.csv" && -e "$out/1/C.csv" && !-e "$out/1/B.csv", 'case-sensitive selection');
	like($stderr, qr/^Tables not found in database: b, nope at /m, 'plural message');

	(undef, undef, $stderr) = export($db, output_dir => "$out/2", tables => ['Z']);
	like($stderr, qr/^Table not found in database: Z at /m, 'singular message');
	ticked('run: Tables not found in database');

	# POD pitfall: an empty list exports nothing and returns 0
	($status) = export($db, output_dir => "$out/3", tables => []);
	is($status, $CONFIG{exit_ok}, 'empty list: 0');
	ok(!glob("$out/3/*.csv"), 'empty list: no files');
};

subtest 'run: dry run and row counts' => sub {
	my ($dir, $db, $out) = workspace();

t/unit.t  view on Meta::CPAN

	verbose_diag('dry run', $stdout);
	is($status, $CONFIG{exit_ok}, 'dry run: 0');
	ok(!-e $out, 'nothing created, not even the directory');
	like($stdout, qr/^DRY RUN\n=======$/m, 'title');
	like($stdout, qr/^TABLE\s+ROWS\s+OUTPUT FILE$/m, 'ROWS column');
	like($stdout, qr/^Orders\s+$CONFIG{row_count}\s+Orders\.csv$/m, 'row');

	# POD: show_counts without mdb-count warns and is switched off
	my $guard2 = mdbtools_scenario(tables => ['Orders'], missing => [$CONFIG{mdb_count}]);
	my $e = $CONFIG{exporter}->new(dry_run => 1, show_counts => 1, progress => 0);
	my $stderr;
	($stdout, $stderr) = capture { $status = $e->run($db) };
	is($status, $CONFIG{exit_ok}, 'still 0');
	like($stderr, qr/^mdb-count not found in PATH; row counts are unavailable at /m, 'warning');
	ticked('run: mdb-count not found in PATH');
	unlike($stdout, qr/ROWS/, 'no ROWS column');
	is($e->{show_counts}, 0, 'setting switched off, as documented');
};

subtest 'run: a row count that fails is only a warning' => sub {
	# POD: a failed count warns; an exported table still counts as
	# exported, and a dry run shows "?"
	my ($dir, $db, $out) = workspace();
	my $guard = mdbtools_scenario(tables => ['Orders']);
	my $scenario = \&App::Access2CSV::Exporter::run3;
	my $failing = mock_scoped("$CONFIG{exporter}::run3" => sub {
		return $scenario->(@_) unless $_[0][0] =~ /mdb-count\z/;
		${ $_[3] } = 'broken';
		$? = 1 << 8;
		return 1;
	});
	my ($status, undef, $stderr) = export($db, output_dir => $out, show_counts => 1);
	is($status, $CONFIG{exit_ok}, 'export: still 0');
	ok(-e "$out/Orders.csv", 'exported');
	like($stderr, qr/^Cannot count the rows of Orders: mdb-count failed with exit status 1: broken at /m, 'warning');
	ticked('run: Cannot count the rows of');

	my $stdout;
	($status, $stdout) = export($db, dry_run => 1, show_counts => 1);
	is($status, $CONFIG{exit_ok}, 'dry run: still 0');
	like($stdout, qr/^Orders\s+\?\s+Orders\.csv$/m, 'count shown as "?"');
};

subtest 'run: fatal errors croak before writing anything' => sub {
	my ($dir, $db, $out) = workspace();

t/unit.t  view on Meta::CPAN

	my $e = $CONFIG{exporter}->new(output_dir => $out, progress => 0);

	check_globals('run with a failure', sub { $e->run($db) });
	check_globals('new', sub { $CONFIG{exporter}->new(progress => 0) });
};

#######################################################################
# 3. App::Access2CSV::run
#######################################################################

# Run the program; return (status, stdout, stderr)
sub cli {
	my @argv = @_;
	my $status;
	my ($stdout, $stderr) = capture { $status = $CONFIG{app}->run(@argv) };
	return ($status, $stdout, $stderr);
}

subtest 'app: exit 0 for success, --help and --man' => sub {
	my ($dir, $db, $out) = workspace();
	my $guard = mdbtools_scenario(tables => ['Orders']);
	my $log = File::Spec->catfile($dir, 'a.log');
	my @made;
	my $lg = mock_scoped('Log::Abstraction::new' => sub { shift; push @made, {@_}; Local::Logger->new() });

	my ($status, $stdout, $stderr) = cli('--output-dir', $out, '--log', $log, $db);
	is($status, $CONFIG{exit_ok}, 'export: 0');
	returns_ok($status, { type => 'integer', min => 0, max => 3 }, 'Output schema');
	ticked('app: returns 0');
	ok(-e "$out/Orders.csv", 'file written');
	ok(-e $log, 'log file created');
	is(join(':', (stat $made[0]{logger}{fd})[0, 1]), join(':', (stat $log)[0, 1]), 'log goes to --log file');

	($status, $stdout) = cli('--help');
	is($status, $CONFIG{exit_ok}, '--help: 0');
	like($stdout, qr/Options:/, 'help on STDOUT');

t/unit.t  view on Meta::CPAN


	my ($status) = cli('--no-log', '--no-progress', '--output-dir', $out, $db);
	is($status, $CONFIG{exit_failure}, 'exit status 1');
	ticked('app: returns 1');
	ok(-e "$out/A.csv", 'the other table was exported');
};

subtest 'app: exit 2 for command-line errors' => sub {
	my ($dir, $db) = workspace();

	my ($status, $stdout, $stderr) = cli('--bogus', $db);
	is($status, $CONFIG{exit_usage}, 'unknown option');
	like($stderr, qr/^Unknown option: bogus$/m, 'message on STDERR');
	is($stdout, '', 'nothing on STDOUT');
	ticked('app: Unknown option');

	($status, undef, $stderr) = cli('--output-dir');
	is($status, $CONFIG{exit_usage}, 'missing value');
	like($stderr, qr/^Option output-dir requires an argument$/m, 'message');
	ticked('app: Option requires an argument');

	($status, undef, $stderr) = cli();
	is($status, $CONFIG{exit_usage}, 'no database');
	like($stderr, qr/^Missing database filename$/m, 'message');
	($status) = cli('a.accdb', 'b.accdb');
	is($status, $CONFIG{exit_usage}, 'two databases');
	ticked('app: Missing database filename');
	ticked('app: returns 2');
};

subtest 'app: exit 3 for fatal errors, as one clean line' => sub {
	my ($dir, $db) = workspace();
	my $missing = File::Spec->catfile($dir, 'missing.accdb');

	my ($status, $stdout, $stderr) = cli('--no-log', $missing);
	is($status, $CONFIG{exit_fatal}, 'missing database');
	is($stderr, "access2csv: Cannot read database $missing: $OS{enoent}\n", 'exact line');
	ticked('app: access2csv: MESSAGE');
	ticked('app: returns 3');

	(undef, undef, $stderr) = cli('--no-log', '--verbose', $missing);
	like($stderr, qr/\Aaccess2csv: Cannot read database .* at \S+ line \d+\.\n\z/, '--verbose adds file and line');

	my $log = File::Spec->catfile($dir, 'no', 'such', 'x.log');
	($status, undef, $stderr) = cli('--log', $log, $db);
	is($status, $CONFIG{exit_fatal}, 'log cannot be opened');
	is($stderr, "access2csv: Cannot open log file $log: $OS{enoent}\n", 'exact line');
	ticked('app: Cannot open log file');

	SKIP: {
		# Windows only allows symbolic links with extra privileges
		skip("cannot create a symbolic link here: $!", 2) unless eval { symlink("$dir/elsewhere", "$dir/link.log") };
		($status, undef, $stderr) = cli('--log', "$dir/link.log", $db);
		is($status, $CONFIG{exit_fatal}, 'log file is a symbolic link');
		is($stderr, "access2csv: Cannot open log file $dir/link.log: it is a symbolic link\n", 'exact reason');
	}
	ticked('app: it is a symbolic link');

	# Database "-": read from standard input, which is reopened here
	my $with_stdin = sub {
		my ($source, @argv) = @_;
		open my $saved, '<&', \*STDIN or die $!;
		open STDIN, '<', $source or die "$source: $!";
		my @result = cli(@argv);
		open STDIN, '<&', $saved or die $!;
		return @result;
	};
	($status, undef, $stderr) = $with_stdin->(File::Spec->devnull(), '--no-log', '-');
	is($status, $CONFIG{exit_fatal}, 'empty standard input');
	is($stderr, "access2csv: Standard input is empty: no database was piped in\n", 'exact message');
	ticked('app: Standard input is empty');

	SKIP: {
		# A directory as standard input opens but cannot be read on Unix.
		# Windows refuses to open a directory as a file at all, and offers no
		# other simple way to make reading standard input fail.
		skip('cannot make reading standard input fail on Windows', 2) if $^O eq 'MSWin32';
		($status, undef, $stderr) = $with_stdin->($dir, '--no-log', '-');
		is($status, $CONFIG{exit_fatal}, 'unreadable standard input (a directory)');
		is($stderr, "access2csv: Cannot read standard input: $OS{eisdir}\n", 'exact message');
	}
	ticked('app: Cannot read standard input');

	SKIP: {
		skip('IO::Pty is needed to provide a terminal', 2) unless eval { require IO::Pty; 1 };
		my $pty = IO::Pty->new();
		($status, undef, $stderr) = $with_stdin->($pty->ttyname(), '--no-log', '-');
		is($status, $CONFIG{exit_usage}, 'terminal on standard input: usage error');
		like($stderr, qr/^Standard input is a terminal: pipe the database in, or give its file name$/m, 'exact message');
	}
	ticked('app: Standard input is a terminal');

	SKIP: {
		# A stalled pipe; a child process then sends SIGTERM to this one.
		# On Windows, fork is emulated and kill 'TERM' ends the whole process
		# outright (there are no signal handlers to catch it), so this can
		# only be tested elsewhere.
		skip('signals cannot interrupt a read on Windows', 2) if $^O eq 'MSWin32';
		pipe(my $reader, my $writer) or die "pipe: $!";

t/unit.t  view on Meta::CPAN

			close $reader;
			syswrite($writer, "T\n");
			select(undef, undef, undef, $CONFIG{signal_delay});
			kill 'TERM', $parent;
			select(undef, undef, undef, $CONFIG{signal_delay});
			exit 0;
		}
		close $writer;
		open my $saved, '<&', \*STDIN or die $!;
		open STDIN, '<&', $reader or die $!;
		($status, undef, $stderr) = cli('--no-log', '-');
		open STDIN, '<&', $saved or die $!;
		waitpid($pid, 0);
		is($status, $CONFIG{exit_fatal}, 'interrupted while reading');
		is($stderr, "access2csv: Interrupted by SIGTERM while reading the database from standard input\n", 'exact message');
	}
	ticked('app: Interrupted while reading standard input');

	{
		# mdb-count answers, but not with a number: a warning, count "?"
		my $guard = mdbtools_scenario(tables => ['T']);
		my $scenario = \&App::Access2CSV::Exporter::run3;
		my $odd = mock_scoped("$CONFIG{exporter}::run3" => sub {
			return $scenario->(@_) unless $_[0][0] =~ /mdb-count\z/;
			${ $_[2] } = "no idea\n";
			${ $_[3] } = '';
			$? = 0;
			return 1;
		});
		my $out;
		($status, $out, $stderr) = cli('--no-log', '--dry-run', '--show-counts', $db);
		is($status, $CONFIG{exit_ok}, 'unreadable count: still 0');
		like($stderr, qr/^Cannot count the rows of T: mdb-count printed no number: "no idea\\x0A" at /m, 'exact message');
		like($out, qr/^T\s+\?\s+T\.csv$/m, 'count shown as "?"');
	}
	ticked('run: mdb-count printed no number');

	{
		my $lg = mock_scoped('Log::Abstraction::new' => sub { return });
		($status, undef, $stderr) = cli('--log', File::Spec->catfile($dir, 'y.log'), $db);
		is($status, $CONFIG{exit_fatal}, 'logger constructor returned nothing');
		like($stderr, qr/\Aaccess2csv: Cannot open log file .*: no logger was created\n\z/, 'exact reason');
		ticked('app: no logger was created');
	}

	($status, undef, $stderr) = cli('--no-log', '--encoding', 'ebcdic', $db);
	is($status, $CONFIG{exit_usage}, 'bad encoding is a usage error');
	like($stderr, qr/^Invalid setting: Parameter 'encoding' \(ebcdic\) must be one of utf8, utf8-bom, cp1252$/m, 'exact message');
	ticked('app: Invalid setting');

	my $version_out;
	($status, $version_out) = cli('--version');
	is($status, $CONFIG{exit_ok}, '--version: 0');
	is($version_out, "access2csv version $App::Access2CSV::VERSION\n", '--version: exact text');
	ticked('app: --version');
};

subtest 'app: does not change the caller\'s array or global state' => sub {



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