Fix false-positives in the no-external-evals assert ( ddcc02d14 )
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest / BaseSchema.pm
1 package #hide from pause
2   DBICTest::BaseSchema;
3
4 use strict;
5 use warnings;
6 use base qw(DBICTest::Base DBIx::Class::Schema);
7
8 use Fcntl qw(:DEFAULT :seek :flock);
9 use IO::Handle ();
10 use DBIx::Class::_Util 'scope_guard';
11 use DBICTest::Util::LeakTracer qw(populate_weakregistry assert_empty_weakregistry);
12 use DBICTest::Util qw( local_umask tmpdir await_flock dbg DEBUG_TEST_CONCURRENCY_LOCKS );
13 use namespace::clean;
14
15 if( $ENV{DBICTEST_ASSERT_NO_SPURIOUS_EXCEPTION_ACTION} ) {
16   my $ea = __PACKAGE__->exception_action( sub {
17
18     # Can not rely on $^S here at all - the exception_action
19     # itself is always called in an eval so that the goto-guard
20     # can work (see 7cb35852)
21
22     my ( $fr_num, $disarmed, $throw_exception_fr_num, $eval_fr_num );
23     while( ! $disarmed and my @fr = caller(++$fr_num) ) {
24
25       $throw_exception_fr_num ||= (
26         $fr[3] =~ /^DBIx::Class::(?:ResultSource|Schema|Storage|Exception)::throw(?:_exception)?$/
27           and
28         # there may be evals in the throwers themselves - skip those
29         ( $eval_fr_num ) = ( undef )
30           and
31         $fr_num
32       );
33
34       # now that the above stops un-setting us, we can find the first
35       # ineresting eval
36       $eval_fr_num ||= (
37         $fr[3] eq '(eval)'
38           and
39         $fr_num
40       );
41
42       $disarmed = !! (
43         $fr[1] =~ / \A (?: \. [\/\\] )? x?t [\/\\] .+ \.t \z /x
44           and
45         (
46           $fr[3] =~ /\A (?:
47             Test::Exception::throws_ok
48               |
49             Test::Exception::dies_ok
50               |
51             Try::Tiny::try
52               |
53             \Q(eval)\E
54           ) \z /x
55             or
56           (
57             $fr[3] eq 'Test::Exception::lives_ok'
58               and
59             ( $::TODO or Test::Builder->new->in_todo )
60           )
61         )
62       );
63     }
64
65     Test::Builder->new->ok(0, join "\n",
66       'Unexpected &exception_action invocation',
67       '',
68       '  You almost certainly used eval/try instead of dbic_internal_try()',
69       "  Adjust *one* of the eval-ish constructs in the callstack starting" . DBICTest::Util::stacktrace($throw_exception_fr_num||())
70     ) if (
71       ! $disarmed
72         and
73       (
74         $eval_fr_num
75           or
76         ! $throw_exception_fr_num
77       )
78     );
79
80     DBIx::Class::Exception->throw( $_[0] );
81   });
82
83   my $interesting_ns_rx = qr/^ (?: main$ | DBIx::Class:: | DBICTest:: ) /x;
84
85   # hard-set $SIG{__DIE__} to the class-wide exception_action
86   # with a little escape preceeding it
87   $SIG{__DIE__} = sub {
88
89     # without this there would be false positives everywhere :(
90     die @_ if (
91       # blindly rethrow if nobody is waiting for us
92       ( defined $^S and ! $^S )
93         or
94       (caller(0))[0] !~ $interesting_ns_rx
95         or
96       (
97         caller(0) eq 'main'
98           and
99         (caller(1))[0] !~ $interesting_ns_rx
100       )
101     );
102
103     &$ea;
104   };
105 }
106
107 sub capture_executed_sql_bind {
108   my ($self, $cref) = @_;
109
110   $self->throw_exception("Expecting a coderef to run") unless ref $cref eq 'CODE';
111
112   require DBICTest::SQLTracerObj;
113
114   # hack around stupid, stupid API
115   no warnings 'redefine';
116   local *DBIx::Class::Storage::DBI::_format_for_trace = sub { $_[1] };
117   Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
118
119   # can not use local() due to an unknown number of storages
120   # (think replicated)
121   my $orig_states = { map
122     { $_ => $self->storage->$_ }
123     qw(debugcb debugobj debug)
124   };
125
126   my $sg = scope_guard {
127     $self->storage->$_ ( $orig_states->{$_} ) for keys %$orig_states;
128   };
129
130   $self->storage->debugcb(undef);
131   $self->storage->debugobj( my $tracer_obj = DBICTest::SQLTracerObj->new );
132   $self->storage->debug(1);
133
134   local $Test::Builder::Level = $Test::Builder::Level + 2;
135   $cref->();
136
137   return $tracer_obj->{sqlbinds} || [];
138 }
139
140 sub is_executed_querycount {
141   my ($self, $cref, $exp_counts, $msg) = @_;
142
143   local $Test::Builder::Level = $Test::Builder::Level + 1;
144
145   $self->throw_exception("Expecting an hashref of counts or an integer representing total query count")
146     unless ref $exp_counts eq 'HASH' or (defined $exp_counts and ! ref $exp_counts);
147
148   my @got = map { $_->[0] } @{ $self->capture_executed_sql_bind($cref) };
149
150   return Test::More::is( @got, $exp_counts, $msg )
151     unless ref $exp_counts;
152
153   my $got_counts = { map { $_ => 0 } keys %$exp_counts };
154   $got_counts->{$_}++ for @got;
155
156   return Test::More::is_deeply(
157     $got_counts,
158     $exp_counts,
159     $msg,
160   );
161 }
162
163 sub is_executed_sql_bind {
164   my ($self, $cref, $sqlbinds, $msg) = @_;
165
166   local $Test::Builder::Level = $Test::Builder::Level + 1;
167
168   $self->throw_exception("Expecting an arrayref of SQL/Bind pairs") unless ref $sqlbinds eq 'ARRAY';
169
170   my @expected = @$sqlbinds;
171
172   my @got = map { $_->[1] } @{ $self->capture_executed_sql_bind($cref) };
173
174
175   return Test::Builder->new->ok(1, $msg || "No queries executed while running $cref")
176     if !@got and !@expected;
177
178   require SQL::Abstract::Test;
179   my $ret = 1;
180   while (@expected or @got) {
181     my $left = shift @got;
182     my $right = shift @expected;
183
184     # allow the right side to "simplify" the entire shebang
185     if ($left and $right) {
186       $left = [ @$left ];
187       for my $i (1..$#$right) {
188         if (
189           ! ref $right->[$i]
190             and
191           ref $left->[$i] eq 'ARRAY'
192             and
193           @{$left->[$i]} == 2
194         ) {
195           $left->[$i] = $left->[$i][1]
196         }
197       }
198     }
199
200     $ret &= SQL::Abstract::Test::is_same_sql_bind(
201       \( $left || [] ),
202       \( $right || [] ),
203       $msg,
204     );
205   }
206
207   return $ret;
208 }
209
210 our $locker;
211 END {
212   # we need the $locker to be referenced here for delayed destruction
213   if ($locker->{lock_name} and ($ENV{DBICTEST_LOCK_HOLDER}||0) == $$) {
214     DEBUG_TEST_CONCURRENCY_LOCKS
215       and dbg "$locker->{type} LOCK RELEASED (END): $locker->{lock_name}";
216   }
217 }
218
219 my $weak_registry = {};
220
221 sub connection {
222   my $self = shift->next::method(@_);
223
224 # MASSIVE FIXME
225 # we can't really lock based on DSN, as we do not yet have a way to tell that e.g.
226 # DBICTEST_MSSQL_DSN=dbi:Sybase:server=192.168.0.11:1433;database=dbtst
227 #  and
228 # DBICTEST_MSSQL_ODBC_DSN=dbi:ODBC:server=192.168.0.11;port=1433;database=dbtst;driver=FreeTDS;tds_version=8.0
229 # are the same server
230 # hence we lock everything based on sqlt_type or just globally if not available
231 # just pretend we are python you know? :)
232
233
234   # when we get a proper DSN resolution sanitize to produce a portable lockfile name
235   # this may look weird and unnecessary, but consider running tests from
236   # windows over a samba share >.>
237   #utf8::encode($dsn);
238   #$dsn =~ s/([^A-Za-z0-9_\-\.\=])/ sprintf '~%02X', ord($1) /ge;
239   #$dsn =~ s/^dbi/dbi/i;
240
241   # provide locking for physical (non-memory) DSNs, so that tests can
242   # safely run in parallel. While the harness (make -jN test) does set
243   # an envvar, we can not detect when a user invokes prove -jN. Hence
244   # perform the locking at all times, it shouldn't hurt.
245   # the lock fh *should* inherit across forks/subprocesses
246   if (
247     ! $DBICTest::global_exclusive_lock
248       and
249     ( ! $ENV{DBICTEST_LOCK_HOLDER} or $ENV{DBICTEST_LOCK_HOLDER} == $$ )
250       and
251     ref($_[0]) ne 'CODE'
252       and
253     ($_[0]||'') !~ /^ (?i:dbi) \: SQLite (?: \: | \W ) .*? (?: dbname\= )? (?: \:memory\: | t [\/\\] var [\/\\] DBIxClass\-) /x
254   ) {
255
256     my $locktype;
257
258     {
259       # guard against infinite recursion
260       local $ENV{DBICTEST_LOCK_HOLDER} = -1;
261
262       # we need to work with a forced fresh clone so that we do not upset any state
263       # of the main $schema (some tests examine it quite closely)
264       local $SIG{__WARN__} = sub {};
265       local $SIG{__DIE__};
266       local $@;
267
268       # this will either give us an undef $locktype or will determine things
269       # properly with a default ( possibly connecting in the process )
270       eval {
271         my $cur_storage = $self->storage;
272
273         $cur_storage = $cur_storage->master
274           if $cur_storage->isa('DBIx::Class::Storage::DBI::Replicated');
275
276         my $s = ref($self)->connect(@{$cur_storage->connect_info})->storage;
277
278         $locktype = $s->sqlt_type || 'generic';
279
280         # in case sqlt_type did connect, doesn't matter if it fails or something
281         $s->disconnect;
282       };
283     }
284
285     # Never hold more than one lock. This solves the "lock in order" issues
286     # unrelated tests may have
287     # Also if there is no connection - there is no lock to be had
288     if ($locktype and (!$locker or $locker->{type} ne $locktype)) {
289
290       # this will release whatever lock we may currently be holding
291       # which is fine since the type does not match as checked above
292       DEBUG_TEST_CONCURRENCY_LOCKS
293         and $locker
294         and dbg "$locker->{type} LOCK RELEASED (UNDEF): $locker->{lock_name}";
295
296       undef $locker;
297
298       my $lockpath = tmpdir . "_dbictest_$locktype.lock";
299
300       DEBUG_TEST_CONCURRENCY_LOCKS
301         and dbg "Waiting for $locktype LOCK: $lockpath...";
302
303       my $lock_fh;
304       {
305         my $u = local_umask(0); # so that the file opens as 666, and any user can lock
306         sysopen ($lock_fh, $lockpath, O_RDWR|O_CREAT) or die "Unable to open $lockpath: $!";
307       }
308
309       await_flock ($lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
310
311       DEBUG_TEST_CONCURRENCY_LOCKS
312         and dbg "Got $locktype LOCK: $lockpath";
313
314       # see if anyone was holding a lock before us, and wait up to 5 seconds for them to terminate
315       # if we do not do this we may end up trampling over some long-running END or somesuch
316       seek ($lock_fh, 0, SEEK_SET) or die "seek failed $!";
317       my $old_pid;
318       if (
319         read ($lock_fh, $old_pid, 100)
320           and
321         ($old_pid) = $old_pid =~ /^(\d+)$/
322       ) {
323         DEBUG_TEST_CONCURRENCY_LOCKS
324           and dbg "Post-grab WAIT for $old_pid START: $lockpath";
325
326         for (1..50) {
327           kill (0, $old_pid) or last;
328           select( undef, undef, undef, 0.1 );
329         }
330
331         DEBUG_TEST_CONCURRENCY_LOCKS
332           and dbg "Post-grab WAIT for $old_pid FINISHED: $lockpath";
333       }
334
335       truncate $lock_fh, 0;
336       seek ($lock_fh, 0, SEEK_SET) or die "seek failed $!";
337       $lock_fh->autoflush(1);
338       print $lock_fh $$;
339
340       $ENV{DBICTEST_LOCK_HOLDER} ||= $$;
341
342       $locker = {
343         type => $locktype,
344         fh => $lock_fh,
345         lock_name => "$lockpath",
346       };
347     }
348   }
349
350   if ($INC{'Test/Builder.pm'}) {
351     populate_weakregistry ( $weak_registry, $self->storage );
352
353     my $cur_connect_call = $self->storage->on_connect_call;
354
355     $self->storage->on_connect_call([
356       (ref $cur_connect_call eq 'ARRAY'
357         ? @$cur_connect_call
358         : ($cur_connect_call || ())
359       ),
360       [sub {
361         populate_weakregistry( $weak_registry, shift->_dbh )
362       }],
363     ]);
364   }
365
366   return $self;
367 }
368
369 sub clone {
370   my $self = shift->next::method(@_);
371   populate_weakregistry ( $weak_registry, $self )
372     if $INC{'Test/Builder.pm'};
373   $self;
374 }
375
376 END {
377   # Make sure we run after any cleanup in other END blocks
378   push @{ B::end_av()->object_2svref }, sub {
379     assert_empty_weakregistry($weak_registry, 'quiet');
380   };
381 }
382
383 1;