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