Add methods wrap_code_ref and wrap_code_refs_within
[p5sagit/p5-mst-13.2.git] / dist / Safe / t / safesort.t
CommitLineData
9d5fa2fe 1#!perl -w
576b33a1 2$|=1;
3BEGIN {
576b33a1 4 require Config; import Config;
5 if ($Config{'extensions'} !~ /\bOpcode\b/ && $Config{'osname'} ne 'VMS') {
6 print "1..0\n";
7 exit 0;
8 }
9}
10
11use Safe 1.00;
fda8057a 12use Test::More tests => 10;
576b33a1 13
14my $safe = Safe->new('PLPerl');
15$safe->permit_only(qw(:default sort));
16
32f28238 17# check basic argument passing and context for anon-subs
18my $func = $safe->reval(q{ sub { @_ } });
19is_deeply [ $func->() ], [ ];
20is_deeply [ $func->("foo") ], [ "foo" ];
21
27c4ce72 22my $func1 = $safe->reval(<<'EOS');
576b33a1 23
24 # uses quotes in { "$a" <=> $b } to avoid the optimizer replacing the block
25 # with a hardwired comparison
32f28238 26 { package Pkg; sub p_sort { return sort { "$a" <=> $b } @_; } }
27 sub l_sort { return sort { "$a" <=> $b } @_; }
576b33a1 28
32f28238 29 return sub { return join(",",l_sort(@_)), join(",",Pkg::p_sort(@_)) }
576b33a1 30
31EOS
32
33is $@, '', 'reval should not fail';
34is ref $func, 'CODE', 'reval should return a CODE ref';
35
27c4ce72 36# $func1 will work in non-threaded perl
37# but RT#60374 "Safe.pm sort {} bug with -Dusethreads"
38# means the sorting won't work unless we wrap the code ref
39# such that it's executed with Safe 'in effect' at runtime
40my $func2 = $safe->wrap_code_ref($func1);
41
42my ($l_sorted, $p_sorted) = $func2->(3,1,2);
576b33a1 43is $l_sorted, "1,2,3";
44is $p_sorted, "1,2,3";
2630fd9e 45
46# check other aspects of closures created inside Safe
47
48my $die_func = $safe->reval(q{ sub { die @_ if @_; 1 } });
49
50# check $@ not affected by successful call
51$@ = 42;
52$die_func->();
53is $@, 42, 'successful closure call should not alter $@';
54
fda8057a 55{
56 my $warns = 0;
57 local $SIG{__WARN__} = sub { $warns++ };
58 ok !eval { $die_func->("died\n"); 1 }, 'should die';
59 is $@, "died\n", '$@ should be set correctly';
60 local $TODO = "Shouldn't warn";
61 is $warns, 0;
62}