1 package # hide from PAUSE
7 # this noop trick initializes the STDOUT, so that the TAP::Harness
8 # issued IO::Select->can_read calls (which are blocking wtf wtf wtf)
9 # keep spinning and scheduling jobs
10 # This results in an overall much smoother job-queue drainage, since
11 # the Harness blocks less
12 # (ideally this needs to be addressed in T::H, but a quick patchjob
13 # broke everything so tabling it for now)
15 if ($INC{'Test/Builder.pm'}) {
21 use Module::Runtime 'module_notional_filename';
23 for my $mod (qw( DBIC::SqlMakerTest SQL::Abstract )) {
24 if ( $INC{ module_notional_filename($mod) } ) {
25 # FIXME this does not seem to work in BEGIN - why?!
27 #$Carp::Internal{ (__PACKAGE__) }++;
28 #Carp::croak( __PACKAGE__ . " must be loaded before $mod" );
31 while (@frame = caller($fr++)) {
32 last if $frame[1] !~ m|^t/lib/DBICTest|;
35 die __PACKAGE__ . " must be loaded before $mod (or modules using $mod) at $frame[1] line $frame[2]\n";
41 use DBICTest::Util::LeakTracer qw/populate_weakregistry assert_empty_weakregistry/;
42 use DBICTest::Util 'local_umask';
44 use Path::Class::File ();
46 use Fcntl qw/:DEFAULT :flock/;
51 DBICTest - Library to be used by DBIx::Class test scripts.
59 my $schema = DBICTest->init_schema();
63 This module provides the basic utilities to write tests against
70 my $schema = DBICTest->init_schema(
73 storage_type=>'::DBI::Replicated',
75 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
79 This method removes the test SQLite database in t/var/DBIxClass.db
80 and then creates a new, empty database.
82 This method will call deploy_schema() by default, unless the
83 no_deploy flag is set.
85 Also, by default, this method will call populate_schema() by
86 default, unless the no_deploy or no_populate flags are set.
90 # some tests are very time sensitive and need to run on their own, without
91 # being disturbed by anything else grabbing CPU or disk IO. Hence why everything
92 # using DBICTest grabs a shared lock, and the few tests that request a :GlobalLock
93 # will ask for an exclusive one and block until they can get it
94 our ($global_lock_fh, $global_exclusive_lock);
98 my $lockpath = DBICTest::RunMode->tmpdir->file('_dbictest_global.lock');
101 my $u = local_umask(0); # so that the file opens as 666, and any user can lock
102 sysopen ($global_lock_fh, $lockpath, O_RDWR|O_CREAT)
103 or die "Unable to open $lockpath: $!";
107 if ($_ eq ':GlobalLock') {
108 flock ($global_lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
109 $global_exclusive_lock = 1;
112 croak "Unknown export $_ requested from $self";
116 unless ($global_exclusive_lock) {
117 flock ($global_lock_fh, LOCK_SH) or die "Unable to lock $lockpath: $!";
122 if ($global_lock_fh) {
123 # delay destruction even more
128 my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
129 $dir->mkpath unless -d "$dir";
132 sub _sqlite_dbfilename {
133 my $holder = $ENV{DBICTEST_LOCK_HOLDER} || $$;
134 $holder = $$ if $holder == -1;
136 # useful for missing cleanup debugging
137 #if ( $holder == $$) {
143 return "$dir/DBIxClass-$holder.db";
151 $SIG{INT} = sub { _cleanup_dbfile(); exit 1 };
153 sub _cleanup_dbfile {
154 # cleanup if this is us
156 ! $ENV{DBICTEST_LOCK_HOLDER}
158 $ENV{DBICTEST_LOCK_HOLDER} == -1
160 $ENV{DBICTEST_LOCK_HOLDER} == $$
162 my $db_file = _sqlite_dbfilename();
163 unlink $_ for ($db_file, "${db_file}-journal");
168 return $ENV{"DBICTEST_DSN"} ? 1:0;
174 return $self->_sqlite_dbfilename if (
175 defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
184 if ($ENV{DBICTEST_DSN}) {
186 (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
187 { AutoCommit => 1, %args },
190 my $db_file = $self->_sqlite_dbname(%args);
192 for ($db_file, "${db_file}-journal") {
194 unlink ($_) or carp (
195 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
199 return ("dbi:SQLite:${db_file}", '', '', {
202 # this is executed on every connect, and thus installs a disconnect/DESTROY
203 # guard for every new $dbh
204 on_connect_do => sub {
207 my $dbh = $storage->_get_dbh;
210 $dbh->do ('PRAGMA synchronous = OFF');
213 $ENV{DBICTEST_SQLITE_REVERSE_DEFAULT_ORDER}
215 # the pragma does not work correctly before libsqlite 3.7.9
216 $storage->_server_info->{normalized_dbms_version} >= 3.007009
218 $dbh->do ('PRAGMA reverse_unordered_selects = ON');
221 # set a *DBI* disconnect callback, to make sure the physical SQLite
222 # file is still there (i.e. the test does not attempt to delete
223 # an open database, which fails on Win32)
224 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
225 $dbh->{Callbacks} = {
226 connect => sub { $guard_cb->('connect') },
227 disconnect => sub { $guard_cb->('disconnect') },
228 DESTROY => sub { $guard_cb->('DESTROY') },
236 sub __mk_disconnect_guard {
237 return if DBIx::Class::_ENV_::PEEPEENESS; # leaks handles, delaying DESTROY, can't work right
240 return unless -f $db_file;
242 my $orig_inode = (stat($db_file))[1]
245 my $clan_connect_caller = '*UNKNOWN*';
247 while ( my ($pack, $file, $line) = caller(++$i) ) {
248 next if $file eq __FILE__;
249 next if $pack =~ /^DBIx::Class|^Try::Tiny/;
250 $clan_connect_caller = "$file line $line";
257 return if $failed_once;
260 if ($event eq 'connect') {
261 # this is necessary in case we are disconnected and connected again, all within the same $dbh object
265 elsif ($event eq 'disconnect') {
268 elsif ($event eq 'DESTROY' and ! $connected ) {
274 $fail_reason = 'is missing';
277 my $cur_inode = (stat($db_file))[1];
279 if ($orig_inode != $cur_inode) {
280 my @inodes = ($orig_inode, $cur_inode);
281 # unless this is a fixed perl (P5RT#84590) pack/unpack before display
282 # to match the unsigned longs returned by `stat`
283 @inodes = map { unpack ('L', pack ('l', $_) ) } @inodes
284 unless $Config{st_ino_size};
286 $fail_reason = sprintf
287 'was recreated (initially inode %s, now %s)',
296 require Test::Builder;
297 my $t = Test::Builder->new;
298 local $Test::Builder::Level = $Test::Builder::Level + 3;
300 "$db_file originally created at $clan_connect_caller $fail_reason before $event "
301 . 'of DBI handle - a strong indicator that the database file was tampered with while '
302 . 'still being open. This action would fail massively if running under Win32, hence '
303 . 'we make sure it fails on any OS :)'
307 return; # this empty return is a DBI requirement
311 my $weak_registry = {};
319 if ($args{compose_connection}) {
320 $schema = DBICTest::Schema->compose_connection(
321 'DBICTest', $self->_database(%args)
324 $schema = DBICTest::Schema->compose_namespace('DBICTest');
327 if( $args{storage_type}) {
328 $schema->storage_type($args{storage_type});
331 if ( !$args{no_connect} ) {
332 $schema = $schema->connect($self->_database(%args));
335 if ( !$args{no_deploy} ) {
336 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
337 __PACKAGE__->populate_schema( $schema )
338 if( !$args{no_populate} );
341 populate_weakregistry ( $weak_registry, $schema->storage )
342 if $INC{'Test/Builder.pm'} and $schema->storage;
348 assert_empty_weakregistry($weak_registry, 'quiet');
353 DBICTest->deploy_schema( $schema );
355 This method does one of two things to the schema. It can either call
356 the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
357 variable is set, otherwise the default is to read in the t/lib/sqlite.sql
358 file and execute the SQL within. Either way you end up with a fresh set
359 of tables for testing.
366 my $args = shift || {};
368 local $schema->storage->{debug}
369 if ($ENV{TRAVIS}||'') eq 'true';
371 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
372 $schema->deploy($args);
374 my $filename = Path::Class::File->new(__FILE__)->dir
375 ->file('sqlite.sql')->stringify;
376 my $sql = do { local (@ARGV, $/) = $filename ; <> };
377 for my $chunk ( split (/;\s*\n+/, $sql) ) {
378 if ( $chunk =~ / ^ (?! --\s* ) \S /xm ) { # there is some real sql in the chunk - a non-space at the start of the string which is not a comment
379 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
386 =head2 populate_schema
388 DBICTest->populate_schema( $schema );
390 After you deploy your schema you can use this method to populate
391 the tables with test data.
395 sub populate_schema {
399 local $schema->storage->{debug}
400 if ($ENV{TRAVIS}||'') eq 'true';
402 $schema->populate('Genre', [
407 $schema->populate('Artist', [
408 [ qw/artistid name/ ],
409 [ 1, 'Caterwauler McCrae' ],
410 [ 2, 'Random Boy Band' ],
411 [ 3, 'We Are Goth' ],
414 $schema->populate('CD', [
415 [ qw/cdid artist title year genreid/ ],
416 [ 1, 1, "Spoonful of bees", 1999, 1 ],
417 [ 2, 1, "Forkful of bees", 2001 ],
418 [ 3, 1, "Caterwaulin' Blues", 1997 ],
419 [ 4, 2, "Generic Manufactured Singles", 2001 ],
420 [ 5, 3, "Come Be Depressed With Us", 1998 ],
423 $schema->populate('LinerNotes', [
424 [ qw/liner_id notes/ ],
425 [ 2, "Buy Whiskey!" ],
427 [ 5, "Kill Yourself!" ],
430 $schema->populate('Tag', [
431 [ qw/tagid cd tag/ ],
443 $schema->populate('TwoKeys', [
450 $schema->populate('FourKeys', [
451 [ qw/foo bar hello goodbye sensors/ ],
452 [ 1, 2, 3, 4, 'online' ],
453 [ 5, 4, 3, 6, 'offline' ],
456 $schema->populate('OneKey', [
457 [ qw/id artist cd/ ],
463 $schema->populate('SelfRef', [
469 $schema->populate('SelfRefAlias', [
470 [ qw/self_ref alias/ ],
474 $schema->populate('ArtistUndirectedMap', [
479 $schema->populate('Producer', [
480 [ qw/producerid name/ ],
481 [ 1, 'Matt S Trout' ],
482 [ 2, 'Bob The Builder' ],
483 [ 3, 'Fred The Phenotype' ],
486 $schema->populate('CD_to_Producer', [
493 $schema->populate('TreeLike', [
494 [ qw/id parent name/ ],
495 [ 1, undef, 'root' ],
504 $schema->populate('Track', [
505 [ qw/trackid cd position title/ ],
506 [ 4, 2, 1, "Stung with Success"],
507 [ 5, 2, 2, "Stripy"],
508 [ 6, 2, 3, "Sticky Honey"],
509 [ 7, 3, 1, "Yowlin"],
510 [ 8, 3, 2, "Howlin"],
511 [ 9, 3, 3, "Fowlin"],
512 [ 10, 4, 1, "Boring Name"],
513 [ 11, 4, 2, "Boring Song"],
514 [ 12, 4, 3, "No More Ideas"],
516 [ 14, 5, 2, "Under The Weather"],
517 [ 15, 5, 3, "Suicidal"],
518 [ 16, 1, 1, "The Bees Knees"],
519 [ 17, 1, 2, "Apiary"],
520 [ 18, 1, 3, "Beehind You"],
523 $schema->populate('Event', [
524 [ qw/id starts_at created_on varchar_date varchar_datetime skip_inflation/ ],
525 [ 1, '2006-04-25 22:24:33', '2006-06-22 21:00:05', '2006-07-23', '2006-05-22 19:05:07', '2006-04-21 18:04:06'],
528 $schema->populate('Link', [
529 [ qw/id url title/ ],
533 $schema->populate('Bookmark', [
538 $schema->populate('Collection', [
539 [ qw/collectionid name/ ],
544 $schema->populate('TypedObject', [
545 [ qw/objectid type value/ ],
546 [ 1, "pointy", "Awl" ],
547 [ 2, "round", "Bearing" ],
548 [ 3, "pointy", "Knife" ],
549 [ 4, "pointy", "Tooth" ],
550 [ 5, "round", "Head" ],
552 $schema->populate('CollectionObject', [
553 [ qw/collection object/ ],
561 $schema->populate('Owners', [
567 $schema->populate('BooksInLibrary', [
568 [ qw/id owner title source price/ ],
569 [ 1, 1, "Programming Perl", "Library", 23 ],
570 [ 2, 1, "Dynamical Systems", "Library", 37 ],
571 [ 3, 2, "Best Recipe Cookbook", "Library", 65 ],