]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - t/28-uvar.t
Allow editing the key SV in uvar callbacks by passing a new option 'copy_key'
[perl/modules/Variable-Magic.git] / t / 28-uvar.t
1 #!perl -T
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7
8 use Variable::Magic qw/wizard cast dispell VMG_UVAR/;
9
10 if (VMG_UVAR) {
11  plan tests => 2 * 10 + 8 + 14 + 1;
12 } else {
13  plan skip_all => 'No nice uvar magic for this perl';
14 }
15
16 use lib 't/lib';
17 use Variable::Magic::TestWatcher;
18
19 my $wiz = init [ qw/fetch store exists delete/ ], 'uvar';
20
21 my %h = (a => 1, b => 2, c => 3);
22
23 my $res = check { cast %h, $wiz } { }, 'cast';
24 ok $res, 'uvar: cast succeeded';
25
26 my $x;
27
28 check { $x = $h{a} } { fetch => 1 }, 'fetch directly';
29 is $x, 1, 'uvar: fetch directly correctly';
30
31 check { $x = "$h{b}" } { fetch => 1 }, 'fetch by interpolation';
32 is $x, 2, 'uvar: fetch by interpolation correctly';
33
34 check { $h{c} = 4 } { store => 1 }, 'store directly';
35
36 check { $x = $h{c} = 5 } { store => 1 }, 'fetch and store';
37 is $x, 5, 'uvar: fetch and store correctly';
38
39 check { $x = exists $h{c} } { exists => 1 }, 'exists';
40 ok $x, 'uvar: exists correctly';
41
42 check { $x = delete $h{c} } { delete => 1 }, 'delete existing key';
43 is $x, 5, 'uvar: delete existing key correctly';
44
45 check { $x = delete $h{z} } { delete => 1 }, 'delete non-existing key';
46 ok !defined $x, 'uvar: delete non-existing key correctly';
47
48 my $wiz2 = wizard get => sub { 0 };
49 cast %h, $wiz2;
50
51 check { $x = $h{a} } { fetch => 1 }, 'fetch directly with also non uvar magic';
52 is $x, 1, 'uvar: fetch directly with also non uvar magic correctly';
53
54 $wiz2 = wizard fetch => sub { 0 };
55 my %h2 = (a => 37, b => 2, c => 3);
56 cast %h2, $wiz2;
57
58 eval {
59  local $SIG{__WARN__} = sub { die };
60  $x = $h2{a};
61 };
62 is $@, '', 'uvar: fetch with incomplete magic doesn\'t croak';
63 is $x, 37, 'uvar: fetch with incomplete magic correctly';
64
65 eval {
66  local $SIG{__WARN__} = sub { die };
67  $h2{a} = 73;
68 };
69 is $@, '',     'uvar: store with incomplete magic doesn\'t croak';
70 is $h2{a}, 73, 'uvar: store with incomplete magic correctly';
71
72 my $wiz3 = wizard store => sub { ++$_[2]; 0 }, copy_key => 1;
73 my %h3 = (a => 3);
74 cast %h3, $wiz3;
75
76 for my $i (1 .. 2) {
77  my $key = 'a';
78  eval { $h3{$key} = 3 + $i };
79  is        $@,   '',  "uvar: change key in store doesn't croak ($i)";
80  is        $key, 'a', "uvar: change key didn't clobber \$key ($i)";
81  is_deeply \%h3, { a => 3, b => 3 + $i },
82                       "uvar: change key in store correcty ($i)";
83 }
84
85 for my $i (1 .. 2) {
86  eval { $h3{b} = 5 + $i };
87  is $@, '',                    "uvar: change readonly key in store croaks ($i)";
88  is_deeply \%h3, { a => 3, b => 5, c => 5 + $i },
89                              "uvar: change readonly key in store correcty ($i)";
90 }