Hash access no works despite lack of existing accessor method.
[dbsrgits/DBIx-Class.git] / t / cdbi-t / columns_as_hashes.t
1 #!/usr/bin/perl -w
2
3 use strict;
4 use Test::More;
5 use Test::Warn;
6
7 BEGIN {
8   eval "use DBIx::Class::CDBICompat;";
9   plan $@ ? (skip_all => "Class::Trigger and DBIx::ContextualFetch required: $@")
10           : ('no_plan');
11 }
12
13 use lib 't/testlib';
14 use Film;
15
16 my $waves = Film->insert({
17     Title     => "Breaking the Waves",
18     Director  => 'Lars von Trier',
19     Rating    => 'R'
20 });
21
22 local $ENV{DBIC_CDBICOMPAT_HASH_WARN} = 0;
23
24 {
25     local $ENV{DBIC_CDBICOMPAT_HASH_WARN} = 1;
26
27     warnings_like {
28         my $rating = $waves->{rating};
29         $waves->Rating("PG");
30         is $rating, "R", 'evaluation of column value is not deferred';
31     } qr{^Column 'rating' of 'Film/$waves' was fetched as a hash at \Q$0};
32
33     warnings_like {
34         is $waves->{title}, $waves->Title, "columns can be accessed as hashes";
35     } qr{^Column 'title' of 'Film/$waves' was fetched as a hash at\b};
36
37     $waves->Rating("G");
38
39     warnings_like {
40         is $waves->{rating}, "G", "updating via the accessor updates the hash";
41     } qr{^Column 'rating' of 'Film/$waves' was fetched as a hash at\b};
42
43
44     warnings_like {
45         $waves->{rating} = "PG";
46     } qr{^Column 'rating' of 'Film/$waves' was stored as a hash at\b};
47
48     $waves->update;
49     my @films = Film->search( Rating => "PG", Title => "Breaking the Waves" );
50     is @films, 1, "column updated as hash was saved";
51 }
52
53 warning_is {
54     $waves->{rating}
55 } '', 'DBIC_CDBICOMPAT_HASH_WARN controls warnings';
56
57
58 {    
59     $waves->rating("R");
60     $waves->update;
61     
62     no warnings 'redefine';
63     local *Film::rating = sub {
64         return "wibble";
65     };
66     
67     is $waves->{rating}, "R";
68 }
69
70
71 {
72     no warnings 'redefine';
73     no warnings 'once';
74     local *Actor::accessor_name_for = sub {
75         my($class, $col) = @_;
76         return "movie" if lc $col eq "film";
77         return $col;
78     };
79     
80     require Actor;
81     
82     my $actor = Actor->insert({
83         name    => 'Emily Watson',
84         film    => $waves,
85     });
86     
87     ok !eval { $actor->film };
88     is $actor->{film}->id, $waves->id,
89        'hash access still works despite lack of accessor';
90 }