Better exception when things get really really bad with prepare()
[dbsrgits/DBIx-Class.git] / t / 52leaks.t
CommitLineData
66917da3 1# work around brain damage in PPerl (yes, it has to be a global)
2$SIG{__WARN__} = sub {
3 warn @_ unless $_[0] =~ /\QUse of "goto" to jump into a construct is deprecated/
4} if ($ENV{DBICTEST_IN_PERSISTENT_ENV});
5
6# the persistent environments run with this flag first to see if
7# we will run at all (e.g. it will fail if $^X doesn't match)
8exit 0 if $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY};
9
f05edfd1 10# Do the override as early as possible so that CORE::bless doesn't get compiled away
11# We will replace $bless_override only if we are in author mode
12my $bless_override;
13BEGIN {
14 $bless_override = sub {
15 CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() );
16 };
17 *CORE::GLOBAL::bless = sub { goto $bless_override };
18}
19
50261284 20use strict;
21use warnings;
a917fb06 22use Test::More;
d5e5fb4b 23
66917da3 24my $TB = Test::More->builder;
25if ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
26 # without this explicit close ->reset below warns
27 close ($TB->$_) for qw/output failure_output/;
28
29 # so done_testing can work
30 $TB->reset;
31
32 # this simulates a subtest
33 $TB->_indent(' ' x 4);
34}
35
d5e5fb4b 36use lib qw(t/lib);
37use DBICTest::RunMode;
d12d8272 38BEGIN {
d5e5fb4b 39 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
40 if DBICTest::RunMode->peepeeness;
d12d8272 41}
42
a8c2c746 43use Scalar::Util qw/refaddr reftype weaken/;
44use Carp qw/longmess/;
45use Try::Tiny;
a917fb06 46
a8c2c746 47my $have_test_cycle;
a917fb06 48BEGIN {
226d1c35 49 require DBIx::Class::Optional::Dependencies;
a8c2c746 50 $have_test_cycle = DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks')
51 and import Test::Memory::Cycle;
a917fb06 52}
53
a8c2c746 54# this is what holds all weakened refs to be checked for leakage
55my $weak_registry = {};
56
57# Skip the heavy-duty leak tracing when just doing an install
58unless (DBICTest::RunMode->is_plain) {
f05edfd1 59 # Some modules are known to install singletons on-load
60 # Load them before we swap out $bless_override
61 require DBI;
62 require DBD::SQLite;
63 require Errno;
64 require Class::Struct;
65 require FileHandle;
307ab4c5 66 require Hash::Merge;
4376a157 67 require Storable;
f05edfd1 68
a8c2c746 69 no warnings qw/redefine once/;
70 no strict qw/refs/;
71
f05edfd1 72 # redefine the bless override so that we can catch each and every object created
73 $bless_override = sub {
74
a8c2c746 75 my $obj = CORE::bless(
76 $_[0], (@_ > 1) ? $_[1] : do {
77 my ($class, $fn, $line) = caller();
78 fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
79 if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
80 $class;
81 }
82 );
83
84 my $slot = (sprintf '%s=%s(0x%x)', # so we don't trigger stringification
85 ref $obj,
86 reftype $obj,
87 refaddr $obj,
88 );
89
90 # weaken immediately to avoid weird side effects
91 $weak_registry->{$slot} = { weakref => $obj, strace => longmess() };
92 weaken $weak_registry->{$slot}{weakref};
93
94 return $obj;
95 };
96
97 for my $func (qw/try catch finally/) {
98 my $orig = \&{"Try::Tiny::$func"};
99 *{"Try::Tiny::$func"} = sub (&;@) {
100
101 my $slot = sprintf ('CODE(0x%x)', refaddr $_[0]);
102
103 $weak_registry->{$slot} = { weakref => $_[0], strace => longmess() };
104 weaken $weak_registry->{$slot}{weakref};
105
106 goto $orig;
107 }
108 }
109}
110
111{
66917da3 112 use_ok ('DBICTest');
a917fb06 113
a8c2c746 114 my $schema = DBICTest->init_schema;
115 my $rs = $schema->resultset ('Artist');
116 my $storage = $schema->storage;
a917fb06 117
a8c2c746 118 ok ($storage->connected, 'we are connected');
a917fb06 119
052b8ce2 120 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
a8c2c746 121 ok ($row_obj, 'row from db');
122
052b8ce2 123 # txn_do to invoke more codepaths
a8c2c746 124 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
125
126 my $artist = $rs->create ({
127 name => 'foo artist',
128 cds => [{
129 title => 'foo cd',
130 year => 1984,
131 }],
132 });
133
134 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
135
136 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
137
138 return ($artist, $pg, $pg_wcount);
139 });
140
141 is ($pager->next_page, 3, 'There is one more page available');
142
143 # based on 66 per 10 pages
144 is ($pager_explicit_count->last_page, 7, 'Correct last page');
551e711a 145
052b8ce2 146 # do some population (invokes some extra codepaths)
147 # also exercise the guard code and the manual txn control
148 {
149 my $guard = $schema->txn_scope_guard;
150 # populate with bindvars
151 $rs->populate([{ name => 'James Bound' }]);
152 $guard->commit;
153
154 $schema->txn_begin;
155 # populate mixed
156 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
157 $schema->txn_commit;
158
159 $schema->txn_begin;
160 # and without bindvars
161 $rs->populate([{ name => \ '"James Unbound"' }]);
162 $schema->txn_rollback;
163 }
164
a8c2c746 165 my $base_collection = {
a8c2c746 166 resultset => $rs,
307ab4c5 167
37aafa2e 168 # twice so that we make sure only one H::M object spawned
169 chained_resultset => $rs->search_rs ({}, { '+columns' => [ 'foo' ] } ),
170 chained_resultset2 => $rs->search_rs ({}, { '+columns' => [ 'bar' ] } ),
171
a8c2c746 172 row_object => $row_obj,
551e711a 173
a8c2c746 174 result_source => $rs->result_source,
551e711a 175
4376a157 176 result_source_handle => $rs->result_source->handle,
177
a8c2c746 178 fresh_pager => $rs->page(5)->pager,
179 pager => $pager,
180 pager_explicit_count => $pager_explicit_count,
551e711a 181
a8c2c746 182 };
574d9b69 183
4376a157 184 %$base_collection = (
185 %$base_collection,
186 refrozen => Storable::dclone( $base_collection ),
187 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
188 schema => $schema,
189 storage => $storage,
190 sql_maker => $storage->sql_maker,
191 dbh => $storage->_dbh,
192 );
193
a8c2c746 194 memory_cycle_ok ($base_collection, 'No cycles in the object collection')
195 if $have_test_cycle;
574d9b69 196
a8c2c746 197 for (keys %$base_collection) {
198 $weak_registry->{"basic $_"} = { weakref => $base_collection->{$_} };
199 weaken $weak_registry->{"basic $_"}{weakref};
574d9b69 200 }
551e711a 201}
202
50261284 203# check that "phantom-chaining" works - we never lose track of the original $schema
204# and have access to the entire tree without leaking anything
205{
206 my $phantom;
207 for (
208 sub { DBICTest->init_schema },
209 sub { shift->source('Artist') },
210 sub { shift->resultset },
211 sub { shift->result_source },
212 sub { shift->schema },
213 sub { shift->resultset('Artist') },
214 sub { shift->find_or_create({ name => 'detachable' }) },
215 sub { shift->result_source },
216 sub { shift->schema },
217 sub { shift->clone },
218 sub { shift->resultset('Artist') },
219 sub { shift->next },
220 sub { shift->result_source },
221 sub { shift->resultset },
222 sub { shift->create({ name => 'detached' }) },
223 sub { shift->update({ name => 'reattached' }) },
224 sub { shift->discard_changes },
225 sub { shift->delete },
226 sub { shift->insert },
227 ) {
228 $phantom = $_->($phantom);
229
230 my $slot = (sprintf 'phantom %s=%s(0x%x)', # so we don't trigger stringification
231 ref $phantom,
232 reftype $phantom,
233 refaddr $phantom,
234 );
235 $weak_registry->{$slot} = $phantom;
236 weaken $weak_registry->{$slot};
237 }
238
239 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
240 is( $phantom->name, 'reattached', 'Still correct name' );
241}
a8c2c746 242
307ab4c5 243# Naturally we have some exceptions
244my $cleared;
245for my $slot (keys %$weak_registry) {
c8194884 246 if ($slot =~ /^\QTest::Builder/) {
247 # T::B 2.0 has result objects and other fancyness
248 delete $weak_registry->{$slot};
249 }
250 elsif ($slot =~ /^\QSQL::Translator/) {
307ab4c5 251 # SQLT is a piece of shit, leaks all over
252 delete $weak_registry->{$slot};
253 }
d12d8272 254 elsif ($slot =~ /^\QHash::Merge/) {
37aafa2e 255 # only clear one object of a specific behavior - more would indicate trouble
307ab4c5 256 delete $weak_registry->{$slot}
257 unless $cleared->{hash_merge_singleton}{$weak_registry->{$slot}{weakref}{behavior}}++;
258 }
1f870d5a 259 elsif ($slot =~ /^__TxnScopeGuard__FIXUP__/) {
48e4eac6 260 delete $weak_registry->{$slot}
261 if $] > 5.013001 and $] < 5.013008;
1f870d5a 262 }
307ab4c5 263}
264
265
a8c2c746 266# FIXME
267# For reasons I can not yet fully understand the table() god-method (located in
268# ::ResultSourceProxy::Table) attaches an actual source instance to each class
269# as virtually *immortal* class-data.
fa442fd5 270# For now just ignore these instances manually but there got to be a saner way
271for ( map { $_->result_source_instance } (
a8c2c746 272 'DBICTest::BaseResult',
273 map { DBICTest::Schema->class ($_) } DBICTest::Schema->sources
fa442fd5 274)) {
275 delete $weak_registry->{$_};
276}
a8c2c746 277
278# FIXME
279# same problem goes for the schema - its classdata contains live result source
280# objects, which to add insult to the injury are *different* instances from the
fa442fd5 281# ones we ignored above
282for ( values %{DBICTest::Schema->source_registrations || {}} ) {
283 delete $weak_registry->{$_};
284}
a8c2c746 285
48e4eac6 286for my $slot (sort keys %$weak_registry) {
a8c2c746 287
288 ok (! defined $weak_registry->{$slot}{weakref}, "No leaks of $slot") or do {
289 my $diag = '';
290
291 $diag .= Devel::FindRef::track ($weak_registry->{$slot}{weakref}, 20) . "\n"
66917da3 292 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
a8c2c746 293
294 if (my $stack = $weak_registry->{$slot}{strace}) {
295 $diag .= " Reference first seen$stack";
296 }
297
298 diag $diag if $diag;
299 };
551e711a 300}
301
66917da3 302
303# we got so far without a failure - this is a good thing
304# now let's try to rerun this script under a "persistent" environment
305# this is ugly and dirty but we do not yet have a Test::Embedded or
306# similar
307
308my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
309my @pperl_term_cmd = @pperl_cmd;
310splice @pperl_term_cmd, 1, 0, '--kill';
311
312# scgi is smart and will auto-reap after -t amount of seconds
313my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
314
315SKIP: {
316 skip 'Test already in a persistent loop', 1
317 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
318
319 skip 'Persistence test disabled on regular installs', 1
320 if DBICTest::RunMode->is_plain;
321
322 skip 'Main test failed - skipping persistent env tests', 1
323 unless $TB->is_passing;
324
325 # set up -I
326 require Config;
327 local $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
328
329 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
330
331 # try with pperl
332 SKIP: {
333 skip 'PPerl persistent environment tests require PPerl', 1
334 unless eval { require PPerl };
335
336 # since PPerl is racy and sucks - just prime the "server"
337 {
338 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
339 system(@pperl_cmd);
340 sleep 1;
341
342 # see if it actually runs - if not might as well bail now
343 skip "Something is wrong with pperl ($!)", 1
344 if system(@pperl_cmd);
345 }
346
347 for (1,2,3) {
348 system(@pperl_cmd);
349 ok (!$?, "Run in persistent env (PPerl pass $_): exit $?");
350 }
351
352 ok (! system (@pperl_term_cmd), 'killed pperl instance');
353 }
354
355 # try with speedy-cgi
356 SKIP: {
357 skip 'SPeedyCGI persistent environment tests require CGI::SpeedyCGI', 1
358 unless eval { require CGI::SpeedyCGI };
359
360 {
361 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
362 skip "Something is wrong with speedy ($!)", 1
363 if system(@scgi_cmd);
364 sleep 1;
365 }
366
367 for (1,2,3) {
368 system(@scgi_cmd);
369 ok (!$?, "Run in persistent env (SpeedyCGI pass $_): exit $?");
370 }
371 }
372}
373
551e711a 374done_testing;
66917da3 375
376# just an extra precaution in case we blew away from the SKIP - since there are no
377# PID files to go by (man does pperl really suck :(
378END {
379 unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
380 close STDOUT;
381 close STDERR;
382 local $?; # otherwise test will inherit $? of the system()
383 system (@pperl_term_cmd);
384 }
385}