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