1 package autovivification::TestCases;
10 *{caller().'::testcase_ok'} = \&testcase_ok;
13 sub in_strict { (caller 0)[8] & (eval { strict::bits(@_) } || 0) };
17 sub set_arg { $_[0] = 1 }
20 my ($var, $init, $code, $exp, $use, $opts, $global) = @_;
21 my $decl = $global ? "our $var; local $var;" : "my $var;";
22 my $test = $var =~ /^[@%]/ ? "\\$var" : $var;
23 my $desc = join('; ', map { my $x = $_; $x=~ s,;\s*$,,; $x }
24 grep /\S/, $decl, $init, $code) . " <$opts>";
25 return <<TESTCASE, $desc;
28 my \$strict = autovivification::TestCases::in_strict('refs');
31 local \$SIG{__WARN__} = sub { die join '', 'warn:', \@_ };
36 like \$@, \$exp[0], \$desc . ' [exception]';
38 is \$@, \$exp[0], \$desc . ' [exception]';
40 is_deeply \$res, \$exp[1], \$desc . ' [return]';
41 is_deeply $test, \$exp[2], \$desc . ' [variable]';
49 my @chunks = split /#+/, "$_ ";
50 s/^\s+//, s/\s+$// for @chunks;
51 my ($init, $code, $exp, $opts) = @chunks;
53 (my $var = $init) =~ s/[^\$@%\w].*//;
54 $init = $var eq $init ? '' : "$init;";
57 for (split ' ', $opts) {
59 $no = 0 if s/^([-+])// and $1 eq '-';
60 $use .= ($no ? 'no' : 'use') . " autovivification '$_';"
62 } elsif (defined $opts) {
64 $use = 'no autovivification;';
70 my @base = ([ $var, $init, $code, $exp, $use ]);
72 my ($name) = $var =~ /^\$(.*)/;
74 my @oldderef = @{$base[0]};
75 $oldderef[2] =~ s/\Q$var\E\->/\$$var/g;
76 push @base, \@oldderef;
78 my @nonref = @{$base[0]};
79 $nonref[0] = $sigil . $name;
80 for ($nonref[1], $nonref[2]) {
81 s/\@\Q$var\E([\[\{])/\@$name$1/g;
82 s/\Q$sigil$var\E/$nonref[0]/g;
85 my $simple = $nonref[2] !~ /->/;
86 my $plain_deref = $nonref[2] =~ /\Q$nonref[0]\E/;
87 my $empty = { '@' => '[ ]', '%' => '{ }' }->{$sigil};
89 and ( $nonref[3] =~ m!qr/\^Reference vivification forbidden.*?/!
90 or $nonref[3] =~ m!qr/\^Can't vivify reference.*?/!))
92 and $nonref[3] =~ m!qr/\^Can't use an undefined value as a.*?/!)) {
95 $nonref[3] = "'', 1, $empty";
97 $nonref[3] =~ s/,\s*undef\s*$/, $empty/;
101 my @testcases = map {
102 my ($var, $init, $code, $exp, $use) = @$_;
103 [ $var, $init, $code, $exp, $use, $opts, 0 ],
104 [ $var, "use strict; $init", $code, $exp, $use, $opts, 1 ],
105 [ $var, "no strict; $init", $code, $exp, $use, $opts, 1 ],
109 my ($testcase, $desc) = generate(@$_);
112 diag "== This testcase failed to compile ==\n$testcase\n## Reason: $@" if $@;