Attempt to build a dist on travis if all tests pass
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest.pm
CommitLineData
8273e845 1package # hide from PAUSE
c6d74d3e 2 DBICTest;
1c339d71 3
4use strict;
5use warnings;
39c9c72d 6use DBICTest::RunMode;
1c339d71 7use DBICTest::Schema;
218b7c12 8use DBICTest::Util::LeakTracer qw/populate_weakregistry assert_empty_weakregistry/;
9use DBICTest::Util 'local_umask';
a258bfc7 10use Carp;
de306d4b 11use Path::Class::File ();
8d6b1478 12use File::Spec;
027e3cc6 13use Fcntl qw/:DEFAULT :flock/;
17e7d7f0 14
15=head1 NAME
16
17DBICTest - Library to be used by DBIx::Class test scripts.
18
19=head1 SYNOPSIS
20
21 use lib qw(t/lib);
22 use DBICTest;
23 use Test::More;
8273e845 24
17e7d7f0 25 my $schema = DBICTest->init_schema();
26
27=head1 DESCRIPTION
28
8273e845 29This module provides the basic utilities to write tests against
17e7d7f0 30DBIx::Class.
31
32=head1 METHODS
33
34=head2 init_schema
35
36 my $schema = DBICTest->init_schema(
37 no_deploy=>1,
38 no_populate=>1,
2bf79155 39 storage_type=>'::DBI::Replicated',
cb6ec758 40 storage_type_args=>{
d7a58a29 41 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
cb6ec758 42 },
17e7d7f0 43 );
44
8273e845 45This method removes the test SQLite database in t/var/DBIxClass.db
17e7d7f0 46and then creates a new, empty database.
47
8273e845 48This method will call deploy_schema() by default, unless the
17e7d7f0 49no_deploy flag is set.
50
8273e845 51Also, by default, this method will call populate_schema() by
17e7d7f0 52default, unless the no_deploy or no_populate flags are set.
53
54=cut
1c339d71 55
8d6b1478 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
60our ($global_lock_fh, $global_exclusive_lock);
61sub import {
62 my $self = shift;
63
9b871b00 64 my $lockpath = DBICTest::RunMode->tmpdir->file('.dbictest_global.lock');
8d6b1478 65
66 {
67 my $u = local_umask(0); # so that the file opens as 666, and any user can lock
027e3cc6 68 sysopen ($global_lock_fh, $lockpath, O_RDWR|O_CREAT)
8d6b1478 69 or die "Unable to open $lockpath: $!";
70 }
71
72 for (@_) {
73 if ($_ eq ':GlobalLock') {
74 flock ($global_lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
75 $global_exclusive_lock = 1;
76 }
77 else {
78 croak "Unknown export $_ requested from $self";
79 }
80 }
81
82 unless ($global_exclusive_lock) {
83 flock ($global_lock_fh, LOCK_SH) or die "Unable to lock $lockpath: $!";
84 }
85}
86
87END {
88 if ($global_lock_fh) {
89 # delay destruction even more
90 }
857d66ca 91}
92
8d6b1478 93{
de306d4b 94 my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
95 $dir->mkpath unless -d "$dir";
8d6b1478 96 $dir = "$dir";
97
98 sub _sqlite_dbfilename {
99 my $holder = $ENV{DBICTEST_LOCK_HOLDER} || $$;
100 $holder = $$ if $holder == -1;
101
102 # useful for missing cleanup debugging
103 #if ( $holder == $$) {
104 # my $x = $0;
105 # $x =~ s/\//#/g;
106 # $holder .= "-$x";
107 #}
108
109 return "$dir/DBIxClass-$holder.db";
110 }
111
112 END {
113 _cleanup_dbfile();
114 }
115}
116
117$SIG{INT} = sub { _cleanup_dbfile(); exit 1 };
118
119sub _cleanup_dbfile {
120 # cleanup if this is us
121 if (
122 ! $ENV{DBICTEST_LOCK_HOLDER}
123 or
124 $ENV{DBICTEST_LOCK_HOLDER} == -1
125 or
126 $ENV{DBICTEST_LOCK_HOLDER} == $$
127 ) {
128 my $db_file = _sqlite_dbfilename();
129 unlink $_ for ($db_file, "${db_file}-journal");
130 }
131}
132
133sub has_custom_dsn {
134 return $ENV{"DBICTEST_DSN"} ? 1:0;
bcb3e850 135}
136
137sub _sqlite_dbname {
481df957 138 my $self = shift;
139 my %args = @_;
39b80a73 140 return $self->_sqlite_dbfilename if (
141 defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
142 );
d7a58a29 143 return ":memory:";
857d66ca 144}
145
579ca3f7 146sub _database {
17e7d7f0 147 my $self = shift;
481df957 148 my %args = @_;
17e7d7f0 149
a258bfc7 150 if ($ENV{DBICTEST_DSN}) {
151 return (
152 (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
153 { AutoCommit => 1, %args },
154 );
155 }
156 my $db_file = $self->_sqlite_dbname(%args);
17e7d7f0 157
a258bfc7 158 for ($db_file, "${db_file}-journal") {
159 next unless -e $_;
160 unlink ($_) or carp (
70c28808 161 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
a258bfc7 162 );
163 }
17e7d7f0 164
a258bfc7 165 return ("dbi:SQLite:${db_file}", '', '', {
166 AutoCommit => 1,
167
168 # this is executed on every connect, and thus installs a disconnect/DESTROY
169 # guard for every new $dbh
170 on_connect_do => sub {
171 my $storage = shift;
172 my $dbh = $storage->_get_dbh;
173
174 # no fsync on commit
175 $dbh->do ('PRAGMA synchronous = OFF');
176
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)
d9c17594 180 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
a258bfc7 181 $dbh->{Callbacks} = {
d9c17594 182 connect => sub { $guard_cb->('connect') },
183 disconnect => sub { $guard_cb->('disconnect') },
184 DESTROY => sub { $guard_cb->('DESTROY') },
a258bfc7 185 };
186 }
187 },
188 %args,
189 });
579ca3f7 190}
191
d9c17594 192sub __mk_disconnect_guard {
0d8817bc 193 return if DBIx::Class::_ENV_::PEEPEENESS; # leaks handles, delaying DESTROY, can't work right
d12d8272 194
d9c17594 195 my $db_file = shift;
196 return unless -f $db_file;
197
198 my $orig_inode = (stat($db_file))[1]
199 or return;
200
201 my $clan_connect_caller = '*UNKNOWN*';
202 my $i;
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";
207 }
208
209 my $failed_once = 0;
210 my $connected = 1;
211
212 return sub {
213 return if $failed_once;
214
215 my $event = shift;
216 if ($event eq 'connect') {
217 # this is necessary in case we are disconnected and connected again, all within the same $dbh object
218 $connected = 1;
219 return;
220 }
221 elsif ($event eq 'disconnect') {
222 $connected = 0;
223 }
224 elsif ($event eq 'DESTROY' and ! $connected ) {
225 return;
226 }
227
228 my $fail_reason;
229 if (! -e $db_file) {
230 $fail_reason = 'is missing';
231 }
232 else {
233 my $cur_inode = (stat($db_file))[1];
234
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 )
239 );
240 }
241 }
242
243 if ($fail_reason) {
244 $failed_once++;
245
246 require Test::Builder;
247 my $t = Test::Builder->new;
248 local $Test::Builder::Level = $Test::Builder::Level + 3;
249 $t->ok (0,
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 :)'
254 );
255 }
256
257 return; # this empty return is a DBI requirement
258 };
259}
260
65d35121 261my $weak_registry = {};
262
579ca3f7 263sub init_schema {
264 my $self = shift;
265 my %args = @_;
266
267 my $schema;
d7a58a29 268
640ac94c 269 if ($args{compose_connection}) {
270 $schema = DBICTest::Schema->compose_connection(
481df957 271 'DBICTest', $self->_database(%args)
640ac94c 272 );
273 } else {
274 $schema = DBICTest::Schema->compose_namespace('DBICTest');
275 }
a258bfc7 276
2bf79155 277 if( $args{storage_type}) {
d7a58a29 278 $schema->storage_type($args{storage_type});
279 }
a258bfc7 280
579ca3f7 281 if ( !$args{no_connect} ) {
481df957 282 $schema = $schema->connect($self->_database(%args));
3943fd63 283 }
a258bfc7 284
17e7d7f0 285 if ( !$args{no_deploy} ) {
89cf6a70 286 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
287 __PACKAGE__->populate_schema( $schema )
288 if( !$args{no_populate} );
17e7d7f0 289 }
65d35121 290
291 populate_weakregistry ( $weak_registry, $schema->storage )
292 if $INC{'Test/Builder.pm'} and $schema->storage;
293
17e7d7f0 294 return $schema;
295}
296
65d35121 297END {
298 assert_empty_weakregistry($weak_registry, 'quiet');
299}
300
17e7d7f0 301=head2 deploy_schema
302
303 DBICTest->deploy_schema( $schema );
304
8273e845 305This method does one of two things to the schema. It can either call
306the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
307variable is set, otherwise the default is to read in the t/lib/sqlite.sql
308file and execute the SQL within. Either way you end up with a fresh set
17e7d7f0 309of tables for testing.
310
311=cut
312
313sub deploy_schema {
314 my $self = shift;
89cf6a70 315 my $schema = shift;
316 my $args = shift || {};
17e7d7f0 317
8273e845 318 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
06e15b8e 319 $schema->deploy($args);
17e7d7f0 320 } else {
de306d4b 321 my $filename = Path::Class::File->new(__FILE__)->dir
322 ->file('sqlite.sql')->stringify;
323 my $sql = do { local (@ARGV, $/) = $filename ; <> };
ebf846e8 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
856e2d17 326 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
ebf846e8 327 }
328 }
17e7d7f0 329 }
89cf6a70 330 return;
17e7d7f0 331}
332
333=head2 populate_schema
334
335 DBICTest->populate_schema( $schema );
336
8273e845 337After you deploy your schema you can use this method to populate
17e7d7f0 338the tables with test data.
339
340=cut
341
342sub populate_schema {
343 my $self = shift;
344 my $schema = shift;
345
972015a7 346 $schema->populate('Genre', [
347 [qw/genreid name/],
348 [qw/1 emo /],
349 ]);
350
17e7d7f0 351 $schema->populate('Artist', [
77211009 352 [ qw/artistid name/ ],
353 [ 1, 'Caterwauler McCrae' ],
354 [ 2, 'Random Boy Band' ],
355 [ 3, 'We Are Goth' ],
17e7d7f0 356 ]);
357
358 $schema->populate('CD', [
972015a7 359 [ qw/cdid artist title year genreid/ ],
360 [ 1, 1, "Spoonful of bees", 1999, 1 ],
17e7d7f0 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 ],
365 ]);
366
367 $schema->populate('LinerNotes', [
368 [ qw/liner_id notes/ ],
369 [ 2, "Buy Whiskey!" ],
370 [ 4, "Buy Merch!" ],
371 [ 5, "Kill Yourself!" ],
372 ]);
373
374 $schema->populate('Tag', [
375 [ qw/tagid cd tag/ ],
376 [ 1, 1, "Blue" ],
377 [ 2, 2, "Blue" ],
378 [ 3, 3, "Blue" ],
379 [ 4, 5, "Blue" ],
380 [ 5, 2, "Cheesy" ],
381 [ 6, 4, "Cheesy" ],
382 [ 7, 5, "Cheesy" ],
383 [ 8, 2, "Shiny" ],
384 [ 9, 4, "Shiny" ],
385 ]);
386
387 $schema->populate('TwoKeys', [
388 [ qw/artist cd/ ],
389 [ 1, 1 ],
390 [ 1, 2 ],
391 [ 2, 2 ],
392 ]);
393
394 $schema->populate('FourKeys', [
3bd6e3e0 395 [ qw/foo bar hello goodbye sensors/ ],
396 [ 1, 2, 3, 4, 'online' ],
397 [ 5, 4, 3, 6, 'offline' ],
17e7d7f0 398 ]);
399
400 $schema->populate('OneKey', [
401 [ qw/id artist cd/ ],
402 [ 1, 1, 1 ],
403 [ 2, 1, 2 ],
404 [ 3, 2, 2 ],
405 ]);
406
407 $schema->populate('SelfRef', [
408 [ qw/id name/ ],
409 [ 1, 'First' ],
410 [ 2, 'Second' ],
411 ]);
412
413 $schema->populate('SelfRefAlias', [
414 [ qw/self_ref alias/ ],
415 [ 1, 2 ]
416 ]);
417
418 $schema->populate('ArtistUndirectedMap', [
419 [ qw/id1 id2/ ],
420 [ 1, 2 ]
421 ]);
422
423 $schema->populate('Producer', [
424 [ qw/producerid name/ ],
425 [ 1, 'Matt S Trout' ],
426 [ 2, 'Bob The Builder' ],
427 [ 3, 'Fred The Phenotype' ],
428 ]);
429
430 $schema->populate('CD_to_Producer', [
431 [ qw/cd producer/ ],
432 [ 1, 1 ],
433 [ 1, 2 ],
434 [ 1, 3 ],
435 ]);
8273e845 436
8871d4ad 437 $schema->populate('TreeLike', [
61177e44 438 [ qw/id parent name/ ],
972015a7 439 [ 1, undef, 'root' ],
8871d4ad 440 [ 2, 1, 'foo' ],
441 [ 3, 2, 'bar' ],
442 [ 6, 2, 'blop' ],
443 [ 4, 3, 'baz' ],
444 [ 5, 4, 'quux' ],
445 [ 7, 3, 'fong' ],
446 ]);
4b8dcc58 447
17e7d7f0 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"],
459 [ 13, 5, 1, "Sad"],
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"],
465 ]);
4b8dcc58 466
ae515736 467 $schema->populate('Event', [
ff8a6e3b 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'],
ae515736 470 ]);
471
17e7d7f0 472 $schema->populate('Link', [
54e0bd06 473 [ qw/id url title/ ],
474 [ 1, '', 'aaa' ]
17e7d7f0 475 ]);
e673f011 476
17e7d7f0 477 $schema->populate('Bookmark', [
478 [ qw/id link/ ],
479 [ 1, 1 ]
480 ]);
78060df8 481
482 $schema->populate('Collection', [
483 [ qw/collectionid name/ ],
484 [ 1, "Tools" ],
485 [ 2, "Body Parts" ],
486 ]);
8273e845 487
78060df8 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" ],
495 ]);
89cf6a70 496 $schema->populate('CollectionObject', [
497 [ qw/collection object/ ],
498 [ 1, 1 ],
499 [ 1, 2 ],
500 [ 1, 3 ],
501 [ 2, 4 ],
502 [ 2, 5 ],
503 ]);
78060df8 504
505 $schema->populate('Owners', [
bed3a173 506 [ qw/id name/ ],
78060df8 507 [ 1, "Newton" ],
508 [ 2, "Waltham" ],
509 ]);
510
511 $schema->populate('BooksInLibrary', [
cda5e082 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 ],
78060df8 516 ]);
1c339d71 517}
4b8dcc58 518
510ca912 5191;