]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - t/lib/Variable/Magic/TestWatcher.pm
Report file/line of failures correctly
[perl/modules/Variable-Magic.git] / t / lib / Variable / Magic / TestWatcher.pm
1 package Variable::Magic::TestWatcher;
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7
8 use Carp qw/croak/;
9 use Variable::Magic qw/wizard/;
10
11 use base qw/Exporter/;
12
13 our @EXPORT = qw/init check/;
14
15 sub _types {
16  my $t = shift;
17  return { } unless defined $t;
18  return {
19   ''      => sub { +{ $t => 1 } },
20   'ARRAY' => sub { my $h = { }; ++$h->{$_} for @$t; $h },
21   'HASH'  => sub { +{ map { $_ => $t->{$_} } grep $t->{$_}, keys %$t } }
22  }->{ref $t}->();
23 }
24
25 our ($wiz, $prefix, %mg);
26
27 sub init ($;$) {
28  croak 'can\'t initialize twice' if defined $wiz;
29  my $types = _types shift;
30  $prefix   = (defined) ? "$_: " : '' for shift;
31  %mg  = ();
32  $wiz = eval 'wizard ' . join(', ', map {
33   "$_ => sub { \$mg{$_}++;" . ($_ eq 'len' ? '$_[2]' : '0') . '}'
34  } keys %$types);
35  is        $@,   '',  $prefix . 'wizard() doesn\'t croak';
36  is_deeply \%mg, { }, $prefix . 'wizard() doesn\'t trigger magic';
37  return $wiz;
38 }
39
40 sub check (&;$$) {
41  my $code = shift;
42  my $exp  = _types shift;
43  my $desc = shift;
44  local %mg = ();
45  local $Test::Builder::Level = ($Test::Builder::Level || 0) + 1;
46  my @ret = eval { $code->() };
47  is        $@,   '',   $prefix . $desc . ' doesn\'t croak';
48  is_deeply \%mg, $exp, $prefix . $desc . ' triggers magic correctly';
49  return @ret;
50 }
51
52 our $mg_end;
53
54 END {
55  if (defined $wiz) {
56   undef $wiz;
57   $mg_end = { } unless defined $mg_end;
58   is_deeply \%mg, $mg_end, $prefix . 'magic triggered at END time';
59  }
60 }
61
62 1;