tests for applying overloads to instances
[gitmo/Role-Tiny.git] / t / overload.t
CommitLineData
9256ec21 1use strict;
2use warnings FATAL => 'all';
3use Test::More;
4
5BEGIN {
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',
c7260eec 14 bool => sub(){0},
9256ec21 15 fallback => 1;
16}
17
18BEGIN {
19 package MyClass;
20 use Role::Tiny::With;
21 with 'MyRole';
22 sub new { bless {}, shift }
23}
24
83a5e1e3 25BEGIN {
26 package MyClass2;
c7260eec 27 use overload
28 fallback => 0,
29 '""' => 'class_string',
30 '0+' => sub { 42 },
31 ;
83a5e1e3 32 use Role::Tiny::With;
33 with 'MyRole';
34 sub new { bless {}, shift }
c7260eec 35 sub class_string { 'yarp' }
83a5e1e3 36}
37
e5dcce87 38BEGIN {
39 package MyClass3;
40 sub new { bless {}, shift }
41}
42
c7260eec 43{
44 my $o = MyClass->new;
45 is "$o", 'welp', 'subref overload';
46 is sprintf('%d', $o), 219, 'method name overload';
47 ok !$o, 'anon subref overload';
48}
9256ec21 49
c7260eec 50{
51 my $o = MyClass2->new;
52 eval { my $f = 0+$o };
53 like $@, qr/no method found/, 'fallback value not overwritten';
54 is "$o", 'yarp', 'method name overload not overwritten';
55 is sprintf('%d', $o), 42, 'subref overload not overwritten';
56}
83a5e1e3 57
e5dcce87 58{
59 my @o = (MyClass3->new) x 2;
60 my $copy = '';
61 for my $o (@o) {
62 Role::Tiny->apply_roles_to_object($o, 'MyRole')
63 unless $copy;
64 local $TODO = 'magic not applied to all ref copies on perl < 5.8.9'
65 if $copy && $] < 5.008009;
66 is "$o", 'welp', 'subref overload applied to instance'.$copy;
67 is sprintf('%d', $o), 219, 'method name overload applied to instance'.$copy;
68 ok !$o, 'anon subref overload applied to instance'.$copy;
69 $copy ||= ' copy';
70 }
71}
72
9256ec21 73done_testing;