File: overload.t

package info (click to toggle)
librole-tiny-perl 1.003004-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 236 kB
  • ctags: 43
  • sloc: perl: 400; makefile: 2
file content (73 lines) | stat: -rw-r--r-- 1,539 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use strict;
use warnings FATAL => 'all';
use Test::More;

BEGIN {
  package MyRole;
  use Role::Tiny;

  sub as_string { "welp" }
  sub as_num { 219 }
  use overload
    '""' => \&as_string,
    '0+' => 'as_num',
    bool => sub(){0},
    fallback => 1;
}

BEGIN {
  package MyClass;
  use Role::Tiny::With;
  with 'MyRole';
  sub new { bless {}, shift }
}

BEGIN {
  package MyClass2;
  use overload
    fallback => 0,
    '""' => 'class_string',
    '0+' => sub { 42 },
    ;
  use Role::Tiny::With;
  with 'MyRole';
  sub new { bless {}, shift }
  sub class_string { 'yarp' }
}

BEGIN {
  package MyClass3;
  sub new { bless {}, shift }
}

{
  my $o = MyClass->new;
  is "$o", 'welp', 'subref overload';
  is sprintf('%d', $o), 219, 'method name overload';
  ok !$o, 'anon subref overload';
}

{
  my $o = MyClass2->new;
  eval { my $f = 0+$o };
  like $@, qr/no method found/, 'fallback value not overwritten';
  is "$o", 'yarp', 'method name overload not overwritten';
  is sprintf('%d', $o), 42, 'subref overload not overwritten';
}

{
  my @o = (MyClass3->new) x 2;
  my $copy = '';
  for my $o (@o) {
    Role::Tiny->apply_roles_to_object($o, 'MyRole')
      unless $copy;
    local $TODO = 'magic not applied to all ref copies on perl < 5.8.9'
      if $copy && $] < 5.008009;
    is "$o", 'welp', 'subref overload applied to instance'.$copy;
    is sprintf('%d', $o), 219, 'method name overload applied to instance'.$copy;
    ok !$o, 'anon subref overload applied to instance'.$copy;
    $copy ||= ' copy';
  }
}

done_testing;