1 package # hide from PAUSE
11 use DBICTest::Util::LeakTracer qw/populate_weakregistry assert_empty_weakregistry/;
12 use DBICTest::Util 'local_umask';
14 use Path::Class::File ();
16 use Fcntl qw/:DEFAULT :flock/;
20 DBICTest - Library to be used by DBIx::Class test scripts.
28 my $schema = DBICTest->init_schema();
32 This module provides the basic utilities to write tests against
39 my $schema = DBICTest->init_schema(
42 storage_type=>'::DBI::Replicated',
44 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
48 This method removes the test SQLite database in t/var/DBIxClass.db
49 and then creates a new, empty database.
51 This method will call deploy_schema() by default, unless the
52 no_deploy flag is set.
54 Also, by default, this method will call populate_schema() by
55 default, unless the no_deploy or no_populate flags are set.
59 # some tests are very time sensitive and need to run on their own, without
60 # being disturbed by anything else grabbing CPU or disk IO. Hence why everything
61 # using DBICTest grabs a shared lock, and the few tests that request a :GlobalLock
62 # will ask for an exclusive one and block until they can get it
63 our ($global_lock_fh, $global_exclusive_lock);
67 my $tmpdir = DBICTest::RunMode->tmpdir;
68 my $lockpath = $tmpdir->file('.dbictest_global.lock');
71 my $u = local_umask(0); # so that the file opens as 666, and any user can lock
72 sysopen ($global_lock_fh, $lockpath, O_RDWR|O_CREAT) or do {
75 my @x_tests = map { (defined $_) ? ( $_ ? 1 : 0 ) : 'U' } map {(-e, -d, -f, -r, -w, -x, -o)} ($tmpdir, $lockpath);
77 die sprintf <<"EOE", $lockpath, $err, scalar $>, scalar $), (stat($tmpdir))[4,5,2], @x_tests;
79 Process EUID/EGID: %s / %s
80 TmpDir UID/GID: %s / %s
82 TmpDir X-tests: -e:%s -d:%s -f:%s -r:%s -w:%s -x:%s -o:%s
83 TmpFile X-tests: -e:%s -d:%s -f:%s -r:%s -w:%s -x:%s -o:%s
89 if ($_ eq ':GlobalLock') {
90 flock ($global_lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
91 $global_exclusive_lock = 1;
94 croak "Unknown export $_ requested from $self";
98 unless ($global_exclusive_lock) {
99 flock ($global_lock_fh, LOCK_SH) or die "Unable to lock $lockpath: $!";
104 if ($global_lock_fh) {
105 # delay destruction even more
110 my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
111 $dir->mkpath unless -d "$dir";
114 sub _sqlite_dbfilename {
115 my $holder = $ENV{DBICTEST_LOCK_HOLDER} || $$;
116 $holder = $$ if $holder == -1;
118 # useful for missing cleanup debugging
119 #if ( $holder == $$) {
125 return "$dir/DBIxClass-$holder.db";
133 $SIG{INT} = sub { _cleanup_dbfile(); exit 1 };
135 sub _cleanup_dbfile {
136 # cleanup if this is us
138 ! $ENV{DBICTEST_LOCK_HOLDER}
140 $ENV{DBICTEST_LOCK_HOLDER} == -1
142 $ENV{DBICTEST_LOCK_HOLDER} == $$
144 my $db_file = _sqlite_dbfilename();
145 unlink $_ for ($db_file, "${db_file}-journal");
150 return $ENV{"DBICTEST_DSN"} ? 1:0;
156 return $self->_sqlite_dbfilename if (
157 defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
166 if ($ENV{DBICTEST_DSN}) {
168 (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
169 { AutoCommit => 1, %args },
172 my $db_file = $self->_sqlite_dbname(%args);
174 for ($db_file, "${db_file}-journal") {
176 unlink ($_) or carp (
177 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
181 return ("dbi:SQLite:${db_file}", '', '', {
184 # this is executed on every connect, and thus installs a disconnect/DESTROY
185 # guard for every new $dbh
186 on_connect_do => sub {
188 my $dbh = $storage->_get_dbh;
191 $dbh->do ('PRAGMA synchronous = OFF');
193 if ($ENV{DBICTEST_SQLITE_REVERSE_DEFAULT_ORDER}) {
195 $storage->throw_exception(
196 'PRAGMA reverse_unordered_selects does not work correctly before libsqlite 3.7.9'
197 ) if $storage->_server_info->{normalized_dbms_version} < 3.007009;
199 $dbh->do ('PRAGMA reverse_unordered_selects = ON');
202 # set a *DBI* disconnect callback, to make sure the physical SQLite
203 # file is still there (i.e. the test does not attempt to delete
204 # an open database, which fails on Win32)
205 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
206 $dbh->{Callbacks} = {
207 connect => sub { $guard_cb->('connect') },
208 disconnect => sub { $guard_cb->('disconnect') },
209 DESTROY => sub { $guard_cb->('DESTROY') },
217 sub __mk_disconnect_guard {
218 return if DBIx::Class::_ENV_::PEEPEENESS; # leaks handles, delaying DESTROY, can't work right
221 return unless -f $db_file;
223 my $orig_inode = (stat($db_file))[1]
226 my $clan_connect_caller = '*UNKNOWN*';
228 while ( my ($pack, $file, $line) = caller(++$i) ) {
229 next if $file eq __FILE__;
230 next if $pack =~ /^DBIx::Class|^Try::Tiny/;
231 $clan_connect_caller = "$file line $line";
238 return if $failed_once;
241 if ($event eq 'connect') {
242 # this is necessary in case we are disconnected and connected again, all within the same $dbh object
246 elsif ($event eq 'disconnect') {
249 elsif ($event eq 'DESTROY' and ! $connected ) {
255 $fail_reason = 'is missing';
258 my $cur_inode = (stat($db_file))[1];
260 if ($orig_inode != $cur_inode) {
261 # pack/unpack to match the unsigned longs returned by `stat`
262 $fail_reason = sprintf 'was recreated (initially inode %s, now %s)', (
263 map { unpack ('L', pack ('l', $_) ) } ($orig_inode, $cur_inode )
271 require Test::Builder;
272 my $t = Test::Builder->new;
273 local $Test::Builder::Level = $Test::Builder::Level + 3;
275 "$db_file originally created at $clan_connect_caller $fail_reason before $event "
276 . 'of DBI handle - a strong indicator that the database file was tampered with while '
277 . 'still being open. This action would fail massively if running under Win32, hence '
278 . 'we make sure it fails on any OS :)'
282 return; # this empty return is a DBI requirement
286 my $weak_registry = {};
294 if ($args{compose_connection}) {
295 $schema = DBICTest::Schema->compose_connection(
296 'DBICTest', $self->_database(%args)
299 $schema = DBICTest::Schema->compose_namespace('DBICTest');
302 if( $args{storage_type}) {
303 $schema->storage_type($args{storage_type});
306 if ( !$args{no_connect} ) {
307 $schema = $schema->connect($self->_database(%args));
310 if ( !$args{no_deploy} ) {
311 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
312 __PACKAGE__->populate_schema( $schema )
313 if( !$args{no_populate} );
316 populate_weakregistry ( $weak_registry, $schema->storage )
317 if $INC{'Test/Builder.pm'} and $schema->storage;
323 assert_empty_weakregistry($weak_registry, 'quiet');
328 DBICTest->deploy_schema( $schema );
330 This method does one of two things to the schema. It can either call
331 the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
332 variable is set, otherwise the default is to read in the t/lib/sqlite.sql
333 file and execute the SQL within. Either way you end up with a fresh set
334 of tables for testing.
341 my $args = shift || {};
343 local $schema->storage->{debug}
344 if ($ENV{TRAVIS}||'') eq 'true';
346 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
347 $schema->deploy($args);
349 my $filename = Path::Class::File->new(__FILE__)->dir
350 ->file('sqlite.sql')->stringify;
351 my $sql = do { local (@ARGV, $/) = $filename ; <> };
352 for my $chunk ( split (/;\s*\n+/, $sql) ) {
353 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
354 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
361 =head2 populate_schema
363 DBICTest->populate_schema( $schema );
365 After you deploy your schema you can use this method to populate
366 the tables with test data.
370 sub populate_schema {
374 local $schema->storage->{debug}
375 if ($ENV{TRAVIS}||'') eq 'true';
377 $schema->populate('Genre', [
382 $schema->populate('Artist', [
383 [ qw/artistid name/ ],
384 [ 1, 'Caterwauler McCrae' ],
385 [ 2, 'Random Boy Band' ],
386 [ 3, 'We Are Goth' ],
389 $schema->populate('CD', [
390 [ qw/cdid artist title year genreid/ ],
391 [ 1, 1, "Spoonful of bees", 1999, 1 ],
392 [ 2, 1, "Forkful of bees", 2001 ],
393 [ 3, 1, "Caterwaulin' Blues", 1997 ],
394 [ 4, 2, "Generic Manufactured Singles", 2001 ],
395 [ 5, 3, "Come Be Depressed With Us", 1998 ],
398 $schema->populate('LinerNotes', [
399 [ qw/liner_id notes/ ],
400 [ 2, "Buy Whiskey!" ],
402 [ 5, "Kill Yourself!" ],
405 $schema->populate('Tag', [
406 [ qw/tagid cd tag/ ],
418 $schema->populate('TwoKeys', [
425 $schema->populate('FourKeys', [
426 [ qw/foo bar hello goodbye sensors/ ],
427 [ 1, 2, 3, 4, 'online' ],
428 [ 5, 4, 3, 6, 'offline' ],
431 $schema->populate('OneKey', [
432 [ qw/id artist cd/ ],
438 $schema->populate('SelfRef', [
444 $schema->populate('SelfRefAlias', [
445 [ qw/self_ref alias/ ],
449 $schema->populate('ArtistUndirectedMap', [
454 $schema->populate('Producer', [
455 [ qw/producerid name/ ],
456 [ 1, 'Matt S Trout' ],
457 [ 2, 'Bob The Builder' ],
458 [ 3, 'Fred The Phenotype' ],
461 $schema->populate('CD_to_Producer', [
468 $schema->populate('TreeLike', [
469 [ qw/id parent name/ ],
470 [ 1, undef, 'root' ],
479 $schema->populate('Track', [
480 [ qw/trackid cd position title/ ],
481 [ 4, 2, 1, "Stung with Success"],
482 [ 5, 2, 2, "Stripy"],
483 [ 6, 2, 3, "Sticky Honey"],
484 [ 7, 3, 1, "Yowlin"],
485 [ 8, 3, 2, "Howlin"],
486 [ 9, 3, 3, "Fowlin"],
487 [ 10, 4, 1, "Boring Name"],
488 [ 11, 4, 2, "Boring Song"],
489 [ 12, 4, 3, "No More Ideas"],
491 [ 14, 5, 2, "Under The Weather"],
492 [ 15, 5, 3, "Suicidal"],
493 [ 16, 1, 1, "The Bees Knees"],
494 [ 17, 1, 2, "Apiary"],
495 [ 18, 1, 3, "Beehind You"],
498 $schema->populate('Event', [
499 [ qw/id starts_at created_on varchar_date varchar_datetime skip_inflation/ ],
500 [ 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'],
503 $schema->populate('Link', [
504 [ qw/id url title/ ],
508 $schema->populate('Bookmark', [
513 $schema->populate('Collection', [
514 [ qw/collectionid name/ ],
519 $schema->populate('TypedObject', [
520 [ qw/objectid type value/ ],
521 [ 1, "pointy", "Awl" ],
522 [ 2, "round", "Bearing" ],
523 [ 3, "pointy", "Knife" ],
524 [ 4, "pointy", "Tooth" ],
525 [ 5, "round", "Head" ],
527 $schema->populate('CollectionObject', [
528 [ qw/collection object/ ],
536 $schema->populate('Owners', [
542 $schema->populate('BooksInLibrary', [
543 [ qw/id owner title source price/ ],
544 [ 1, 1, "Programming Perl", "Library", 23 ],
545 [ 2, 1, "Dynamical Systems", "Library", 37 ],
546 [ 3, 2, "Best Recipe Cookbook", "Library", 65 ],