]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - t/14-callbacks.t
77fdd00d68105e0107588826b02b3bc35809df47
[perl/modules/Variable-Magic.git] / t / 14-callbacks.t
1 #!perl -T
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 17;
7
8 use Variable::Magic qw<wizard cast>;
9
10 my $wiz = eval { wizard get => sub { undef } };
11 is($@, '',             'wizard creation doesn\'t croak');
12 ok(defined $wiz,       'wizard is defined');
13 is(ref $wiz, 'SCALAR', 'wizard is a scalar ref');
14
15 my $n = int rand 1000;
16 my $a = $n;
17
18 my $res = eval { cast $a, $wiz };
19 is($@, '', 'cast doesn\'t croak');
20 ok($res,   'cast is valid');
21
22 my $x;
23 eval {
24  local $SIG{__WARN__} = sub { die };
25  $x = $a
26 };
27 is($@, '', 'callback returning undef doesn\'t warn/croak');
28 is($x, $n, 'callback returning undef fails');
29
30 {
31  my $c = 0;
32  sub X::wat { ++$c }
33  my $wiz = eval { wizard get => \'X::wat' };
34  is($@, '', 'wizard with a string callback doesn\'t croak');
35  my $b = $n;
36  my $res = eval { cast $b, $wiz };
37  is($@, '', 'cast a wizard with a string callback doesn\'t croak');
38  my $x;
39  eval {
40   local $SIG{__WARN__} = sub { die };
41   $x = $b;
42  };
43  is($@, '', 'string callback doesn\'t warn/croak');
44  is($c, 1,  'string callback is called');
45  is($x, $n, 'string callback returns the right thing');
46 }
47
48 my @callers;
49 $wiz = wizard get => sub {
50  my @c;
51  my $i = 0;
52  while (@c = caller $i++) {
53   push @callers, [ @c[0, 1, 2] ];
54  }
55 };
56
57 my $b;
58 cast $b, $wiz;
59
60 my $u = $b;
61 is_deeply(\@callers, [
62  ([ 'main', $0, __LINE__-2 ]) x 2,
63 ], 'caller into callback returns the right thing');
64
65 @callers = ();
66 $u = $b;
67 is_deeply(\@callers, [
68  ([ 'main', $0, __LINE__-2 ]) x 2,
69 ], 'caller into callback returns the right thing (second time)');
70
71 {
72  @callers = ();
73  my $u = $b;
74  is_deeply(\@callers, [
75   ([ 'main', $0, __LINE__-2 ]) x 2,
76  ], 'caller into callback into block returns the right thing');
77 }
78
79 @callers = ();
80 eval { my $u = $b };
81 is($@, '', 'caller into callback doesn\'t croak');
82 is_deeply(\@callers, [
83  ([ 'main', $0, __LINE__-3 ]) x 3,
84 ], 'caller into callback into eval returns the right thing');
85