1 package # hide from PAUSE
7 # Needs to load 1st so that the correct SQLA::Test is picked up
8 use DBIx::Class::_TempExtlib;
10 # this noop trick initializes the STDOUT, so that the TAP::Harness
11 # issued IO::Select->can_read calls (which are blocking wtf wtf wtf)
12 # keep spinning and scheduling jobs
13 # This results in an overall much smoother job-queue drainage, since
14 # the Harness blocks less
15 # (ideally this needs to be addressed in T::H, but a quick patchjob
16 # broke everything so tabling it for now)
18 if ($INC{'Test/Builder.pm'}) {
24 use Module::Runtime 'module_notional_filename';
26 for my $mod (qw( DBIC::SqlMakerTest SQL::Abstract )) {
27 if ( $INC{ module_notional_filename($mod) } ) {
28 # FIXME this does not seem to work in BEGIN - why?!
30 #$Carp::Internal{ (__PACKAGE__) }++;
31 #Carp::croak( __PACKAGE__ . " must be loaded before $mod" );
34 while (@frame = caller($fr++)) {
35 last if $frame[1] !~ m|^t/lib/DBICTest|;
38 die __PACKAGE__ . " must be loaded before $mod (or modules using $mod) at $frame[1] line $frame[2]\n";
43 use DBICTest::RunMode;
45 use DBICTest::Util::LeakTracer qw/populate_weakregistry assert_empty_weakregistry/;
46 use DBICTest::Util 'local_umask';
48 use Path::Class::File ();
50 use Fcntl qw/:DEFAULT :flock/;
54 DBICTest - Library to be used by DBIx::Class test scripts.
62 my $schema = DBICTest->init_schema();
66 This module provides the basic utilities to write tests against
73 my $schema = DBICTest->init_schema(
76 storage_type=>'::DBI::Replicated',
78 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
82 This method removes the test SQLite database in t/var/DBIxClass.db
83 and then creates a new, empty database.
85 This method will call deploy_schema() by default, unless the
86 no_deploy flag is set.
88 Also, by default, this method will call populate_schema() by
89 default, unless the no_deploy or no_populate flags are set.
93 # some tests are very time sensitive and need to run on their own, without
94 # being disturbed by anything else grabbing CPU or disk IO. Hence why everything
95 # using DBICTest grabs a shared lock, and the few tests that request a :GlobalLock
96 # will ask for an exclusive one and block until they can get it
97 our ($global_lock_fh, $global_exclusive_lock);
101 my $tmpdir = DBICTest::RunMode->tmpdir;
102 my $lockpath = $tmpdir->file('.dbictest_global.lock');
105 my $u = local_umask(0); # so that the file opens as 666, and any user can lock
106 sysopen ($global_lock_fh, $lockpath, O_RDWR|O_CREAT) or do {
109 my @x_tests = map { (defined $_) ? ( $_ ? 1 : 0 ) : 'U' } map {(-e, -d, -f, -r, -w, -x, -o)} ($tmpdir, $lockpath);
111 die sprintf <<"EOE", $lockpath, $err, scalar $>, scalar $), (stat($tmpdir))[4,5,2], @x_tests;
112 Unable to open %s: %s
113 Process EUID/EGID: %s / %s
114 TmpDir UID/GID: %s / %s
116 TmpDir X-tests: -e:%s -d:%s -f:%s -r:%s -w:%s -x:%s -o:%s
117 TmpFile X-tests: -e:%s -d:%s -f:%s -r:%s -w:%s -x:%s -o:%s
123 if ($_ eq ':GlobalLock') {
124 flock ($global_lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
125 $global_exclusive_lock = 1;
128 croak "Unknown export $_ requested from $self";
132 unless ($global_exclusive_lock) {
133 flock ($global_lock_fh, LOCK_SH) or die "Unable to lock $lockpath: $!";
138 if ($global_lock_fh) {
139 # delay destruction even more
144 my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
145 $dir->mkpath unless -d "$dir";
148 sub _sqlite_dbfilename {
149 my $holder = $ENV{DBICTEST_LOCK_HOLDER} || $$;
150 $holder = $$ if $holder == -1;
152 # useful for missing cleanup debugging
153 #if ( $holder == $$) {
159 return "$dir/DBIxClass-$holder.db";
167 $SIG{INT} = sub { _cleanup_dbfile(); exit 1 };
169 sub _cleanup_dbfile {
170 # cleanup if this is us
172 ! $ENV{DBICTEST_LOCK_HOLDER}
174 $ENV{DBICTEST_LOCK_HOLDER} == -1
176 $ENV{DBICTEST_LOCK_HOLDER} == $$
178 my $db_file = _sqlite_dbfilename();
179 unlink $_ for ($db_file, "${db_file}-journal");
184 return $ENV{"DBICTEST_DSN"} ? 1:0;
190 return $self->_sqlite_dbfilename if (
191 defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
200 if ($ENV{DBICTEST_DSN}) {
202 (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
203 { AutoCommit => 1, %args },
206 my $db_file = $self->_sqlite_dbname(%args);
208 for ($db_file, "${db_file}-journal") {
210 unlink ($_) or carp (
211 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
215 return ("dbi:SQLite:${db_file}", '', '', {
218 # this is executed on every connect, and thus installs a disconnect/DESTROY
219 # guard for every new $dbh
220 on_connect_do => sub {
222 my $dbh = $storage->_get_dbh;
225 $dbh->do ('PRAGMA synchronous = OFF');
227 if ($ENV{DBICTEST_SQLITE_REVERSE_DEFAULT_ORDER}) {
229 $storage->throw_exception(
230 'PRAGMA reverse_unordered_selects does not work correctly before libsqlite 3.7.9'
231 ) if $storage->_server_info->{normalized_dbms_version} < 3.007009;
233 $dbh->do ('PRAGMA reverse_unordered_selects = ON');
236 # set a *DBI* disconnect callback, to make sure the physical SQLite
237 # file is still there (i.e. the test does not attempt to delete
238 # an open database, which fails on Win32)
239 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
240 $dbh->{Callbacks} = {
241 connect => sub { $guard_cb->('connect') },
242 disconnect => sub { $guard_cb->('disconnect') },
243 DESTROY => sub { $guard_cb->('DESTROY') },
251 sub __mk_disconnect_guard {
252 return if DBIx::Class::_ENV_::PEEPEENESS; # leaks handles, delaying DESTROY, can't work right
255 return unless -f $db_file;
257 my $orig_inode = (stat($db_file))[1]
260 my $clan_connect_caller = '*UNKNOWN*';
262 while ( my ($pack, $file, $line) = caller(++$i) ) {
263 next if $file eq __FILE__;
264 next if $pack =~ /^DBIx::Class|^Try::Tiny/;
265 $clan_connect_caller = "$file line $line";
272 return if $failed_once;
275 if ($event eq 'connect') {
276 # this is necessary in case we are disconnected and connected again, all within the same $dbh object
280 elsif ($event eq 'disconnect') {
283 elsif ($event eq 'DESTROY' and ! $connected ) {
289 $fail_reason = 'is missing';
292 my $cur_inode = (stat($db_file))[1];
294 if ($orig_inode != $cur_inode) {
295 # pack/unpack to match the unsigned longs returned by `stat`
296 $fail_reason = sprintf 'was recreated (initially inode %s, now %s)', (
297 map { unpack ('L', pack ('l', $_) ) } ($orig_inode, $cur_inode )
305 require Test::Builder;
306 my $t = Test::Builder->new;
307 local $Test::Builder::Level = $Test::Builder::Level + 3;
309 "$db_file originally created at $clan_connect_caller $fail_reason before $event "
310 . 'of DBI handle - a strong indicator that the database file was tampered with while '
311 . 'still being open. This action would fail massively if running under Win32, hence '
312 . 'we make sure it fails on any OS :)'
316 return; # this empty return is a DBI requirement
320 my $weak_registry = {};
328 if ($args{compose_connection}) {
329 $schema = DBICTest::Schema->compose_connection(
330 'DBICTest', $self->_database(%args)
333 $schema = DBICTest::Schema->compose_namespace('DBICTest');
336 if( $args{storage_type}) {
337 $schema->storage_type($args{storage_type});
340 if ( !$args{no_connect} ) {
341 $schema = $schema->connect($self->_database(%args));
344 if ( !$args{no_deploy} ) {
345 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
346 __PACKAGE__->populate_schema( $schema )
347 if( !$args{no_populate} );
350 populate_weakregistry ( $weak_registry, $schema->storage )
351 if $INC{'Test/Builder.pm'} and $schema->storage;
357 assert_empty_weakregistry($weak_registry, 'quiet');
362 DBICTest->deploy_schema( $schema );
364 This method does one of two things to the schema. It can either call
365 the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
366 variable is set, otherwise the default is to read in the t/lib/sqlite.sql
367 file and execute the SQL within. Either way you end up with a fresh set
368 of tables for testing.
375 my $args = shift || {};
377 local $schema->storage->{debug}
378 if ($ENV{TRAVIS}||'') eq 'true';
380 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
381 $schema->deploy($args);
383 my $filename = Path::Class::File->new(__FILE__)->dir
384 ->file('sqlite.sql')->stringify;
385 my $sql = do { local (@ARGV, $/) = $filename ; <> };
386 for my $chunk ( split (/;\s*\n+/, $sql) ) {
387 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
388 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
395 =head2 populate_schema
397 DBICTest->populate_schema( $schema );
399 After you deploy your schema you can use this method to populate
400 the tables with test data.
404 sub populate_schema {
408 local $schema->storage->{debug}
409 if ($ENV{TRAVIS}||'') eq 'true';
411 $schema->populate('Genre', [
416 $schema->populate('Artist', [
417 [ qw/artistid name/ ],
418 [ 1, 'Caterwauler McCrae' ],
419 [ 2, 'Random Boy Band' ],
420 [ 3, 'We Are Goth' ],
423 $schema->populate('CD', [
424 [ qw/cdid artist title year genreid/ ],
425 [ 1, 1, "Spoonful of bees", 1999, 1 ],
426 [ 2, 1, "Forkful of bees", 2001 ],
427 [ 3, 1, "Caterwaulin' Blues", 1997 ],
428 [ 4, 2, "Generic Manufactured Singles", 2001 ],
429 [ 5, 3, "Come Be Depressed With Us", 1998 ],
432 $schema->populate('LinerNotes', [
433 [ qw/liner_id notes/ ],
434 [ 2, "Buy Whiskey!" ],
436 [ 5, "Kill Yourself!" ],
439 $schema->populate('Tag', [
440 [ qw/tagid cd tag/ ],
452 $schema->populate('TwoKeys', [
459 $schema->populate('FourKeys', [
460 [ qw/foo bar hello goodbye sensors/ ],
461 [ 1, 2, 3, 4, 'online' ],
462 [ 5, 4, 3, 6, 'offline' ],
465 $schema->populate('OneKey', [
466 [ qw/id artist cd/ ],
472 $schema->populate('SelfRef', [
478 $schema->populate('SelfRefAlias', [
479 [ qw/self_ref alias/ ],
483 $schema->populate('ArtistUndirectedMap', [
488 $schema->populate('Producer', [
489 [ qw/producerid name/ ],
490 [ 1, 'Matt S Trout' ],
491 [ 2, 'Bob The Builder' ],
492 [ 3, 'Fred The Phenotype' ],
495 $schema->populate('CD_to_Producer', [
502 $schema->populate('TreeLike', [
503 [ qw/id parent name/ ],
504 [ 1, undef, 'root' ],
513 $schema->populate('Track', [
514 [ qw/trackid cd position title/ ],
515 [ 4, 2, 1, "Stung with Success"],
516 [ 5, 2, 2, "Stripy"],
517 [ 6, 2, 3, "Sticky Honey"],
518 [ 7, 3, 1, "Yowlin"],
519 [ 8, 3, 2, "Howlin"],
520 [ 9, 3, 3, "Fowlin"],
521 [ 10, 4, 1, "Boring Name"],
522 [ 11, 4, 2, "Boring Song"],
523 [ 12, 4, 3, "No More Ideas"],
525 [ 14, 5, 2, "Under The Weather"],
526 [ 15, 5, 3, "Suicidal"],
527 [ 16, 1, 1, "The Bees Knees"],
528 [ 17, 1, 2, "Apiary"],
529 [ 18, 1, 3, "Beehind You"],
532 $schema->populate('Event', [
533 [ qw/id starts_at created_on varchar_date varchar_datetime skip_inflation/ ],
534 [ 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'],
537 $schema->populate('Link', [
538 [ qw/id url title/ ],
542 $schema->populate('Bookmark', [
547 $schema->populate('Collection', [
548 [ qw/collectionid name/ ],
553 $schema->populate('TypedObject', [
554 [ qw/objectid type value/ ],
555 [ 1, "pointy", "Awl" ],
556 [ 2, "round", "Bearing" ],
557 [ 3, "pointy", "Knife" ],
558 [ 4, "pointy", "Tooth" ],
559 [ 5, "round", "Head" ],
561 $schema->populate('CollectionObject', [
562 [ qw/collection object/ ],
570 $schema->populate('Owners', [
576 $schema->populate('BooksInLibrary', [
577 [ qw/id owner title source price/ ],
578 [ 1, 1, "Programming Perl", "Library", 23 ],
579 [ 2, 1, "Dynamical Systems", "Library", 37 ],
580 [ 3, 2, "Best Recipe Cookbook", "Library", 65 ],