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 # whether or to invoke IC::DT
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
67 require Class::Struct;
72 # this loads the DT armada as well
73 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
75 no warnings qw/redefine once/;
78 # redefine the bless override so that we can catch each and every object created
79 $bless_override = sub {
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;
90 my $slot = (sprintf '%s=%s(0x%x)', # so we don't trigger stringification
96 # weaken immediately to avoid weird side effects
97 $weak_registry->{$slot} = { weakref => $obj, strace => longmess() };
98 weaken $weak_registry->{$slot}{weakref};
103 for my $func (qw/try catch finally/) {
104 my $orig = \&{"Try::Tiny::$func"};
105 *{"Try::Tiny::$func"} = sub (&;@) {
107 my $slot = sprintf ('CODE(0x%x)', refaddr $_[0]);
109 $weak_registry->{$slot} = { weakref => $_[0], strace => longmess() };
110 weaken $weak_registry->{$slot}{weakref};
120 my $schema = DBICTest->init_schema;
121 my $rs = $schema->resultset ('Artist');
122 my $storage = $schema->storage;
124 ok ($storage->connected, 'we are connected');
126 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
127 ok ($row_obj, 'row from db');
129 # txn_do to invoke more codepaths
130 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
132 my $artist = $rs->create ({
133 name => 'foo artist',
140 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
142 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
144 return ($artist, $pg, $pg_wcount);
147 is ($pager->next_page, 3, 'There is one more page available');
149 # based on 66 per 10 pages
150 is ($pager_explicit_count->last_page, 7, 'Correct last page');
152 # do some population (invokes some extra codepaths)
153 # also exercise the guard code and the manual txn control
155 my $guard = $schema->txn_scope_guard;
156 # populate with bindvars
157 $rs->populate([{ name => 'James Bound' }]);
162 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
166 # and without bindvars
167 $rs->populate([{ name => \ '"James Unbound"' }]);
168 $schema->txn_rollback;
171 my $base_collection = {
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' ] } ),
178 row_object => $row_obj,
180 result_source => $rs->result_source,
182 result_source_handle => $rs->result_source->handle,
184 fresh_pager => $rs->page(5)->pager,
186 pager_explicit_count => $pager_explicit_count,
190 %$base_collection = (
192 refrozen => Storable::dclone( $base_collection ),
193 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
196 sql_maker => $storage->sql_maker,
197 dbh => $storage->_dbh,
201 my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
203 my $now = DateTime->now;
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 => $_),
212 my @dummy = $rs->all;
215 memory_cycle_ok ($base_collection, 'No cycles in the object collection')
218 for (keys %$base_collection) {
219 $weak_registry->{"basic $_"} = { weakref => $base_collection->{$_} };
220 weaken $weak_registry->{"basic $_"}{weakref};
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
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') },
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 },
249 $phantom = $_->($phantom);
251 my $slot = (sprintf 'phantom %s=%s(0x%x)', # so we don't trigger stringification
256 $weak_registry->{$slot} = $phantom;
257 weaken $weak_registry->{$slot};
260 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
261 is( $phantom->name, 'reattached', 'Still correct name' );
264 # Naturally we have some exceptions
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};
271 elsif ($slot =~ /^SQL::Translator/) {
272 # SQLT is a piece of shit, leaks all over
273 delete $weak_registry->{$slot};
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}}++;
280 elsif ($slot =~ /^__TxnScopeGuard__FIXUP__/) {
281 delete $weak_registry->{$slot}
282 if $] > 5.013001 and $] < 5.013008;
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
296 delete $weak_registry->{$_};
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->{$_};
307 for my $slot (sort keys %$weak_registry) {
309 ok (! defined $weak_registry->{$slot}{weakref}, "No leaks of $slot") or do {
312 $diag .= Devel::FindRef::track ($weak_registry->{$slot}{weakref}, 20) . "\n"
313 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
315 if (my $stack = $weak_registry->{$slot}{strace}) {
316 $diag .= " Reference first seen$stack";
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
329 my @pperl_cmd = (qw/pperl --prefork=1/, __FILE__);
330 my @pperl_term_cmd = @pperl_cmd;
331 splice @pperl_term_cmd, 1, 0, '--kill';
333 # scgi is smart and will auto-reap after -t amount of seconds
334 my @scgi_cmd = (qw/speedy -- -t5/, __FILE__);
337 skip 'Test already in a persistent loop', 1
338 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
340 skip 'Persistence test disabled on regular installs', 1
341 if DBICTest::RunMode->is_plain;
343 skip 'Main test failed - skipping persistent env tests', 1
344 unless $TB->is_passing;
348 local $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
350 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
354 skip 'PPerl persistent environment tests require PPerl', 1
355 unless eval { require PPerl };
357 # since PPerl is racy and sucks - just prime the "server"
359 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
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);
370 ok (!$?, "Run in persistent env (PPerl pass $_): exit $?");
373 ok (! system (@pperl_term_cmd), 'killed pperl instance');
376 # try with speedy-cgi
378 skip 'SPeedyCGI persistent environment tests require CGI::SpeedyCGI', 1
379 unless eval { require CGI::SpeedyCGI };
382 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
383 skip "Something is wrong with speedy ($!)", 1
384 if system(@scgi_cmd);
390 ok (!$?, "Run in persistent env (SpeedyCGI pass $_): exit $?");
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 :(
400 unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
403 local $?; # otherwise test will inherit $? of the system()
404 system (@pperl_term_cmd);