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 older TBs warn in END after a ->reset
27 if ($TB->VERSION < 1.005) {
28 close ($TB->$_) for (qw/output failure_output todo_output/);
31 # if I do not do this, I get happy sigpipes on new TB, no idea why
32 # (the above close-and-forget doesn't work - new TB does *not* reopen
33 # its handles automatically anymore)
35 for (qw/failure_output todo_output/) {
37 open ($TB->$_, '>&', *STDERR);
41 open ($TB->output, '>&', *STDOUT);
44 # so done_testing can work on every persistent pass
49 use DBICTest::RunMode;
50 use DBICTest::Util::LeakTracer qw/populate_weakregistry assert_empty_weakregistry/;
53 plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
54 if DBIx::Class::_ENV_::PEEPEENESS;
57 # this is what holds all weakened refs to be checked for leakage
58 my $weak_registry = {};
60 # whether or to invoke IC::DT
63 # Skip the heavy-duty leak tracing when just doing an install
64 unless (DBICTest::RunMode->is_plain) {
66 # redefine the bless override so that we can catch each and every object created
67 no warnings qw/redefine once/;
70 $bless_override = sub {
72 my $obj = CORE::bless(
73 $_[0], (@_ > 1) ? $_[1] : do {
74 my ($class, $fn, $line) = caller();
75 fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
76 if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
81 # unicode is tricky, and now we happen to invoke it early via a
82 # regex in connection()
83 return $obj if (ref $obj) =~ /^utf8/;
85 # Test Builder is now making a new object for every pass/fail (que bloat?)
86 # and as such we can't really store any of its objects (since it will
87 # re-populate the registry while checking it, ewwww!)
88 return $obj if (ref $obj) =~ /^TB2::/;
90 # weaken immediately to avoid weird side effects
91 return populate_weakregistry ($weak_registry, $obj );
95 for my $func (qw/try catch finally/) {
96 my $orig = \&{"Try::Tiny::$func"};
97 *{"Try::Tiny::$func"} = sub (&;@) {
98 populate_weakregistry( $weak_registry, $_[0] );
103 # Some modules are known to install singletons on-load
104 # Load them and empty the registry
106 # this loads the DT armada
107 $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for('test_dt_sqlite');
115 %$weak_registry = ();
121 my $schema = DBICTest->init_schema;
122 my $rs = $schema->resultset ('Artist');
123 my $storage = $schema->storage;
125 ok ($storage->connected, 'we are connected');
127 my $row_obj = $rs->search({}, { rows => 1})->next; # so that commits/rollbacks work
128 ok ($row_obj, 'row from db');
130 # txn_do to invoke more codepaths
131 my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
133 my $artist = $schema->resultset('Artist')->create ({
134 name => 'foo artist',
142 genre => { name => 'mauve' },
146 my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
148 my $pg_wcount = $rs->page(4)->pager->total_entries (66);
150 return ($artist, $pg, $pg_wcount);
153 # more codepaths - error handling in txn_do
155 eval { $schema->txn_do ( sub {
156 $storage->_dbh->begin_work;
157 fail ('how did we get so far?!');
160 eval { $schema->txn_do ( sub {
161 $schema->txn_do ( sub {
162 die "It's called EXCEPTION";
163 fail ('how did we get so far?!');
165 fail ('how did we get so far?!');
167 like( $@, qr/It\'s called EXCEPTION/, 'Exception correctly propagated in nested txn_do' );
171 my ($rs_bind_circref, $cond_rowobj) = $schema->storage->dbh_do ( sub {
172 my $row = $_[0]->schema->resultset('Artist')->new({});
173 my $rs = $_[0]->schema->resultset('Artist')->search({
174 name => $row, # this is deliberately bogus, see FIXME below!
179 is ($pager->next_page, 3, 'There is one more page available');
181 # based on 66 per 10 pages
182 is ($pager_explicit_count->last_page, 7, 'Correct last page');
184 # do some population (invokes some extra codepaths)
185 # also exercise the guard code and the manual txn control
187 my $guard = $schema->txn_scope_guard;
188 # populate with bindvars
189 $rs->populate([{ name => 'James Bound' }]);
194 $rs->populate([{ name => 'James Rebound', rank => \ '11' }]);
198 # and without bindvars
199 $rs->populate([{ name => \ '"James Unbound"' }]);
200 $schema->txn_rollback;
204 my $cds_rs = $schema->resultset('CD');
205 my $cds_with_artist = $cds_rs->search({}, { prefetch => 'artist' });
206 my $cds_with_tracks = $cds_rs->search({}, { prefetch => 'tracks' });
207 my $cds_with_stuff = $cds_rs->search({}, { prefetch => [ 'genre', { artist => { cds => { tracks => 'cd_single' } } } ] });
210 my $cds_with_impl_artist = $cds_rs->search({}, { columns => [qw/me.title artist.name/], join => 'artist' });
213 my $getcol_rs = $cds_rs->get_column('me.cdid');
214 my $pref_getcol_rs = $cds_with_stuff->get_column('me.cdid');
216 # fire the column getters
217 my @throwaway = $pref_getcol_rs->all;
219 my $base_collection = {
222 pref_precursor => $cds_rs,
224 pref_rs_single => $cds_with_artist,
225 pref_rs_multi => $cds_with_tracks,
226 pref_rs_nested => $cds_with_stuff,
228 pref_rs_implicit => $cds_with_impl_artist,
230 pref_row_single => $cds_with_artist->next,
231 pref_row_multi => $cds_with_tracks->next,
232 pref_row_nested => $cds_with_stuff->next,
234 # even though this does not leak Storable croaks on it :(((
235 #pref_row_implicit => $cds_with_impl_artist->next,
237 get_column_rs_plain => $getcol_rs,
238 get_column_rs_pref => $pref_getcol_rs,
240 # twice so that we make sure only one H::M object spawned
241 chained_resultset => $rs->search_rs ({}, { '+columns' => [ 'foo' ] } ),
242 chained_resultset2 => $rs->search_rs ({}, { '+columns' => [ 'bar' ] } ),
244 row_object => $row_obj,
246 mc_row_object => $mc_row_obj,
248 result_source => $rs->result_source,
250 result_source_handle => $rs->result_source->handle,
252 pager_explicit_count => $pager_explicit_count,
254 leaky_resultset => $rs_bind_circref,
255 leaky_resultset_cond => $cond_rowobj,
258 # this needs to fire, even if it can't find anything
260 # we run this only on smokers - trying to establish a pattern
261 $rs_bind_circref->next
262 if ( ($ENV{TRAVIS}||'') ne 'true' and DBICTest::RunMode->is_smoker);
265 %$base_collection = (
267 refrozen => Storable::dclone( $base_collection ),
268 rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
269 pref_row_implicit => $cds_with_impl_artist->next,
272 sql_maker => $storage->sql_maker,
273 dbh => $storage->_dbh,
274 fresh_pager => $rs->page(5)->pager,
279 my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
281 my $now = DateTime->now;
283 $base_collection->{"icdt_row_$_"} = $rs->create({
284 created_on => DateTime->new(year => 2011, month => 1, day => $_, time_zone => "-0${_}00" ),
285 starts_at => $now->clone->add(days => $_),
290 my @dummy = $rs->all;
293 # dbh's are created in XS space, so pull them separately
294 for ( grep { defined } map { @{$_->{ChildHandles}} } values %{ {DBI->installed_drivers()} } ) {
295 $base_collection->{"DBI handle $_"} = $_;
298 populate_weakregistry ($weak_registry, $base_collection->{$_}, "basic $_")
299 for keys %$base_collection;
302 # check that "phantom-chaining" works - we never lose track of the original $schema
303 # and have access to the entire tree without leaking anything
307 sub { DBICTest->init_schema( sqlite_use_file => 0 ) },
308 sub { shift->source('Artist') },
309 sub { shift->resultset },
310 sub { shift->result_source },
311 sub { shift->schema },
312 sub { shift->resultset('Artist') },
313 sub { shift->find_or_create({ name => 'detachable' }) },
314 sub { shift->result_source },
315 sub { shift->schema },
316 sub { shift->clone },
317 sub { shift->resultset('CD') },
319 sub { shift->artist },
320 sub { shift->search_related('cds') },
322 sub { shift->search_related('artist') },
323 sub { shift->result_source },
324 sub { shift->resultset },
325 sub { shift->create({ name => 'detached' }) },
326 sub { shift->update({ name => 'reattached' }) },
327 sub { shift->discard_changes },
328 sub { shift->delete },
329 sub { shift->insert },
331 $phantom = populate_weakregistry ( $weak_registry, scalar $_->($phantom) );
334 ok( $phantom->in_storage, 'Properly deleted/reinserted' );
335 is( $phantom->name, 'reattached', 'Still correct name' );
338 # Naturally we have some exceptions
340 for my $addr (keys %$weak_registry) {
341 my $names = join "\n", keys %{$weak_registry->{$addr}{slot_names}};
343 if ($names =~ /^Test::Builder/m) {
344 # T::B 2.0 has result objects and other fancyness
345 delete $weak_registry->{$addr};
347 elsif ($names =~ /^Hash::Merge/m) {
348 # only clear one object of a specific behavior - more would indicate trouble
349 delete $weak_registry->{$addr}
350 unless $cleared->{hash_merge_singleton}{$weak_registry->{$addr}{weakref}{behavior}}++;
355 # There is an actual strong circular reference taking place here, but because
356 # half of it is in XS no leaktracer sees it, and Devel::FindRef is equally
357 # stumped when trying to trace the origin. The problem is:
359 # $cond_object --> result_source --> schema --> storage --> $dbh --> {CachedKids}
361 # \-------- bound value on prepared/cached STH <-----------/
364 local $TODO = 'This fails intermittently - see RT#82942';
365 if ( my $r = ($weak_registry->{'basic leaky_resultset_cond'}||{})->{weakref} ) {
366 ok(! defined $r, 'Self-referential RS conditions no longer leak!')
367 or $r->result_source(undef);
371 assert_empty_weakregistry ($weak_registry);
373 # we got so far without a failure - this is a good thing
374 # now let's try to rerun this script under a "persistent" environment
375 # this is ugly and dirty but we do not yet have a Test::Embedded or
380 $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
381 ($ENV{PATH}) = $ENV{PATH} =~ /(.+)/;
384 my $persistence_tests = {
386 cmd => [qw/pperl --prefork=1/, __FILE__],
388 'CGI::SpeedyCGI' => {
389 cmd => [qw/speedy -- -t5/, __FILE__],
393 # scgi is smart and will auto-reap after -t amount of seconds
394 # pperl needs an actual killer :(
395 $persistence_tests->{PPerl}{termcmd} = [
396 $persistence_tests->{PPerl}{cmd}[0],
398 @{$persistence_tests->{PPerl}{cmd}}[ 1 .. $#{$persistence_tests->{PPerl}{cmd}} ],
402 skip 'Test already in a persistent loop', 1
403 if $ENV{DBICTEST_IN_PERSISTENT_ENV};
405 skip 'Main test failed - skipping persistent env tests', 1
406 unless $TB->is_passing;
408 local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
412 for my $type (keys %$persistence_tests) { SKIP: {
413 unless (eval "require $type") {
414 # Don't terminate what we didn't start
415 delete $persistence_tests->{$type}{termcmd};
416 skip "$type module not found", 1;
419 my @cmd = @{$persistence_tests->{$type}{cmd}};
421 # since PPerl is racy and sucks - just prime the "server"
423 local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
427 # see if the thing actually runs, if not - might as well bail now
428 skip "Something is wrong with $type ($!)", 1
433 note ("Starting run in persistent env ($type pass $_)");
434 IPC::Open2::open2(my $out, undef, @cmd);
436 while (my $ln = <$out>) {
437 next if $ln =~ /^\s*$/;
438 push @out_lines, " $ln";
439 last if $ln =~ /^\d+\.\.\d+$/; # this is persistence, we need to terminate reading on our end
441 print $_ for @out_lines;
444 ok (!$?, "Run in persistent env ($type pass $_): exit $?");
445 ok (scalar @out_lines, "Run in persistent env ($type pass $_): got output");
448 ok (! system (@{$persistence_tests->{$type}{termcmd}}), "killed $type server instance")
449 if $persistence_tests->{$type}{termcmd};
455 # just an extra precaution in case we blew away from the SKIP - since there are no
456 # PID files to go by (man does pperl really suck :(
458 unless ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
459 close $_ for (*STDIN, *STDOUT, *STDERR);
460 local $?; # otherwise test will inherit $? of the system()
461 system (@{$persistence_tests->{PPerl}{termcmd}})
462 if $persistence_tests->{PPerl}{termcmd};