App-Access2CSV

 view release on metacpan or  search on metacpan

t/function.t  view on Meta::CPAN

#!perl

# White-box tests: one or more subtests for every function, public and
# private, in each module under lib/, taken one module at a time:
#
#	1. App::Access2CSV::I18N
#	2. App::Access2CSV::Exporter
#	3. App::Access2CSV
#
# Strategy: each function is tested on its own.  The other functions it
# calls - in the same module or in non-core modules such as IPC::Run3,
# File::Which and Log::Abstraction - are replaced with Test::Mockingbird
# mocks, so a failure points at exactly one function.  Params::Get,
# Params::Validate::Strict and Return::Set are spied on rather than
# replaced, because validating arguments is part of each function's job.
#
# 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
$Sub::Private::BYPASS = 1;
$Sub::Protected::BYPASS = 1;

# Messages must be English whatever locale the tester uses
delete @ENV{qw(LANGUAGE LC_ALL LC_MESSAGES LANG)};

# Names and values shared by many subtests
Readonly::Hash my %CONFIG => (
	i18n          => 'App::Access2CSV::I18N',
	exporter      => 'App::Access2CSV::Exporter',
	app           => 'App::Access2CSV',
	database      => 'shop.accdb',
	table         => 'Orders',
	mdb_tables    => 'mdb-tables',
	mdb_export    => 'mdb-export',
	mdb_count     => 'mdb-count',
	fake_path     => '/opt/mdbtools/bin',
	exit_ok       => 0,
	exit_failure  => 1,
	exit_usage    => 2,
	exit_fatal    => 3,
	child_status  => 3,
	signal        => 15,
	row_count     => 42,
	pod_synopsis  => 0,
	pod_options   => 1,
	pod_full      => 2,
	utf8_bom      => "\xEF\xBB\xBF",
	sentinel      => "sentinel error\n",
	max_name_chars => 64,
	max_name_bytes => 240,
	name_max      => 255,
);

# The text Perl itself uses for ENOENT, in the current locale
Readonly::Scalar my $ENOENT_TEXT => do { local $! = ENOENT; "$!" };

# Show internal state, but only when asked to
sub verbose_diag {
	my ($label, $data) = @_;
	diag("$label: ", Test::More::explain($data)) if $ENV{TEST_VERBOSE};
	return;
}

# UTF-8 bytes of a character string, the form mdbtools gives names in
sub bytes {
	my $text = shift;
	utf8::encode($text);
	return $text;
}

t/function.t  view on Meta::CPAN

	is($e->_is_system_table($_), 1, "$_ is a system table") foreach qw(MSysObjects msysACEs USysRibbons ~TMPCLP1);
	is($e->_is_system_table($_), 0, "$_ is a user table") foreach ('Orders', 'MyMSys', 'Sys', 'User ~ table');
};

subtest 'Exporter::_select_tables applies the table filter' => sub {
	my @warned;
	my $guard = mock_scoped("$CONFIG{exporter}::_warn" => sub { shift; push @warned, [@_]; return });

	my $all = ['A', 'B', 'C'];
	is(new_exporter()->_select_tables($all), $all, 'no filter: same list');

	my $picked = new_exporter(tables => ['C', 'A', 'Nope', 'Nada'])->_select_tables($all);
	is_deeply($picked, ['A', 'C'], 'database order kept');
	is_deeply(\@warned, [['unknown_tables', { params => ['Nada, Nope'], count => 2 }]], 'unknown names warned, sorted, with count');

	@warned = ();
	new_exporter(tables => ['B'])->_select_tables($all);
	is_deeply(\@warned, [], 'no warning when all are found');
};

subtest 'Exporter::_make_output_dir creates the directory or croaks' => sub {
	my $dir = tempdir(CLEANUP => 1);

	# An existing directory must not even reach File::Path
	my $spy = spy("$CONFIG{exporter}::make_path");
	my $e = new_exporter(output_dir => $dir);
	is($e->_make_output_dir(), $e, 'existing directory: returns $self');
	is(scalar($spy->()), 0, 'make_path not called');
	restore_all();

	my $nested = File::Spec->catdir($dir, 'a', 'b');
	new_exporter(output_dir => $nested)->_make_output_dir();
	ok(-d $nested, 'nested directory created');

	# File::Path reports errors through its error option
	my $bad = File::Spec->catdir($dir, 'denied');
	my $guard = mock_scoped("$CONFIG{exporter}::make_path" => sub {
		my ($path, $opts) = @_;
		${ $opts->{error} } = [{ $path => 'Permission denied' }];
		return;
	});
	throws_ok { new_exporter(output_dir => $bad)->_make_output_dir() } qr/\ACannot create output directory \Q$bad\E: Permission denied at /, 'exact message';
};

