]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - t/25-copy.t
04ed1c95fbd65d64a904c26a6498fc8c3ef7d7d0
[perl/modules/Variable-Magic.git] / t / 25-copy.t
1 #!perl -T
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7
8 use Variable::Magic qw<cast dispell>;
9
10 plan tests => 2 + ((2 * 5 + 3) + (2 * 2 + 1)) + (2 * 9 + 6) + 1;
11
12 use lib 't/lib';
13 use Variable::Magic::TestWatcher;
14 use Variable::Magic::TestValue;
15
16 my $wiz = init_watcher 'copy', 'copy';
17
18 SKIP: {
19  my $has_tie_array = do { local $@; eval { require Tie::Array; 1 } };
20  skip 'Tie::Array required to test copy magic on arrays'
21                              => (2 * 5 + 3) + (2 * 2 + 1) unless $has_tie_array;
22  defined and diag "Using Tie::Array $_" for $Tie::Array::VERSION;
23
24  tie my @a, 'Tie::StdArray';
25  @a = (1 .. 10);
26
27  my $res = watch { cast @a, $wiz } { }, 'cast on tied array';
28  ok $res, 'copy: cast on tied array succeeded';
29
30  watch { $a[3] = 13 } { copy => 1 }, 'tied array store';
31
32  my $s = watch { $a[3] } { copy => 1 }, 'tied array fetch';
33  is $s, 13, 'copy: tied array fetch correctly';
34
35  $s = watch { exists $a[3] } { copy => 1 }, 'tied array exists';
36  ok $s, 'copy: tied array exists correctly';
37
38  watch { undef @a } { }, 'tied array undef';
39
40  {
41   tie my @val, 'Tie::StdArray';
42   @val = (4 .. 6);
43
44   my $wv = init_value @val, 'copy', 'copy';
45
46   value { $val[3] = 8 } [ 4 .. 6 ];
47
48   dispell @val, $wv;
49   is_deeply \@val, [ 4 .. 6, 8 ], 'copy: value after';
50  }
51 }
52
53 SKIP: {
54  my $has_tie_hash = do { local $@; eval { require Tie::Hash; 1 } };
55  skip 'Tie::Hash required to test copy magic on hashes'
56                                               => 2 * 9 + 6 unless $has_tie_hash;
57  defined and diag "Using Tie::Hash $_" for $Tie::Hash::VERSION;
58
59  tie my %h, 'Tie::StdHash';
60  %h = (a => 1, b => 2, c => 3);
61
62  my $res = watch { cast %h, $wiz } { }, 'cast on tied hash';
63  ok $res, 'copy: cast on tied hash succeeded';
64
65  watch { $h{b} = 7 } { copy => 1 }, 'tied hash store';
66
67  my $s = watch { $h{c} } { copy => 1 }, 'tied hash fetch';
68  is $s, 3, 'copy: tied hash fetch correctly';
69
70  $s = watch { exists $h{a} } { copy => 1 }, 'tied hash exists';
71  ok $s, 'copy: tied hash exists correctly';
72
73  $s = watch { delete $h{b} } { copy => 1 }, 'tied hash delete';
74  is $s, 7, 'copy: tied hash delete correctly';
75
76  watch { my ($k, $v) = each %h } { copy => 1 }, 'tied hash each';
77
78  my @k = watch { keys %h } { }, 'tied hash keys';
79  is_deeply [ sort @k ], [ qw<a c> ], 'copy: tied hash keys correctly';
80
81  my @v = watch { values %h } { copy => 2 }, 'tied hash values';
82  is_deeply [ sort { $a <=> $b } @v ], [ 1, 3 ], 'copy: tied hash values correctly';
83
84  watch { undef %h } { }, 'tied hash undef';
85 }