elTriberium has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I don't know if this a bug or a feature but die_on_fail of the Test::Most CPAN module doesn't exactly do what I would expect (and want) it to do. Please have a look at this short example test:
#!/usr/bin/perl use Test::Most tests => 3; die_on_fail; ok(1==2, "checkpoint 1"); lives_ok ( sub { print "checkpoint 2\n"; }, "lives_ok test" ); ok(1==1, "checkpoint 3");
Test 1 obviously fails, so I want it to exit the test immediately. But it still executes the subroutine of the 2nd test before exiting. Here is the program output:
-bash:perl$ perl dieonfail.pl 1..3 not ok 1 - checkpoint 1 # Failed test 'checkpoint 1' # at dieonfail.pl line 6. checkpoint 2 Test failed. Stopping test. # Looks like you planned 3 tests but only ran 1. # Looks like you failed 1 test of 1 run. # Looks like your test died just after 1.
It doesn't execute test 3, so die_on_fail is working, but it still enters the subroutine of test 2. Is there any way to keep it from running the subroutine if test 1 failed? I can of course always manually enter "|| or die" after each test, but I would prefer something automated like the "die_on_fail" option.

Replies are listed 'Best First'.
Re: die_on_fail of Test::Most only dies after the next test
by ELISHEVA (Prior) on May 21, 2009 at 21:41 UTC

    Test::Most implements die_on_fail by checking the result from the last run test before it runs the next. Therefore the die doesn't happen immediately. Rather it waits until your second call to ok. Then it dies before it runs the test. Any code between the two calls to ok gets executed.

    You can see this for yourself by looking at the source code for Test::Most (see the link on the upper left side of the page). When you open the source code page scroll down to the definition of die_on_fail. That function is simply a wrapper around set_failure_handler. set_failure_handler simply redefines Test::Builder::ok to save the result from each test and then check it the next time a test is run.

    Best, beth

    Update: fixed typo as noted below in reply, and one additional typo (s/Test::More::ok/Test::Builder::ok/).

      Thanks, I think you mean Test::Most instead of Test::More (die_on_fail is not defined in Test::More), but I understand what you mean. There's also a note that I can write my own failure_handler, although I'm currently not sure how to get it to die immediately. I'll play around a bit with it.