f4ce2666a965458dfc6481d3abba6695408f0d68
[gitmo/Role-Tiny.git] / t / overload.t
1 use strict;
2 use warnings FATAL => 'all';
3 use Test::More;
4
5 BEGIN {
6   package MyRole;
7   use Role::Tiny;
8
9   sub as_string { "welp" }
10   sub as_num { 219 }
11   use overload
12     '""' => \&as_string,
13     '0+' => 'as_num',
14     bool => sub(){0},
15     fallback => 1;
16 }
17
18 BEGIN {
19   package MyClass;
20   use Role::Tiny::With;
21   with 'MyRole';
22   sub new { bless {}, shift }
23 }
24
25 BEGIN {
26   package MyClass2;
27   use overload
28     fallback => 0,
29     '""' => 'class_string',
30     '0+' => sub { 42 },
31     ;
32   use Role::Tiny::With;
33   with 'MyRole';
34   sub new { bless {}, shift }
35   sub class_string { 'yarp' }
36 }
37
38 {
39   my $o = MyClass->new;
40   is "$o", 'welp', 'subref overload';
41   is sprintf('%d', $o), 219, 'method name overload';
42   ok !$o, 'anon subref overload';
43 }
44
45 {
46   my $o = MyClass2->new;
47   eval { my $f = 0+$o };
48   like $@, qr/no method found/, 'fallback value not overwritten';
49   is "$o", 'yarp', 'method name overload not overwritten';
50   is sprintf('%d', $o), 42, 'subref overload not overwritten';
51 }
52
53 done_testing;