2010-01-12 54 views
5

我有以下Perl代碼:爲什麼Perl的eval從Test :: Cmd :: Common-> unlink捕獲問題?

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([email protected], "file unlike"); 

print "done.\n"; 

的$測試 - >取消鏈接()線將失敗,並拋出異常。但問題是:eval不處理該異常並且代碼執行被中斷。

輸出:

$ 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. 

是EVAL在這裏做合適的工作?或者我誤解了一些東西?

F.

回答

11

從測試:: Cmd的常見::文檔的「刪除指定文件退出NO的結果,如果任何文件不能以任何理由被刪除。」。並通過查看源,測試:: Cmd的::俗稱的Test :: CMD-> no_result,這確實

exit (2); 

「退出」不能被EVAL被困,所以它是預期的行爲。

+0

未經檢驗的,但如何'*測試:: Cmd的:: no_result = {子死'沒有結果'}'? – jrockway

1

這是略正交的,但如果你想測試,如果操作「成功」或死亡,使用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';