]> git.vpit.fr Git - perl/modules/Sub-Prototype-Util.git/blob - t/12-recall.t
Don't import Scalar::Util::set_prototype()
[perl/modules/Sub-Prototype-Util.git] / t / 12-recall.t
1 #!perl -T
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 8 + 20 + (("$]" >= 5.010) ? 4 : 0);
7
8 use Scalar::Util;
9 use Sub::Prototype::Util qw<recall>;
10
11 sub exception {
12  my ($msg) = @_;
13  $msg =~ s/\s+/\\s+/g;
14  return qr/^$msg.*?at\s+\Q$0\E\s+line\s+\d+/;
15 }
16
17 eval { recall undef };
18 like $@, exception('No subroutine'), 'recall undef croaks';
19 eval { recall '' };
20 like $@, exception('No subroutine'), 'recall "" croaks';
21 eval { recall \1 };
22 like $@, exception('Unhandled SCALAR'), 'recall scalarref croaks';
23 eval { recall [ ] };
24 like $@, exception('Unhandled ARRAY'), 'recall arrayref croaks';
25 eval { recall sub { } };
26 like $@, exception('Unhandled CODE'), 'recall coderef croaks';
27 eval { recall { 'foo' => undef, 'bar' => undef } };
28 like $@, qr!exactly\s+one\s+key/value\s+pair!,
29                                            'recall hashref with 2 pairs croaks';
30 eval { recall 'hlagh' };
31 like $@, qr/^Undefined\s+subroutine/, 'recall <unknown> croaks';
32 eval { recall 'for' };
33 like $@, exception('syntax error'), 'invalid eval code croaks';
34
35 sub noproto { $_[1], $_[0] }
36 sub mytrunc ($;$) { $_[1], $_[0] }
37 sub mygrep1 (&@) { grep { $_[0]->() } @_[1 .. $#_] }
38 sub mygrep2 (\&@) { grep { $_[0]->() } @_[1 .. $#_] }
39 sub modify ($) { my $old = $_[0]; $_[0] = 5; $old }
40
41 my $t = [ 1, 2, 3, 4 ];
42 my $m = [ sub { $_ + 10 }, 1 .. 5 ];
43 my $g = [ sub { $_ > 2 }, 1 .. 5 ];
44
45 my @tests = (
46  [ 'main::noproto', 'no prototype', $t, $t, [ 2, 1 ] ],
47  [ { 'main::noproto' => undef }, 'no prototype forced', $t, $t, [ 2, 1 ] ],
48  [ 'CORE::push', 'push', [ [ 1, 2 ], 3, 5 ], [ [ 1, 2, 3, 5 ], 3, 5 ], [ 4 ] ],
49  [ { 'CORE::push' => '\@$' }, 'push just one', [ [ 1, 2 ], 3, 5 ], [ [ 1, 2, 3 ], 3, 5 ], [ 3 ] ],
50  [ { 'CORE::map' => '\&@' }, 'map', $m, $m, [ 11 .. 15 ] ],
51  [ 'main::mytrunc', 'truncate 1', [ 1 ], [ 1 ], [ undef, 1 ] ],
52  [ 'main::mytrunc', 'truncate 2', $t, $t, [ 2, 1 ] ],
53  [ 'main::mygrep1', 'grep1', $g, $g, [ 3 .. 5 ] ],
54  [ 'main::mygrep2', 'grep2', $g, $g, [ 3 .. 5 ] ],
55  [ 'main::modify', 'modify arguments', [ 1 ], [ 5 ], [ 1 ] ],
56 );
57
58 sub myit { push @{$_[0]->[2]}, 3; return 4 };
59 if ("$]" >= 5.010) {
60  Scalar::Util::set_prototype(\&myit, '_');
61  push @tests, [ 'main::myit', '_ with argument',
62                 [ [ 1, 2, [ ] ], 5 ],
63                 [ [ 1, 2, [ 3 ] ], 5 ],
64                 [ 4 ]
65               ];
66  push @tests, [ 'main::myit', '_ with no argument', [ ], [ 3 ], [ 4 ] ];
67 }
68
69 for (@tests) {
70  my $r = [ recall $_->[0], @{$_->[2]} ];
71  is_deeply($r, $_->[4], $_->[1] . ' return value');
72  is_deeply($_->[2], $_->[3], $_->[1] . ' arguments modification');
73 }