cd875be019a1ac026b8f2f203cc556a4f75e833a
[p5sagit/p5-mst-13.2.git] / lib / Test / Simple / t / overload.t
1 #!/usr/bin/perl -w
2 # $Id: /mirror/googlecode/test-more/t/overload.t 57943 2008-08-18T02:09:22.275428Z brooklyn.kid51  $
3
4 BEGIN {
5     if( $ENV{PERL_CORE} ) {
6         chdir 't';
7         @INC = ('../lib', 'lib');
8     }
9     else {
10         unshift @INC, 't/lib';
11     }
12 }
13
14 use strict;
15 use Test::More tests => 15;
16
17
18 package Overloaded;
19
20 use overload
21   q{eq}    => sub { $_[0]->{string} },
22   q{==}    => sub { $_[0]->{num} },
23   q{""}    => sub { $_[0]->{stringfy}++; $_[0]->{string} },
24   q{0+}    => sub { $_[0]->{numify}++;   $_[0]->{num}    }
25 ;
26
27 sub new {
28     my $class = shift;
29     bless {
30         string  => shift,
31         num     => shift,
32         stringify       => 0,
33         numify          => 0,
34     }, $class;
35 }
36
37
38 package main;
39
40 local $SIG{__DIE__} = sub {
41     my($call_file, $call_line) = (caller)[1,2];
42     fail("SIGDIE accidentally called");
43     diag("From $call_file at $call_line");
44 };
45
46 my $obj = Overloaded->new('foo', 42);
47 isa_ok $obj, 'Overloaded';
48
49 is $obj, 'foo',            'is() with string overloading';
50 cmp_ok $obj, 'eq', 'foo',  'cmp_ok() ...';
51 is $obj->{stringify}, 0, 'cmp_ok() eq does not stringify';
52 cmp_ok $obj, '==', 42,     'cmp_ok() with number overloading';
53 is $obj->{numify}, 0,    'cmp_ok() == does not numify';
54
55 is_deeply [$obj], ['foo'],                 'is_deeply with string overloading';
56 ok eq_array([$obj], ['foo']),              'eq_array ...';
57 ok eq_hash({foo => $obj}, {foo => 'foo'}), 'eq_hash ...';
58
59 # rt.cpan.org 13506
60 is_deeply $obj, 'foo',        'is_deeply with string overloading at the top';
61
62 Test::More->builder->is_num($obj, 42);
63 Test::More->builder->is_eq ($obj, "foo");
64
65
66 {
67     # rt.cpan.org 14675
68     package TestPackage;
69     use overload q{""} => sub { ::fail("This should not be called") };
70
71     package Foo;
72     ::is_deeply(['TestPackage'], ['TestPackage']);
73     ::is_deeply({'TestPackage' => 'TestPackage'}, 
74                 {'TestPackage' => 'TestPackage'});
75     ::is_deeply('TestPackage', 'TestPackage');
76 }