1 package #hide from pause
6 use base qw(DBICTest::Base DBIx::Class::Schema);
8 use Fcntl qw(:DEFAULT :seek :flock);
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 );
15 if( $ENV{DBICTEST_ASSERT_NO_SPURIOUS_EXCEPTION_ACTION} ) {
16 my $ea = __PACKAGE__->exception_action( sub {
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)
22 my ( $fr_num, $disarmed, $throw_exception_fr_num, $eval_fr_num );
23 while( ! $disarmed and my @fr = caller(++$fr_num) ) {
25 $throw_exception_fr_num ||= (
26 $fr[3] =~ /^DBIx::Class::(?:ResultSource|Schema|Storage|Exception)::throw(?:_exception)?$/
28 # there may be evals in the throwers themselves - skip those
29 ( $eval_fr_num ) = ( undef )
34 # now that the above stops un-setting us, we can find the first
43 $fr[1] =~ / \A (?: \. [\/\\] )? x?t [\/\\] .+ \.t \z /x
47 Test::Exception::throws_ok
49 Test::Exception::dies_ok
57 $fr[3] eq 'Test::Exception::lives_ok'
59 ( $::TODO or Test::Builder->new->in_todo )
65 Test::Builder->new->ok(0, join "\n",
66 'Unexpected &exception_action invocation',
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||())
76 ! $throw_exception_fr_num
80 DBIx::Class::Exception->throw( $_[0] );
83 my $interesting_ns_rx = qr/^ (?: main$ | DBIx::Class:: | DBICTest:: ) /x;
85 # hard-set $SIG{__DIE__} to the class-wide exception_action
86 # with a little escape preceeding it
89 # without this there would be false positives everywhere :(
91 # blindly rethrow if nobody is waiting for us
92 ( defined $^S and ! $^S )
94 (caller(0))[0] !~ $interesting_ns_rx
99 ( (caller(1))[0] || '' ) !~ $interesting_ns_rx
107 sub capture_executed_sql_bind {
108 my ($self, $cref) = @_;
110 $self->throw_exception("Expecting a coderef to run") unless ref $cref eq 'CODE';
112 require DBICTest::SQLTracerObj;
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;
119 # can not use local() due to an unknown number of storages
121 my $orig_states = { map
122 { $_ => $self->storage->$_ }
123 qw(debugcb debugobj debug)
126 my $sg = scope_guard {
127 $self->storage->$_ ( $orig_states->{$_} ) for keys %$orig_states;
130 $self->storage->debugcb(undef);
131 $self->storage->debugobj( my $tracer_obj = DBICTest::SQLTracerObj->new );
132 $self->storage->debug(1);
134 local $Test::Builder::Level = $Test::Builder::Level + 2;
137 return $tracer_obj->{sqlbinds} || [];
140 sub is_executed_querycount {
141 my ($self, $cref, $exp_counts, $msg) = @_;
143 local $Test::Builder::Level = $Test::Builder::Level + 1;
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);
148 my @got = map { $_->[0] } @{ $self->capture_executed_sql_bind($cref) };
150 return Test::More::is( @got, $exp_counts, $msg )
151 unless ref $exp_counts;
153 my $got_counts = { map { $_ => 0 } keys %$exp_counts };
154 $got_counts->{$_}++ for @got;
156 return Test::More::is_deeply(
163 sub is_executed_sql_bind {
164 my ($self, $cref, $sqlbinds, $msg) = @_;
166 local $Test::Builder::Level = $Test::Builder::Level + 1;
168 $self->throw_exception("Expecting an arrayref of SQL/Bind pairs") unless ref $sqlbinds eq 'ARRAY';
170 my @expected = @$sqlbinds;
172 my @got = map { $_->[1] } @{ $self->capture_executed_sql_bind($cref) };
175 return Test::Builder->new->ok(1, $msg || "No queries executed while running $cref")
176 if !@got and !@expected;
178 require SQL::Abstract::Test;
180 while (@expected or @got) {
181 my $left = shift @got;
182 my $right = shift @expected;
184 # allow the right side to "simplify" the entire shebang
185 if ($left and $right) {
187 for my $i (1..$#$right) {
191 ref $left->[$i] eq 'ARRAY'
195 $left->[$i] = $left->[$i][1]
200 $ret &= SQL::Abstract::Test::is_same_sql_bind(
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}";
219 my $weak_registry = {};
222 my $self = shift->next::method(@_);
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
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? :)
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 >.>
238 #$dsn =~ s/([^A-Za-z0-9_\-\.\=])/ sprintf '~%02X', ord($1) /ge;
239 #$dsn =~ s/^dbi/dbi/i;
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
247 ! $DBICTest::global_exclusive_lock
249 ( ! $ENV{DBICTEST_LOCK_HOLDER} or $ENV{DBICTEST_LOCK_HOLDER} == $$ )
253 ($_[0]||'') !~ /^ (?i:dbi) \: SQLite (?: \: | \W ) .*? (?: dbname\= )? (?: \:memory\: | t [\/\\] var [\/\\] DBIxClass\-) /x
259 # guard against infinite recursion
260 local $ENV{DBICTEST_LOCK_HOLDER} = -1;
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__} if $SIG{__DIE__};
268 # this will either give us an undef $locktype or will determine things
269 # properly with a default ( possibly connecting in the process )
271 my $cur_storage = $self->storage;
273 $cur_storage = $cur_storage->master
274 if $cur_storage->isa('DBIx::Class::Storage::DBI::Replicated');
276 my $s = ref($self)->connect(@{$cur_storage->connect_info})->storage;
278 $locktype = $s->sqlt_type || 'generic';
280 # in case sqlt_type did connect, doesn't matter if it fails or something
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)) {
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
294 and dbg "$locker->{type} LOCK RELEASED (UNDEF): $locker->{lock_name}";
298 my $lockpath = tmpdir . "_dbictest_$locktype.lock";
300 DEBUG_TEST_CONCURRENCY_LOCKS
301 and dbg "Waiting for $locktype LOCK: $lockpath...";
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: $!";
309 await_flock ($lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
311 DEBUG_TEST_CONCURRENCY_LOCKS
312 and dbg "Got $locktype LOCK: $lockpath";
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 $!";
319 read ($lock_fh, $old_pid, 100)
321 ($old_pid) = $old_pid =~ /^(\d+)$/
323 DEBUG_TEST_CONCURRENCY_LOCKS
324 and dbg "Post-grab WAIT for $old_pid START: $lockpath";
327 kill (0, $old_pid) or last;
328 select( undef, undef, undef, 0.1 );
331 DEBUG_TEST_CONCURRENCY_LOCKS
332 and dbg "Post-grab WAIT for $old_pid FINISHED: $lockpath";
335 truncate $lock_fh, 0;
336 seek ($lock_fh, 0, SEEK_SET) or die "seek failed $!";
337 $lock_fh->autoflush(1);
340 $ENV{DBICTEST_LOCK_HOLDER} ||= $$;
345 lock_name => "$lockpath",
350 if ($INC{'Test/Builder.pm'}) {
351 populate_weakregistry ( $weak_registry, $self->storage );
353 my $cur_connect_call = $self->storage->on_connect_call;
355 $self->storage->on_connect_call([
356 (ref $cur_connect_call eq 'ARRAY'
358 : ($cur_connect_call || ())
361 populate_weakregistry( $weak_registry, shift->_dbh )
370 my $self = shift->next::method(@_);
371 populate_weakregistry ( $weak_registry, $self )
372 if $INC{'Test/Builder.pm'};
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');