Fix failures with DBICTEST_SQLITE_USE_FILE=1 introduced by 50261284
[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;
65d35121 38use DBICTest::Util qw/populate_weakregistry assert_empty_weakregistry/;
e0b2dc74 39use DBIx::Class;
dee99c24 40use B 'svref_2object';
d12d8272 41BEGIN {
d5e5fb4b 42 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
dee99c24 43 if DBIx::Class::_ENV_::PEEPEENESS;
d12d8272 44}
45
a8c2c746 46# this is what holds all weakened refs to be checked for leakage
47my $weak_registry = {};
48
6a43bc0c 49# whether or to invoke IC::DT
50my $has_dt;
51
a8c2c746 52# Skip the heavy-duty leak tracing when just doing an install
53unless (DBICTest::RunMode->is_plain) {
f05edfd1 54
eb7aa960 55 # redefine the bless override so that we can catch each and every object created
a8c2c746 56 no warnings qw/redefine once/;
57 no strict qw/refs/;
58
f05edfd1 59 $bless_override = sub {
60
a8c2c746 61 my $obj = CORE::bless(
62 $_[0], (@_ > 1) ? $_[1] : do {
63 my ($class, $fn, $line) = caller();
64 fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
65 if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
66 $class;
67 }
68 );
69
a8c2c746 70 # weaken immediately to avoid weird side effects
65d35121 71 return populate_weakregistry ($weak_registry, $obj );
a8c2c746 72 };
73
eb7aa960 74 require Try::Tiny;
a8c2c746 75 for my $func (qw/try catch finally/) {
76 my $orig = \&{"Try::Tiny::$func"};
77 *{"Try::Tiny::$func"} = sub (&;@) {
65d35121 78 populate_weakregistry( $weak_registry, $_[0] );
a8c2c746 79 goto $orig;
80 }
81 }
eb7aa960 82
83 # Some modules are known to install singletons on-load
84 # Load them and empty the registry
85
86 # this loads the DT armada
87 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
88
89 require Errno;
90 require DBI;
91 require DBD::SQLite;
92 require FileHandle;
93
94 %$weak_registry = ();
a8c2c746 95}
96
dee99c24 97my @compose_ns_classes;
a8c2c746 98{
66917da3 99 use_ok ('DBICTest');
a917fb06 100
a8c2c746 101 my $schema = DBICTest->init_schema;
102 my $rs = $schema->resultset ('Artist');
103 my $storage = $schema->storage;
a917fb06 104
dee99c24 105 @compose_ns_classes = map { "DBICTest::${_}" } keys %{$schema->source_registrations};
106
a8c2c746 107 ok ($storage->connected, 'we are connected');
a917fb06 108
052b8ce2 109 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
a8c2c746 110 ok ($row_obj, 'row from db');
111
052b8ce2 112 # txn_do to invoke more codepaths
a8c2c746 113 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
114
9345b14c 115 my $artist = $schema->resultset('Artist')->create ({
a8c2c746 116 name => 'foo artist',
117 cds => [{
118 title => 'foo cd',
119 year => 1984,
187ec69a 120 tracks => [
121 { title => 't1' },
122 { title => 't2' },
123 ],
124 genre => { name => 'mauve' },
a8c2c746 125 }],
126 });
127
128 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
129
130 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
131
132 return ($artist, $pg, $pg_wcount);
133 });
134
9345b14c 135 # more codepaths - error handling in txn_do
136 {
137 eval { $schema->txn_do ( sub {
138 $storage->_dbh->begin_work;
139 fail ('how did we get so far?!');
140 } ) };
141
142 eval { $schema->txn_do ( sub {
143 $schema->txn_do ( sub {
144 die "It's called EXCEPTION";
145 fail ('how did we get so far?!');
146 } );
147 fail ('how did we get so far?!');
148 } ) };
149 like( $@, qr/It\'s called EXCEPTION/, 'Exception correctly propagated in nested txn_do' );
150 }
151
152 # dbh_do codepath
187ec69a 153 my ($rs_bind_circref, $cond_rowobj) = $schema->storage->dbh_do ( sub {
154 my $row = $_[0]->schema->resultset('Artist')->new({});
155 my $rs = $_[0]->schema->resultset('Artist')->search({
156 name => $row, # this is deliberately bogus, see FIXME below!
157 });
158 return ($rs, $row);
159 });
160
a8c2c746 161 is ($pager->next_page, 3, 'There is one more page available');
162
163 # based on 66 per 10 pages
164 is ($pager_explicit_count->last_page, 7, 'Correct last page');
551e711a 165
052b8ce2 166 # do some population (invokes some extra codepaths)
167 # also exercise the guard code and the manual txn control
168 {
169 my $guard = $schema->txn_scope_guard;
170 # populate with bindvars
171 $rs->populate([{ name => 'James Bound' }]);
172 $guard->commit;
173
174 $schema->txn_begin;
175 # populate mixed
176 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
177 $schema->txn_commit;
178
179 $schema->txn_begin;
180 # and without bindvars
181 $rs->populate([{ name => \ '"James Unbound"' }]);
182 $schema->txn_rollback;
183 }
184
0a03206a 185 # prefetching
186 my $cds_rs = $schema->resultset('CD');
187 my $cds_with_artist = $cds_rs->search({}, { prefetch => 'artist' });
188 my $cds_with_tracks = $cds_rs->search({}, { prefetch => 'tracks' });
189 my $cds_with_stuff = $cds_rs->search({}, { prefetch => [ 'genre', { artist => { cds => { tracks => 'cd_single' } } } ] });
190
191 # implicit pref
192 my $cds_with_impl_artist = $cds_rs->search({}, { columns => [qw/me.title artist.name/], join => 'artist' });
193
194 # get_column
195 my $getcol_rs = $cds_rs->get_column('me.cdid');
196 my $pref_getcol_rs = $cds_with_stuff->get_column('me.cdid');
197
198 # fire the column getters
199 my @throwaway = $pref_getcol_rs->all;
200
a8c2c746 201 my $base_collection = {
a8c2c746 202 resultset => $rs,
307ab4c5 203
0a03206a 204 pref_precursor => $cds_rs,
205
206 pref_rs_single => $cds_with_artist,
207 pref_rs_multi => $cds_with_tracks,
208 pref_rs_nested => $cds_with_stuff,
209
210 pref_rs_implicit => $cds_with_impl_artist,
211
212 pref_row_single => $cds_with_artist->next,
213 pref_row_multi => $cds_with_tracks->next,
214 pref_row_nested => $cds_with_stuff->next,
215
216 # even though this does not leak Storable croaks on it :(((
217 #pref_row_implicit => $cds_with_impl_artist->next,
218
219 get_column_rs_plain => $getcol_rs,
220 get_column_rs_pref => $pref_getcol_rs,
221
37aafa2e 222 # twice so that we make sure only one H::M object spawned
223 chained_resultset => $rs->search_rs ({}, { '+columns' => [ 'foo' ] } ),
224 chained_resultset2 => $rs->search_rs ({}, { '+columns' => [ 'bar' ] } ),
225
a8c2c746 226 row_object => $row_obj,
551e711a 227
187ec69a 228 mc_row_object => $mc_row_obj,
229
a8c2c746 230 result_source => $rs->result_source,
551e711a 231
4376a157 232 result_source_handle => $rs->result_source->handle,
233
a8c2c746 234 pager_explicit_count => $pager_explicit_count,
187ec69a 235
236 leaky_resultset => $rs_bind_circref,
237 leaky_resultset_cond => $cond_rowobj,
238 leaky_resultset_member => $rs_bind_circref->next,
a8c2c746 239 };
574d9b69 240
eb7aa960 241 require Storable;
4376a157 242 %$base_collection = (
243 %$base_collection,
244 refrozen => Storable::dclone( $base_collection ),
245 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
0a03206a 246 pref_row_implicit => $cds_with_impl_artist->next,
4376a157 247 schema => $schema,
248 storage => $storage,
249 sql_maker => $storage->sql_maker,
250 dbh => $storage->_dbh,
cd122820 251 fresh_pager => $rs->page(5)->pager,
252 pager => $pager,
4376a157 253 );
254
6a43bc0c 255 if ($has_dt) {
256 my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
257
258 my $now = DateTime->now;
259 for (1..5) {
260 $base_collection->{"icdt_row_$_"} = $rs->create({
261 created_on => DateTime->new(year => 2011, month => 1, day => $_, time_zone => "-0${_}00" ),
262 starts_at => $now->clone->add(days => $_),
263 });
264 }
265
266 # re-search
267 my @dummy = $rs->all;
268 }
269
eb7aa960 270 # dbh's are created in XS space, so pull them separately
271 for ( grep { defined } map { @{$_->{ChildHandles}} } values %{ {DBI->installed_drivers()} } ) {
272 $base_collection->{"DBI handle $_"} = $_;
273 }
274
187ec69a 275 SKIP: {
276 if ( DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks') ) {
277 Test::Memory::Cycle::memory_cycle_ok ($base_collection, 'No cycles in the object collection')
278 }
279 else {
280 skip 'Circular ref test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_leaks'), 1;
281 }
eb7aa960 282 }
574d9b69 283
65d35121 284 populate_weakregistry ($weak_registry, $base_collection->{$_}, "basic $_")
285 for keys %$base_collection;
551e711a 286}
287
50261284 288# check that "phantom-chaining" works - we never lose track of the original $schema
289# and have access to the entire tree without leaking anything
290{
291 my $phantom;
292 for (
39b80a73 293 sub { DBICTest->init_schema( sqlite_use_file => 0 ) },
50261284 294 sub { shift->source('Artist') },
295 sub { shift->resultset },
296 sub { shift->result_source },
297 sub { shift->schema },
298 sub { shift->resultset('Artist') },
299 sub { shift->find_or_create({ name => 'detachable' }) },
300 sub { shift->result_source },
301 sub { shift->schema },
302 sub { shift->clone },
187ec69a 303 sub { shift->resultset('CD') },
304 sub { shift->next },
305 sub { shift->artist },
306 sub { shift->search_related('cds') },
50261284 307 sub { shift->next },
187ec69a 308 sub { shift->search_related('artist') },
50261284 309 sub { shift->result_source },
310 sub { shift->resultset },
311 sub { shift->create({ name => 'detached' }) },
312 sub { shift->update({ name => 'reattached' }) },
313 sub { shift->discard_changes },
314 sub { shift->delete },
315 sub { shift->insert },
316 ) {
65d35121 317 $phantom = populate_weakregistry ( $weak_registry, scalar $_->($phantom) );
50261284 318 }
319
320 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
321 is( $phantom->name, 'reattached', 'Still correct name' );
322}
a8c2c746 323
307ab4c5 324# Naturally we have some exceptions
325my $cleared;
326for my $slot (keys %$weak_registry) {
6a43bc0c 327 if ($slot =~ /^Test::Builder/) {
c8194884 328 # T::B 2.0 has result objects and other fancyness
329 delete $weak_registry->{$slot};
330 }
9345b14c 331 elsif ($slot =~ /^Method::Generate::(?:Accessor|Constructor)/) {
332 # Moo keeps globals around, this is normal
333 delete $weak_registry->{$slot};
334 }
6a43bc0c 335 elsif ($slot =~ /^SQL::Translator/) {
307ab4c5 336 # SQLT is a piece of shit, leaks all over
337 delete $weak_registry->{$slot};
338 }
6a43bc0c 339 elsif ($slot =~ /^Hash::Merge/) {
37aafa2e 340 # only clear one object of a specific behavior - more would indicate trouble
307ab4c5 341 delete $weak_registry->{$slot}
342 unless $cleared->{hash_merge_singleton}{$weak_registry->{$slot}{weakref}{behavior}}++;
343 }
b4ad8a74 344 elsif (DBIx::Class::_ENV_::INVISIBLE_DOLLAR_AT and $slot =~ /^__TxnScopeGuard__FIXUP__/) {
48e4eac6 345 delete $weak_registry->{$slot}
1f870d5a 346 }
eb7aa960 347 elsif ($slot =~ /^DateTime::TimeZone/) {
348 # DT is going through a refactor it seems - let it leak zones for now
349 delete $weak_registry->{$slot};
350 }
307ab4c5 351}
352
dee99c24 353# every result class has a result source instance as classdata
354# make sure these are all present and distinct before ignoring
355# (distinct means only 1 reference)
356for my $rs_class (
a8c2c746 357 'DBICTest::BaseResult',
dee99c24 358 @compose_ns_classes,
a8c2c746 359 map { DBICTest::Schema->class ($_) } DBICTest::Schema->sources
dee99c24 360) {
361 # need to store the SVref and examine it separately, to push the rsrc instance off the pad
362 my $SV = svref_2object($rs_class->result_source_instance);
363 is( $SV->REFCNT, 1, "Source instance of $rs_class referenced exactly once" );
364
365 # ignore it
366 delete $weak_registry->{$rs_class->result_source_instance};
fa442fd5 367}
a8c2c746 368
dee99c24 369# Schema classes also hold sources, but these are clones, since
370# each source contains the schema (or schema class name in this case)
371# Hence the clone so that the same source can be registered with
372# multiple schemas
373for my $moniker ( keys %{DBICTest::Schema->source_registrations || {}} ) {
374
375 my $SV = svref_2object(DBICTest::Schema->source($moniker));
376 is( $SV->REFCNT, 1, "Source instance registered under DBICTest::Schema as $moniker referenced exactly once" );
377
378 delete $weak_registry->{DBICTest::Schema->source($moniker)};
fa442fd5 379}
a8c2c746 380
187ec69a 381# FIXME !!!
382# There is an actual strong circular reference taking place here, but because
383# half of it is in XS no leaktracer sees it, and Devel::FindRef is equally
384# stumped when trying to trace the origin. The problem is:
385#
386# $cond_object --> result_source --> schema --> storage --> $dbh --> {cached_kids}
387# ^ /
388# \-------- bound value on prepared/cached STH <-----------/
389#
390TODO: {
391 local $TODO = 'Not sure how to fix this yet, an entanglment could be an option';
392 my $r = $weak_registry->{'basic leaky_resultset_cond'}{weakref};
393 ok(! defined $r, 'We no longer leak!')
394 or $r->result_source(undef);
395}
396
65d35121 397assert_empty_weakregistry ($weak_registry);
551e711a 398
66917da3 399# we got so far without a failure - this is a good thing
400# now let's try to rerun this script under a "persistent" environment
401# this is ugly and dirty but we do not yet have a Test::Embedded or
402# similar
403
404my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
405my @pperl_term_cmd = @pperl_cmd;
406splice @pperl_term_cmd, 1, 0, '--kill';
407
408# scgi is smart and will auto-reap after -t amount of seconds
409my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
410
411SKIP: {
412 skip 'Test already in a persistent loop', 1
413 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
414
415 skip 'Persistence test disabled on regular installs', 1
416 if DBICTest::RunMode->is_plain;
417
418 skip 'Main test failed - skipping persistent env tests', 1
419 unless $TB->is_passing;
420
421 # set up -I
422 require Config;
423 local $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
424
425 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
426
427 # try with pperl
428 SKIP: {
429 skip 'PPerl persistent environment tests require PPerl', 1
430 unless eval { require PPerl };
431
432 # since PPerl is racy and sucks - just prime the "server"
433 {
434 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
435 system(@pperl_cmd);
436 sleep 1;
437
438 # see if it actually runs - if not might as well bail now
439 skip "Something is wrong with pperl ($!)", 1
440 if system(@pperl_cmd);
441 }
442
443 for (1,2,3) {
444 system(@pperl_cmd);
445 ok (!$?, "Run in persistent env (PPerl pass $_): exit $?");
446 }
447
448 ok (! system (@pperl_term_cmd), 'killed pperl instance');
449 }
450
451 # try with speedy-cgi
452 SKIP: {
453 skip 'SPeedyCGI persistent environment tests require CGI::SpeedyCGI', 1
454 unless eval { require CGI::SpeedyCGI };
455
456 {
457 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
458 skip "Something is wrong with speedy ($!)", 1
459 if system(@scgi_cmd);
460 sleep 1;
461 }
462
463 for (1,2,3) {
464 system(@scgi_cmd);
465 ok (!$?, "Run in persistent env (SpeedyCGI pass $_): exit $?");
466 }
467 }
468}
469
551e711a 470done_testing;
66917da3 471
472# just an extra precaution in case we blew away from the SKIP - since there are no
473# PID files to go by (man does pperl really suck :(
474END {
475 unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
476 close STDOUT;
477 close STDERR;
478 local $?; # otherwise test will inherit $? of the system()
479 system (@pperl_term_cmd);
480 }
481}