Remove the transparrent hook lazy-pager-count experiment
[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;
e0b2dc74 38use DBIx::Class;
d12d8272 39BEGIN {
d5e5fb4b 40 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
e0b2dc74 41 if DBIx::Class::_ENV_::PEEPEENESS();
d12d8272 42}
43
a8c2c746 44use Scalar::Util qw/refaddr reftype weaken/;
a917fb06 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 # have our own little stack maker - Carp infloops due to the bless override
56 my $trace = sub {
57 my $depth = 1;
58 my (@stack, @frame);
59
60 while (@frame = caller($depth++)) {
61 push @stack, [@frame[3,1,2]];
62 }
6a43bc0c 63
eb7aa960 64 $stack[0][0] = '';
65 return join "\tinvoked as ", map { sprintf ("%s at %s line %d\n", @$_ ) } @stack;
66 };
67
68 # redefine the bless override so that we can catch each and every object created
a8c2c746 69 no warnings qw/redefine once/;
70 no strict qw/refs/;
71
f05edfd1 72 $bless_override = sub {
73
a8c2c746 74 my $obj = CORE::bless(
75 $_[0], (@_ > 1) ? $_[1] : do {
76 my ($class, $fn, $line) = caller();
77 fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
78 if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
79 $class;
80 }
81 );
82
83 my $slot = (sprintf '%s=%s(0x%x)', # so we don't trigger stringification
84 ref $obj,
85 reftype $obj,
86 refaddr $obj,
87 );
88
89 # weaken immediately to avoid weird side effects
eb7aa960 90 $weak_registry->{$slot} = { weakref => $obj, strace => $trace->() };
a8c2c746 91 weaken $weak_registry->{$slot}{weakref};
92
93 return $obj;
94 };
95
eb7aa960 96 require Try::Tiny;
a8c2c746 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
eb7aa960 103 $weak_registry->{$slot} = { weakref => $_[0], strace => $trace->() };
a8c2c746 104 weaken $weak_registry->{$slot}{weakref};
105
106 goto $orig;
107 }
108 }
eb7aa960 109
110 # Some modules are known to install singletons on-load
111 # Load them and empty the registry
112
113 # this loads the DT armada
114 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
115
116 require Errno;
117 require DBI;
118 require DBD::SQLite;
119 require FileHandle;
120
121 %$weak_registry = ();
a8c2c746 122}
123
124{
66917da3 125 use_ok ('DBICTest');
a917fb06 126
a8c2c746 127 my $schema = DBICTest->init_schema;
128 my $rs = $schema->resultset ('Artist');
129 my $storage = $schema->storage;
a917fb06 130
a8c2c746 131 ok ($storage->connected, 'we are connected');
a917fb06 132
052b8ce2 133 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
a8c2c746 134 ok ($row_obj, 'row from db');
135
052b8ce2 136 # txn_do to invoke more codepaths
a8c2c746 137 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
138
139 my $artist = $rs->create ({
140 name => 'foo artist',
141 cds => [{
142 title => 'foo cd',
143 year => 1984,
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
154 is ($pager->next_page, 3, 'There is one more page available');
155
156 # based on 66 per 10 pages
157 is ($pager_explicit_count->last_page, 7, 'Correct last page');
551e711a 158
052b8ce2 159 # do some population (invokes some extra codepaths)
160 # also exercise the guard code and the manual txn control
161 {
162 my $guard = $schema->txn_scope_guard;
163 # populate with bindvars
164 $rs->populate([{ name => 'James Bound' }]);
165 $guard->commit;
166
167 $schema->txn_begin;
168 # populate mixed
169 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
170 $schema->txn_commit;
171
172 $schema->txn_begin;
173 # and without bindvars
174 $rs->populate([{ name => \ '"James Unbound"' }]);
175 $schema->txn_rollback;
176 }
177
a8c2c746 178 my $base_collection = {
a8c2c746 179 resultset => $rs,
307ab4c5 180
37aafa2e 181 # twice so that we make sure only one H::M object spawned
182 chained_resultset => $rs->search_rs ({}, { '+columns' => [ 'foo' ] } ),
183 chained_resultset2 => $rs->search_rs ({}, { '+columns' => [ 'bar' ] } ),
184
a8c2c746 185 row_object => $row_obj,
551e711a 186
a8c2c746 187 result_source => $rs->result_source,
551e711a 188
4376a157 189 result_source_handle => $rs->result_source->handle,
190
a8c2c746 191 pager_explicit_count => $pager_explicit_count,
551e711a 192
a8c2c746 193 };
574d9b69 194
eb7aa960 195 require Storable;
4376a157 196 %$base_collection = (
197 %$base_collection,
198 refrozen => Storable::dclone( $base_collection ),
199 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
200 schema => $schema,
201 storage => $storage,
202 sql_maker => $storage->sql_maker,
203 dbh => $storage->_dbh,
cd122820 204 fresh_pager => $rs->page(5)->pager,
205 pager => $pager,
4376a157 206 );
207
6a43bc0c 208 if ($has_dt) {
209 my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
210
211 my $now = DateTime->now;
212 for (1..5) {
213 $base_collection->{"icdt_row_$_"} = $rs->create({
214 created_on => DateTime->new(year => 2011, month => 1, day => $_, time_zone => "-0${_}00" ),
215 starts_at => $now->clone->add(days => $_),
216 });
217 }
218
219 # re-search
220 my @dummy = $rs->all;
221 }
222
eb7aa960 223 # dbh's are created in XS space, so pull them separately
224 for ( grep { defined } map { @{$_->{ChildHandles}} } values %{ {DBI->installed_drivers()} } ) {
225 $base_collection->{"DBI handle $_"} = $_;
226 }
227
228 if ( DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks') ) {
229 Test::Memory::Cycle::memory_cycle_ok ($base_collection, 'No cycles in the object collection')
230 }
574d9b69 231
a8c2c746 232 for (keys %$base_collection) {
233 $weak_registry->{"basic $_"} = { weakref => $base_collection->{$_} };
234 weaken $weak_registry->{"basic $_"}{weakref};
574d9b69 235 }
551e711a 236}
237
50261284 238# check that "phantom-chaining" works - we never lose track of the original $schema
239# and have access to the entire tree without leaking anything
240{
241 my $phantom;
242 for (
243 sub { DBICTest->init_schema },
244 sub { shift->source('Artist') },
245 sub { shift->resultset },
246 sub { shift->result_source },
247 sub { shift->schema },
248 sub { shift->resultset('Artist') },
249 sub { shift->find_or_create({ name => 'detachable' }) },
250 sub { shift->result_source },
251 sub { shift->schema },
252 sub { shift->clone },
253 sub { shift->resultset('Artist') },
254 sub { shift->next },
255 sub { shift->result_source },
256 sub { shift->resultset },
257 sub { shift->create({ name => 'detached' }) },
258 sub { shift->update({ name => 'reattached' }) },
259 sub { shift->discard_changes },
260 sub { shift->delete },
261 sub { shift->insert },
262 ) {
263 $phantom = $_->($phantom);
264
265 my $slot = (sprintf 'phantom %s=%s(0x%x)', # so we don't trigger stringification
266 ref $phantom,
267 reftype $phantom,
268 refaddr $phantom,
269 );
270 $weak_registry->{$slot} = $phantom;
271 weaken $weak_registry->{$slot};
272 }
273
274 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
275 is( $phantom->name, 'reattached', 'Still correct name' );
276}
a8c2c746 277
307ab4c5 278# Naturally we have some exceptions
279my $cleared;
280for my $slot (keys %$weak_registry) {
6a43bc0c 281 if ($slot =~ /^Test::Builder/) {
c8194884 282 # T::B 2.0 has result objects and other fancyness
283 delete $weak_registry->{$slot};
284 }
6a43bc0c 285 elsif ($slot =~ /^SQL::Translator/) {
307ab4c5 286 # SQLT is a piece of shit, leaks all over
287 delete $weak_registry->{$slot};
288 }
6a43bc0c 289 elsif ($slot =~ /^Hash::Merge/) {
37aafa2e 290 # only clear one object of a specific behavior - more would indicate trouble
307ab4c5 291 delete $weak_registry->{$slot}
292 unless $cleared->{hash_merge_singleton}{$weak_registry->{$slot}{weakref}{behavior}}++;
293 }
b4ad8a74 294 elsif (DBIx::Class::_ENV_::INVISIBLE_DOLLAR_AT and $slot =~ /^__TxnScopeGuard__FIXUP__/) {
48e4eac6 295 delete $weak_registry->{$slot}
1f870d5a 296 }
eb7aa960 297 elsif ($slot =~ /^DateTime::TimeZone/) {
298 # DT is going through a refactor it seems - let it leak zones for now
299 delete $weak_registry->{$slot};
300 }
307ab4c5 301}
302
303
a8c2c746 304# FIXME
305# For reasons I can not yet fully understand the table() god-method (located in
306# ::ResultSourceProxy::Table) attaches an actual source instance to each class
307# as virtually *immortal* class-data.
fa442fd5 308# For now just ignore these instances manually but there got to be a saner way
309for ( map { $_->result_source_instance } (
a8c2c746 310 'DBICTest::BaseResult',
311 map { DBICTest::Schema->class ($_) } DBICTest::Schema->sources
fa442fd5 312)) {
313 delete $weak_registry->{$_};
314}
a8c2c746 315
316# FIXME
317# same problem goes for the schema - its classdata contains live result source
318# objects, which to add insult to the injury are *different* instances from the
fa442fd5 319# ones we ignored above
320for ( values %{DBICTest::Schema->source_registrations || {}} ) {
321 delete $weak_registry->{$_};
322}
a8c2c746 323
48e4eac6 324for my $slot (sort keys %$weak_registry) {
a8c2c746 325
326 ok (! defined $weak_registry->{$slot}{weakref}, "No leaks of $slot") or do {
327 my $diag = '';
328
329 $diag .= Devel::FindRef::track ($weak_registry->{$slot}{weakref}, 20) . "\n"
66917da3 330 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
a8c2c746 331
332 if (my $stack = $weak_registry->{$slot}{strace}) {
333 $diag .= " Reference first seen$stack";
334 }
335
336 diag $diag if $diag;
337 };
551e711a 338}
339
66917da3 340
341# we got so far without a failure - this is a good thing
342# now let's try to rerun this script under a "persistent" environment
343# this is ugly and dirty but we do not yet have a Test::Embedded or
344# similar
345
346my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
347my @pperl_term_cmd = @pperl_cmd;
348splice @pperl_term_cmd, 1, 0, '--kill';
349
350# scgi is smart and will auto-reap after -t amount of seconds
351my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
352
353SKIP: {
354 skip 'Test already in a persistent loop', 1
355 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
356
357 skip 'Persistence test disabled on regular installs', 1
358 if DBICTest::RunMode->is_plain;
359
360 skip 'Main test failed - skipping persistent env tests', 1
361 unless $TB->is_passing;
362
363 # set up -I
364 require Config;
365 local $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
366
367 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
368
369 # try with pperl
370 SKIP: {
371 skip 'PPerl persistent environment tests require PPerl', 1
372 unless eval { require PPerl };
373
374 # since PPerl is racy and sucks - just prime the "server"
375 {
376 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
377 system(@pperl_cmd);
378 sleep 1;
379
380 # see if it actually runs - if not might as well bail now
381 skip "Something is wrong with pperl ($!)", 1
382 if system(@pperl_cmd);
383 }
384
385 for (1,2,3) {
386 system(@pperl_cmd);
387 ok (!$?, "Run in persistent env (PPerl pass $_): exit $?");
388 }
389
390 ok (! system (@pperl_term_cmd), 'killed pperl instance');
391 }
392
393 # try with speedy-cgi
394 SKIP: {
395 skip 'SPeedyCGI persistent environment tests require CGI::SpeedyCGI', 1
396 unless eval { require CGI::SpeedyCGI };
397
398 {
399 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
400 skip "Something is wrong with speedy ($!)", 1
401 if system(@scgi_cmd);
402 sleep 1;
403 }
404
405 for (1,2,3) {
406 system(@scgi_cmd);
407 ok (!$?, "Run in persistent env (SpeedyCGI pass $_): exit $?");
408 }
409 }
410}
411
551e711a 412done_testing;
66917da3 413
414# just an extra precaution in case we blew away from the SKIP - since there are no
415# PID files to go by (man does pperl really suck :(
416END {
417 unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
418 close STDOUT;
419 close STDERR;
420 local $?; # otherwise test will inherit $? of the system()
421 system (@pperl_term_cmd);
422 }
423}