4fa2f208a7349f665bed4f9eb1c9ec1c30d79b4d
[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     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] );
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   };
79 }
80
81 sub capture_executed_sql_bind {
82   my ($self, $cref) = @_;
83
84   $self->throw_exception("Expecting a coderef to run") unless ref $cref eq 'CODE';
85
86   require DBICTest::SQLTracerObj;
87
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
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   };
99
100   my $sg = scope_guard {
101     $self->storage->$_ ( $orig_states->{$_} ) for keys %$orig_states;
102   };
103
104   $self->storage->debugcb(undef);
105   $self->storage->debugobj( my $tracer_obj = DBICTest::SQLTracerObj->new );
106   $self->storage->debug(1);
107
108   local $Test::Builder::Level = $Test::Builder::Level + 2;
109   $cref->();
110
111   return $tracer_obj->{sqlbinds} || [];
112 }
113
114 sub 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
137 sub 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
184 our $locker;
185 END {
186   # we need the $locker to be referenced here for delayed destruction
187   if ($locker->{lock_name} and ($ENV{DBICTEST_LOCK_HOLDER}||0) == $$) {
188     DEBUG_TEST_CONCURRENCY_LOCKS
189       and dbg "$locker->{type} LOCK RELEASED (END): $locker->{lock_name}";
190   }
191 }
192
193 my $weak_registry = {};
194
195 sub 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
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
227     ($_[0]||'') !~ /^ (?i:dbi) \: SQLite (?: \: | \W ) .*? (?: dbname\= )? (?: \:memory\: | t [\/\\] var [\/\\] DBIxClass\-) /x
228   ) {
229
230     my $locktype;
231
232     {
233       # guard against infinite recursion
234       local $ENV{DBICTEST_LOCK_HOLDER} = -1;
235
236       # we need to work with a forced fresh clone so that we do not upset any state
237       # of the main $schema (some tests examine it quite closely)
238       local $SIG{__WARN__} = sub {};
239       local $SIG{__DIE__};
240       local $@;
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 {
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;
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;
256       };
257     }
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
266       DEBUG_TEST_CONCURRENCY_LOCKS
267         and $locker
268         and dbg "$locker->{type} LOCK RELEASED (UNDEF): $locker->{lock_name}";
269
270       undef $locker;
271
272       my $lockpath = tmpdir . "_dbictest_$locktype.lock";
273
274       DEBUG_TEST_CONCURRENCY_LOCKS
275         and dbg "Waiting for $locktype LOCK: $lockpath...";
276
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       }
282
283       await_flock ($lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
284
285       DEBUG_TEST_CONCURRENCY_LOCKS
286         and dbg "Got $locktype LOCK: $lockpath";
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       ) {
297         DEBUG_TEST_CONCURRENCY_LOCKS
298           and dbg "Post-grab WAIT for $old_pid START: $lockpath";
299
300         for (1..50) {
301           kill (0, $old_pid) or last;
302           select( undef, undef, undef, 0.1 );
303         }
304
305         DEBUG_TEST_CONCURRENCY_LOCKS
306           and dbg "Post-grab WAIT for $old_pid FINISHED: $lockpath";
307       }
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
343 sub clone {
344   my $self = shift->next::method(@_);
345   populate_weakregistry ( $weak_registry, $self )
346     if $INC{'Test/Builder.pm'};
347   $self;
348 }
349
350 END {
351   # Make sure we run after any cleanup in other END blocks
352   push @{ B::end_av()->object_2svref }, sub {
353     assert_empty_weakregistry($weak_registry, 'quiet');
354   };
355 }
356
357 1;