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