Port to B::Hooks::Parser.
[p5sagit/Devel-Declare.git] / t / sugar.t
1 use Devel::Declare;
2
3 BEGIN {
4
5   Devel::Declare->install_declarator(
6     'DeclareTest', 'method', DECLARE_PACKAGE | DECLARE_PROTO,
7     sub {
8       my ($name, $proto) = @_;
9 #no warnings 'uninitialized';
10 #warn "NP: ".join(', ', @_)."\n";
11       return 'my $self = shift;' unless defined $proto && $proto ne '@_';
12       return 'my ($self'.(length $proto ? ", ${proto}" : "").') = @_;';
13     },
14     sub {
15       my ($name, $proto, $sub, @rest) = @_;
16 #no warnings 'uninitialized';
17 #warn "NPS: ".join(', ', @_)."\n";
18       if (defined $name && length $name) {
19         unless ($name =~ /::/) {
20           $name = "DeclareTest::${name}";
21         }
22         no strict 'refs';
23         *{$name} = $sub;
24       }
25       return wantarray ? ($sub, @rest) : $sub;
26     }
27   );
28
29 }
30
31 my ($test_method1, $test_method2, @test_list);
32
33 {
34   package DeclareTest;
35
36   method new {
37     my $class = ref $self || $self;
38     return bless({ @_ }, $class);
39   };
40
41   method foo ($foo) {
42     return (ref $self).': Foo: '.$foo;
43   };
44
45   method upgrade(){ # no spaces to make case pathological
46     bless($self, 'DeclareTest2');
47   };
48
49   method DeclareTest2::bar () {
50     return 'DeclareTest2: bar';
51   };
52
53   $test_method1 = method {
54     return join(', ', $self->{attr}, $_[1]);
55   };
56
57   $test_method2 = method ($what) {
58     return join(', ', ref $self, $what);
59   };
60
61   method main () { return "main"; };
62
63   #@test_list = method { 1 }, sub { 2 }, method () { 3 }, sub { 4 };
64
65 }
66
67 use Test::More 'no_plan';
68
69 my $o = DeclareTest->new(attr => "value");
70
71 isa_ok($o, 'DeclareTest');
72
73 is($o->{attr}, 'value', '@_ args ok');
74
75 is($o->foo('yay'), 'DeclareTest: Foo: yay', 'method with argument ok');
76
77 is($o->main, 'main', 'declaration of package named method ok');
78
79 $o->upgrade;
80
81 isa_ok($o, 'DeclareTest2');
82
83 is($o->bar, 'DeclareTest2: bar', 'absolute method declaration ok');
84
85 is($o->$test_method1('no', 'yes'), 'value, yes', 'anon method with @_ ok');
86
87 is($o->$test_method2('this'), 'DeclareTest2, this', 'anon method with proto ok');
88
89 #warn map { $_->() } @test_list;