Remove the transparrent hook lazy-pager-count experiment
[dbsrgits/DBIx-Class.git] / t / 52leaks.t
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)
8 exit 0 if $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY};
9
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
12 my $bless_override;
13 BEGIN {
14   $bless_override = sub {
15     CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() );
16   };
17   *CORE::GLOBAL::bless = sub { goto $bless_override };
18 }
19
20 use strict;
21 use warnings;
22 use Test::More;
23
24 my $TB = Test::More->builder;
25 if ($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
36 use lib qw(t/lib);
37 use DBICTest::RunMode;
38 use DBIx::Class;
39 BEGIN {
40   plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
41     if DBIx::Class::_ENV_::PEEPEENESS();
42 }
43
44 use Scalar::Util qw/refaddr reftype weaken/;
45
46 # this is what holds all weakened refs to be checked for leakage
47 my $weak_registry = {};
48
49 # whether or to invoke IC::DT
50 my $has_dt;
51
52 # Skip the heavy-duty leak tracing when just doing an install
53 unless (DBICTest::RunMode->is_plain) {
54
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     }
63
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
69   no warnings qw/redefine once/;
70   no strict qw/refs/;
71
72   $bless_override = sub {
73
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
90     $weak_registry->{$slot} = { weakref => $obj, strace => $trace->() };
91     weaken $weak_registry->{$slot}{weakref};
92
93     return $obj;
94   };
95
96   require Try::Tiny;
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 => $trace->() };
104       weaken $weak_registry->{$slot}{weakref};
105
106       goto $orig;
107     }
108   }
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 = ();
122 }
123
124 {
125   use_ok ('DBICTest');
126
127   my $schema = DBICTest->init_schema;
128   my $rs = $schema->resultset ('Artist');
129   my $storage = $schema->storage;
130
131   ok ($storage->connected, 'we are connected');
132
133   my $row_obj = $rs->search({}, { rows => 1})->next;  # so that commits/rollbacks work
134   ok ($row_obj, 'row from db');
135
136   # txn_do to invoke more codepaths
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');
158
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
178   my $base_collection = {
179     resultset => $rs,
180
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
185     row_object => $row_obj,
186
187     result_source => $rs->result_source,
188
189     result_source_handle => $rs->result_source->handle,
190
191     pager_explicit_count => $pager_explicit_count,
192
193   };
194
195   require Storable;
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,
204     fresh_pager => $rs->page(5)->pager,
205     pager => $pager,
206   );
207
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
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   }
231
232   for (keys %$base_collection) {
233     $weak_registry->{"basic $_"} = { weakref => $base_collection->{$_} };
234     weaken $weak_registry->{"basic $_"}{weakref};
235   }
236 }
237
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 }
277
278 # Naturally we have some exceptions
279 my $cleared;
280 for my $slot (keys %$weak_registry) {
281   if ($slot =~ /^Test::Builder/) {
282     # T::B 2.0 has result objects and other fancyness
283     delete $weak_registry->{$slot};
284   }
285   elsif ($slot =~ /^SQL::Translator/) {
286     # SQLT is a piece of shit, leaks all over
287     delete $weak_registry->{$slot};
288   }
289   elsif ($slot =~ /^Hash::Merge/) {
290     # only clear one object of a specific behavior - more would indicate trouble
291     delete $weak_registry->{$slot}
292       unless $cleared->{hash_merge_singleton}{$weak_registry->{$slot}{weakref}{behavior}}++;
293   }
294   elsif (DBIx::Class::_ENV_::INVISIBLE_DOLLAR_AT and $slot =~ /^__TxnScopeGuard__FIXUP__/) {
295     delete $weak_registry->{$slot}
296   }
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   }
301 }
302
303
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. 
308 # For now just ignore these instances manually but there got to be a saner way
309 for ( map { $_->result_source_instance } (
310   'DBICTest::BaseResult',
311   map { DBICTest::Schema->class ($_) } DBICTest::Schema->sources
312 )) {
313   delete $weak_registry->{$_};
314 }
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
319 # ones we ignored above
320 for ( values %{DBICTest::Schema->source_registrations || {}} ) {
321   delete $weak_registry->{$_};
322 }
323
324 for my $slot (sort keys %$weak_registry) {
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"
330       if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
331
332     if (my $stack = $weak_registry->{$slot}{strace}) {
333       $diag .= "    Reference first seen$stack";
334     }
335
336     diag $diag if $diag;
337   };
338 }
339
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
346 my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
347 my @pperl_term_cmd = @pperl_cmd;
348 splice @pperl_term_cmd, 1, 0, '--kill';
349
350 # scgi is smart and will auto-reap after -t amount of seconds
351 my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
352
353 SKIP: {
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
412 done_testing;
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 :(
416 END {
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 }