Stop using precomputed SQLite testdb name, fix test-end bug in replicated.t
[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}) {
7be5717e 26 # without this explicit close older TBs warn in END after a ->reset
27 if ($TB->VERSION < 1.005) {
28 close ($TB->$_) for (qw/output failure_output todo_output/);
29 }
66917da3 30
7be5717e 31 # if I do not do this, I get happy sigpipes on new TB, no idea why
32 # (the above close-and-forget doesn't work - new TB does *not* reopen
33 # its handles automatically anymore)
34 else {
35 for (qw/failure_output todo_output/) {
36 close $TB->$_;
37 open ($TB->$_, '>&', *STDERR);
38 }
66917da3 39
7be5717e 40 close $TB->output;
41 open ($TB->output, '>&', *STDOUT);
42 }
43
44 # so done_testing can work on every persistent pass
45 $TB->reset;
66917da3 46}
47
d5e5fb4b 48use lib qw(t/lib);
49use DBICTest::RunMode;
5dc4301c 50use DBICTest::Util::LeakTracer qw(populate_weakregistry assert_empty_weakregistry visit_refs hrefaddr);
b35500f1 51use Scalar::Util qw(weaken blessed);
e0b2dc74 52use DBIx::Class;
d12d8272 53BEGIN {
d5e5fb4b 54 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
dee99c24 55 if DBIx::Class::_ENV_::PEEPEENESS;
d12d8272 56}
57
a8c2c746 58# this is what holds all weakened refs to be checked for leakage
59my $weak_registry = {};
60
6a43bc0c 61# whether or to invoke IC::DT
62my $has_dt;
63
a8c2c746 64# Skip the heavy-duty leak tracing when just doing an install
65unless (DBICTest::RunMode->is_plain) {
f05edfd1 66
eb7aa960 67 # redefine the bless override so that we can catch each and every object created
a8c2c746 68 no warnings qw/redefine once/;
69 no strict qw/refs/;
70
f05edfd1 71 $bless_override = sub {
72
a8c2c746 73 my $obj = CORE::bless(
74 $_[0], (@_ > 1) ? $_[1] : do {
75 my ($class, $fn, $line) = caller();
76 fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
77 if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
78 $class;
79 }
80 );
81
8d6b1478 82 # unicode is tricky, and now we happen to invoke it early via a
83 # regex in connection()
84 return $obj if (ref $obj) =~ /^utf8/;
85
7be5717e 86 # Test Builder is now making a new object for every pass/fail (que bloat?)
87 # and as such we can't really store any of its objects (since it will
88 # re-populate the registry while checking it, ewwww!)
89 return $obj if (ref $obj) =~ /^TB2::/;
90
5dc4301c 91 # populate immediately to avoid weird side effects
65d35121 92 return populate_weakregistry ($weak_registry, $obj );
a8c2c746 93 };
94
eb7aa960 95 require Try::Tiny;
a8c2c746 96 for my $func (qw/try catch finally/) {
97 my $orig = \&{"Try::Tiny::$func"};
98 *{"Try::Tiny::$func"} = sub (&;@) {
65d35121 99 populate_weakregistry( $weak_registry, $_[0] );
a8c2c746 100 goto $orig;
101 }
102 }
eb7aa960 103
104 # Some modules are known to install singletons on-load
105 # Load them and empty the registry
106
107 # this loads the DT armada
108 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
109
110 require Errno;
111 require DBI;
112 require DBD::SQLite;
113 require FileHandle;
e6ff3658 114 require Moo;
eb7aa960 115
116 %$weak_registry = ();
a8c2c746 117}
118
119{
66917da3 120 use_ok ('DBICTest');
a917fb06 121
a8c2c746 122 my $schema = DBICTest->init_schema;
123 my $rs = $schema->resultset ('Artist');
124 my $storage = $schema->storage;
a917fb06 125
a8c2c746 126 ok ($storage->connected, 'we are connected');
a917fb06 127
052b8ce2 128 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
a8c2c746 129 ok ($row_obj, 'row from db');
130
052b8ce2 131 # txn_do to invoke more codepaths
a8c2c746 132 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
133
9345b14c 134 my $artist = $schema->resultset('Artist')->create ({
a8c2c746 135 name => 'foo artist',
136 cds => [{
137 title => 'foo cd',
138 year => 1984,
187ec69a 139 tracks => [
140 { title => 't1' },
141 { title => 't2' },
142 ],
143 genre => { name => 'mauve' },
a8c2c746 144 }],
145 });
146
147 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
148
149 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
150
151 return ($artist, $pg, $pg_wcount);
152 });
153
9345b14c 154 # more codepaths - error handling in txn_do
155 {
156 eval { $schema->txn_do ( sub {
157 $storage->_dbh->begin_work;
158 fail ('how did we get so far?!');
159 } ) };
160
161 eval { $schema->txn_do ( sub {
162 $schema->txn_do ( sub {
163 die "It's called EXCEPTION";
164 fail ('how did we get so far?!');
165 } );
166 fail ('how did we get so far?!');
167 } ) };
168 like( $@, qr/It\'s called EXCEPTION/, 'Exception correctly propagated in nested txn_do' );
169 }
170
171 # dbh_do codepath
187ec69a 172 my ($rs_bind_circref, $cond_rowobj) = $schema->storage->dbh_do ( sub {
173 my $row = $_[0]->schema->resultset('Artist')->new({});
174 my $rs = $_[0]->schema->resultset('Artist')->search({
175 name => $row, # this is deliberately bogus, see FIXME below!
176 });
177 return ($rs, $row);
178 });
179
a8c2c746 180 is ($pager->next_page, 3, 'There is one more page available');
181
182 # based on 66 per 10 pages
183 is ($pager_explicit_count->last_page, 7, 'Correct last page');
551e711a 184
052b8ce2 185 # do some population (invokes some extra codepaths)
186 # also exercise the guard code and the manual txn control
187 {
188 my $guard = $schema->txn_scope_guard;
189 # populate with bindvars
190 $rs->populate([{ name => 'James Bound' }]);
191 $guard->commit;
192
193 $schema->txn_begin;
194 # populate mixed
195 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
196 $schema->txn_commit;
197
198 $schema->txn_begin;
199 # and without bindvars
200 $rs->populate([{ name => \ '"James Unbound"' }]);
201 $schema->txn_rollback;
202 }
203
0a03206a 204 # prefetching
205 my $cds_rs = $schema->resultset('CD');
206 my $cds_with_artist = $cds_rs->search({}, { prefetch => 'artist' });
207 my $cds_with_tracks = $cds_rs->search({}, { prefetch => 'tracks' });
208 my $cds_with_stuff = $cds_rs->search({}, { prefetch => [ 'genre', { artist => { cds => { tracks => 'cd_single' } } } ] });
209
210 # implicit pref
211 my $cds_with_impl_artist = $cds_rs->search({}, { columns => [qw/me.title artist.name/], join => 'artist' });
212
213 # get_column
214 my $getcol_rs = $cds_rs->get_column('me.cdid');
215 my $pref_getcol_rs = $cds_with_stuff->get_column('me.cdid');
216
217 # fire the column getters
218 my @throwaway = $pref_getcol_rs->all;
219
a8c2c746 220 my $base_collection = {
a8c2c746 221 resultset => $rs,
307ab4c5 222
0a03206a 223 pref_precursor => $cds_rs,
224
225 pref_rs_single => $cds_with_artist,
226 pref_rs_multi => $cds_with_tracks,
227 pref_rs_nested => $cds_with_stuff,
228
229 pref_rs_implicit => $cds_with_impl_artist,
230
231 pref_row_single => $cds_with_artist->next,
232 pref_row_multi => $cds_with_tracks->next,
233 pref_row_nested => $cds_with_stuff->next,
234
235 # even though this does not leak Storable croaks on it :(((
236 #pref_row_implicit => $cds_with_impl_artist->next,
237
238 get_column_rs_plain => $getcol_rs,
239 get_column_rs_pref => $pref_getcol_rs,
240
37aafa2e 241 # twice so that we make sure only one H::M object spawned
b35500f1 242 chained_resultset => $rs->search_rs ({}, { '+columns' => { foo => 'artistid' } } ),
243 chained_resultset2 => $rs->search_rs ({}, { '+columns' => { bar => 'artistid' } } ),
37aafa2e 244
a8c2c746 245 row_object => $row_obj,
551e711a 246
187ec69a 247 mc_row_object => $mc_row_obj,
248
a8c2c746 249 result_source => $rs->result_source,
551e711a 250
4376a157 251 result_source_handle => $rs->result_source->handle,
252
a8c2c746 253 pager_explicit_count => $pager_explicit_count,
187ec69a 254
255 leaky_resultset => $rs_bind_circref,
256 leaky_resultset_cond => $cond_rowobj,
a8c2c746 257 };
574d9b69 258
b35500f1 259 # fire all resultsets multiple times
260 # even if some of them can't find anything
261 # (notably leaky_resultset)
262 my @rsets = grep
263 { blessed $_ and $_->isa('DBIx::Class::ResultSet') }
264 values %$base_collection
265 ;
266
267 push @{$base_collection->{random_results}}, map { $_->all } @rsets
268 for (1,2);
269
270 # FIXME - something throws a Storable for a spin if we keep
271 # the results in-collection. The same problem is seen above,
272 # swept under the rug back in 0a03206a, damned lazy ribantainer
273{
274 local $base_collection->{random_results};
218b7c12 275
eb7aa960 276 require Storable;
4376a157 277 %$base_collection = (
278 %$base_collection,
279 refrozen => Storable::dclone( $base_collection ),
280 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
0a03206a 281 pref_row_implicit => $cds_with_impl_artist->next,
4376a157 282 schema => $schema,
283 storage => $storage,
284 sql_maker => $storage->sql_maker,
285 dbh => $storage->_dbh,
cd122820 286 fresh_pager => $rs->page(5)->pager,
287 pager => $pager,
4376a157 288 );
b35500f1 289}
4376a157 290
21aa86aa 291 # FIXME - ideally this kind of collector ought to be global, but attempts
292 # with an invasive debugger-based tracer did not quite work out... yet
293 # Manually scan the innards of everything we have in the base collection
294 # we assembled so far (skip the DT madness below) *recursively*
295 #
296 # Only do this when we do have the bits to look inside CVs properly,
297 # without it we are liable to pick up object defaults that are locked
298 # in method closures
299 if (DBICTest::Util::LeakTracer::CV_TRACING) {
300 visit_refs(
301 refs => [ $base_collection ],
302 action => sub {
303 populate_weakregistry ($weak_registry, $_[0]);
304 1; # true means "keep descending"
305 },
306 );
307 }
308
6a43bc0c 309 if ($has_dt) {
310 my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
311
312 my $now = DateTime->now;
313 for (1..5) {
314 $base_collection->{"icdt_row_$_"} = $rs->create({
315 created_on => DateTime->new(year => 2011, month => 1, day => $_, time_zone => "-0${_}00" ),
316 starts_at => $now->clone->add(days => $_),
317 });
318 }
319
320 # re-search
321 my @dummy = $rs->all;
322 }
323
eb7aa960 324 # dbh's are created in XS space, so pull them separately
325 for ( grep { defined } map { @{$_->{ChildHandles}} } values %{ {DBI->installed_drivers()} } ) {
326 $base_collection->{"DBI handle $_"} = $_;
327 }
328
65d35121 329 populate_weakregistry ($weak_registry, $base_collection->{$_}, "basic $_")
330 for keys %$base_collection;
551e711a 331}
332
50261284 333# check that "phantom-chaining" works - we never lose track of the original $schema
334# and have access to the entire tree without leaking anything
335{
336 my $phantom;
337 for (
39b80a73 338 sub { DBICTest->init_schema( sqlite_use_file => 0 ) },
50261284 339 sub { shift->source('Artist') },
340 sub { shift->resultset },
341 sub { shift->result_source },
342 sub { shift->schema },
343 sub { shift->resultset('Artist') },
344 sub { shift->find_or_create({ name => 'detachable' }) },
345 sub { shift->result_source },
346 sub { shift->schema },
347 sub { shift->clone },
187ec69a 348 sub { shift->resultset('CD') },
349 sub { shift->next },
350 sub { shift->artist },
351 sub { shift->search_related('cds') },
50261284 352 sub { shift->next },
187ec69a 353 sub { shift->search_related('artist') },
50261284 354 sub { shift->result_source },
355 sub { shift->resultset },
356 sub { shift->create({ name => 'detached' }) },
357 sub { shift->update({ name => 'reattached' }) },
358 sub { shift->discard_changes },
359 sub { shift->delete },
360 sub { shift->insert },
361 ) {
65d35121 362 $phantom = populate_weakregistry ( $weak_registry, scalar $_->($phantom) );
50261284 363 }
364
365 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
366 is( $phantom->name, 'reattached', 'Still correct name' );
367}
a8c2c746 368
307ab4c5 369# Naturally we have some exceptions
370my $cleared;
96577657 371for my $addr (keys %$weak_registry) {
372 my $names = join "\n", keys %{$weak_registry->{$addr}{slot_names}};
373
374 if ($names =~ /^Test::Builder/m) {
c8194884 375 # T::B 2.0 has result objects and other fancyness
96577657 376 delete $weak_registry->{$addr};
c8194884 377 }
96577657 378 elsif ($names =~ /^Hash::Merge/m) {
37aafa2e 379 # only clear one object of a specific behavior - more would indicate trouble
96577657 380 delete $weak_registry->{$addr}
381 unless $cleared->{hash_merge_singleton}{$weak_registry->{$addr}{weakref}{behavior}}++;
307ab4c5 382 }
383}
384
187ec69a 385# FIXME !!!
386# There is an actual strong circular reference taking place here, but because
5dc4301c 387# half of it is in XS, so it is a bit harder to track down (it stumps D::FR)
388# (our tracker does not yet do it, but it'd be nice)
389# The problem is:
187ec69a 390#
728f32b5 391# $cond_object --> result_source --> schema --> storage --> $dbh --> {CachedKids}
187ec69a 392# ^ /
393# \-------- bound value on prepared/cached STH <-----------/
394#
728f32b5 395{
5dc4301c 396 my @circreffed;
397
398 for my $r (map
399 { $_->{weakref} }
400 grep
401 { $_->{slot_names}{'basic leaky_resultset_cond'} }
402 values %$weak_registry
403 ) {
404 local $TODO = 'Needs Data::Entangled or somesuch - see RT#82942';
728f32b5 405 ok(! defined $r, 'Self-referential RS conditions no longer leak!')
5dc4301c 406 or push @circreffed, $r;
407 }
408
409 if (@circreffed) {
410 is (scalar @circreffed, 1, 'One resultset expected to leak');
411
412 # this is useless on its own, it is to showcase the circref-diag
413 # and eventually test it when it is operational
414 local $TODO = 'Needs Data::Entangled or somesuch - see RT#82942';
415 while (@circreffed) {
416 weaken (my $r = shift @circreffed);
417
418 populate_weakregistry( (my $mini_registry = {}), $r );
419 assert_empty_weakregistry( $mini_registry );
420
421 $r->result_source(undef);
422 }
728f32b5 423 }
187ec69a 424}
425
65d35121 426assert_empty_weakregistry ($weak_registry);
551e711a 427
66917da3 428# we got so far without a failure - this is a good thing
429# now let's try to rerun this script under a "persistent" environment
430# this is ugly and dirty but we do not yet have a Test::Embedded or
431# similar
432
f3ec358e 433# set up -I
434require Config;
435$ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
436($ENV{PATH}) = $ENV{PATH} =~ /(.+)/;
437
438
7be5717e 439my $persistence_tests = {
440 PPerl => {
441 cmd => [qw/pperl --prefork=1/, __FILE__],
442 },
443 'CGI::SpeedyCGI' => {
444 cmd => [qw/speedy -- -t5/, __FILE__],
445 },
446};
66917da3 447
448# scgi is smart and will auto-reap after -t amount of seconds
7be5717e 449# pperl needs an actual killer :(
450$persistence_tests->{PPerl}{termcmd} = [
451 $persistence_tests->{PPerl}{cmd}[0],
452 '--kill',
453 @{$persistence_tests->{PPerl}{cmd}}[ 1 .. $#{$persistence_tests->{PPerl}{cmd}} ],
454];
66917da3 455
456SKIP: {
457 skip 'Test already in a persistent loop', 1
458 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
459
66917da3 460 skip 'Main test failed - skipping persistent env tests', 1
461 unless $TB->is_passing;
462
66917da3 463 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
464
7be5717e 465 require IPC::Open2;
466
467 for my $type (keys %$persistence_tests) { SKIP: {
53a5200d 468 unless (eval "require $type") {
469 # Don't terminate what we didn't start
470 delete $persistence_tests->{$type}{termcmd};
471 skip "$type module not found", 1;
472 }
7be5717e 473
474 my @cmd = @{$persistence_tests->{$type}{cmd}};
66917da3 475
476 # since PPerl is racy and sucks - just prime the "server"
477 {
478 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
7be5717e 479 system(@cmd);
66917da3 480 sleep 1;
481
7be5717e 482 # see if the thing actually runs, if not - might as well bail now
483 skip "Something is wrong with $type ($!)", 1
484 if system(@cmd);
66917da3 485 }
486
487 for (1,2,3) {
7be5717e 488 note ("Starting run in persistent env ($type pass $_)");
489 IPC::Open2::open2(my $out, undef, @cmd);
490 my @out_lines;
491 while (my $ln = <$out>) {
492 next if $ln =~ /^\s*$/;
493 push @out_lines, " $ln";
494 last if $ln =~ /^\d+\.\.\d+$/; # this is persistence, we need to terminate reading on our end
495 }
496 print $_ for @out_lines;
497 close $out;
498 wait;
499 ok (!$?, "Run in persistent env ($type pass $_): exit $?");
500 ok (scalar @out_lines, "Run in persistent env ($type pass $_): got output");
66917da3 501 }
502
7be5717e 503 ok (! system (@{$persistence_tests->{$type}{termcmd}}), "killed $type server instance")
504 if $persistence_tests->{$type}{termcmd};
505 }}
66917da3 506}
507
551e711a 508done_testing;
66917da3 509
510# just an extra precaution in case we blew away from the SKIP - since there are no
511# PID files to go by (man does pperl really suck :(
512END {
513 unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
7be5717e 514 close $_ for (*STDIN, *STDOUT, *STDERR);
66917da3 515 local $?; # otherwise test will inherit $? of the system()
53a5200d 516 system (@{$persistence_tests->{PPerl}{termcmd}})
517 if $persistence_tests->{PPerl}{termcmd};
66917da3 518 }
519}