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 DBICTest::RunMode;
23 use DBICTest::Util::LeakTracer qw/populate_weakregistry assert_empty_weakregistry/;
24 use DBICTest::Util 'local_umask';
26 use Path::Class::File ();
28 use Fcntl qw/:DEFAULT :flock/;
32 DBICTest - Library to be used by DBIx::Class test scripts.
40 my $schema = DBICTest->init_schema();
44 This module provides the basic utilities to write tests against
51 my $schema = DBICTest->init_schema(
54 storage_type=>'::DBI::Replicated',
56 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
60 This method removes the test SQLite database in t/var/DBIxClass.db
61 and then creates a new, empty database.
63 This method will call deploy_schema() by default, unless the
64 no_deploy flag is set.
66 Also, by default, this method will call populate_schema() by
67 default, unless the no_deploy or no_populate flags are set.
71 # some tests are very time sensitive and need to run on their own, without
72 # being disturbed by anything else grabbing CPU or disk IO. Hence why everything
73 # using DBICTest grabs a shared lock, and the few tests that request a :GlobalLock
74 # will ask for an exclusive one and block until they can get it
75 our ($global_lock_fh, $global_exclusive_lock);
79 my $tmpdir = DBICTest::RunMode->tmpdir;
80 my $lockpath = $tmpdir->file('.dbictest_global.lock');
83 my $u = local_umask(0); # so that the file opens as 666, and any user can lock
84 sysopen ($global_lock_fh, $lockpath, O_RDWR|O_CREAT) or do {
87 my @x_tests = map { (defined $_) ? ( $_ ? 1 : 0 ) : 'U' } map {(-e, -d, -f, -r, -w, -x, -o)} ($tmpdir, $lockpath);
89 die sprintf <<"EOE", $lockpath, $err, scalar $>, scalar $), (stat($tmpdir))[4,5,2], @x_tests;
91 Process EUID/EGID: %s / %s
92 TmpDir UID/GID: %s / %s
94 TmpDir X-tests: -e:%s -d:%s -f:%s -r:%s -w:%s -x:%s -o:%s
95 TmpFile X-tests: -e:%s -d:%s -f:%s -r:%s -w:%s -x:%s -o:%s
101 if ($_ eq ':GlobalLock') {
102 flock ($global_lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
103 $global_exclusive_lock = 1;
106 croak "Unknown export $_ requested from $self";
110 unless ($global_exclusive_lock) {
111 flock ($global_lock_fh, LOCK_SH) or die "Unable to lock $lockpath: $!";
116 if ($global_lock_fh) {
117 # delay destruction even more
122 my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
123 $dir->mkpath unless -d "$dir";
126 sub _sqlite_dbfilename {
127 my $holder = $ENV{DBICTEST_LOCK_HOLDER} || $$;
128 $holder = $$ if $holder == -1;
130 # useful for missing cleanup debugging
131 #if ( $holder == $$) {
137 return "$dir/DBIxClass-$holder.db";
145 $SIG{INT} = sub { _cleanup_dbfile(); exit 1 };
147 sub _cleanup_dbfile {
148 # cleanup if this is us
150 ! $ENV{DBICTEST_LOCK_HOLDER}
152 $ENV{DBICTEST_LOCK_HOLDER} == -1
154 $ENV{DBICTEST_LOCK_HOLDER} == $$
156 my $db_file = _sqlite_dbfilename();
157 unlink $_ for ($db_file, "${db_file}-journal");
162 return $ENV{"DBICTEST_DSN"} ? 1:0;
168 return $self->_sqlite_dbfilename if (
169 defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
178 if ($ENV{DBICTEST_DSN}) {
180 (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
181 { AutoCommit => 1, %args },
184 my $db_file = $self->_sqlite_dbname(%args);
186 for ($db_file, "${db_file}-journal") {
188 unlink ($_) or carp (
189 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
193 return ("dbi:SQLite:${db_file}", '', '', {
196 # this is executed on every connect, and thus installs a disconnect/DESTROY
197 # guard for every new $dbh
198 on_connect_do => sub {
200 my $dbh = $storage->_get_dbh;
203 $dbh->do ('PRAGMA synchronous = OFF');
205 if ($ENV{DBICTEST_SQLITE_REVERSE_DEFAULT_ORDER}) {
207 $storage->throw_exception(
208 'PRAGMA reverse_unordered_selects does not work correctly before libsqlite 3.7.9'
209 ) if $storage->_server_info->{normalized_dbms_version} < 3.007009;
211 $dbh->do ('PRAGMA reverse_unordered_selects = ON');
214 # set a *DBI* disconnect callback, to make sure the physical SQLite
215 # file is still there (i.e. the test does not attempt to delete
216 # an open database, which fails on Win32)
217 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
218 $dbh->{Callbacks} = {
219 connect => sub { $guard_cb->('connect') },
220 disconnect => sub { $guard_cb->('disconnect') },
221 DESTROY => sub { $guard_cb->('DESTROY') },
229 sub __mk_disconnect_guard {
230 return if DBIx::Class::_ENV_::PEEPEENESS; # leaks handles, delaying DESTROY, can't work right
233 return unless -f $db_file;
235 my $orig_inode = (stat($db_file))[1]
238 my $clan_connect_caller = '*UNKNOWN*';
240 while ( my ($pack, $file, $line) = caller(++$i) ) {
241 next if $file eq __FILE__;
242 next if $pack =~ /^DBIx::Class|^Try::Tiny/;
243 $clan_connect_caller = "$file line $line";
250 return if $failed_once;
253 if ($event eq 'connect') {
254 # this is necessary in case we are disconnected and connected again, all within the same $dbh object
258 elsif ($event eq 'disconnect') {
261 elsif ($event eq 'DESTROY' and ! $connected ) {
267 $fail_reason = 'is missing';
270 my $cur_inode = (stat($db_file))[1];
272 if ($orig_inode != $cur_inode) {
273 # pack/unpack to match the unsigned longs returned by `stat`
274 $fail_reason = sprintf 'was recreated (initially inode %s, now %s)', (
275 map { unpack ('L', pack ('l', $_) ) } ($orig_inode, $cur_inode )
283 require Test::Builder;
284 my $t = Test::Builder->new;
285 local $Test::Builder::Level = $Test::Builder::Level + 3;
287 "$db_file originally created at $clan_connect_caller $fail_reason before $event "
288 . 'of DBI handle - a strong indicator that the database file was tampered with while '
289 . 'still being open. This action would fail massively if running under Win32, hence '
290 . 'we make sure it fails on any OS :)'
294 return; # this empty return is a DBI requirement
298 my $weak_registry = {};
306 if ($args{compose_connection}) {
307 $schema = DBICTest::Schema->compose_connection(
308 'DBICTest', $self->_database(%args)
311 $schema = DBICTest::Schema->compose_namespace('DBICTest');
314 if( $args{storage_type}) {
315 $schema->storage_type($args{storage_type});
318 if ( !$args{no_connect} ) {
319 $schema = $schema->connect($self->_database(%args));
322 if ( !$args{no_deploy} ) {
323 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
324 __PACKAGE__->populate_schema( $schema )
325 if( !$args{no_populate} );
328 populate_weakregistry ( $weak_registry, $schema->storage )
329 if $INC{'Test/Builder.pm'} and $schema->storage;
335 assert_empty_weakregistry($weak_registry, 'quiet');
340 DBICTest->deploy_schema( $schema );
342 This method does one of two things to the schema. It can either call
343 the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
344 variable is set, otherwise the default is to read in the t/lib/sqlite.sql
345 file and execute the SQL within. Either way you end up with a fresh set
346 of tables for testing.
353 my $args = shift || {};
355 local $schema->storage->{debug}
356 if ($ENV{TRAVIS}||'') eq 'true';
358 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
359 $schema->deploy($args);
361 my $filename = Path::Class::File->new(__FILE__)->dir
362 ->file('sqlite.sql')->stringify;
363 my $sql = do { local (@ARGV, $/) = $filename ; <> };
364 for my $chunk ( split (/;\s*\n+/, $sql) ) {
365 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
366 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
373 =head2 populate_schema
375 DBICTest->populate_schema( $schema );
377 After you deploy your schema you can use this method to populate
378 the tables with test data.
382 sub populate_schema {
386 local $schema->storage->{debug}
387 if ($ENV{TRAVIS}||'') eq 'true';
389 $schema->populate('Genre', [
394 $schema->populate('Artist', [
395 [ qw/artistid name/ ],
396 [ 1, 'Caterwauler McCrae' ],
397 [ 2, 'Random Boy Band' ],
398 [ 3, 'We Are Goth' ],
401 $schema->populate('CD', [
402 [ qw/cdid artist title year genreid/ ],
403 [ 1, 1, "Spoonful of bees", 1999, 1 ],
404 [ 2, 1, "Forkful of bees", 2001 ],
405 [ 3, 1, "Caterwaulin' Blues", 1997 ],
406 [ 4, 2, "Generic Manufactured Singles", 2001 ],
407 [ 5, 3, "Come Be Depressed With Us", 1998 ],
410 $schema->populate('LinerNotes', [
411 [ qw/liner_id notes/ ],
412 [ 2, "Buy Whiskey!" ],
414 [ 5, "Kill Yourself!" ],
417 $schema->populate('Tag', [
418 [ qw/tagid cd tag/ ],
430 $schema->populate('TwoKeys', [
437 $schema->populate('FourKeys', [
438 [ qw/foo bar hello goodbye sensors/ ],
439 [ 1, 2, 3, 4, 'online' ],
440 [ 5, 4, 3, 6, 'offline' ],
443 $schema->populate('OneKey', [
444 [ qw/id artist cd/ ],
450 $schema->populate('SelfRef', [
456 $schema->populate('SelfRefAlias', [
457 [ qw/self_ref alias/ ],
461 $schema->populate('ArtistUndirectedMap', [
466 $schema->populate('Producer', [
467 [ qw/producerid name/ ],
468 [ 1, 'Matt S Trout' ],
469 [ 2, 'Bob The Builder' ],
470 [ 3, 'Fred The Phenotype' ],
473 $schema->populate('CD_to_Producer', [
480 $schema->populate('TreeLike', [
481 [ qw/id parent name/ ],
482 [ 1, undef, 'root' ],
491 $schema->populate('Track', [
492 [ qw/trackid cd position title/ ],
493 [ 4, 2, 1, "Stung with Success"],
494 [ 5, 2, 2, "Stripy"],
495 [ 6, 2, 3, "Sticky Honey"],
496 [ 7, 3, 1, "Yowlin"],
497 [ 8, 3, 2, "Howlin"],
498 [ 9, 3, 3, "Fowlin"],
499 [ 10, 4, 1, "Boring Name"],
500 [ 11, 4, 2, "Boring Song"],
501 [ 12, 4, 3, "No More Ideas"],
503 [ 14, 5, 2, "Under The Weather"],
504 [ 15, 5, 3, "Suicidal"],
505 [ 16, 1, 1, "The Bees Knees"],
506 [ 17, 1, 2, "Apiary"],
507 [ 18, 1, 3, "Beehind You"],
510 $schema->populate('Event', [
511 [ qw/id starts_at created_on varchar_date varchar_datetime skip_inflation/ ],
512 [ 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'],
515 $schema->populate('Link', [
516 [ qw/id url title/ ],
520 $schema->populate('Bookmark', [
525 $schema->populate('Collection', [
526 [ qw/collectionid name/ ],
531 $schema->populate('TypedObject', [
532 [ qw/objectid type value/ ],
533 [ 1, "pointy", "Awl" ],
534 [ 2, "round", "Bearing" ],
535 [ 3, "pointy", "Knife" ],
536 [ 4, "pointy", "Tooth" ],
537 [ 5, "round", "Head" ],
539 $schema->populate('CollectionObject', [
540 [ qw/collection object/ ],
548 $schema->populate('Owners', [
554 $schema->populate('BooksInLibrary', [
555 [ qw/id owner title source price/ ],
556 [ 1, 1, "Programming Perl", "Library", 23 ],
557 [ 2, 1, "Dynamical Systems", "Library", 37 ],
558 [ 3, 2, "Best Recipe Cookbook", "Library", 65 ],