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