1 package # hide from PAUSE
8 use DBICTest::Util::LeakTracer qw/populate_weakregistry assert_empty_weakregistry/;
9 use DBICTest::Util 'local_umask';
11 use Path::Class::File ();
13 use Fcntl qw/:DEFAULT :flock/;
17 DBICTest - Library to be used by DBIx::Class test scripts.
25 my $schema = DBICTest->init_schema();
29 This module provides the basic utilities to write tests against
36 my $schema = DBICTest->init_schema(
39 storage_type=>'::DBI::Replicated',
41 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
45 This method removes the test SQLite database in t/var/DBIxClass.db
46 and then creates a new, empty database.
48 This method will call deploy_schema() by default, unless the
49 no_deploy flag is set.
51 Also, by default, this method will call populate_schema() by
52 default, unless the no_deploy or no_populate flags are set.
56 # some tests are very time sensitive and need to run on their own, without
57 # being disturbed by anything else grabbing CPU or disk IO. Hence why everything
58 # using DBICTest grabs a shared lock, and the few tests that request a :GlobalLock
59 # will ask for an exclusive one and block until they can get it
60 our ($global_lock_fh, $global_exclusive_lock);
64 my $lockpath = DBICTest::RunMode->tmpdir->file('.dbictest_global.lock');
67 my $u = local_umask(0); # so that the file opens as 666, and any user can lock
68 sysopen ($global_lock_fh, $lockpath, O_RDWR|O_CREAT)
69 or die "Unable to open $lockpath: $!";
73 if ($_ eq ':GlobalLock') {
74 flock ($global_lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
75 $global_exclusive_lock = 1;
78 croak "Unknown export $_ requested from $self";
82 unless ($global_exclusive_lock) {
83 flock ($global_lock_fh, LOCK_SH) or die "Unable to lock $lockpath: $!";
88 if ($global_lock_fh) {
89 # delay destruction even more
94 my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
95 $dir->mkpath unless -d "$dir";
98 sub _sqlite_dbfilename {
99 my $holder = $ENV{DBICTEST_LOCK_HOLDER} || $$;
100 $holder = $$ if $holder == -1;
102 # useful for missing cleanup debugging
103 #if ( $holder == $$) {
109 return "$dir/DBIxClass-$holder.db";
117 $SIG{INT} = sub { _cleanup_dbfile(); exit 1 };
119 sub _cleanup_dbfile {
120 # cleanup if this is us
122 ! $ENV{DBICTEST_LOCK_HOLDER}
124 $ENV{DBICTEST_LOCK_HOLDER} == -1
126 $ENV{DBICTEST_LOCK_HOLDER} == $$
128 my $db_file = _sqlite_dbfilename();
129 unlink $_ for ($db_file, "${db_file}-journal");
134 return $ENV{"DBICTEST_DSN"} ? 1:0;
140 return $self->_sqlite_dbfilename if (
141 defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
150 if ($ENV{DBICTEST_DSN}) {
152 (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
153 { AutoCommit => 1, %args },
156 my $db_file = $self->_sqlite_dbname(%args);
158 for ($db_file, "${db_file}-journal") {
160 unlink ($_) or carp (
161 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
165 return ("dbi:SQLite:${db_file}", '', '', {
168 # this is executed on every connect, and thus installs a disconnect/DESTROY
169 # guard for every new $dbh
170 on_connect_do => sub {
172 my $dbh = $storage->_get_dbh;
175 $dbh->do ('PRAGMA synchronous = OFF');
177 # set a *DBI* disconnect callback, to make sure the physical SQLite
178 # file is still there (i.e. the test does not attempt to delete
179 # an open database, which fails on Win32)
180 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
181 $dbh->{Callbacks} = {
182 connect => sub { $guard_cb->('connect') },
183 disconnect => sub { $guard_cb->('disconnect') },
184 DESTROY => sub { $guard_cb->('DESTROY') },
192 sub __mk_disconnect_guard {
193 return if DBIx::Class::_ENV_::PEEPEENESS; # leaks handles, delaying DESTROY, can't work right
196 return unless -f $db_file;
198 my $orig_inode = (stat($db_file))[1]
201 my $clan_connect_caller = '*UNKNOWN*';
203 while ( my ($pack, $file, $line) = caller(++$i) ) {
204 next if $file eq __FILE__;
205 next if $pack =~ /^DBIx::Class|^Try::Tiny/;
206 $clan_connect_caller = "$file line $line";
213 return if $failed_once;
216 if ($event eq 'connect') {
217 # this is necessary in case we are disconnected and connected again, all within the same $dbh object
221 elsif ($event eq 'disconnect') {
224 elsif ($event eq 'DESTROY' and ! $connected ) {
230 $fail_reason = 'is missing';
233 my $cur_inode = (stat($db_file))[1];
235 if ($orig_inode != $cur_inode) {
236 # pack/unpack to match the unsigned longs returned by `stat`
237 $fail_reason = sprintf 'was recreated (initially inode %s, now %s)', (
238 map { unpack ('L', pack ('l', $_) ) } ($orig_inode, $cur_inode )
246 require Test::Builder;
247 my $t = Test::Builder->new;
248 local $Test::Builder::Level = $Test::Builder::Level + 3;
250 "$db_file originally created at $clan_connect_caller $fail_reason before $event "
251 . 'of DBI handle - a strong indicator that the database file was tampered with while '
252 . 'still being open. This action would fail massively if running under Win32, hence '
253 . 'we make sure it fails on any OS :)'
257 return; # this empty return is a DBI requirement
261 my $weak_registry = {};
269 if ($args{compose_connection}) {
270 $schema = DBICTest::Schema->compose_connection(
271 'DBICTest', $self->_database(%args)
274 $schema = DBICTest::Schema->compose_namespace('DBICTest');
277 if( $args{storage_type}) {
278 $schema->storage_type($args{storage_type});
281 if ( !$args{no_connect} ) {
282 $schema = $schema->connect($self->_database(%args));
285 if ( !$args{no_deploy} ) {
286 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
287 __PACKAGE__->populate_schema( $schema )
288 if( !$args{no_populate} );
291 populate_weakregistry ( $weak_registry, $schema->storage )
292 if $INC{'Test/Builder.pm'} and $schema->storage;
298 assert_empty_weakregistry($weak_registry, 'quiet');
303 DBICTest->deploy_schema( $schema );
305 This method does one of two things to the schema. It can either call
306 the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
307 variable is set, otherwise the default is to read in the t/lib/sqlite.sql
308 file and execute the SQL within. Either way you end up with a fresh set
309 of tables for testing.
316 my $args = shift || {};
318 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
319 $schema->deploy($args);
321 my $filename = Path::Class::File->new(__FILE__)->dir
322 ->file('sqlite.sql')->stringify;
323 my $sql = do { local (@ARGV, $/) = $filename ; <> };
324 for my $chunk ( split (/;\s*\n+/, $sql) ) {
325 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
326 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
333 =head2 populate_schema
335 DBICTest->populate_schema( $schema );
337 After you deploy your schema you can use this method to populate
338 the tables with test data.
342 sub populate_schema {
346 $schema->populate('Genre', [
351 $schema->populate('Artist', [
352 [ qw/artistid name/ ],
353 [ 1, 'Caterwauler McCrae' ],
354 [ 2, 'Random Boy Band' ],
355 [ 3, 'We Are Goth' ],
358 $schema->populate('CD', [
359 [ qw/cdid artist title year genreid/ ],
360 [ 1, 1, "Spoonful of bees", 1999, 1 ],
361 [ 2, 1, "Forkful of bees", 2001 ],
362 [ 3, 1, "Caterwaulin' Blues", 1997 ],
363 [ 4, 2, "Generic Manufactured Singles", 2001 ],
364 [ 5, 3, "Come Be Depressed With Us", 1998 ],
367 $schema->populate('LinerNotes', [
368 [ qw/liner_id notes/ ],
369 [ 2, "Buy Whiskey!" ],
371 [ 5, "Kill Yourself!" ],
374 $schema->populate('Tag', [
375 [ qw/tagid cd tag/ ],
387 $schema->populate('TwoKeys', [
394 $schema->populate('FourKeys', [
395 [ qw/foo bar hello goodbye sensors/ ],
396 [ 1, 2, 3, 4, 'online' ],
397 [ 5, 4, 3, 6, 'offline' ],
400 $schema->populate('OneKey', [
401 [ qw/id artist cd/ ],
407 $schema->populate('SelfRef', [
413 $schema->populate('SelfRefAlias', [
414 [ qw/self_ref alias/ ],
418 $schema->populate('ArtistUndirectedMap', [
423 $schema->populate('Producer', [
424 [ qw/producerid name/ ],
425 [ 1, 'Matt S Trout' ],
426 [ 2, 'Bob The Builder' ],
427 [ 3, 'Fred The Phenotype' ],
430 $schema->populate('CD_to_Producer', [
437 $schema->populate('TreeLike', [
438 [ qw/id parent name/ ],
439 [ 1, undef, 'root' ],
448 $schema->populate('Track', [
449 [ qw/trackid cd position title/ ],
450 [ 4, 2, 1, "Stung with Success"],
451 [ 5, 2, 2, "Stripy"],
452 [ 6, 2, 3, "Sticky Honey"],
453 [ 7, 3, 1, "Yowlin"],
454 [ 8, 3, 2, "Howlin"],
455 [ 9, 3, 3, "Fowlin"],
456 [ 10, 4, 1, "Boring Name"],
457 [ 11, 4, 2, "Boring Song"],
458 [ 12, 4, 3, "No More Ideas"],
460 [ 14, 5, 2, "Under The Weather"],
461 [ 15, 5, 3, "Suicidal"],
462 [ 16, 1, 1, "The Bees Knees"],
463 [ 17, 1, 2, "Apiary"],
464 [ 18, 1, 3, "Beehind You"],
467 $schema->populate('Event', [
468 [ qw/id starts_at created_on varchar_date varchar_datetime skip_inflation/ ],
469 [ 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'],
472 $schema->populate('Link', [
473 [ qw/id url title/ ],
477 $schema->populate('Bookmark', [
482 $schema->populate('Collection', [
483 [ qw/collectionid name/ ],
488 $schema->populate('TypedObject', [
489 [ qw/objectid type value/ ],
490 [ 1, "pointy", "Awl" ],
491 [ 2, "round", "Bearing" ],
492 [ 3, "pointy", "Knife" ],
493 [ 4, "pointy", "Tooth" ],
494 [ 5, "round", "Head" ],
496 $schema->populate('CollectionObject', [
497 [ qw/collection object/ ],
505 $schema->populate('Owners', [
511 $schema->populate('BooksInLibrary', [
512 [ qw/id owner title source price/ ],
513 [ 1, 1, "Programming Perl", "Library", 23 ],
514 [ 2, 1, "Dynamical Systems", "Library", 37 ],
515 [ 3, 2, "Best Recipe Cookbook", "Library", 65 ],