]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - t/lib/Variable/Magic/TestWatcher.pm
Factor some test logic in a helper module
[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  my @ret = eval { $code->() };
46  is        $@,   '',   $prefix . $desc . ' doesn\'t croak';
47  is_deeply \%mg, $exp, $prefix . $desc . ' triggers magic correctly';
48  return @ret;
49 }
50
51 our $mg_end;
52
53 END {
54  if (defined $wiz) {
55   undef $wiz;
56   $mg_end = { } unless defined $mg_end;
57   is_deeply \%mg, $mg_end, $prefix . 'magic triggered at END time';
58  }
59 }
60
61 1;