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;
39 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
40 if DBICTest::RunMode->peepeeness;
43 use Scalar::Util qw/refaddr reftype weaken/;
44 use Carp qw/longmess/;
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;
54 # this is what holds all weakened refs to be checked for leakage
55 my $weak_registry = {};
57 # Skip the heavy-duty leak tracing when just doing an install
58 unless (DBICTest::RunMode->is_plain) {
59 # Some modules are known to install singletons on-load
60 # Load them before we swap out $bless_override
64 require Class::Struct;
69 no warnings qw/redefine once/;
72 # redefine the bless override so that we can catch each and every object created
73 $bless_override = sub {
75 my $obj = CORE::bless(
76 $_[0], (@_ > 1) ? $_[1] : do {
77 my ($class, $fn, $line) = caller();
78 fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
79 if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
84 my $slot = (sprintf '%s=%s(0x%x)', # so we don't trigger stringification
90 # weaken immediately to avoid weird side effects
91 $weak_registry->{$slot} = { weakref => $obj, strace => longmess() };
92 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 => longmess() };
104 weaken $weak_registry->{$slot}{weakref};
114 my $schema = DBICTest->init_schema;
115 my $rs = $schema->resultset ('Artist');
116 my $storage = $schema->storage;
118 ok ($storage->connected, 'we are connected');
120 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
121 ok ($row_obj, 'row from db');
123 # txn_do to invoke more codepaths
124 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
126 my $artist = $rs->create ({
127 name => 'foo artist',
134 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
136 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
138 return ($artist, $pg, $pg_wcount);
141 is ($pager->next_page, 3, 'There is one more page available');
143 # based on 66 per 10 pages
144 is ($pager_explicit_count->last_page, 7, 'Correct last page');
146 # do some population (invokes some extra codepaths)
147 # also exercise the guard code and the manual txn control
149 my $guard = $schema->txn_scope_guard;
150 # populate with bindvars
151 $rs->populate([{ name => 'James Bound' }]);
156 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
160 # and without bindvars
161 $rs->populate([{ name => \ '"James Unbound"' }]);
162 $schema->txn_rollback;
165 my $base_collection = {
168 # twice so that we make sure only one H::M object spawned
169 chained_resultset => $rs->search_rs ({}, { '+columns' => [ 'foo' ] } ),
170 chained_resultset2 => $rs->search_rs ({}, { '+columns' => [ 'bar' ] } ),
172 row_object => $row_obj,
174 result_source => $rs->result_source,
176 result_source_handle => $rs->result_source->handle,
178 fresh_pager => $rs->page(5)->pager,
180 pager_explicit_count => $pager_explicit_count,
184 %$base_collection = (
186 refrozen => Storable::dclone( $base_collection ),
187 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
190 sql_maker => $storage->sql_maker,
191 dbh => $storage->_dbh,
194 memory_cycle_ok ($base_collection, 'No cycles in the object collection')
197 for (keys %$base_collection) {
198 $weak_registry->{"basic $_"} = { weakref => $base_collection->{$_} };
199 weaken $weak_registry->{"basic $_"}{weakref};
203 # check that "phantom-chaining" works - we never lose track of the original $schema
204 # and have access to the entire tree without leaking anything
208 sub { DBICTest->init_schema },
209 sub { shift->source('Artist') },
210 sub { shift->resultset },
211 sub { shift->result_source },
212 sub { shift->schema },
213 sub { shift->resultset('Artist') },
214 sub { shift->find_or_create({ name => 'detachable' }) },
215 sub { shift->result_source },
216 sub { shift->schema },
217 sub { shift->clone },
218 sub { shift->resultset('Artist') },
220 sub { shift->result_source },
221 sub { shift->resultset },
222 sub { shift->create({ name => 'detached' }) },
223 sub { shift->update({ name => 'reattached' }) },
224 sub { shift->discard_changes },
225 sub { shift->delete },
226 sub { shift->insert },
228 $phantom = $_->($phantom);
230 my $slot = (sprintf 'phantom %s=%s(0x%x)', # so we don't trigger stringification
235 $weak_registry->{$slot} = $phantom;
236 weaken $weak_registry->{$slot};
239 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
240 is( $phantom->name, 'reattached', 'Still correct name' );
243 # Naturally we have some exceptions
245 for my $slot (keys %$weak_registry) {
246 if ($slot =~ /^\QTest::Builder/) {
247 # T::B 2.0 has result objects and other fancyness
248 delete $weak_registry->{$slot};
250 elsif ($slot =~ /^\QSQL::Translator/) {
251 # SQLT is a piece of shit, leaks all over
252 delete $weak_registry->{$slot};
254 elsif ($slot =~ /^\QHash::Merge/) {
255 # only clear one object of a specific behavior - more would indicate trouble
256 delete $weak_registry->{$slot}
257 unless $cleared->{hash_merge_singleton}{$weak_registry->{$slot}{weakref}{behavior}}++;
259 elsif ($slot =~ /^__TxnScopeGuard__FIXUP__/) {
260 delete $weak_registry->{$slot}
261 if $] > 5.013001 and $] < 5.013008;
267 # For reasons I can not yet fully understand the table() god-method (located in
268 # ::ResultSourceProxy::Table) attaches an actual source instance to each class
269 # as virtually *immortal* class-data.
270 # For now just ignore these instances manually but there got to be a saner way
271 for ( map { $_->result_source_instance } (
272 'DBICTest::BaseResult',
273 map { DBICTest::Schema->class ($_) } DBICTest::Schema->sources
275 delete $weak_registry->{$_};
279 # same problem goes for the schema - its classdata contains live result source
280 # objects, which to add insult to the injury are *different* instances from the
281 # ones we ignored above
282 for ( values %{DBICTest::Schema->source_registrations || {}} ) {
283 delete $weak_registry->{$_};
286 for my $slot (sort keys %$weak_registry) {
288 ok (! defined $weak_registry->{$slot}{weakref}, "No leaks of $slot") or do {
291 $diag .= Devel::FindRef::track ($weak_registry->{$slot}{weakref}, 20) . "\n"
292 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
294 if (my $stack = $weak_registry->{$slot}{strace}) {
295 $diag .= " Reference first seen$stack";
303 # we got so far without a failure - this is a good thing
304 # now let's try to rerun this script under a "persistent" environment
305 # this is ugly and dirty but we do not yet have a Test::Embedded or
308 my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
309 my @pperl_term_cmd = @pperl_cmd;
310 splice @pperl_term_cmd, 1, 0, '--kill';
312 # scgi is smart and will auto-reap after -t amount of seconds
313 my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
316 skip 'Test already in a persistent loop', 1
317 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
319 skip 'Persistence test disabled on regular installs', 1
320 if DBICTest::RunMode->is_plain;
322 skip 'Main test failed - skipping persistent env tests', 1
323 unless $TB->is_passing;
327 local $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
329 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
333 skip 'PPerl persistent environment tests require PPerl', 1
334 unless eval { require PPerl };
336 # since PPerl is racy and sucks - just prime the "server"
338 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
342 # see if it actually runs - if not might as well bail now
343 skip "Something is wrong with pperl ($!)", 1
344 if system(@pperl_cmd);
349 ok (!$?, "Run in persistent env (PPerl pass $_): exit $?");
352 ok (! system (@pperl_term_cmd), 'killed pperl instance');
355 # try with speedy-cgi
357 skip 'SPeedyCGI persistent environment tests require CGI::SpeedyCGI', 1
358 unless eval { require CGI::SpeedyCGI };
361 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
362 skip "Something is wrong with speedy ($!)", 1
363 if system(@scgi_cmd);
369 ok (!$?, "Run in persistent env (SpeedyCGI pass $_): exit $?");
376 # just an extra precaution in case we blew away from the SKIP - since there are no
377 # PID files to go by (man does pperl really suck :(
379 unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
382 local $?; # otherwise test will inherit $? of the system()
383 system (@pperl_term_cmd);