subtest 'Exporter::_make_output_dir notices a directory that silently did not appear' => sub {
	my $bad = File::Spec->catdir(tempdir(CLEANUP => 1), 'ghost');
	my $guard = mock_scoped("$CONFIG{exporter}::make_path" => sub { ${ $_[1]{error} } = []; $! = ENOENT; return });
	throws_ok { new_exporter(output_dir => $bad)->_make_output_dir() } qr/\ACannot create output directory \Q$bad\E: \Q$ENOENT_TEXT\E at /, 'OS text used';
};

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] },
	);

	my @tables = ('A', 'B', 'C');
	my ($first) = each @tables;
	new_exporter()->_export_all($CONFIG{database}, \@tables);
	is_deeply(\@exported, ['A', 'B', 'C'], 'no table skipped');
};

subtest 'Exporter::_export_all leaves the caller\'s $@ alone' => sub {
	my $guard = mock_scoped($CONFIG{exporter},
		_export_table => sub { die "kaput\n" },
		_warn         => sub { $_[0] },
		_log          => sub { $_[0] },
	);

	# Build the object first: the constructor's own validation may reset $@
	my $e = new_exporter();
	local $@ = $CONFIG{sentinel};
	$e->_export_all($CONFIG{database}, ['A']);
	is($@, $CONFIG{sentinel}, '$@ localised');
};

# Export helpers write through _run_program into a file handle; this
# double does the same with fixed content
sub mock_export_output {
	my ($content, $calls) = @_;
	return ("$CONFIG{exporter}::_run_program" => sub {
		my ($self, $name, $args, $fh) = @_;
		push @{$calls}, [$name, $args] if $calls;
		print {$fh} $content;
		$fh->flush();
		return $self;
	});
}

