Doit
view release on metacpan or search on metacpan
#!/usr/bin/perl -w
# -*- cperl -*-
#
# Author: Slaven Rezic
#
use Doit;
use Doit::Util 'new_scope_cleanup';
use File::Glob 'bsd_glob';
use File::Temp 'tempdir';
use Test::More;
sub slurp ($) { open my $fh, shift or die $!; local $/; <$fh> }
sub slurp_utf8 ($) { open my $fh, shift or die $!; binmode $fh, ':encoding(utf-8)'; local $/; <$fh> }
return 1 if caller;
require FindBin;
{ no warnings 'once'; push @INC, $FindBin::RealBin; }
require TestUtil;
sub no_leftover_tmp ($;$) {
my($tmp_dir, $tmp_suffix) = @_;
$tmp_suffix = '.tmp' if !defined $tmp_suffix;
local $Test::Builder::Level = $Test::Builder::Level + 1;
my @files = bsd_glob("$tmp_dir/*$tmp_suffix");
is_deeply \@files, [], "no temporary file left-overs with suffix $tmp_suffix in $tmp_dir";
}
plan 'no_plan';
my $doit = Doit->init;
$doit->add_component('file');
my $doit_dryrun = do {
local @ARGV = '--dry-run';
Doit->init;
};
ok $doit_dryrun->is_dry_run, 'created dry-run Doit object';
# Accidentally it's not required to call add_component('file') here,
# as the add_component calls affect the class, not the object.
my $tempdir = tempdir('doit_XXXXXXXX', TMPDIR => 1, CLEANUP => 1);
$doit->mkdir("$tempdir/another_tmp");
{
eval { $doit->file_atomic_write };
like $@, qr{file parameter is missing}i, "too few params";
}
{
eval { $doit->file_atomic_write("$tempdir/1st") };
like $@, qr{code parameter is missing}i, "too few params";
ok !-e "$tempdir/1st", "file was not created";
}
{
eval { $doit->file_atomic_write("$tempdir/1st", "not a sub") };
like $@, qr{code parameter should be an anonymous subroutine or subroutine reference}i, "wrong type";
ok !-e "$tempdir/1st", "file was not created";
}
{
eval { $doit->file_atomic_write("$tempdir/1st", sub { }, does_not_exist => 1) };
like $@, qr{unhandled option}i, "unhandled option error";
ok !-e "$tempdir/1st", "file was not created";
}
{
eval { $doit->file_atomic_write("$tempdir/1st", sub { die "something failed" }) };
like $@, qr{something failed}i, "exception in code";
ok !-e "$tempdir/1st", "file was not created";
no_leftover_tmp $tempdir;
}
{ # This should be the first test case creating the new file
$doit->create_file_if_nonexisting("$tempdir/stat_reference");
is $doit->file_atomic_write("$tempdir/1st", sub {
my $fh = shift;
binmode $fh, ':encoding(utf-8)';
print $fh "\x{20ac}uro\n";
}), 1;
ok -s "$tempdir/1st", 'Created file exists and is non-empty';
is slurp_utf8("$tempdir/1st"), "\x{20ac}uro\n", 'expected content';
my(@stat_reference) = stat("$tempdir/stat_reference");
my(@stat_atomic_write) = stat("$tempdir/1st");
is $stat_atomic_write[4], $stat_reference[4], 'expected owner on initial creation';
is $stat_atomic_write[5], $stat_reference[5], 'expected group on initial creation';
is(($stat_atomic_write[2] & 07777), ($stat_reference[2] & 07777), 'expected mode on initial creation');
no_leftover_tmp $tempdir;
}
( run in 0.710 second using v1.01-cache-2.11-cpan-ad19def0cd9 )