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;
40 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
41 if DBIx::Class::_ENV_::PEEPEENESS();
44 use Scalar::Util qw/refaddr reftype weaken/;
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 # have our own little stack maker - Carp infloops due to the bless override
60 while (@frame = caller($depth++)) {
61 push @stack, [@frame[3,1,2]];
65 return join "\tinvoked as ", map { sprintf ("%s at %s line %d\n", @$_ ) } @stack;
68 # redefine the bless override so that we can catch each and every object created
69 no warnings qw/redefine once/;
72 $bless_override = sub {
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;
83 my $slot = (sprintf '%s=%s(0x%x)', # so we don't trigger stringification
89 # weaken immediately to avoid weird side effects
90 $weak_registry->{$slot} = { weakref => $obj, strace => $trace->() };
91 weaken $weak_registry->{$slot}{weakref};
97 for my $func (qw/try catch finally/) {
98 my $orig = \&{"Try::Tiny::$func"};
99 *{"Try::Tiny::$func"} = sub (&;@) {
101 my $slot = sprintf ('CODE(0x%x)', refaddr $_[0]);
103 $weak_registry->{$slot} = { weakref => $_[0], strace => $trace->() };
104 weaken $weak_registry->{$slot}{weakref};
110 # Some modules are known to install singletons on-load
111 # Load them and empty the registry
113 # this loads the DT armada
114 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
121 %$weak_registry = ();
127 my $schema = DBICTest->init_schema;
128 my $rs = $schema->resultset ('Artist');
129 my $storage = $schema->storage;
131 ok ($storage->connected, 'we are connected');
133 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
134 ok ($row_obj, 'row from db');
136 # txn_do to invoke more codepaths
137 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
139 my $artist = $rs->create ({
140 name => 'foo artist',
147 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
149 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
151 return ($artist, $pg, $pg_wcount);
154 is ($pager->next_page, 3, 'There is one more page available');
156 # based on 66 per 10 pages
157 is ($pager_explicit_count->last_page, 7, 'Correct last page');
159 # do some population (invokes some extra codepaths)
160 # also exercise the guard code and the manual txn control
162 my $guard = $schema->txn_scope_guard;
163 # populate with bindvars
164 $rs->populate([{ name => 'James Bound' }]);
169 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
173 # and without bindvars
174 $rs->populate([{ name => \ '"James Unbound"' }]);
175 $schema->txn_rollback;
178 my $base_collection = {
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' ] } ),
185 row_object => $row_obj,
187 result_source => $rs->result_source,
189 result_source_handle => $rs->result_source->handle,
191 fresh_pager => $rs->page(5)->pager,
193 pager_explicit_count => $pager_explicit_count,
198 %$base_collection = (
200 refrozen => Storable::dclone( $base_collection ),
201 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
204 sql_maker => $storage->sql_maker,
205 dbh => $storage->_dbh,
209 my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
211 my $now = DateTime->now;
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 => $_),
220 my @dummy = $rs->all;
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 $_"} = $_;
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')
232 for (keys %$base_collection) {
233 $weak_registry->{"basic $_"} = { weakref => $base_collection->{$_} };
234 weaken $weak_registry->{"basic $_"}{weakref};
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
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') },
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 },
263 $phantom = $_->($phantom);
265 my $slot = (sprintf 'phantom %s=%s(0x%x)', # so we don't trigger stringification
270 $weak_registry->{$slot} = $phantom;
271 weaken $weak_registry->{$slot};
274 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
275 is( $phantom->name, 'reattached', 'Still correct name' );
278 # Naturally we have some exceptions
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};
285 elsif ($slot =~ /^SQL::Translator/) {
286 # SQLT is a piece of shit, leaks all over
287 delete $weak_registry->{$slot};
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}}++;
294 elsif (DBIx::Class::_ENV_::INVISIBLE_DOLLAR_AT and $slot =~ /^__TxnScopeGuard__FIXUP__/) {
295 delete $weak_registry->{$slot}
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};
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
313 delete $weak_registry->{$_};
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->{$_};
324 for my $slot (sort keys %$weak_registry) {
326 ok (! defined $weak_registry->{$slot}{weakref}, "No leaks of $slot") or do {
329 $diag .= Devel::FindRef::track ($weak_registry->{$slot}{weakref}, 20) . "\n"
330 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
332 if (my $stack = $weak_registry->{$slot}{strace}) {
333 $diag .= " Reference first seen$stack";
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
346 my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
347 my @pperl_term_cmd = @pperl_cmd;
348 splice @pperl_term_cmd, 1, 0, '--kill';
350 # scgi is smart and will auto-reap after -t amount of seconds
351 my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
354 skip 'Test already in a persistent loop', 1
355 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
357 skip 'Persistence test disabled on regular installs', 1
358 if DBICTest::RunMode->is_plain;
360 skip 'Main test failed - skipping persistent env tests', 1
361 unless $TB->is_passing;
365 local $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
367 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
371 skip 'PPerl persistent environment tests require PPerl', 1
372 unless eval { require PPerl };
374 # since PPerl is racy and sucks - just prime the "server"
376 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
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);
387 ok (!$?, "Run in persistent env (PPerl pass $_): exit $?");
390 ok (! system (@pperl_term_cmd), 'killed pperl instance');
393 # try with speedy-cgi
395 skip 'SPeedyCGI persistent environment tests require CGI::SpeedyCGI', 1
396 unless eval { require CGI::SpeedyCGI };
399 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
400 skip "Something is wrong with speedy ($!)", 1
401 if system(@scgi_cmd);
407 ok (!$?, "Run in persistent env (SpeedyCGI pass $_): exit $?");
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 :(
417 unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
420 local $?; # otherwise test will inherit $? of the system()
421 system (@pperl_term_cmd);