Institute a central "load this first in testing" package
[dbsrgits/DBIx-Class.git] / t / storage / txn_scope_guard.t
1 BEGIN { do "./t/lib/ANFANG.pm" or die ( $@ || $! ) }
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7 use Test::Warn;
8 use Test::Exception;
9
10 use List::Util 'shuffle';
11 use DBIx::Class::_Util 'sigwarn_silencer';
12
13
14 use DBICTest;
15
16 # Test txn_scope_guard
17 {
18   my $schema = DBICTest->init_schema();
19
20   is($schema->storage->transaction_depth, 0, "Correct transaction depth");
21   my $artist_rs = $schema->resultset('Artist');
22
23   my $fn = __FILE__;
24   throws_ok {
25    my $guard = $schema->txn_scope_guard;
26
27     $artist_rs->create({
28       name => 'Death Cab for Cutie',
29       made_up_column => 1,
30     });
31
32    $guard->commit;
33   } qr/No such column 'made_up_column' .*? at .*?\Q$fn\E line \d+/s, "Error propogated okay";
34
35   ok(!$artist_rs->find({name => 'Death Cab for Cutie'}), "Artist not created");
36
37   my $inner_exception = '';  # set in inner() below
38   throws_ok (sub {
39     outer($schema, 1);
40   }, qr/$inner_exception/, "Nested exceptions propogated");
41
42   ok(!$artist_rs->find({name => 'Death Cab for Cutie'}), "Artist not created");
43
44   lives_ok (sub {
45
46     # this weird assignment is to stop perl <= 5.8.9 leaking $schema on nested sub{}s
47     my $s = $schema;
48
49     warnings_exist ( sub {
50       # The 0 arg says don't die, just let the scope guard go out of scope
51       # forcing a txn_rollback to happen
52       outer($s, 0);
53     }, qr/A DBIx::Class::Storage::TxnScopeGuard went out of scope without explicit commit or error. Rolling back./, 'Out of scope warning detected');
54
55     ok(!$artist_rs->find({name => 'Death Cab for Cutie'}), "Artist not created");
56
57   }, 'rollback successful withot exception');
58
59   sub outer {
60     my ($schema, $fatal) = @_;
61
62     my $guard = $schema->txn_scope_guard;
63     $schema->resultset('Artist')->create({
64       name => 'Death Cab for Cutie',
65     });
66     inner($schema, $fatal);
67   }
68
69   sub inner {
70     my ($schema, $fatal) = @_;
71
72     my $inner_guard = $schema->txn_scope_guard;
73     is($schema->storage->transaction_depth, 2, "Correct transaction depth");
74
75     my $artist = $schema->resultset('Artist')->find({ name => 'Death Cab for Cutie' });
76
77     eval {
78       $artist->cds->create({
79         title => 'Plans',
80         year => 2005,
81         $fatal ? ( foo => 'bar' ) : ()
82       });
83     };
84     if ($@) {
85       # Record what got thrown so we can test it propgates out properly.
86       $inner_exception = $@;
87       die $@;
88     }
89
90     # inner guard should commit without consequences
91     $inner_guard->commit;
92   }
93 }
94
95 # make sure the guard does not eat exceptions
96 {
97   my $schema = DBICTest->init_schema;
98
99   no warnings 'redefine';
100   local *DBIx::Class::Storage::DBI::txn_rollback = sub { die 'die die my darling' };
101   Class::C3->reinitialize() if DBIx::Class::_ENV_::OLD_MRO;
102
103   throws_ok (sub {
104     my $guard = $schema->txn_scope_guard;
105     $schema->resultset ('Artist')->create ({ name => 'bohhoo'});
106
107     # this should freak out the guard rollback
108     # but it won't work because DBD::SQLite is buggy
109     # instead just install a toxic rollback above
110     #$schema->storage->_dbh( $schema->storage->_dbh->clone );
111
112     die 'Deliberate exception';
113   }, ( "$]" >= 5.013008 )
114     ? qr/Deliberate exception/s # temporary until we get the generic exception wrapper rolling
115     : qr/Deliberate exception.+Rollback failed/s
116   );
117
118   # just to mask off warning since we could not disconnect above
119   $schema->storage->_dbh->disconnect;
120 }
121
122 # make sure it warns *big* on failed rollbacks
123 # test with and without a poisoned $@
124 require DBICTest::AntiPattern::TrueZeroLen;
125 require DBICTest::AntiPattern::NullObject;
126 {
127   my @want = (
128     qr/A DBIx::Class::Storage::TxnScopeGuard went out of scope without explicit commit or error. Rolling back./,
129     qr/\*+ ROLLBACK FAILED\!\!\! \*+/,
130   );
131
132   my @w;
133   local $SIG{__WARN__} = sub {
134     if (grep {$_[0] =~ $_} (@want)) {
135       push @w, $_[0];
136     }
137     else {
138       warn $_[0];
139     }
140   };
141
142   no warnings 'redefine';
143   local *DBIx::Class::Storage::DBI::txn_rollback = sub { die 'die die my darling' };
144   Class::C3->reinitialize() if DBIx::Class::_ENV_::OLD_MRO;
145
146   my @poisons = shuffle (
147     undef,
148     DBICTest::AntiPattern::TrueZeroLen->new,
149     DBICTest::AntiPattern::NullObject->new,
150     'GIFT!',
151   );
152
153   for my $pre_poison (@poisons) {
154     for my $post_poison (@poisons) {
155
156       @w = ();
157
158       my $schema = DBICTest->init_schema(no_populate => 1);
159
160       # the actual scope where the guard is created/freed
161       {
162         # in this particular case these are not the warnings we are looking for
163         local $SIG{__WARN__} = sigwarn_silencer qr/implementing the so called null-object-pattern/;
164
165         # if is inside the eval, to clear $@ in the undef case
166         eval { die $pre_poison if defined $pre_poison };
167
168         my $guard = $schema->txn_scope_guard;
169
170         eval { die $post_poison if defined $post_poison };
171
172         $schema->resultset ('Artist')->create ({ name => "bohhoo, too bad we'll roll you back"});
173       }
174
175       local $TODO = 'Do not know how to deal with trapped exceptions occuring after guard instantiation...'
176         if ( defined $post_poison and (
177           # take no chances on installation
178           DBICTest::RunMode->is_plain
179             or
180           # I do not understand why but on <= 5.8.8 and on 5.10.0
181           # "$pre_poison == $post_poison == string" passes...
182           # so todoify 5.8.9 and 5.10.1+, and deal with the rest below
183           ( ( "$]" > 5.008008 and "$]" < 5.010000 ) or "$]" > 5.010000 )
184             or
185           ! defined $pre_poison
186             or
187           length ref $pre_poison
188             or
189           length ref $post_poison
190         ));
191
192       is (@w, 2, sprintf 'Both expected warnings found - $@ poisonstate:   pre-poison:%s   post-poison:%s',
193         map {
194           ! defined $_      ? 'UNDEF'
195         : ! length ref $_   ? $_
196                             : ref $_
197
198         } ($pre_poison, $post_poison)
199       );
200
201       # just to mask off warning since we could not disconnect above
202       $schema->storage->_dbh->disconnect;
203     }
204   }
205 }
206
207 # add a TODO to catch when Text::Balanced is finally fixed
208 # https://rt.cpan.org/Public/Bug/Display.html?id=74994
209 #
210 # while it doesn't matter much for DBIC itself, this particular bug
211 # is a *BANE*, and DBIC is to bump its dep as soon as possible
212 {
213
214   require Text::Balanced;
215
216   my @w;
217   local $SIG{__WARN__} = sub {
218     $_[0] =~ /External exception class .+? \Qimplements partial (broken) overloading/
219       ? push @w, @_
220       : warn @_
221   };
222
223   lives_ok {
224     # this is what poisons $@
225     Text::Balanced::extract_bracketed( '(foo', '()' );
226     DBIx::Class::_Util::is_exception($@);
227
228     my $s = DBICTest::Schema->connect('dbi:SQLite::memory:');
229     my $g = $s->txn_scope_guard;
230     $g->commit;
231   } 'Broken Text::Balanced is not screwing up txn_guard';
232
233   local $TODO = 'RT#74994 *STILL* not fixed';
234   is(scalar @w, 0, 'no warnings \o/');
235 }
236
237 # ensure Devel::StackTrace-refcapture-like effects are countered
238 {
239   my $s = DBICTest::Schema->connect('dbi:SQLite::memory:');
240   my $g = $s->txn_scope_guard;
241
242   my @arg_capture;
243   {
244     local $SIG{__WARN__} = sub {
245       package DB;
246       my $frnum;
247       while (my @f = CORE::caller(++$frnum) ) {
248         push @arg_capture, @DB::args;
249       }
250     };
251
252     undef $g;
253     1;
254   }
255
256   warnings_exist
257     { @arg_capture = () }
258     qr/\QPreventing *MULTIPLE* DESTROY() invocations on DBIx::Class::Storage::TxnScopeGuard/
259   ;
260 }
261
262 done_testing;