Overhaul populate code - fix \[] support and exotic values (arrays, etc.)
[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;
d12d8272 38BEGIN {
d5e5fb4b 39 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
40 if DBICTest::RunMode->peepeeness;
d12d8272 41}
42
a8c2c746 43use Scalar::Util qw/refaddr reftype weaken/;
44use Carp qw/longmess/;
45use Try::Tiny;
a917fb06 46
a8c2c746 47my $have_test_cycle;
a917fb06 48BEGIN {
226d1c35 49 require DBIx::Class::Optional::Dependencies;
a8c2c746 50 $have_test_cycle = DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks')
51 and import Test::Memory::Cycle;
a917fb06 52}
53
a8c2c746 54# this is what holds all weakened refs to be checked for leakage
55my $weak_registry = {};
56
6a43bc0c 57# whether or to invoke IC::DT
58my $has_dt;
59
a8c2c746 60# Skip the heavy-duty leak tracing when just doing an install
61unless (DBICTest::RunMode->is_plain) {
f05edfd1 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;
307ab4c5 69 require Hash::Merge;
4376a157 70 require Storable;
f05edfd1 71
6a43bc0c 72 # this loads the DT armada as well
73 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
74
a8c2c746 75 no warnings qw/redefine once/;
76 no strict qw/refs/;
77
f05edfd1 78 # redefine the bless override so that we can catch each and every object created
79 $bless_override = sub {
80
a8c2c746 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{
66917da3 118 use_ok ('DBICTest');
a917fb06 119
a8c2c746 120 my $schema = DBICTest->init_schema;
121 my $rs = $schema->resultset ('Artist');
122 my $storage = $schema->storage;
a917fb06 123
a8c2c746 124 ok ($storage->connected, 'we are connected');
a917fb06 125
052b8ce2 126 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
a8c2c746 127 ok ($row_obj, 'row from db');
128
052b8ce2 129 # txn_do to invoke more codepaths
a8c2c746 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');
551e711a 151
052b8ce2 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
a8c2c746 171 my $base_collection = {
a8c2c746 172 resultset => $rs,
307ab4c5 173
37aafa2e 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
a8c2c746 178 row_object => $row_obj,
551e711a 179
a8c2c746 180 result_source => $rs->result_source,
551e711a 181
4376a157 182 result_source_handle => $rs->result_source->handle,
183
a8c2c746 184 fresh_pager => $rs->page(5)->pager,
185 pager => $pager,
186 pager_explicit_count => $pager_explicit_count,
551e711a 187
a8c2c746 188 };
574d9b69 189
4376a157 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
6a43bc0c 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
a8c2c746 215 memory_cycle_ok ($base_collection, 'No cycles in the object collection')
216 if $have_test_cycle;
574d9b69 217
a8c2c746 218 for (keys %$base_collection) {
219 $weak_registry->{"basic $_"} = { weakref => $base_collection->{$_} };
220 weaken $weak_registry->{"basic $_"}{weakref};
574d9b69 221 }
551e711a 222}
223
50261284 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}
a8c2c746 263
307ab4c5 264# Naturally we have some exceptions
265my $cleared;
266for my $slot (keys %$weak_registry) {
6a43bc0c 267 if ($slot =~ /^Test::Builder/) {
c8194884 268 # T::B 2.0 has result objects and other fancyness
269 delete $weak_registry->{$slot};
270 }
6a43bc0c 271 elsif ($slot =~ /^SQL::Translator/) {
307ab4c5 272 # SQLT is a piece of shit, leaks all over
273 delete $weak_registry->{$slot};
274 }
6a43bc0c 275 elsif ($slot =~ /^Hash::Merge/) {
37aafa2e 276 # only clear one object of a specific behavior - more would indicate trouble
307ab4c5 277 delete $weak_registry->{$slot}
278 unless $cleared->{hash_merge_singleton}{$weak_registry->{$slot}{weakref}{behavior}}++;
279 }
1f870d5a 280 elsif ($slot =~ /^__TxnScopeGuard__FIXUP__/) {
48e4eac6 281 delete $weak_registry->{$slot}
282 if $] > 5.013001 and $] < 5.013008;
1f870d5a 283 }
307ab4c5 284}
285
286
a8c2c746 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.
fa442fd5 291# For now just ignore these instances manually but there got to be a saner way
292for ( map { $_->result_source_instance } (
a8c2c746 293 'DBICTest::BaseResult',
294 map { DBICTest::Schema->class ($_) } DBICTest::Schema->sources
fa442fd5 295)) {
296 delete $weak_registry->{$_};
297}
a8c2c746 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
fa442fd5 302# ones we ignored above
303for ( values %{DBICTest::Schema->source_registrations || {}} ) {
304 delete $weak_registry->{$_};
305}
a8c2c746 306
48e4eac6 307for my $slot (sort keys %$weak_registry) {
a8c2c746 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"
66917da3 313 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
a8c2c746 314
315 if (my $stack = $weak_registry->{$slot}{strace}) {
316 $diag .= " Reference first seen$stack";
317 }
318
319 diag $diag if $diag;
320 };
551e711a 321}
322
66917da3 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
329my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
330my @pperl_term_cmd = @pperl_cmd;
331splice @pperl_term_cmd, 1, 0, '--kill';
332
333# scgi is smart and will auto-reap after -t amount of seconds
334my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
335
336SKIP: {
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
551e711a 395done_testing;
66917da3 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 :(
399END {
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}