Test :: No longer knows if the test is dying - so how can I check?

I am collecting a bunch of routines that are common to a bunch of my scripts in a module. (I should have done this before, but started with legacy scripts.) I model my work on a very useful example here using Test :: More and Module :: Build

All routines that read or write from files include the line open() or die "errmsg" . I am in the process of writing a test for a module and ran into this problem. One of the routines checks whether the path points to something or not, dies on error. In legacy scripts, the routine is as follows:

 sub checkExist { my ($type, $path) = @_; if ($type eq 'd') { if (! -d $path) { warn("dir not found: $path\n"); die $pathNotFound; } } elsif ($type eq 'f') { if (! -f $path) { warn("file not found: $path\n"); die $pathNotFound; } elsif (! -s $path) { warn("empty file: $path\n"); die $emptyFile; } } } 

Now, I am testing this with the following line:

 is(HomeBrew::IO::checkExist('f', $0), '', "can checkExist find file $0 ?"); 

which works fine if I do not choose a path that does not exist, in which case the test script dies, but the test succeeds , producing the following output:

 # Looks like your test exited with 2 just after 5. Dubious, test returned 2 (wstat 512, 0x200) All 5 subtests passed 

I would prefer this to be an unsuccessful test (rather than a dubious pass), but since this is obsolete code, I also want this routine to stop execution on error. What to do? Is it stupid to write a function test, is it simple?

I already wrote a checkExist2 function, which I will use in the future, which returns undef if the non-zero error completes successfully (so I can write die if checkExist2() elsewhere). Other suggestions that do not support checkExist functionality are welcome.

+7
module perl testing
source share
2 answers

The correct way to check if the code is alive or is able with the correct error, with Test :: Exception . You can port this test to other test cases, as it just takes coderef:

 use Test::More; use Test::Exception; lives_ok { is(HomeBrew::IO::checkExist('f', $0), '', "can checkExist find file $0 ?") } '...and code does not die'; 
+16
source share

Why don't you have a helper routine in the test module that wraps the call to eval{} around HomeBrew::IO::checkExist and checks for a failure via $@ ?

 sub runcheckExist { my $res = eval { HomeBrew::IO::checkExist('f', $0) }; # May want more logic here # for checking $@ for specific error text pattern # or $res return $@ ? 1 : 0; } my $expect_to_die = 1; is(runcheckExist(), $expect_to_die, "can checkExist find file $0 ?"); 
+2
source share

All Articles