]> git.vpit.fr Git - perl/modules/Lexical-Types.git/blob - t/22-magic.t
Test magical tags
[perl/modules/Lexical-Types.git] / t / 22-magic.t
1 #!perl -T
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7
8 BEGIN {
9  plan skip_all => 'Variable::Magic required to test magic'
10                                       unless eval "use Variable::Magic; 1";
11 }
12
13 {
14  package Lexical::Types::Test::Str;
15
16  use Variable::Magic qw/wizard cast/;
17
18  our $wiz;
19  BEGIN {
20   $wiz = wizard data => sub { +{ } },
21                 get  => sub { ++$_[1]->{get}; () },
22                 set  => sub { ++$_[1]->{set}; () };
23  }
24  
25  sub TYPEDSCALAR { cast $_[1], $wiz, $_[2]; () }
26 }
27
28 { package Str; }
29
30 BEGIN {
31  plan tests => 2 * 8;
32 }
33
34 use Lexical::Types as => 'Lexical::Types::Test';
35
36 sub check (&$$;$) {
37  my $got = Variable::Magic::getdata($_[1], $Lexical::Types::Test::Str::wiz);
38  my ($test, $exp, $desc) = @_[0, 2, 3];
39  my $want = wantarray;
40  my @ret;
41  {
42   local @{$got}{qw/get set/}; delete @{$got}{qw/get set/};
43   if ($want) {
44    @ret = eval { $test->() };
45   } elsif (defined $want) {
46    $ret[0] = eval { $test->() };
47   } else {
48    eval { $test->() };
49   }
50   is_deeply $got, $exp, $desc;
51  }
52  return $want ? @ret : $ret[0];
53 }
54
55 sub zzz {
56  my $d = Variable::Magic::getdata($_[0], $Lexical::Types::Test::Str::wiz);
57  isnt $d,    undef,  'typed lexicals are tagged';
58  is ref($d), 'HASH', 'typed lexicals are correctly tagged';
59 }
60
61 for (1 .. 2) {
62  my Str $x = "abc";
63
64  my $y = check { "$x" } $x, { get => 1 }, 'interpolate';
65  is $y, 'abc', 'interpolate correctly';
66
67  check { $x .= "foo" } $x, { get => 1, set => 1 }, 'append';
68  is $x, 'abcfoo', 'append correctly';
69
70  my Str $z;
71  check { $z = "bar" . $x } $z, { set => 1 }, 'scalar assign';
72  is $z, 'barabcfoo', 'scalar assign correctly';
73
74  zzz($z);
75 }