1 package # hide from PAUSE
8 use DBICTest::Util qw/populate_weakregistry assert_empty_weakregistry/;
10 use Path::Class::File ();
14 DBICTest - Library to be used by DBIx::Class test scripts.
22 my $schema = DBICTest->init_schema();
26 This module provides the basic utilities to write tests against
33 my $schema = DBICTest->init_schema(
36 storage_type=>'::DBI::Replicated',
38 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
42 This method removes the test SQLite database in t/var/DBIxClass.db
43 and then creates a new, empty database.
45 This method will call deploy_schema() by default, unless the
46 no_deploy flag is set.
48 Also, by default, this method will call populate_schema() by
49 default, unless the no_deploy or no_populate flags are set.
54 return $ENV{"DBICTEST_DSN"} ? 1:0;
57 sub _sqlite_dbfilename {
58 my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
59 $dir->mkpath unless -d "$dir";
60 return $dir->file('DBIxClass.db')->stringify;
66 return $self->_sqlite_dbfilename if (
67 defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
76 if ($ENV{DBICTEST_DSN}) {
78 (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
79 { AutoCommit => 1, %args },
82 my $db_file = $self->_sqlite_dbname(%args);
84 for ($db_file, "${db_file}-journal") {
87 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
91 return ("dbi:SQLite:${db_file}", '', '', {
94 # this is executed on every connect, and thus installs a disconnect/DESTROY
95 # guard for every new $dbh
96 on_connect_do => sub {
98 my $dbh = $storage->_get_dbh;
101 $dbh->do ('PRAGMA synchronous = OFF');
103 # set a *DBI* disconnect callback, to make sure the physical SQLite
104 # file is still there (i.e. the test does not attempt to delete
105 # an open database, which fails on Win32)
106 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
107 $dbh->{Callbacks} = {
108 connect => sub { $guard_cb->('connect') },
109 disconnect => sub { $guard_cb->('disconnect') },
110 DESTROY => sub { $guard_cb->('DESTROY') },
118 sub __mk_disconnect_guard {
119 return if DBIx::Class::_ENV_::PEEPEENESS(); # leaks handles, delaying DESTROY, can't work right
122 return unless -f $db_file;
124 my $orig_inode = (stat($db_file))[1]
127 my $clan_connect_caller = '*UNKNOWN*';
129 while ( my ($pack, $file, $line) = caller(++$i) ) {
130 next if $file eq __FILE__;
131 next if $pack =~ /^DBIx::Class|^Try::Tiny/;
132 $clan_connect_caller = "$file line $line";
139 return if $failed_once;
142 if ($event eq 'connect') {
143 # this is necessary in case we are disconnected and connected again, all within the same $dbh object
147 elsif ($event eq 'disconnect') {
150 elsif ($event eq 'DESTROY' and ! $connected ) {
156 $fail_reason = 'is missing';
159 my $cur_inode = (stat($db_file))[1];
161 if ($orig_inode != $cur_inode) {
162 # pack/unpack to match the unsigned longs returned by `stat`
163 $fail_reason = sprintf 'was recreated (initially inode %s, now %s)', (
164 map { unpack ('L', pack ('l', $_) ) } ($orig_inode, $cur_inode )
172 require Test::Builder;
173 my $t = Test::Builder->new;
174 local $Test::Builder::Level = $Test::Builder::Level + 3;
176 "$db_file originally created at $clan_connect_caller $fail_reason before $event "
177 . 'of DBI handle - a strong indicator that the database file was tampered with while '
178 . 'still being open. This action would fail massively if running under Win32, hence '
179 . 'we make sure it fails on any OS :)'
183 return; # this empty return is a DBI requirement
187 my $weak_registry = {};
195 if ($args{compose_connection}) {
196 $schema = DBICTest::Schema->compose_connection(
197 'DBICTest', $self->_database(%args)
200 $schema = DBICTest::Schema->compose_namespace('DBICTest');
203 if( $args{storage_type}) {
204 $schema->storage_type($args{storage_type});
207 if ( !$args{no_connect} ) {
208 $schema = $schema->connect($self->_database(%args));
211 if ( !$args{no_deploy} ) {
212 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
213 __PACKAGE__->populate_schema( $schema )
214 if( !$args{no_populate} );
217 populate_weakregistry ( $weak_registry, $schema->storage )
218 if $INC{'Test/Builder.pm'} and $schema->storage;
224 assert_empty_weakregistry($weak_registry, 'quiet');
229 DBICTest->deploy_schema( $schema );
231 This method does one of two things to the schema. It can either call
232 the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
233 variable is set, otherwise the default is to read in the t/lib/sqlite.sql
234 file and execute the SQL within. Either way you end up with a fresh set
235 of tables for testing.
242 my $args = shift || {};
244 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
245 $schema->deploy($args);
247 my $filename = Path::Class::File->new(__FILE__)->dir
248 ->file('sqlite.sql')->stringify;
249 my $sql = do { local (@ARGV, $/) = $filename ; <> };
250 for my $chunk ( split (/;\s*\n+/, $sql) ) {
251 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
252 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
259 =head2 populate_schema
261 DBICTest->populate_schema( $schema );
263 After you deploy your schema you can use this method to populate
264 the tables with test data.
268 sub populate_schema {
272 $schema->populate('Genre', [
277 $schema->populate('Artist', [
278 [ qw/artistid name/ ],
279 [ 1, 'Caterwauler McCrae' ],
280 [ 2, 'Random Boy Band' ],
281 [ 3, 'We Are Goth' ],
284 $schema->populate('CD', [
285 [ qw/cdid artist title year genreid/ ],
286 [ 1, 1, "Spoonful of bees", 1999, 1 ],
287 [ 2, 1, "Forkful of bees", 2001 ],
288 [ 3, 1, "Caterwaulin' Blues", 1997 ],
289 [ 4, 2, "Generic Manufactured Singles", 2001 ],
290 [ 5, 3, "Come Be Depressed With Us", 1998 ],
293 $schema->populate('LinerNotes', [
294 [ qw/liner_id notes/ ],
295 [ 2, "Buy Whiskey!" ],
297 [ 5, "Kill Yourself!" ],
300 $schema->populate('Tag', [
301 [ qw/tagid cd tag/ ],
313 $schema->populate('TwoKeys', [
320 $schema->populate('FourKeys', [
321 [ qw/foo bar hello goodbye sensors/ ],
322 [ 1, 2, 3, 4, 'online' ],
323 [ 5, 4, 3, 6, 'offline' ],
326 $schema->populate('OneKey', [
327 [ qw/id artist cd/ ],
333 $schema->populate('SelfRef', [
339 $schema->populate('SelfRefAlias', [
340 [ qw/self_ref alias/ ],
344 $schema->populate('ArtistUndirectedMap', [
349 $schema->populate('Producer', [
350 [ qw/producerid name/ ],
351 [ 1, 'Matt S Trout' ],
352 [ 2, 'Bob The Builder' ],
353 [ 3, 'Fred The Phenotype' ],
356 $schema->populate('CD_to_Producer', [
363 $schema->populate('TreeLike', [
364 [ qw/id parent name/ ],
365 [ 1, undef, 'root' ],
374 $schema->populate('Track', [
375 [ qw/trackid cd position title/ ],
376 [ 4, 2, 1, "Stung with Success"],
377 [ 5, 2, 2, "Stripy"],
378 [ 6, 2, 3, "Sticky Honey"],
379 [ 7, 3, 1, "Yowlin"],
380 [ 8, 3, 2, "Howlin"],
381 [ 9, 3, 3, "Fowlin"],
382 [ 10, 4, 1, "Boring Name"],
383 [ 11, 4, 2, "Boring Song"],
384 [ 12, 4, 3, "No More Ideas"],
386 [ 14, 5, 2, "Under The Weather"],
387 [ 15, 5, 3, "Suicidal"],
388 [ 16, 1, 1, "The Bees Knees"],
389 [ 17, 1, 2, "Apiary"],
390 [ 18, 1, 3, "Beehind You"],
393 $schema->populate('Event', [
394 [ qw/id starts_at created_on varchar_date varchar_datetime skip_inflation/ ],
395 [ 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'],
398 $schema->populate('Link', [
399 [ qw/id url title/ ],
403 $schema->populate('Bookmark', [
408 $schema->populate('Collection', [
409 [ qw/collectionid name/ ],
414 $schema->populate('TypedObject', [
415 [ qw/objectid type value/ ],
416 [ 1, "pointy", "Awl" ],
417 [ 2, "round", "Bearing" ],
418 [ 3, "pointy", "Knife" ],
419 [ 4, "pointy", "Tooth" ],
420 [ 5, "round", "Head" ],
422 $schema->populate('CollectionObject', [
423 [ qw/collection object/ ],
431 $schema->populate('Owners', [
437 $schema->populate('BooksInLibrary', [
438 [ qw/id owner title source price/ ],
439 [ 1, 1, "Programming Perl", "Library", 23 ],
440 [ 2, 1, "Dynamical Systems", "Library", 37 ],
441 [ 3, 2, "Best Recipe Cookbook", "Library", 65 ],