1 package # hide from PAUSE
8 use DBICTest::Util qw/populate_weakregistry assert_empty_weakregistry local_umask/;
10 use Path::Class::File ();
12 use Fcntl qw/:DEFAULT :flock/;
16 DBICTest - Library to be used by DBIx::Class test scripts.
24 my $schema = DBICTest->init_schema();
28 This module provides the basic utilities to write tests against
35 my $schema = DBICTest->init_schema(
38 storage_type=>'::DBI::Replicated',
40 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
44 This method removes the test SQLite database in t/var/DBIxClass.db
45 and then creates a new, empty database.
47 This method will call deploy_schema() by default, unless the
48 no_deploy flag is set.
50 Also, by default, this method will call populate_schema() by
51 default, unless the no_deploy or no_populate flags are set.
55 # some tests are very time sensitive and need to run on their own, without
56 # being disturbed by anything else grabbing CPU or disk IO. Hence why everything
57 # using DBICTest grabs a shared lock, and the few tests that request a :GlobalLock
58 # will ask for an exclusive one and block until they can get it
59 our ($global_lock_fh, $global_exclusive_lock);
63 my $lockpath = DBICTest::RunMode->tmpdir->file('.dbictest_global.lock');
66 my $u = local_umask(0); # so that the file opens as 666, and any user can lock
67 sysopen ($global_lock_fh, $lockpath, O_RDWR|O_CREAT)
68 or die "Unable to open $lockpath: $!";
72 if ($_ eq ':GlobalLock') {
73 flock ($global_lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
74 $global_exclusive_lock = 1;
77 croak "Unknown export $_ requested from $self";
81 unless ($global_exclusive_lock) {
82 flock ($global_lock_fh, LOCK_SH) or die "Unable to lock $lockpath: $!";
87 if ($global_lock_fh) {
88 # delay destruction even more
93 my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
94 $dir->mkpath unless -d "$dir";
97 sub _sqlite_dbfilename {
98 my $holder = $ENV{DBICTEST_LOCK_HOLDER} || $$;
99 $holder = $$ if $holder == -1;
101 # useful for missing cleanup debugging
102 #if ( $holder == $$) {
108 return "$dir/DBIxClass-$holder.db";
116 $SIG{INT} = sub { _cleanup_dbfile(); exit 1 };
118 sub _cleanup_dbfile {
119 # cleanup if this is us
121 ! $ENV{DBICTEST_LOCK_HOLDER}
123 $ENV{DBICTEST_LOCK_HOLDER} == -1
125 $ENV{DBICTEST_LOCK_HOLDER} == $$
127 my $db_file = _sqlite_dbfilename();
128 unlink $_ for ($db_file, "${db_file}-journal");
133 return $ENV{"DBICTEST_DSN"} ? 1:0;
139 return $self->_sqlite_dbfilename if (
140 defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
149 if ($ENV{DBICTEST_DSN}) {
151 (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
152 { AutoCommit => 1, %args },
155 my $db_file = $self->_sqlite_dbname(%args);
157 for ($db_file, "${db_file}-journal") {
159 unlink ($_) or carp (
160 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
164 return ("dbi:SQLite:${db_file}", '', '', {
167 # this is executed on every connect, and thus installs a disconnect/DESTROY
168 # guard for every new $dbh
169 on_connect_do => sub {
171 my $dbh = $storage->_get_dbh;
174 $dbh->do ('PRAGMA synchronous = OFF');
176 # set a *DBI* disconnect callback, to make sure the physical SQLite
177 # file is still there (i.e. the test does not attempt to delete
178 # an open database, which fails on Win32)
179 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
180 $dbh->{Callbacks} = {
181 connect => sub { $guard_cb->('connect') },
182 disconnect => sub { $guard_cb->('disconnect') },
183 DESTROY => sub { $guard_cb->('DESTROY') },
191 sub __mk_disconnect_guard {
192 return if DBIx::Class::_ENV_::PEEPEENESS(); # leaks handles, delaying DESTROY, can't work right
195 return unless -f $db_file;
197 my $orig_inode = (stat($db_file))[1]
200 my $clan_connect_caller = '*UNKNOWN*';
202 while ( my ($pack, $file, $line) = caller(++$i) ) {
203 next if $file eq __FILE__;
204 next if $pack =~ /^DBIx::Class|^Try::Tiny/;
205 $clan_connect_caller = "$file line $line";
212 return if $failed_once;
215 if ($event eq 'connect') {
216 # this is necessary in case we are disconnected and connected again, all within the same $dbh object
220 elsif ($event eq 'disconnect') {
223 elsif ($event eq 'DESTROY' and ! $connected ) {
229 $fail_reason = 'is missing';
232 my $cur_inode = (stat($db_file))[1];
234 if ($orig_inode != $cur_inode) {
235 # pack/unpack to match the unsigned longs returned by `stat`
236 $fail_reason = sprintf 'was recreated (initially inode %s, now %s)', (
237 map { unpack ('L', pack ('l', $_) ) } ($orig_inode, $cur_inode )
245 require Test::Builder;
246 my $t = Test::Builder->new;
247 local $Test::Builder::Level = $Test::Builder::Level + 3;
249 "$db_file originally created at $clan_connect_caller $fail_reason before $event "
250 . 'of DBI handle - a strong indicator that the database file was tampered with while '
251 . 'still being open. This action would fail massively if running under Win32, hence '
252 . 'we make sure it fails on any OS :)'
256 return; # this empty return is a DBI requirement
260 my $weak_registry = {};
268 if ($args{compose_connection}) {
269 $schema = DBICTest::Schema->compose_connection(
270 'DBICTest', $self->_database(%args)
273 $schema = DBICTest::Schema->compose_namespace('DBICTest');
276 if( $args{storage_type}) {
277 $schema->storage_type($args{storage_type});
280 if ( !$args{no_connect} ) {
281 $schema = $schema->connect($self->_database(%args));
284 if ( !$args{no_deploy} ) {
285 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
286 __PACKAGE__->populate_schema( $schema )
287 if( !$args{no_populate} );
290 populate_weakregistry ( $weak_registry, $schema->storage )
291 if $INC{'Test/Builder.pm'} and $schema->storage;
297 assert_empty_weakregistry($weak_registry, 'quiet');
302 DBICTest->deploy_schema( $schema );
304 This method does one of two things to the schema. It can either call
305 the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
306 variable is set, otherwise the default is to read in the t/lib/sqlite.sql
307 file and execute the SQL within. Either way you end up with a fresh set
308 of tables for testing.
315 my $args = shift || {};
317 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
318 $schema->deploy($args);
320 my $filename = Path::Class::File->new(__FILE__)->dir
321 ->file('sqlite.sql')->stringify;
322 my $sql = do { local (@ARGV, $/) = $filename ; <> };
323 for my $chunk ( split (/;\s*\n+/, $sql) ) {
324 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
325 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
332 =head2 populate_schema
334 DBICTest->populate_schema( $schema );
336 After you deploy your schema you can use this method to populate
337 the tables with test data.
341 sub populate_schema {
345 $schema->populate('Genre', [
350 $schema->populate('Artist', [
351 [ qw/artistid name/ ],
352 [ 1, 'Caterwauler McCrae' ],
353 [ 2, 'Random Boy Band' ],
354 [ 3, 'We Are Goth' ],
357 $schema->populate('CD', [
358 [ qw/cdid artist title year genreid/ ],
359 [ 1, 1, "Spoonful of bees", 1999, 1 ],
360 [ 2, 1, "Forkful of bees", 2001 ],
361 [ 3, 1, "Caterwaulin' Blues", 1997 ],
362 [ 4, 2, "Generic Manufactured Singles", 2001 ],
363 [ 5, 3, "Come Be Depressed With Us", 1998 ],
366 $schema->populate('LinerNotes', [
367 [ qw/liner_id notes/ ],
368 [ 2, "Buy Whiskey!" ],
370 [ 5, "Kill Yourself!" ],
373 $schema->populate('Tag', [
374 [ qw/tagid cd tag/ ],
386 $schema->populate('TwoKeys', [
393 $schema->populate('FourKeys', [
394 [ qw/foo bar hello goodbye sensors/ ],
395 [ 1, 2, 3, 4, 'online' ],
396 [ 5, 4, 3, 6, 'offline' ],
399 $schema->populate('OneKey', [
400 [ qw/id artist cd/ ],
406 $schema->populate('SelfRef', [
412 $schema->populate('SelfRefAlias', [
413 [ qw/self_ref alias/ ],
417 $schema->populate('ArtistUndirectedMap', [
422 $schema->populate('Producer', [
423 [ qw/producerid name/ ],
424 [ 1, 'Matt S Trout' ],
425 [ 2, 'Bob The Builder' ],
426 [ 3, 'Fred The Phenotype' ],
429 $schema->populate('CD_to_Producer', [
436 $schema->populate('TreeLike', [
437 [ qw/id parent name/ ],
438 [ 1, undef, 'root' ],
447 $schema->populate('Track', [
448 [ qw/trackid cd position title/ ],
449 [ 4, 2, 1, "Stung with Success"],
450 [ 5, 2, 2, "Stripy"],
451 [ 6, 2, 3, "Sticky Honey"],
452 [ 7, 3, 1, "Yowlin"],
453 [ 8, 3, 2, "Howlin"],
454 [ 9, 3, 3, "Fowlin"],
455 [ 10, 4, 1, "Boring Name"],
456 [ 11, 4, 2, "Boring Song"],
457 [ 12, 4, 3, "No More Ideas"],
459 [ 14, 5, 2, "Under The Weather"],
460 [ 15, 5, 3, "Suicidal"],
461 [ 16, 1, 1, "The Bees Knees"],
462 [ 17, 1, 2, "Apiary"],
463 [ 18, 1, 3, "Beehind You"],
466 $schema->populate('Event', [
467 [ qw/id starts_at created_on varchar_date varchar_datetime skip_inflation/ ],
468 [ 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'],
471 $schema->populate('Link', [
472 [ qw/id url title/ ],
476 $schema->populate('Bookmark', [
481 $schema->populate('Collection', [
482 [ qw/collectionid name/ ],
487 $schema->populate('TypedObject', [
488 [ qw/objectid type value/ ],
489 [ 1, "pointy", "Awl" ],
490 [ 2, "round", "Bearing" ],
491 [ 3, "pointy", "Knife" ],
492 [ 4, "pointy", "Tooth" ],
493 [ 5, "round", "Head" ],
495 $schema->populate('CollectionObject', [
496 [ qw/collection object/ ],
504 $schema->populate('Owners', [
510 $schema->populate('BooksInLibrary', [
511 [ qw/id owner title source price/ ],
512 [ 1, 1, "Programming Perl", "Library", 23 ],
513 [ 2, 1, "Dynamical Systems", "Library", 37 ],
514 [ 3, 2, "Best Recipe Cookbook", "Library", 65 ],