subtest 'Exporter::_export_table writes the data through a temporary file' => sub {
	my $dir = tempdir(CLEANUP => 1);
	my (@calls, %installed, @logged);

	my $guard = mock_scoped(
		mock_export_output("\"id\"\n1\n", \@calls),
		"$CONFIG{exporter}::_csv_filename" => sub { "$_[1].csv" },
		"$CONFIG{exporter}::_install_file" => sub {
			my ($self, $tmp, $out) = @_;
			open my $fh, '<:raw', $tmp->filename() or die $!;
			local $/;
			%installed = (content => scalar(<$fh>), out => $out, tmp => $tmp->filename());
			return $self;
		},
		"$CONFIG{exporter}::_log" => sub { shift; push @logged, [@_]; $_[0] },
	);

t/function.t  view on Meta::CPAN

subtest 'Exporter::_install_file renames into place with normal permissions' => sub {
	my $dir = tempdir(CLEANUP => 1);
	my $outfile = File::Spec->catfile($dir, 'out.csv');
	my $e = new_exporter(output_dir => $dir);

	my $old_umask = umask(oct(22));
	{
		my $tmp = File::Temp->new(DIR => $dir, UNLINK => 1);
		print {$tmp} "data\n";
		local $@ = $CONFIG{sentinel};
		is($e->_install_file($tmp, $outfile), $e, 'returns $self');
		is($@, $CONFIG{sentinel}, '$@ localised');
		ok(!-e $tmp->filename(), 'temporary name gone');
	}
	umask($old_umask);

	ok(-f $outfile, 'still there after the temporary object is destroyed');

	# Whatever the platform, the result is an ordinary file the user can
	# read and write (File::Temp's own files are private, mode 0600)
	ok(-r $outfile && -w $outfile, 'readable and writable');

	SKIP: {
		# Windows has no Unix permission bits: stat() makes the mode up from
		# the read-only flag (0666 for any writable file) and umask has no
		# effect, so the exact bits can only be checked elsewhere
		skip('Unix permission bits do not exist on Windows', 1) if $^O eq 'MSWin32';
		is((stat($outfile))[2] & oct(777), oct(644), '0666 less umask 022');
	}
};

subtest 'Exporter::_install_file croaks with the OS reason on failure' => sub {
	my $dir = tempdir(CLEANUP => 1);
	my $outfile = File::Spec->catfile($dir, 'no', 'such', 'dir', 'out.csv');
	my $tmp = File::Temp->new(DIR => $dir, UNLINK => 1);

	throws_ok { new_exporter()->_install_file($tmp, $outfile) } qr/\ACannot write \Q$outfile\E: \Q$ENOENT_TEXT\E at /, 'exact message';
};

subtest 'Exporter::_count_rows reads the number from mdb-count' => sub {
	my ($output, @calls) = ("  $CONFIG{row_count}\n");
	my $guard = mock_scoped("$CONFIG{exporter}::_run_program" => sub {
		push @calls, [$_[1], $_[2]];
		${ $_[3] } = $output;
		return $_[0];
	});

	my $rows = new_exporter()->_count_rows($CONFIG{database}, $CONFIG{table});
	is($rows, $CONFIG{row_count}, 'number parsed despite whitespace');
	returns_ok($rows, { type => 'integer', min => 0 }, 'an integer');
	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();
	$e->{programs} = { $CONFIG{mdb_export} => program_path($CONFIG{mdb_export}) };
	my $stdout = '';
	is($e->_run_program($CONFIG{mdb_export}, [$CONFIG{database}, 'Or; rm -rf /'], \$stdout), $e, 'returns $self');
	verbose_diag('run3 call', \@calls);

	is_deeply($calls[0][0], [program_path($CONFIG{mdb_export}), $CONFIG{database}, 'Or; rm -rf /'], 'command as a list');
	is(${ $calls[0][1] }, undef, 'stdin is empty');
	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();
	$e->{programs} = { $CONFIG{mdb_export} => program_path($CONFIG{mdb_export}) };
	my $guard = mock_scoped(mock_run3(0, ''));

	local $? = $CONFIG{child_status} << 8;
	open my $in, '<', \"a\nb\n" or die $!;
	<$in>;
	$e->_run_program($CONFIG{mdb_export}, [], \my $out);
	is($? >> 8, $CONFIG{child_status}, '$? localised');
	is($., 1, '$. still refers to the caller\'s handle');
};

subtest 'Exporter::_csv_filename makes safe, unique names' => sub {
	# The full matrix is in t/filename-collision.t; these are the rules
	my $e = new_exporter();
	is($e->_csv_filename('A/B'), 'A_B.csv', 'unsafe character');
	is($e->_csv_filename('a:b'), 'a_b_2.csv', 'case-insensitive collision');
	is($e->_csv_filename('A_B_2'), 'A_B_2_2.csv', 'suffix cannot collide with a real name');
	is($e->_csv_filename('NUL'), '_NUL.csv', 'device name');
	is($e->_csv_filename(' .x. '), '_x.csv', 'trim, no hidden file, no trailing dot');
	is($e->_csv_filename(undef), 'unnamed.csv', 'undef');
	is_deeply([sort keys %{ $e->{used_names} }], [sort map { lc } qw(A_B.csv a_b_2.csv A_B_2_2.csv _NUL.csv _x.csv unnamed.csv)], 'all names recorded in lower case');
	returns_ok($e->_csv_filename('z'), { type => 'string', matches => qr/\.csv\z/ }, 'a .csv name');
};

subtest 'Exporter::_csv_filename replaces bad bytes, shortens long names, then trims the end' => sub {
	my $e = new_exporter();
	my $max = $CONFIG{max_name_chars};
	is($e->_csv_filename(('a' x ($max - 1)) . ' bc'), ('a' x ($max - 1)) . '.csv', 'space left at the cut is removed');
	is($e->_csv_filename(('b' x ($max - 1)) . '.c'), ('b' x ($max - 1)) . '.csv', 'dot left at the cut is removed');
	is($e->_csv_filename("Caf\xE9 \xC3"), 'Caf_ _.csv', 'bytes that are not UTF-8 replaced');
	is($e->_csv_filename(('c' x ($max - 1)) . "\xFF\xFF"), ('c' x ($max - 1)) . '_.csv', 'replaced before shortening');
};

subtest 'Exporter::_shorten_name keeps whole graphemes within both limits' => sub {
	my $e = new_exporter();
	my $max = $CONFIG{max_name_chars};

	is($e->_shorten_name('a' x $max), 'a' x $max, 'at the limit: unchanged');
	is($e->_shorten_name('a' x ($max + 1)), 'a' x $max, 'one over: cut');

	# Characters in, characters out (and bytes in, bytes out)
	my $chars = "\x{fc}" x $CONFIG{name_max};
	utf8::upgrade($chars);    # below U+0100, Perl would otherwise keep it as bytes
	my $short = $e->_shorten_name($chars);
	ok(utf8::is_utf8($short), 'character string stays a character string');
	is($short, "\x{fc}" x $max, 'counted in characters, not bytes');

	my $bytes = $chars;
	utf8::encode($bytes);
	$short = $e->_shorten_name($bytes);

t/function.t  view on Meta::CPAN

	is_deeply(\@usage, [[$CONFIG{exit_ok}, $CONFIG{pod_full}]], 'full manual');

	my $result;
	warning_like { $result = $parse->('--bogus', $CONFIG{database}) } qr/Unknown option: bogus/, 'Getopt::Long warns';
	is($result, $CONFIG{exit_usage}, 'bad option');
	is_deeply(\@usage, [[$CONFIG{exit_usage}, $CONFIG{pod_synopsis}]], 'synopsis only');

	is($parse->(), $CONFIG{exit_usage}, 'no database');
	is_deeply(\@usage, [[$CONFIG{exit_usage}, $CONFIG{pod_synopsis}, 'Missing database filename']], 'with a message');
	is($parse->('a', 'b'), $CONFIG{exit_usage}, 'two databases');
};

subtest 'App::_usage calls Pod::Usage without exiting' => sub {
	my @calls;
	my $guard = mock_scoped("$CONFIG{app}::pod2usage" => sub { push @calls, {@_}; return });

	is($CONFIG{app}->_usage($CONFIG{exit_ok}, $CONFIG{pod_options}), $CONFIG{exit_ok}, 'returns the status');
	is($calls[0]{-exitval}, 'NOEXIT', 'never exits');
	is($calls[0]{-verbose}, $CONFIG{pod_options}, 'verbosity');
	is($calls[0]{-output}, \*STDOUT, 'help goes to STDOUT');
	like($calls[0]{-input}, qr/Access2CSV\.pm\z/, 'POD read from the module');
	ok(!exists $calls[0]{-message}, 'no message');

	$CONFIG{app}->_usage($CONFIG{exit_usage}, $CONFIG{pod_synopsis}, 'why');
	is($calls[1]{-output}, \*STDERR, 'errors go to STDERR');
	is($calls[1]{-message}, 'why', 'message passed');
};

subtest 'App::_make_logger opens the log only when wanted' => sub {
	my $dir = tempdir(CLEANUP => 1);
	my @created;
	my $guard = mock_scoped('Log::Abstraction::new' => sub { shift; push @created, {@_}; bless {}, 'Local::Logger' });

	is($CONFIG{app}->_make_logger({ log => undef }), undef, 'undef: no log');
	is($CONFIG{app}->_make_logger({ log => '' }), undef, 'empty: no log');
	is(scalar(@created), 0, 'Log::Abstraction not called');

	my $file = File::Spec->catfile($dir, 'x.log');
	local $@ = $CONFIG{sentinel};
	isa_ok($CONFIG{app}->_make_logger({ log => $file }), 'Local::Logger');
	is($@, $CONFIG{sentinel}, '$@ localised');
	ok(-e $file, 'file created up front');
	is_deeply([sort keys %{$created[0]}], [qw(level logger)], 'only logger and level given');
	is($created[0]{level}, 'info', 'info level');
	is_deeply([keys %{$created[0]{logger}}], ['fd'], 'logger is a handle, not a file name');
	my $fd = $created[0]{logger}{fd};
	ok(defined fileno($fd), 'handle is open');
	is(join(':', (stat $fd)[0, 1]), join(':', (stat $file)[0, 1]), 'handle is on the log file');
	ok($fd->autoflush(), 'each line is written at once');

	$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();



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