Move base from ext/ to dist/
[p5sagit/p5-mst-13.2.git] / dist / base / t / fields.t
1 #!/usr/bin/perl -w
2
3 my $Has_PH;
4 BEGIN {
5     $Has_PH = $] < 5.009;
6 }
7
8 use strict;
9 use Test::More tests => 16;
10
11 BEGIN { use_ok('fields'); }
12
13
14 package Foo;
15
16 use fields qw(_no Pants who _up_yours);
17 use fields qw(what);
18
19 sub new { fields::new(shift) }
20 sub magic_new { bless [] }  # Doesn't 100% work, perl's problem.
21
22 package main;
23
24 is_deeply( [sort keys %Foo::FIELDS], 
25            [sort qw(_no Pants who _up_yours what)]
26 );
27
28 sub show_fields {
29     my($base, $mask) = @_;
30     no strict 'refs';
31     my $fields = \%{$base.'::FIELDS'};
32     return grep { ($fields::attr{$base}[$fields->{$_}] & $mask) == $mask} 
33                 keys %$fields;
34 }
35
36 is_deeply( [sort &show_fields('Foo', fields::PUBLIC)],
37            [sort qw(Pants who what)]);
38 is_deeply( [sort &show_fields('Foo', fields::PRIVATE)],
39            [sort qw(_no _up_yours)]);
40
41 # We should get compile time failures field name typos
42 eval q(my Foo $obj = Foo->new; $obj->{notthere} = "");
43
44 like $@, qr/^No such .*field "notthere"/i;
45
46
47 foreach (Foo->new) {
48     my Foo $obj = $_;
49     my %test = ( Pants => 'Whatever', _no => 'Yeah',
50                  what  => 'Ahh',      who => 'Moo',
51                  _up_yours => 'Yip' );
52
53     $obj->{Pants} = 'Whatever';
54     $obj->{_no}   = 'Yeah';
55     @{$obj}{qw(what who _up_yours)} = ('Ahh', 'Moo', 'Yip');
56
57     while(my($k,$v) = each %test) {
58         is($obj->{$k}, $v);
59     }
60 }
61
62 {
63     local $SIG{__WARN__} = sub {
64         return if $_[0] =~ /^Pseudo-hashes are deprecated/ 
65     };
66     my $phash;
67     eval { $phash = fields::phash(name => "Joe", rank => "Captain") };
68     if( $Has_PH ) {
69         is( $phash->{rank}, "Captain" );
70     }
71     else {
72         like $@, qr/^Pseudo-hashes have been removed from Perl/;
73     }
74 }
75
76
77 # check if fields autovivify
78 {
79     package Foo::Autoviv;
80     use fields qw(foo bar);
81     sub new { fields::new($_[0]) }
82
83     package main;
84     my Foo::Autoviv $a = Foo::Autoviv->new();
85     $a->{foo} = ['a', 'ok', 'c'];
86     $a->{bar} = { A => 'ok' };
87     is( $a->{foo}[1],    'ok' );
88     is( $a->{bar}->{A},, 'ok' );
89 }
90
91 package Test::FooBar;
92
93 use fields qw(a b c);
94
95 sub new {
96     my $self = fields::new(shift);
97     %$self = @_ if @_;
98     $self;
99 }
100
101 package main;
102
103 {
104     my $x = Test::FooBar->new( a => 1, b => 2);
105
106     is(ref $x, 'Test::FooBar', 'x is a Test::FooBar');
107     ok(exists $x->{a}, 'x has a');
108     ok(exists $x->{b}, 'x has b');
109 }