Trailing WS crusade - got to save them bits
[dbsrgits/DBIx-Class.git] / t / cdbi / columns_as_hashes.t
1 use strict;
2 use Test::More;
3 use Test::Warn;
4
5 BEGIN {
6   eval "use DBIx::Class::CDBICompat;";
7   plan skip_all => "Class::Trigger and DBIx::ContextualFetch required: $@" if $@;
8 }
9
10 use lib 't/cdbi/testlib';
11 use Film;
12
13 my $waves = Film->insert({
14     Title     => "Breaking the Waves",
15     Director  => 'Lars von Trier',
16     Rating    => 'R'
17 });
18
19 local $ENV{DBIC_CDBICOMPAT_HASH_WARN} = 0;
20
21 {
22     local $ENV{DBIC_CDBICOMPAT_HASH_WARN} = 1;
23
24     warnings_like {
25         my $rating = $waves->{rating};
26         $waves->Rating("PG");
27         is $rating, "R", 'evaluation of column value is not deferred';
28     } qr{^Column 'rating' of 'Film/$waves' was fetched as a hash at\b};
29
30     warnings_like {
31         is $waves->{title}, $waves->Title, "columns can be accessed as hashes";
32     } qr{^Column 'title' of 'Film/$waves' was fetched as a hash at\b};
33
34     $waves->Rating("G");
35
36     warnings_like {
37         is $waves->{rating}, "G", "updating via the accessor updates the hash";
38     } qr{^Column 'rating' of 'Film/$waves' was fetched as a hash at\b};
39
40
41     warnings_like {
42         $waves->{rating} = "PG";
43     } qr{^Column 'rating' of 'Film/$waves' was stored as a hash at\b};
44
45     $waves->update;
46     my @films = Film->search( Rating => "PG", Title => "Breaking the Waves" );
47     is @films, 1, "column updated as hash was saved";
48 }
49
50 warning_is {
51     $waves->{rating}
52 } '', 'DBIC_CDBICOMPAT_HASH_WARN controls warnings';
53
54
55 {
56     $waves->rating("R");
57     $waves->update;
58
59     no warnings 'redefine';
60     local *Film::rating = sub {
61         return "wibble";
62     };
63
64     is $waves->{rating}, "R";
65 }
66
67
68 {
69     no warnings 'redefine';
70     no warnings 'once';
71     local *Actor::accessor_name_for = sub {
72         my($class, $col) = @_;
73         return "movie" if lc $col eq "film";
74         return $col;
75     };
76
77     require Actor;
78     Actor->has_a( film => "Film" );
79
80     my $actor = Actor->insert({
81         name    => 'Emily Watson',
82         film    => $waves,
83     });
84
85     ok !eval { $actor->film };
86     is $actor->{film}->id, $waves->id,
87        'hash access still works despite lack of accessor';
88 }
89
90
91 # Emulate that Class::DBI inflates immediately
92 SKIP: {
93     unless (eval { require MyFoo }) {
94       my ($err) = $@ =~ /([^\n]+)/;
95       skip $err, 3
96     }
97
98     my $foo = MyFoo->insert({
99         name    => 'Whatever',
100         tdate   => '1949-02-01',
101     });
102     isa_ok $foo, 'MyFoo';
103
104     isa_ok $foo->{tdate}, 'Date::Simple';
105     is $foo->{tdate}->year, 1949;
106 }
107
108 done_testing;