Fix false-positives in the no-external-evals assert ( ddcc02d14 )
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest / BaseSchema.pm
CommitLineData
27a701f9 1package #hide from pause
2 DBICTest::BaseSchema;
3
4use strict;
5use warnings;
bedbc811 6use base qw(DBICTest::Base DBIx::Class::Schema);
27a701f9 7
e952df76 8use Fcntl qw(:DEFAULT :seek :flock);
e48635f7 9use IO::Handle ();
bbf6a9a5 10use DBIx::Class::_Util 'scope_guard';
e952df76 11use DBICTest::Util::LeakTracer qw(populate_weakregistry assert_empty_weakregistry);
439a7283 12use DBICTest::Util qw( local_umask tmpdir await_flock dbg DEBUG_TEST_CONCURRENCY_LOCKS );
e952df76 13use namespace::clean;
14
ddcc02d1 15if( $ENV{DBICTEST_ASSERT_NO_SPURIOUS_EXCEPTION_ACTION} ) {
5c33c8be 16 my $ea = __PACKAGE__->exception_action( sub {
ddcc02d1 17
44c1a75d 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 );
ddcc02d1 23 while( ! $disarmed and my @fr = caller(++$fr_num) ) {
24
25 $throw_exception_fr_num ||= (
44c1a75d 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)'
ddcc02d1 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||())
44c1a75d 70 ) if (
71 ! $disarmed
72 and
73 (
74 $eval_fr_num
75 or
76 ! $throw_exception_fr_num
77 )
78 );
ddcc02d1 79
80 DBIx::Class::Exception->throw( $_[0] );
5c33c8be 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 (
44c1a75d 91 # blindly rethrow if nobody is waiting for us
92 ( defined $^S and ! $^S )
93 or
5c33c8be 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 };
ddcc02d1 105}
106
2cfc22dd 107sub capture_executed_sql_bind {
108 my ($self, $cref) = @_;
109
110 $self->throw_exception("Expecting a coderef to run") unless ref $cref eq 'CODE';
111
4faaf174 112 require DBICTest::SQLTracerObj;
113
2cfc22dd 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
b74b15b0 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 };
4faaf174 125
bbf6a9a5 126 my $sg = scope_guard {
b74b15b0 127 $self->storage->$_ ( $orig_states->{$_} ) for keys %$orig_states;
bbf6a9a5 128 };
b74b15b0 129
130 $self->storage->debugcb(undef);
131 $self->storage->debugobj( my $tracer_obj = DBICTest::SQLTracerObj->new );
132 $self->storage->debug(1);
2cfc22dd 133
49eeb48d 134 local $Test::Builder::Level = $Test::Builder::Level + 2;
2cfc22dd 135 $cref->();
136
137 return $tracer_obj->{sqlbinds} || [];
138}
139
49eeb48d 140sub 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
2cfc22dd 163sub 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
e952df76 210our $locker;
211END {
212 # we need the $locker to be referenced here for delayed destruction
213 if ($locker->{lock_name} and ($ENV{DBICTEST_LOCK_HOLDER}||0) == $$) {
69016f65 214 DEBUG_TEST_CONCURRENCY_LOCKS
215 and dbg "$locker->{type} LOCK RELEASED (END): $locker->{lock_name}";
e952df76 216 }
217}
218
219my $weak_registry = {};
220
221sub 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
e952df76 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
e4328872 253 ($_[0]||'') !~ /^ (?i:dbi) \: SQLite (?: \: | \W ) .*? (?: dbname\= )? (?: \:memory\: | t [\/\\] var [\/\\] DBIxClass\-) /x
e952df76 254 ) {
255
0f6d86e4 256 my $locktype;
257
258 {
e952df76 259 # guard against infinite recursion
260 local $ENV{DBICTEST_LOCK_HOLDER} = -1;
261
0f6d86e4 262 # we need to work with a forced fresh clone so that we do not upset any state
e952df76 263 # of the main $schema (some tests examine it quite closely)
264 local $SIG{__WARN__} = sub {};
5c33c8be 265 local $SIG{__DIE__};
e952df76 266 local $@;
0f6d86e4 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 {
bf726d9c 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;
0f6d86e4 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;
e952df76 282 };
0f6d86e4 283 }
e952df76 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
69016f65 292 DEBUG_TEST_CONCURRENCY_LOCKS
293 and $locker
294 and dbg "$locker->{type} LOCK RELEASED (UNDEF): $locker->{lock_name}";
295
e952df76 296 undef $locker;
297
439a7283 298 my $lockpath = tmpdir . "_dbictest_$locktype.lock";
e952df76 299
69016f65 300 DEBUG_TEST_CONCURRENCY_LOCKS
301 and dbg "Waiting for $locktype LOCK: $lockpath...";
302
e952df76 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 }
69016f65 308
630e2ea8 309 await_flock ($lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
69016f65 310
311 DEBUG_TEST_CONCURRENCY_LOCKS
312 and dbg "Got $locktype LOCK: $lockpath";
e952df76 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 ) {
69016f65 323 DEBUG_TEST_CONCURRENCY_LOCKS
324 and dbg "Post-grab WAIT for $old_pid START: $lockpath";
325
e952df76 326 for (1..50) {
327 kill (0, $old_pid) or last;
5a8d5308 328 select( undef, undef, undef, 0.1 );
e952df76 329 }
69016f65 330
331 DEBUG_TEST_CONCURRENCY_LOCKS
332 and dbg "Post-grab WAIT for $old_pid FINISHED: $lockpath";
e952df76 333 }
e952df76 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
369sub clone {
370 my $self = shift->next::method(@_);
371 populate_weakregistry ( $weak_registry, $self )
372 if $INC{'Test/Builder.pm'};
373 $self;
374}
375
376END {
961d79db 377 # Make sure we run after any cleanup in other END blocks
961d79db 378 push @{ B::end_av()->object_2svref }, sub {
379 assert_empty_weakregistry($weak_registry, 'quiet');
380 };
e952df76 381}
27a701f9 382
3831;