1 # work around brain damage in PPerl (yes, it has to be a global)
3 warn @_ unless $_[0] =~ /\QUse of "goto" to jump into a construct is deprecated/
4 } if ($ENV{DBICTEST_IN_PERSISTENT_ENV});
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};
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
14 $bless_override = sub {
15 CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() );
17 *CORE::GLOBAL::bless = sub { goto $bless_override };
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/;
29 # so done_testing can work
32 # this simulates a subtest
33 $TB->_indent(' ' x 4);
37 use DBICTest::RunMode;
38 use DBICTest::Util qw/populate_weakregistry assert_empty_weakregistry/;
40 use B 'svref_2object';
42 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
43 if DBIx::Class::_ENV_::PEEPEENESS;
46 # this is what holds all weakened refs to be checked for leakage
47 my $weak_registry = {};
49 # whether or to invoke IC::DT
52 # Skip the heavy-duty leak tracing when just doing an install
53 unless (DBICTest::RunMode->is_plain) {
55 # redefine the bless override so that we can catch each and every object created
56 no warnings qw/redefine once/;
59 $bless_override = sub {
61 my $obj = CORE::bless(
62 $_[0], (@_ > 1) ? $_[1] : do {
63 my ($class, $fn, $line) = caller();
64 fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
65 if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
70 # weaken immediately to avoid weird side effects
71 return populate_weakregistry ($weak_registry, $obj );
75 for my $func (qw/try catch finally/) {
76 my $orig = \&{"Try::Tiny::$func"};
77 *{"Try::Tiny::$func"} = sub (&;@) {
78 populate_weakregistry( $weak_registry, $_[0] );
83 # Some modules are known to install singletons on-load
84 # Load them and empty the registry
86 # this loads the DT armada
87 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
97 my @compose_ns_classes;
101 my $schema = DBICTest->init_schema;
102 my $rs = $schema->resultset ('Artist');
103 my $storage = $schema->storage;
105 @compose_ns_classes = map { "DBICTest::${_}" } keys %{$schema->source_registrations};
107 ok ($storage->connected, 'we are connected');
109 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
110 ok ($row_obj, 'row from db');
112 # txn_do to invoke more codepaths
113 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
115 my $artist = $schema->resultset('Artist')->create ({
116 name => 'foo artist',
124 genre => { name => 'mauve' },
128 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
130 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
132 return ($artist, $pg, $pg_wcount);
135 # more codepaths - error handling in txn_do
137 eval { $schema->txn_do ( sub {
138 $storage->_dbh->begin_work;
139 fail ('how did we get so far?!');
142 eval { $schema->txn_do ( sub {
143 $schema->txn_do ( sub {
144 die "It's called EXCEPTION";
145 fail ('how did we get so far?!');
147 fail ('how did we get so far?!');
149 like( $@, qr/It\'s called EXCEPTION/, 'Exception correctly propagated in nested txn_do' );
153 my ($rs_bind_circref, $cond_rowobj) = $schema->storage->dbh_do ( sub {
154 my $row = $_[0]->schema->resultset('Artist')->new({});
155 my $rs = $_[0]->schema->resultset('Artist')->search({
156 name => $row, # this is deliberately bogus, see FIXME below!
161 is ($pager->next_page, 3, 'There is one more page available');
163 # based on 66 per 10 pages
164 is ($pager_explicit_count->last_page, 7, 'Correct last page');
166 # do some population (invokes some extra codepaths)
167 # also exercise the guard code and the manual txn control
169 my $guard = $schema->txn_scope_guard;
170 # populate with bindvars
171 $rs->populate([{ name => 'James Bound' }]);
176 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
180 # and without bindvars
181 $rs->populate([{ name => \ '"James Unbound"' }]);
182 $schema->txn_rollback;
186 my $cds_rs = $schema->resultset('CD');
187 my $cds_with_artist = $cds_rs->search({}, { prefetch => 'artist' });
188 my $cds_with_tracks = $cds_rs->search({}, { prefetch => 'tracks' });
189 my $cds_with_stuff = $cds_rs->search({}, { prefetch => [ 'genre', { artist => { cds => { tracks => 'cd_single' } } } ] });
192 my $cds_with_impl_artist = $cds_rs->search({}, { columns => [qw/me.title artist.name/], join => 'artist' });
195 my $getcol_rs = $cds_rs->get_column('me.cdid');
196 my $pref_getcol_rs = $cds_with_stuff->get_column('me.cdid');
198 # fire the column getters
199 my @throwaway = $pref_getcol_rs->all;
201 my $base_collection = {
204 pref_precursor => $cds_rs,
206 pref_rs_single => $cds_with_artist,
207 pref_rs_multi => $cds_with_tracks,
208 pref_rs_nested => $cds_with_stuff,
210 pref_rs_implicit => $cds_with_impl_artist,
212 pref_row_single => $cds_with_artist->next,
213 pref_row_multi => $cds_with_tracks->next,
214 pref_row_nested => $cds_with_stuff->next,
216 # even though this does not leak Storable croaks on it :(((
217 #pref_row_implicit => $cds_with_impl_artist->next,
219 get_column_rs_plain => $getcol_rs,
220 get_column_rs_pref => $pref_getcol_rs,
222 # twice so that we make sure only one H::M object spawned
223 chained_resultset => $rs->search_rs ({}, { '+columns' => [ 'foo' ] } ),
224 chained_resultset2 => $rs->search_rs ({}, { '+columns' => [ 'bar' ] } ),
226 row_object => $row_obj,
228 mc_row_object => $mc_row_obj,
230 result_source => $rs->result_source,
232 result_source_handle => $rs->result_source->handle,
234 pager_explicit_count => $pager_explicit_count,
236 leaky_resultset => $rs_bind_circref,
237 leaky_resultset_cond => $cond_rowobj,
238 leaky_resultset_member => $rs_bind_circref->next,
242 %$base_collection = (
244 refrozen => Storable::dclone( $base_collection ),
245 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
246 pref_row_implicit => $cds_with_impl_artist->next,
249 sql_maker => $storage->sql_maker,
250 dbh => $storage->_dbh,
251 fresh_pager => $rs->page(5)->pager,
256 my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
258 my $now = DateTime->now;
260 $base_collection->{"icdt_row_$_"} = $rs->create({
261 created_on => DateTime->new(year => 2011, month => 1, day => $_, time_zone => "-0${_}00" ),
262 starts_at => $now->clone->add(days => $_),
267 my @dummy = $rs->all;
270 # dbh's are created in XS space, so pull them separately
271 for ( grep { defined } map { @{$_->{ChildHandles}} } values %{ {DBI->installed_drivers()} } ) {
272 $base_collection->{"DBI handle $_"} = $_;
276 if ( DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks') ) {
277 Test::Memory::Cycle::memory_cycle_ok ($base_collection, 'No cycles in the object collection')
280 skip 'Circular ref test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_leaks'), 1;
284 populate_weakregistry ($weak_registry, $base_collection->{$_}, "basic $_")
285 for keys %$base_collection;
288 # check that "phantom-chaining" works - we never lose track of the original $schema
289 # and have access to the entire tree without leaking anything
293 sub { DBICTest->init_schema },
294 sub { shift->source('Artist') },
295 sub { shift->resultset },
296 sub { shift->result_source },
297 sub { shift->schema },
298 sub { shift->resultset('Artist') },
299 sub { shift->find_or_create({ name => 'detachable' }) },
300 sub { shift->result_source },
301 sub { shift->schema },
302 sub { shift->clone },
303 sub { shift->resultset('CD') },
305 sub { shift->artist },
306 sub { shift->search_related('cds') },
308 sub { shift->search_related('artist') },
309 sub { shift->result_source },
310 sub { shift->resultset },
311 sub { shift->create({ name => 'detached' }) },
312 sub { shift->update({ name => 'reattached' }) },
313 sub { shift->discard_changes },
314 sub { shift->delete },
315 sub { shift->insert },
317 $phantom = populate_weakregistry ( $weak_registry, scalar $_->($phantom) );
320 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
321 is( $phantom->name, 'reattached', 'Still correct name' );
324 # Naturally we have some exceptions
326 for my $slot (keys %$weak_registry) {
327 if ($slot =~ /^Test::Builder/) {
328 # T::B 2.0 has result objects and other fancyness
329 delete $weak_registry->{$slot};
331 elsif ($slot =~ /^Method::Generate::(?:Accessor|Constructor)/) {
332 # Moo keeps globals around, this is normal
333 delete $weak_registry->{$slot};
335 elsif ($slot =~ /^SQL::Translator/) {
336 # SQLT is a piece of shit, leaks all over
337 delete $weak_registry->{$slot};
339 elsif ($slot =~ /^Hash::Merge/) {
340 # only clear one object of a specific behavior - more would indicate trouble
341 delete $weak_registry->{$slot}
342 unless $cleared->{hash_merge_singleton}{$weak_registry->{$slot}{weakref}{behavior}}++;
344 elsif (DBIx::Class::_ENV_::INVISIBLE_DOLLAR_AT and $slot =~ /^__TxnScopeGuard__FIXUP__/) {
345 delete $weak_registry->{$slot}
347 elsif ($slot =~ /^DateTime::TimeZone/) {
348 # DT is going through a refactor it seems - let it leak zones for now
349 delete $weak_registry->{$slot};
353 # every result class has a result source instance as classdata
354 # make sure these are all present and distinct before ignoring
355 # (distinct means only 1 reference)
357 'DBICTest::BaseResult',
359 map { DBICTest::Schema->class ($_) } DBICTest::Schema->sources
361 # need to store the SVref and examine it separately, to push the rsrc instance off the pad
362 my $SV = svref_2object($rs_class->result_source_instance);
363 is( $SV->REFCNT, 1, "Source instance of $rs_class referenced exactly once" );
366 delete $weak_registry->{$rs_class->result_source_instance};
369 # Schema classes also hold sources, but these are clones, since
370 # each source contains the schema (or schema class name in this case)
371 # Hence the clone so that the same source can be registered with
373 for my $moniker ( keys %{DBICTest::Schema->source_registrations || {}} ) {
375 my $SV = svref_2object(DBICTest::Schema->source($moniker));
376 is( $SV->REFCNT, 1, "Source instance registered under DBICTest::Schema as $moniker referenced exactly once" );
378 delete $weak_registry->{DBICTest::Schema->source($moniker)};
382 # There is an actual strong circular reference taking place here, but because
383 # half of it is in XS no leaktracer sees it, and Devel::FindRef is equally
384 # stumped when trying to trace the origin. The problem is:
386 # $cond_object --> result_source --> schema --> storage --> $dbh --> {cached_kids}
388 # \-------- bound value on prepared/cached STH <-----------/
391 local $TODO = 'Not sure how to fix this yet, an entanglment could be an option';
392 my $r = $weak_registry->{'basic leaky_resultset_cond'}{weakref};
393 ok(! defined $r, 'We no longer leak!')
394 or $r->result_source(undef);
397 assert_empty_weakregistry ($weak_registry);
399 # we got so far without a failure - this is a good thing
400 # now let's try to rerun this script under a "persistent" environment
401 # this is ugly and dirty but we do not yet have a Test::Embedded or
404 my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
405 my @pperl_term_cmd = @pperl_cmd;
406 splice @pperl_term_cmd, 1, 0, '--kill';
408 # scgi is smart and will auto-reap after -t amount of seconds
409 my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
412 skip 'Test already in a persistent loop', 1
413 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
415 skip 'Persistence test disabled on regular installs', 1
416 if DBICTest::RunMode->is_plain;
418 skip 'Main test failed - skipping persistent env tests', 1
419 unless $TB->is_passing;
423 local $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
425 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
429 skip 'PPerl persistent environment tests require PPerl', 1
430 unless eval { require PPerl };
432 # since PPerl is racy and sucks - just prime the "server"
434 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
438 # see if it actually runs - if not might as well bail now
439 skip "Something is wrong with pperl ($!)", 1
440 if system(@pperl_cmd);
445 ok (!$?, "Run in persistent env (PPerl pass $_): exit $?");
448 ok (! system (@pperl_term_cmd), 'killed pperl instance');
451 # try with speedy-cgi
453 skip 'SPeedyCGI persistent environment tests require CGI::SpeedyCGI', 1
454 unless eval { require CGI::SpeedyCGI };
457 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
458 skip "Something is wrong with speedy ($!)", 1
459 if system(@scgi_cmd);
465 ok (!$?, "Run in persistent env (SpeedyCGI pass $_): exit $?");
472 # just an extra precaution in case we blew away from the SKIP - since there are no
473 # PID files to go by (man does pperl really suck :(
475 unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
478 local $?; # otherwise test will inherit $? of the system()
479 system (@pperl_term_cmd);