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 qw( emit_loud_diag scope_guard set_subname get_subname );
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 Scalar::Util qw( refaddr weaken );
16 if( $ENV{DBICTEST_ASSERT_NO_SPURIOUS_EXCEPTION_ACTION} ) {
17 my $ea = __PACKAGE__->exception_action( sub {
19 # Can not rely on $^S here at all - the exception_action
20 # itself is always called in an eval so that the goto-guard
21 # can work (see 7cb35852)
23 my ( $fr_num, $disarmed, $throw_exception_fr_num, $eval_fr_num );
24 while( ! $disarmed and my @fr = caller(++$fr_num) ) {
26 $throw_exception_fr_num ||= (
27 $fr[3] =~ /^DBIx::Class::(?:ResultSource|Schema|Storage|Exception)::throw(?:_exception)?$/
29 # there may be evals in the throwers themselves - skip those
30 ( $eval_fr_num ) = ( undef )
35 # now that the above stops un-setting us, we can find the first
44 $fr[1] =~ / \A (?: \. [\/\\] )? x?t [\/\\] .+ \.t \z /x
48 Test::Exception::throws_ok
50 Test::Exception::dies_ok
58 $fr[3] eq 'Test::Exception::lives_ok'
60 ( $::TODO or Test::Builder->new->in_todo )
66 Test::Builder->new->ok(0, join "\n",
67 'Unexpected &exception_action invocation',
69 ' You almost certainly used eval/try instead of dbic_internal_try()',
70 " Adjust *one* of the eval-ish constructs in the callstack starting" . DBICTest::Util::stacktrace($throw_exception_fr_num||())
77 ! $throw_exception_fr_num
81 DBIx::Class::Exception->throw( $_[0] );
84 my $interesting_ns_rx = qr/^ (?: main$ | DBIx::Class:: | DBICTest:: ) /x;
86 # hard-set $SIG{__DIE__} to the class-wide exception_action
87 # with a little escape preceeding it
90 # without this there would be false positives everywhere :(
92 # blindly rethrow if nobody is waiting for us
93 ( defined $^S and ! $^S )
95 (caller(0))[0] !~ $interesting_ns_rx
100 ( (caller(1))[0] || '' ) !~ $interesting_ns_rx
108 sub capture_executed_sql_bind {
109 my ($self, $cref) = @_;
111 $self->throw_exception("Expecting a coderef to run") unless ref $cref eq 'CODE';
113 require DBICTest::SQLTracerObj;
115 # hack around stupid, stupid API
116 no warnings 'redefine';
117 local *DBIx::Class::Storage::DBI::_format_for_trace = sub { $_[1] };
118 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
120 # can not use local() due to an unknown number of storages
122 my $orig_states = { map
123 { $_ => $self->storage->$_ }
124 qw(debugcb debugobj debug)
127 my $sg = scope_guard {
128 $self->storage->$_ ( $orig_states->{$_} ) for keys %$orig_states;
131 $self->storage->debugcb(undef);
132 $self->storage->debugobj( my $tracer_obj = DBICTest::SQLTracerObj->new );
133 $self->storage->debug(1);
135 local $Test::Builder::Level = $Test::Builder::Level + 2;
138 return $tracer_obj->{sqlbinds} || [];
141 sub is_executed_querycount {
142 my ($self, $cref, $exp_counts, $msg) = @_;
144 local $Test::Builder::Level = $Test::Builder::Level + 1;
146 $self->throw_exception("Expecting an hashref of counts or an integer representing total query count")
147 unless ref $exp_counts eq 'HASH' or (defined $exp_counts and ! ref $exp_counts);
149 my @got = map { $_->[0] } @{ $self->capture_executed_sql_bind($cref) };
151 return Test::More::is( @got, $exp_counts, $msg )
152 unless ref $exp_counts;
154 my $got_counts = { map { $_ => 0 } keys %$exp_counts };
155 $got_counts->{$_}++ for @got;
157 return Test::More::is_deeply(
164 sub is_executed_sql_bind {
165 my ($self, $cref, $sqlbinds, $msg) = @_;
167 local $Test::Builder::Level = $Test::Builder::Level + 1;
169 $self->throw_exception("Expecting an arrayref of SQL/Bind pairs") unless ref $sqlbinds eq 'ARRAY';
171 my @expected = @$sqlbinds;
173 my @got = map { $_->[1] } @{ $self->capture_executed_sql_bind($cref) };
176 return Test::Builder->new->ok(1, $msg || "No queries executed while running $cref")
177 if !@got and !@expected;
179 require SQL::Abstract::Test;
181 while (@expected or @got) {
182 my $left = shift @got;
183 my $right = shift @expected;
185 # allow the right side to "simplify" the entire shebang
186 if ($left and $right) {
188 for my $i (1..$#$right) {
192 ref $left->[$i] eq 'ARRAY'
196 $left->[$i] = $left->[$i][1]
201 $ret &= SQL::Abstract::Test::is_same_sql_bind(
213 # we need the $locker to be referenced here for delayed destruction
214 if ($locker->{lock_name} and ($ENV{DBICTEST_LOCK_HOLDER}||0) == $$) {
215 DEBUG_TEST_CONCURRENCY_LOCKS
216 and dbg "$locker->{type} LOCK RELEASED (END): $locker->{lock_name}";
220 my ( $weak_registry, $assertion_arounds ) = ( {}, {} );
222 sub DBICTest::__RsrcRedefiner_iThreads_handler__::CLONE {
223 if( DBIx::Class::_ENV_::ASSERT_NO_ERRONEOUS_METAINSTANCE_USE ) {
224 %$assertion_arounds = map {
226 ? ( refaddr($_) => $_ )
228 } values %$assertion_arounds;
230 weaken($_) for values %$assertion_arounds;
235 my $self = shift->next::method(@_);
238 # we can't really lock based on DSN, as we do not yet have a way to tell that e.g.
239 # DBICTEST_MSSQL_DSN=dbi:Sybase:server=192.168.0.11:1433;database=dbtst
241 # DBICTEST_MSSQL_ODBC_DSN=dbi:ODBC:server=192.168.0.11;port=1433;database=dbtst;driver=FreeTDS;tds_version=8.0
242 # are the same server
243 # hence we lock everything based on sqlt_type or just globally if not available
244 # just pretend we are python you know? :)
247 # when we get a proper DSN resolution sanitize to produce a portable lockfile name
248 # this may look weird and unnecessary, but consider running tests from
249 # windows over a samba share >.>
251 #$dsn =~ s/([^A-Za-z0-9_\-\.\=])/ sprintf '~%02X', ord($1) /ge;
252 #$dsn =~ s/^dbi/dbi/i;
254 # provide locking for physical (non-memory) DSNs, so that tests can
255 # safely run in parallel. While the harness (make -jN test) does set
256 # an envvar, we can not detect when a user invokes prove -jN. Hence
257 # perform the locking at all times, it shouldn't hurt.
258 # the lock fh *should* inherit across forks/subprocesses
260 ! $DBICTest::global_exclusive_lock
262 ( ! $ENV{DBICTEST_LOCK_HOLDER} or $ENV{DBICTEST_LOCK_HOLDER} == $$ )
266 ($_[0]||'') !~ /^ (?i:dbi) \: SQLite (?: \: | \W ) .*? (?: dbname\= )? (?: \:memory\: | t [\/\\] var [\/\\] DBIxClass\-) /x
272 # guard against infinite recursion
273 local $ENV{DBICTEST_LOCK_HOLDER} = -1;
275 # we need to work with a forced fresh clone so that we do not upset any state
276 # of the main $schema (some tests examine it quite closely)
277 local $SIG{__WARN__} = sub {};
278 local $SIG{__DIE__} if $SIG{__DIE__};
281 # this will either give us an undef $locktype or will determine things
282 # properly with a default ( possibly connecting in the process )
284 my $cur_storage = $self->storage;
286 $cur_storage = $cur_storage->master
287 if $cur_storage->isa('DBIx::Class::Storage::DBI::Replicated');
289 my $s = ref($self)->connect(@{$cur_storage->connect_info})->storage;
291 $locktype = $s->sqlt_type || 'generic';
293 # in case sqlt_type did connect, doesn't matter if it fails or something
298 # Never hold more than one lock. This solves the "lock in order" issues
299 # unrelated tests may have
300 # Also if there is no connection - there is no lock to be had
301 if ($locktype and (!$locker or $locker->{type} ne $locktype)) {
303 # this will release whatever lock we may currently be holding
304 # which is fine since the type does not match as checked above
305 DEBUG_TEST_CONCURRENCY_LOCKS
307 and dbg "$locker->{type} LOCK RELEASED (UNDEF): $locker->{lock_name}";
311 my $lockpath = tmpdir . "_dbictest_$locktype.lock";
313 DEBUG_TEST_CONCURRENCY_LOCKS
314 and dbg "Waiting for $locktype LOCK: $lockpath...";
318 my $u = local_umask(0); # so that the file opens as 666, and any user can lock
319 sysopen ($lock_fh, $lockpath, O_RDWR|O_CREAT) or die "Unable to open $lockpath: $!";
322 await_flock ($lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
324 DEBUG_TEST_CONCURRENCY_LOCKS
325 and dbg "Got $locktype LOCK: $lockpath";
327 # see if anyone was holding a lock before us, and wait up to 5 seconds for them to terminate
328 # if we do not do this we may end up trampling over some long-running END or somesuch
329 seek ($lock_fh, 0, SEEK_SET) or die "seek failed $!";
332 read ($lock_fh, $old_pid, 100)
334 ($old_pid) = $old_pid =~ /^(\d+)$/
336 DEBUG_TEST_CONCURRENCY_LOCKS
337 and dbg "Post-grab WAIT for $old_pid START: $lockpath";
340 kill (0, $old_pid) or last;
341 select( undef, undef, undef, 0.1 );
344 DEBUG_TEST_CONCURRENCY_LOCKS
345 and dbg "Post-grab WAIT for $old_pid FINISHED: $lockpath";
348 truncate $lock_fh, 0;
349 seek ($lock_fh, 0, SEEK_SET) or die "seek failed $!";
350 $lock_fh->autoflush(1);
353 $ENV{DBICTEST_LOCK_HOLDER} ||= $$;
358 lock_name => "$lockpath",
363 if ($INC{'Test/Builder.pm'}) {
364 populate_weakregistry ( $weak_registry, $self->storage );
366 my $cur_connect_call = $self->storage->on_connect_call;
368 $self->storage->on_connect_call([
369 (ref $cur_connect_call eq 'ARRAY'
371 : ($cur_connect_call || ())
374 populate_weakregistry( $weak_registry, shift->_dbh )
380 # Check an explicit level of indirection: makes sure that folks doing
381 # use `base "DBIx::Class::Core"; __PACKAGE__->add_column("foo")`
382 # will see the correct error message
384 # In the future this all is likely to be folded into a single method in
385 # some way, but that's a fight for another maint
387 if( DBIx::Class::_ENV_::ASSERT_NO_ERRONEOUS_METAINSTANCE_USE ) {
389 for my $class_of_interest (
391 map { $self->class($_) } ($self->sources)
394 my $orig_rsrc = $class_of_interest->can('result_source')
395 or die "How did we get here?!";
397 unless ( $assertion_arounds->{refaddr $orig_rsrc} ) {
399 my ($origin) = get_subname($orig_rsrc);
401 no warnings 'redefine';
404 *{"${origin}::result_source"} = my $replacement = set_subname "${origin}::result_source" => sub {
409 (CORE::caller(0))[1] !~ / (?: ^ | [\/\\] ) x?t [\/\\] .+? \.t $ /x
412 msg => 'Incorrect indirect call of result_source() as setter must be changed to result_source_instance()',
418 ! (CORE::caller($_))[7]
420 ( (CORE::caller($_))[3] || '' ) eq '(eval)'
422 ( (CORE::caller($_))[1] || '' ) !~ / (?: ^ | [\/\\] ) x?t [\/\\] .+? \.t $ /x
425 # these evals are legit
426 ( (CORE::caller(4))[3] || '' ) !~ /^ (?:
427 DBIx::Class::Schema::_ns_get_rsrc_instance
429 DBIx::Class::Relationship::BelongsTo::belongs_to
431 DBIx::Class::Relationship::HasOne::_has_one
433 Class::C3::Componentised::.+
437 # not much else we can do (aside from exit(1) which is too obnoxious)
438 msg => 'Incorrect call of result_source() in an eval',
445 weaken( $assertion_arounds->{refaddr $replacement} = $replacement );
449 # no rsrc_instance to mangle
450 next if $class_of_interest eq 'DBIx::Class::Row';
453 my $orig_rsrc_instance = $class_of_interest->can('result_source_instance')
454 or die "How did we get here?!";
456 # Do the around() per definition-site as result_source_instance is a CAG inherited cref
457 unless ( $assertion_arounds->{refaddr $orig_rsrc_instance} ) {
459 my ($origin) = get_subname($orig_rsrc_instance);
461 no warnings 'redefine';
464 *{"${origin}::result_source_instance"} = my $replacement = set_subname "${origin}::result_source_instance" => sub {
469 # special cased as we do not care whether there is a source
470 ( (CORE::caller(4))[3] || '' ) ne 'DBIx::Class::Schema::_register_source'
472 # special case because I am paranoid
473 ( (CORE::caller(4))[3] || '' ) ne 'DBIx::Class::Row::throw_exception'
475 ( (CORE::caller(1))[3] || '' ) !~ / ^ DBIx::Class:: (?:
480 ResultSourceProxy::Table:: (?: _init_result_source_instance | table )
482 ResultSourceHandle::STORABLE_thaw
485 (CORE::caller(0))[1] !~ / (?: ^ | [\/\\] ) x?t [\/\\] .+? \.t $ /x
488 msg => 'Incorrect direct call of result_source_instance() as getter must be changed to result_source()',
494 ! (CORE::caller($_))[7]
496 ( (CORE::caller($_))[3] || '' ) eq '(eval)'
498 ( (CORE::caller($_))[1] || '' ) !~ / (?: ^ | [\/\\] ) x?t [\/\\] .+? \.t $ /x
501 # special cased as we do not care whether there is a source
502 ( (CORE::caller(4))[3] || '' ) ne 'DBIx::Class::Schema::_register_source'
504 # special case because I am paranoid
505 ( (CORE::caller(4))[3] || '' ) ne 'DBIx::Class::Row::throw_exception'
507 # special case for Storable, which in turn calls from an eval
508 ( (CORE::caller(1))[3] || '' ) ne 'DBIx::Class::ResultSourceHandle::STORABLE_thaw'
511 # not much else we can do (aside from exit(1) which is too obnoxious)
512 msg => 'Incorrect call of result_source_instance() in an eval',
517 &$orig_rsrc_instance;
520 weaken( $assertion_arounds->{refaddr $replacement} = $replacement );
525 Class::C3::initialize if DBIx::Class::_ENV_::OLD_MRO;
528 # END Check an explicit level of indirection
534 my $self = shift->next::method(@_);
535 populate_weakregistry ( $weak_registry, $self )
536 if $INC{'Test/Builder.pm'};
541 # Make sure we run after any cleanup in other END blocks
542 push @{ B::end_av()->object_2svref }, sub {
543 assert_empty_weakregistry($weak_registry, 'quiet');