PageRenderTime 44ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/t/lib/Test/Warn.pm

https://github.com/gjuggler/bioperl-live
Perl | 487 lines | 405 code | 82 blank | 0 comment | 39 complexity | 7a562730a84899202b07ee2fb0609348 MD5 | raw file
  1. =head1 NAME
  2. Test::Warn - Perl extension to test methods for warnings
  3. =head1 SYNOPSIS
  4. use Test::Warn;
  5. warning_is {foo(-dri => "/")} "Unknown Parameter 'dri'", "dri != dir gives warning";
  6. warnings_are {bar(1,1)} ["Width very small", "Height very small"];
  7. warning_is {add(2,2)} undef, "No warning to calc 2+2"; # or
  8. warnings_are {add(2,2)} [], "No warning to calc 2+2"; # what reads better :-)
  9. warning_like {foo(-dri => "/")} qr/unknown param/i, "an unknown parameter test";
  10. warnings_like {bar(1,1)} [qr/width.*small/i, qr/height.*small/i];
  11. warning_is {foo()} {carped => "didn't found the right parameters"};
  12. warnings_like {foo()} [qr/undefined/,qr/undefined/,{carped => qr/no result/i}];
  13. warning_like {foo(undef)} 'uninitialized';
  14. warning_like {bar(file => '/etc/passwd')} 'io';
  15. warning_like {eval q/"$x"; $x;/}
  16. [qw/void uninitialized/],
  17. "some warnings at compile time";
  18. =head1 DESCRIPTION
  19. This module provides a few convenience methods for testing warning based code.
  20. If you are not already familiar with the Test::More manpage
  21. now would be the time to go take a look.
  22. =head2 FUNCTIONS
  23. =over 4
  24. =item warning_is BLOCK STRING, TEST_NAME
  25. Tests that BLOCK gives exactly the one specificated warning.
  26. The test fails if the BLOCK warns more then one times or doesn't warn.
  27. If the string is undef,
  28. then the tests succeeds iff the BLOCK doesn't give any warning.
  29. Another way to say that there aren't ary warnings in the block,
  30. is C<warnings_are {foo()} [], "no warnings in">.
  31. If you want to test for a warning given by carp,
  32. You have to write something like:
  33. C<warning_is {carp "msg"} {carped =E<gt> 'msg'}, "Test for a carped warning">.
  34. The test will fail,
  35. if a "normal" warning is found instead of a "carped" one.
  36. Note: C<warn "foo"> would print something like C<foo at -e line 1>.
  37. This method ignores everything after the at. That means, to match this warning
  38. you would have to call C<warning_is {warn "foo"} "foo", "Foo succeeded">.
  39. If you need to test for a warning at an exactly line,
  40. try better something like C<warning_like {warn "foo"} qr/at XYZ.dat line 5/>.
  41. warning_is and warning_are are only aliases to the same method.
  42. So you also could write
  43. C<warning_is {foo()} [], "no warning"> or something similar.
  44. I decided me to give two methods to have some better readable method names.
  45. A true value is returned if the test succeeds, false otherwise.
  46. The test name is optional, but recommended.
  47. =item warnings_are BLOCK ARRAYREF, TEST_NAME
  48. Tests to see that BLOCK gives exactly the specificated warnings.
  49. The test fails if the BLOCK warns a different number than the size of the ARRAYREf
  50. would have expected.
  51. If the ARRAYREF is equal to [],
  52. then the test succeeds iff the BLOCK doesn't give any warning.
  53. Please read also the notes to warning_is as these methods are only aliases.
  54. If you want more than one tests for carped warnings look that way:
  55. C<warnings_are {carp "c1"; carp "c2"} {carped => ['c1','c2'];> or
  56. C<warnings_are {foo()} ["Warning 1", {carped => ["Carp 1", "Carp 2"]}, "Warning 2"]>.
  57. Note that C<{carped => ...}> has always to be a hash ref.
  58. =item warning_like BLOCK REGEXP, TEST_NAME
  59. Tests that BLOCK gives exactly one warning and it can be matched to the given regexp.
  60. If the string is undef,
  61. then the tests succeeds iff the BLOCK doesn't give any warning.
  62. The REGEXP is matched after the whole warn line,
  63. which consists in general of "WARNING at __FILE__ line __LINE__".
  64. So you can check for a warning in at File Foo.pm line 5 with
  65. C<warning_like {bar()} qr/at Foo.pm line 5/, "Testname">.
  66. I don't know whether it's sensful to do such a test :-(
  67. However, you should be prepared as a matching with 'at', 'file', '\d'
  68. or similar will always pass.
  69. Think to the qr/^foo/ if you want to test for warning "foo something" in file foo.pl.
  70. You can also write the regexp in a string as "/.../"
  71. instead of using the qr/.../ syntax.
  72. Note that the slashes are important in the string,
  73. as strings without slashes are reserved for warning categories
  74. (to match warning categories as can be seen in the perllexwarn man page).
  75. Similar to C<warning_is>,
  76. you can test for warnings via C<carp> with:
  77. C<warning_like {bar()} {carped => qr/bar called too early/i};>
  78. Similar to C<warning_is>/C<warnings_are>,
  79. C<warning_like> and C<warnings_like> are only aliases to the same methods.
  80. A true value is returned if the test succeeds, false otherwise.
  81. The test name is optional, but recommended.
  82. =item warning_like BLOCK STRING, TEST_NAME
  83. Tests whether a BLOCK gives exactly one warning of the passed category.
  84. The categories are grouped in a tree,
  85. like it is expressed in perllexwarn.
  86. Note, that they have the hierarchical structure from perl 5.8.0,
  87. wich has a little bit changed to 5.6.1 or earlier versions
  88. (You can access the internal used tree with C<$Test::Warn::Categorization::tree>,
  89. allthough I wouldn't recommend it)
  90. Thanks to the grouping in a tree,
  91. it's simple possible to test for an 'io' warning,
  92. instead for testing for a 'closed|exec|layer|newline|pipe|unopened' warning.
  93. Note, that warnings occuring at compile time,
  94. can only be catched in an eval block. So
  95. warning_like {eval q/"$x"; $x;/}
  96. [qw/void uninitialized/],
  97. "some warnings at compile time";
  98. will work,
  99. while it wouldn't work without the eval.
  100. Note, that it isn't possible yet,
  101. to test for own categories,
  102. created with warnings::register.
  103. =item warnings_like BLOCK ARRAYREF, TEST_NAME
  104. Tests to see that BLOCK gives exactly the number of the specificated warnings
  105. and all the warnings have to match in the defined order to the
  106. passed regexes.
  107. Please read also the notes to warning_like as these methods are only aliases.
  108. Similar to C<warnings_are>,
  109. you can test for multiple warnings via C<carp>
  110. and for warning categories, too:
  111. warnings_like {foo()}
  112. [qr/bar warning/,
  113. qr/bar warning/,
  114. {carped => qr/bar warning/i},
  115. 'io'
  116. ],
  117. "I hope, you'll never have to write a test for so many warnings :-)";
  118. =back
  119. =head2 EXPORT
  120. C<warning_is>,
  121. C<warnings_are>,
  122. C<warning_like>,
  123. C<warnings_like> by default.
  124. =head1 BUGS
  125. Please note that warnings with newlines inside are making a lot of trouble.
  126. The only sensful way to handle them is to use are the C<warning_like> or
  127. C<warnings_like> methods. Background for these problems is that there is no
  128. really secure way to distinguish between warnings with newlines and a tracing
  129. stacktrace.
  130. If a method has it's own warn handler,
  131. overwriting C<$SIG{__WARN__}>,
  132. my test warning methods won't get these warnings.
  133. The C<warning_like BLOCK CATEGORY, TEST_NAME> method isn't extremely tested.
  134. Please use this calling style with higher attention and
  135. tell me if you find a bug.
  136. =head1 TODO
  137. Improve this documentation.
  138. The code has some parts doubled - especially in the test scripts.
  139. This is really awkward and has to be changed.
  140. Please feel free to suggest me any improvements.
  141. =head1 SEE ALSO
  142. Have a look to the similar L<Test::Exception> module. Test::Trap
  143. =head1 THANKS
  144. Many thanks to Adrian Howard, chromatic and Michael G. Schwern,
  145. who have given me a lot of ideas.
  146. =head1 AUTHOR
  147. Janek Schleicher, E<lt>bigj AT kamelfreund.deE<gt>
  148. =head1 COPYRIGHT AND LICENSE
  149. Copyright 2002 by Janek Schleicher
  150. This library is free software; you can redistribute it and/or modify
  151. it under the same terms as Perl itself.
  152. =cut
  153. package Test::Warn;
  154. use 5.006;
  155. use strict;
  156. use warnings;
  157. use Array::Compare;
  158. use Sub::Uplevel 0.12;
  159. our $VERSION = '0.11';
  160. require Exporter;
  161. our @ISA = qw(Exporter);
  162. our %EXPORT_TAGS = ( 'all' => [ qw(
  163. @EXPORT
  164. ) ] );
  165. our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
  166. our @EXPORT = qw(
  167. warning_is warnings_are
  168. warning_like warnings_like
  169. );
  170. use Test::Builder;
  171. my $Tester = Test::Builder->new;
  172. *warning_is = *warnings_are;
  173. sub warnings_are (&$;$) {
  174. my $block = shift;
  175. my @exp_warning = map {_canonical_exp_warning($_)}
  176. _to_array_if_necessary( shift() || [] );
  177. my $testname = shift;
  178. my @got_warning = ();
  179. local $SIG{__WARN__} = sub {
  180. my ($called_from) = caller(0); # to find out Carping methods
  181. push @got_warning, _canonical_got_warning($called_from, shift());
  182. };
  183. uplevel 1,$block;
  184. my $ok = _cmp_is( \@got_warning, \@exp_warning );
  185. $Tester->ok( $ok, $testname );
  186. $ok or _diag_found_warning(@got_warning),
  187. _diag_exp_warning(@exp_warning);
  188. return $ok;
  189. }
  190. *warning_like = *warnings_like;
  191. sub warnings_like (&$;$) {
  192. my $block = shift;
  193. my @exp_warning = map {_canonical_exp_warning($_)}
  194. _to_array_if_necessary( shift() || [] );
  195. my $testname = shift;
  196. my @got_warning = ();
  197. local $SIG{__WARN__} = sub {
  198. my ($called_from) = caller(0); # to find out Carping methods
  199. push @got_warning, _canonical_got_warning($called_from, shift());
  200. };
  201. uplevel 1,$block;
  202. my $ok = _cmp_like( \@got_warning, \@exp_warning );
  203. $Tester->ok( $ok, $testname );
  204. $ok or _diag_found_warning(@got_warning),
  205. _diag_exp_warning(@exp_warning);
  206. return $ok;
  207. }
  208. sub _to_array_if_necessary {
  209. return (ref($_[0]) eq 'ARRAY') ? @{$_[0]} : ($_[0]);
  210. }
  211. sub _canonical_got_warning {
  212. my ($called_from, $msg) = @_;
  213. my $warn_kind = $called_from eq 'Carp' ? 'carped' : 'warn';
  214. my @warning_stack = split /\n/, $msg; # some stuff of uplevel is included
  215. return {$warn_kind => $warning_stack[0]}; # return only the real message
  216. }
  217. sub _canonical_exp_warning {
  218. my ($exp) = @_;
  219. if (ref($exp) eq 'HASH') { # could be {carped => ...}
  220. my $to_carp = $exp->{carped} or return; # undefined message are ignored
  221. return (ref($to_carp) eq 'ARRAY') # is {carped => [ ..., ...] }
  222. ? map({ {carped => $_} } grep {defined $_} @$to_carp)
  223. : +{carped => $to_carp};
  224. }
  225. return {warn => $exp};
  226. }
  227. sub _cmp_got_to_exp_warning {
  228. my ($got_kind, $got_msg) = %{ shift() };
  229. my ($exp_kind, $exp_msg) = %{ shift() };
  230. return 0 if ($got_kind eq 'warn') && ($exp_kind eq 'carped');
  231. my $cmp = $got_msg =~ /^\Q$exp_msg\E at \S+ line \d+\.?$/;
  232. return $cmp;
  233. }
  234. sub _cmp_got_to_exp_warning_like {
  235. my ($got_kind, $got_msg) = %{ shift() };
  236. my ($exp_kind, $exp_msg) = %{ shift() };
  237. return 0 if ($got_kind eq 'warn') && ($exp_kind eq 'carped');
  238. if (my $re = $Tester->maybe_regex($exp_msg)) {
  239. my $cmp = $got_msg =~ /$re/;
  240. return $cmp;
  241. } else {
  242. return Test::Warn::Categorization::warning_like_category($got_msg,$exp_msg);
  243. }
  244. }
  245. sub _cmp_is {
  246. my @got = @{ shift() };
  247. my @exp = @{ shift() };
  248. scalar @got == scalar @exp or return 0;
  249. my $cmp = 1;
  250. $cmp &&= _cmp_got_to_exp_warning($got[$_],$exp[$_]) for (0 .. $#got);
  251. return $cmp;
  252. }
  253. sub _cmp_like {
  254. my @got = @{ shift() };
  255. my @exp = @{ shift() };
  256. scalar @got == scalar @exp or return 0;
  257. my $cmp = 1;
  258. $cmp &&= _cmp_got_to_exp_warning_like($got[$_],$exp[$_]) for (0 .. $#got);
  259. return $cmp;
  260. }
  261. sub _diag_found_warning {
  262. foreach (@_) {
  263. if (ref($_) eq 'HASH') {
  264. ${$_}{carped} ? $Tester->diag("found carped warning: ${$_}{carped}")
  265. : $Tester->diag("found warning: ${$_}{warn}");
  266. } else {
  267. $Tester->diag( "found warning: $_" );
  268. }
  269. }
  270. $Tester->diag( "didn't found a warning" ) unless @_;
  271. }
  272. sub _diag_exp_warning {
  273. foreach (@_) {
  274. if (ref($_) eq 'HASH') {
  275. ${$_}{carped} ? $Tester->diag("expected to find carped warning: ${$_}{carped}")
  276. : $Tester->diag("expected to find warning: ${$_}{warn}");
  277. } else {
  278. $Tester->diag( "expected to find warning: $_" );
  279. }
  280. }
  281. $Tester->diag( "didn't expect to find a warning" ) unless @_;
  282. }
  283. package Tree::MyDAG_Node;
  284. use strict;
  285. use warnings;
  286. use base 'Tree::DAG_Node';
  287. sub nice_lol_to_tree {
  288. my $class = shift;
  289. $class->new(
  290. {
  291. name => shift(),
  292. daughters => [_nice_lol_to_daughters(shift())]
  293. });
  294. }
  295. sub _nice_lol_to_daughters {
  296. my @names = @{ shift() };
  297. my @daughters = ();
  298. my $last_daughter = undef;
  299. foreach (@names) {
  300. if (ref($_) ne 'ARRAY') {
  301. $last_daughter = Tree::DAG_Node->new({name => $_});
  302. push @daughters, $last_daughter;
  303. } else {
  304. $last_daughter->add_daughters(_nice_lol_to_daughters($_));
  305. }
  306. }
  307. return @daughters;
  308. }
  309. sub depthsearch {
  310. my ($self, $search_name) = @_;
  311. my $found_node = undef;
  312. $self->walk_down({callback => sub {
  313. my $node = shift();
  314. $node->name eq $search_name and $found_node = $node,!"go on";
  315. "go on with searching";
  316. }});
  317. return $found_node;
  318. }
  319. package Test::Warn::Categorization;
  320. use Carp;
  321. our $tree = Tree::MyDAG_Node->nice_lol_to_tree(
  322. all => [ 'closure',
  323. 'deprecated',
  324. 'exiting',
  325. 'glob',
  326. 'io' => [ 'closed',
  327. 'exec',
  328. 'layer',
  329. 'newline',
  330. 'pipe',
  331. 'unopened'
  332. ],
  333. 'misc',
  334. 'numeric',
  335. 'once',
  336. 'overflow',
  337. 'pack',
  338. 'portable',
  339. 'recursion',
  340. 'redefine',
  341. 'regexp',
  342. 'severe' => [ 'debugging',
  343. 'inplace',
  344. 'internal',
  345. 'malloc'
  346. ],
  347. 'signal',
  348. 'substr',
  349. 'syntax' => [ 'ambiguous',
  350. 'bareword',
  351. 'digit',
  352. 'parenthesis',
  353. 'precedence',
  354. 'printf',
  355. 'prototype',
  356. 'qw',
  357. 'reserved',
  358. 'semicolon'
  359. ],
  360. 'taint',
  361. 'threads',
  362. 'uninitialized',
  363. 'unpack',
  364. 'untie',
  365. 'utf8',
  366. 'void',
  367. 'y2k'
  368. ]
  369. );
  370. sub _warning_category_regexp {
  371. my $sub_tree = $tree->depthsearch(shift()) or return undef;
  372. my $re = join "|", map {$_->name} $sub_tree->leaves_under;
  373. return qr/(?=\w)$re/;
  374. }
  375. sub warning_like_category {
  376. my ($warning, $category) = @_;
  377. my $re = _warning_category_regexp($category) or
  378. carp("Unknown warning category '$category'"),return undef;
  379. my $ok = $warning =~ /$re/;
  380. return $ok;
  381. }
  382. 1;