Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Perl's eval catch problems from Test::Cmd::Common->unlink?

Tags:

perl

eval

I have the following perl code :

use strict;
use warnings;
use Test::Cmd::Common;

my $path = "/something/not/available";
my $test = Test::Cmd::Common->new(string => 'File system operations');

eval{
        $test->unlink("$path");
};
ok(!$@, "file unlike");

print "done.\n";

The $test->unlink() line will fail and throw exception. but the problem : eval is not handling that exception and the code execution is being interrupted.

the output :

$ perl test.pl 
could not unlink files (/something/not/available): No such file or directory
NO RESULT for test at line 561 of /home/y/lib/perl5/site_perl/5.8/Test/Cmd/Common.pm (Test::Cmd::Common::unlink)
    from line 9 of test.pl.

Is eval doing the right job here? or I am misunderstanding something?

F.

like image 874
Firas Avatar asked Jan 12 '10 10:01

Firas


2 Answers

From documentation of Test::Cmd::Common: "Removes the specified files. Exits NO RESULT if any file could not be removed for any reason.". And by looking at source, Test::Cmd::Common calls Test::Cmd->no_result, which really does

exit (2);

"exit" cannot be trapped by eval, so it is expected behavior.

like image 122
Alexandr Ciornii Avatar answered Nov 01 '22 05:11

Alexandr Ciornii


This is slightly orthogonal, but if you want to test if an operation "succeeded" or died, use Test::Exception:

use strict;
use warnings;
use Test::More tests => 2;
use Test::Exception;

note 'File system operations';
dies_ok
    { some_operation_which_may_die(); }
    'operation died';

throws_ok
    { some_operation_which_may_die(); }
    /String we expect to see on death/,
    'operation died with expected message';
like image 35
Ether Avatar answered Nov 01 '22 05:11

Ether