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

I'm trying to start using the test harness (test::more) for the first time and I'm having what appears to me to be a strange test failure. The test fails on a for loop (if I take out the for loop it no longer fails). This happens even if I don't have the for loop do anything. The original function looks like:

sub parse { my ($self, $file_name) = @_; $self->{'_xbrl_file'} = $file_name; if ( -e $self->{'_xbrl_file'}) { my $parser = XML::LibXML->new(); my $dom = $parser->load_xml( location => $self->{'_xbrl_file'} +); #Deal with the contexts my @context_nodes = $dom->findnodes('/xbrli:xbrl/xbrli:context +'); foreach my $node (@context_nodes) { &add_context($self, $node); } } else { croak "$file_name doesn't exist"; } }

The test looks like:

ok($xbrl->parse($incoming_file));

In order to trouble shoot, I added some print statements (to a file) which results in the following code:

sub parse { my ($self, $file_name) = @_; $self->{'_xbrl_file'} = $file_name; if ( -e $self->{'_xbrl_file'}) { my $parser = XML::LibXML->new(); my $dom = $parser->load_xml( location => $self->{'_xbrl_file'} +); #Deal with the contexts my @context_nodes = $dom->findnodes('/xbrli:xbrl/xbrli:context +'); open(FH, ">junk.txt") or croak "can't open junk.txt"; foreach my $node (@context_nodes) { print FH $node->toString(); # &add_context($self, $node); } close FH; } else { croak "$file_name doesn't exist"; } }
Changing the code so it writes out to file (and the file does in fact exist with the appropriate entries) causes the test to pass. I'm completely stumped and the usual sources (man Test::Tutorial) don't seem to cover this. Any help would be greatly appreciated. Thanks!

Replies are listed 'Best First'.
Re: Test::More fails on foreach loop
by chromatic (Archbishop) on Mar 16, 2011 at 19:24 UTC

    What does parse() return?

    I'm not being flippant; ok() expects a boolean. If the method returns something which coerces to a true value, that test assertion will pass.

    If you want to continue to use the ok() assertion, make the method return a boolean value in all normal cases.

    Update: I posted before I wrote what I really want to write: in the absence of an explicit return, the method will perform an implicit return of the last expression evaluated. Sometimes that's okay, but in this case it's not what you want.

      Ok. Returning 1 fixed the issue. Thanks for helping me understand.
        Not really. Now you have a test that can't possibly fail. You want
        # Not ok if parse throws an exception. ok(eval { $xbrl->parse($incoming_file); 1 });
Re: Test::More fails on foreach loop
by ikegami (Patriarch) on Mar 16, 2011 at 20:04 UTC

    What do you think your parse function returns?

    Update: Oops, replying in stale window.