LanX has asked for the wisdom of the Perl Monks concerning the following question:
My colleague came up with a question regarding a very special case of unit testing and I'm not sure how to answer it.
My response was the clean approach is to refactor the code into additional subs called from the "printers" returning the data structures and test those nested "units".
Obviously the code would be easier to maintain and reusable.
The advantage is that every code conditioned by ... if TEST won't show up in production code.
Here a condensed demo in a single file, the output of B::Deparse shows that the TEST code disappears. (In a real test.t file the "PKG::TEST" flag has to be set before requiring the module PKG to be effective)
Question Is there a better way to do this?
# set TEST flag before compiling tested module use constant 'PKG::TEST' => 1; # ### here normally use PKG { package PKG; use strict; use warnings; use Data::Dump qw/pp dd/; use v5.16; sub create_output { my $count =shift; my $string; my $fh; my %hash; # create (mildly) complex demo HoA $hash{$_} = [reverse 1.. $count--] for "a".."f"; # memorize datastructure when testing $PKG::TEST_result = \%hash if TEST; my $target = "c:/tmp/output.txt"; # redirect filehande to string when testing $target = \$PKG::TEST_content if TEST; open $fh, '>', $target; # Output to "file" print $fh pp \%hash; } } # ### my tests package main; use B::Deparse; use Data::Dump qw/pp dd/; # prove that TEST code disappears unless TEST is true print B::Deparse->new->coderef2text(\&PKG::create_output); PKG::create_output(5); if ( PKG::TEST ) { use Test::More; my $expected ={ a => [5, 4, 3, 2, 1], b => [4, 3, 2, 1], c => [3, 2, 1], d => [2, 1], e => [1], f => [], }; is_deeply( $PKG::TEST_result, $expected, "internal result" ); my $expected_str = pp $expected; is( $PKG::TEST_content, $expected_str, "file output" ); done_testing(); }
The problems I see:
Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery
FootballPerl is like chess, only without the dice
*) a case were inlining would be nice, more about that in a future post
added comments to code
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: "deep" unit testing
by stevieb (Canon) on Mar 27, 2019 at 20:43 UTC | |
by LanX (Saint) on Mar 27, 2019 at 20:46 UTC | |
by stevieb (Canon) on Mar 27, 2019 at 20:52 UTC | |
by LanX (Saint) on Mar 27, 2019 at 20:58 UTC | |
by stevieb (Canon) on Mar 28, 2019 at 02:21 UTC | |
| |
|
Re: "deep" unit testing
by haukex (Archbishop) on Mar 28, 2019 at 20:33 UTC | |
by LanX (Saint) on Mar 28, 2019 at 22:28 UTC |