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