DBICTest result class now loading ExprDeclare
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest.pm
CommitLineData
8273e845 1package # hide from PAUSE
c6d74d3e 2 DBICTest;
1c339d71 3
4use strict;
5use warnings;
c5ffac15 6
7use lib 't/dqlib';
b3577eae 8
39568b8a 9# this noop trick initializes the STDOUT, so that the TAP::Harness
10# issued IO::Select->can_read calls (which are blocking wtf wtf wtf)
11# keep spinning and scheduling jobs
12# This results in an overall much smoother job-queue drainage, since
13# the Harness blocks less
14# (ideally this needs to be addressed in T::H, but a quick patchjob
15# broke everything so tabling it for now)
16BEGIN {
17 if ($INC{'Test/Builder.pm'}) {
18 local $| = 1;
19 print "#\n";
20 }
21}
5e724964 22
23use Module::Runtime 'module_notional_filename';
24BEGIN {
25 for my $mod (qw( DBIC::SqlMakerTest SQL::Abstract )) {
26 if ( $INC{ module_notional_filename($mod) } ) {
27 # FIXME this does not seem to work in BEGIN - why?!
28 #require Carp;
29 #$Carp::Internal{ (__PACKAGE__) }++;
30 #Carp::croak( __PACKAGE__ . " must be loaded before $mod" );
31
32 my ($fr, @frame) = 1;
33 while (@frame = caller($fr++)) {
34 last if $frame[1] !~ m|^t/lib/DBICTest|;
35 }
36
37 die __PACKAGE__ . " must be loaded before $mod (or modules using $mod) at $frame[1] line $frame[2]\n";
38 }
39 }
40}
c5ffac15 41
39c9c72d 42use DBICTest::RunMode;
1c339d71 43use DBICTest::Schema;
218b7c12 44use DBICTest::Util::LeakTracer qw/populate_weakregistry assert_empty_weakregistry/;
45use DBICTest::Util 'local_umask';
a258bfc7 46use Carp;
de306d4b 47use Path::Class::File ();
8d6b1478 48use File::Spec;
027e3cc6 49use Fcntl qw/:DEFAULT :flock/;
17e7d7f0 50
51=head1 NAME
52
53DBICTest - Library to be used by DBIx::Class test scripts.
54
55=head1 SYNOPSIS
56
57 use lib qw(t/lib);
58 use DBICTest;
59 use Test::More;
8273e845 60
17e7d7f0 61 my $schema = DBICTest->init_schema();
62
63=head1 DESCRIPTION
64
8273e845 65This module provides the basic utilities to write tests against
17e7d7f0 66DBIx::Class.
67
68=head1 METHODS
69
70=head2 init_schema
71
72 my $schema = DBICTest->init_schema(
73 no_deploy=>1,
74 no_populate=>1,
2bf79155 75 storage_type=>'::DBI::Replicated',
cb6ec758 76 storage_type_args=>{
d7a58a29 77 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
cb6ec758 78 },
17e7d7f0 79 );
80
8273e845 81This method removes the test SQLite database in t/var/DBIxClass.db
17e7d7f0 82and then creates a new, empty database.
83
8273e845 84This method will call deploy_schema() by default, unless the
17e7d7f0 85no_deploy flag is set.
86
8273e845 87Also, by default, this method will call populate_schema() by
17e7d7f0 88default, unless the no_deploy or no_populate flags are set.
89
90=cut
1c339d71 91
8d6b1478 92# some tests are very time sensitive and need to run on their own, without
93# being disturbed by anything else grabbing CPU or disk IO. Hence why everything
94# using DBICTest grabs a shared lock, and the few tests that request a :GlobalLock
95# will ask for an exclusive one and block until they can get it
96our ($global_lock_fh, $global_exclusive_lock);
97sub import {
98 my $self = shift;
99
7bdb56be 100 my $tmpdir = DBICTest::RunMode->tmpdir;
101 my $lockpath = $tmpdir->file('.dbictest_global.lock');
8d6b1478 102
103 {
104 my $u = local_umask(0); # so that the file opens as 666, and any user can lock
7bdb56be 105 sysopen ($global_lock_fh, $lockpath, O_RDWR|O_CREAT) or do {
106 my $err = $!;
107
108 my @x_tests = map { (defined $_) ? ( $_ ? 1 : 0 ) : 'U' } map {(-e, -d, -f, -r, -w, -x, -o)} ($tmpdir, $lockpath);
109
110 die sprintf <<"EOE", $lockpath, $err, scalar $>, scalar $), (stat($tmpdir))[4,5,2], @x_tests;
111Unable to open %s: %s
112Process EUID/EGID: %s / %s
113TmpDir UID/GID: %s / %s
114TmpDir StatMode: %o
115TmpDir X-tests: -e:%s -d:%s -f:%s -r:%s -w:%s -x:%s -o:%s
116TmpFile X-tests: -e:%s -d:%s -f:%s -r:%s -w:%s -x:%s -o:%s
117EOE
118 };
8d6b1478 119 }
120
121 for (@_) {
122 if ($_ eq ':GlobalLock') {
123 flock ($global_lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
124 $global_exclusive_lock = 1;
125 }
126 else {
127 croak "Unknown export $_ requested from $self";
128 }
129 }
130
131 unless ($global_exclusive_lock) {
132 flock ($global_lock_fh, LOCK_SH) or die "Unable to lock $lockpath: $!";
133 }
134}
135
136END {
137 if ($global_lock_fh) {
138 # delay destruction even more
139 }
857d66ca 140}
141
8d6b1478 142{
de306d4b 143 my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
144 $dir->mkpath unless -d "$dir";
8d6b1478 145 $dir = "$dir";
146
147 sub _sqlite_dbfilename {
148 my $holder = $ENV{DBICTEST_LOCK_HOLDER} || $$;
149 $holder = $$ if $holder == -1;
150
151 # useful for missing cleanup debugging
152 #if ( $holder == $$) {
153 # my $x = $0;
154 # $x =~ s/\//#/g;
155 # $holder .= "-$x";
156 #}
157
158 return "$dir/DBIxClass-$holder.db";
159 }
160
161 END {
162 _cleanup_dbfile();
163 }
164}
165
166$SIG{INT} = sub { _cleanup_dbfile(); exit 1 };
167
168sub _cleanup_dbfile {
169 # cleanup if this is us
170 if (
171 ! $ENV{DBICTEST_LOCK_HOLDER}
172 or
173 $ENV{DBICTEST_LOCK_HOLDER} == -1
174 or
175 $ENV{DBICTEST_LOCK_HOLDER} == $$
176 ) {
177 my $db_file = _sqlite_dbfilename();
178 unlink $_ for ($db_file, "${db_file}-journal");
179 }
180}
181
182sub has_custom_dsn {
183 return $ENV{"DBICTEST_DSN"} ? 1:0;
bcb3e850 184}
185
186sub _sqlite_dbname {
481df957 187 my $self = shift;
188 my %args = @_;
39b80a73 189 return $self->_sqlite_dbfilename if (
190 defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
191 );
d7a58a29 192 return ":memory:";
857d66ca 193}
194
579ca3f7 195sub _database {
17e7d7f0 196 my $self = shift;
481df957 197 my %args = @_;
17e7d7f0 198
a258bfc7 199 if ($ENV{DBICTEST_DSN}) {
200 return (
201 (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
202 { AutoCommit => 1, %args },
203 );
204 }
205 my $db_file = $self->_sqlite_dbname(%args);
17e7d7f0 206
a258bfc7 207 for ($db_file, "${db_file}-journal") {
208 next unless -e $_;
209 unlink ($_) or carp (
70c28808 210 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
a258bfc7 211 );
212 }
17e7d7f0 213
a258bfc7 214 return ("dbi:SQLite:${db_file}", '', '', {
215 AutoCommit => 1,
216
217 # this is executed on every connect, and thus installs a disconnect/DESTROY
218 # guard for every new $dbh
219 on_connect_do => sub {
220 my $storage = shift;
221 my $dbh = $storage->_get_dbh;
222
223 # no fsync on commit
224 $dbh->do ('PRAGMA synchronous = OFF');
225
4a24dba9 226 if ($ENV{DBICTEST_SQLITE_REVERSE_DEFAULT_ORDER}) {
227
228 $storage->throw_exception(
229 'PRAGMA reverse_unordered_selects does not work correctly before libsqlite 3.7.9'
230 ) if $storage->_server_info->{normalized_dbms_version} < 3.007009;
231
232 $dbh->do ('PRAGMA reverse_unordered_selects = ON');
233 }
fb88ca2c 234
a258bfc7 235 # set a *DBI* disconnect callback, to make sure the physical SQLite
236 # file is still there (i.e. the test does not attempt to delete
237 # an open database, which fails on Win32)
d9c17594 238 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
a258bfc7 239 $dbh->{Callbacks} = {
d9c17594 240 connect => sub { $guard_cb->('connect') },
241 disconnect => sub { $guard_cb->('disconnect') },
242 DESTROY => sub { $guard_cb->('DESTROY') },
a258bfc7 243 };
244 }
245 },
246 %args,
247 });
579ca3f7 248}
249
d9c17594 250sub __mk_disconnect_guard {
0d8817bc 251 return if DBIx::Class::_ENV_::PEEPEENESS; # leaks handles, delaying DESTROY, can't work right
d12d8272 252
d9c17594 253 my $db_file = shift;
254 return unless -f $db_file;
255
256 my $orig_inode = (stat($db_file))[1]
257 or return;
258
259 my $clan_connect_caller = '*UNKNOWN*';
260 my $i;
261 while ( my ($pack, $file, $line) = caller(++$i) ) {
262 next if $file eq __FILE__;
263 next if $pack =~ /^DBIx::Class|^Try::Tiny/;
264 $clan_connect_caller = "$file line $line";
265 }
266
267 my $failed_once = 0;
268 my $connected = 1;
269
270 return sub {
271 return if $failed_once;
272
273 my $event = shift;
274 if ($event eq 'connect') {
275 # this is necessary in case we are disconnected and connected again, all within the same $dbh object
276 $connected = 1;
277 return;
278 }
279 elsif ($event eq 'disconnect') {
280 $connected = 0;
281 }
282 elsif ($event eq 'DESTROY' and ! $connected ) {
283 return;
284 }
285
286 my $fail_reason;
287 if (! -e $db_file) {
288 $fail_reason = 'is missing';
289 }
290 else {
291 my $cur_inode = (stat($db_file))[1];
292
293 if ($orig_inode != $cur_inode) {
294 # pack/unpack to match the unsigned longs returned by `stat`
295 $fail_reason = sprintf 'was recreated (initially inode %s, now %s)', (
296 map { unpack ('L', pack ('l', $_) ) } ($orig_inode, $cur_inode )
297 );
298 }
299 }
300
301 if ($fail_reason) {
302 $failed_once++;
303
304 require Test::Builder;
305 my $t = Test::Builder->new;
306 local $Test::Builder::Level = $Test::Builder::Level + 3;
307 $t->ok (0,
308 "$db_file originally created at $clan_connect_caller $fail_reason before $event "
309 . 'of DBI handle - a strong indicator that the database file was tampered with while '
310 . 'still being open. This action would fail massively if running under Win32, hence '
311 . 'we make sure it fails on any OS :)'
312 );
313 }
314
315 return; # this empty return is a DBI requirement
316 };
317}
318
65d35121 319my $weak_registry = {};
320
579ca3f7 321sub init_schema {
322 my $self = shift;
323 my %args = @_;
324
325 my $schema;
d7a58a29 326
640ac94c 327 if ($args{compose_connection}) {
328 $schema = DBICTest::Schema->compose_connection(
481df957 329 'DBICTest', $self->_database(%args)
640ac94c 330 );
331 } else {
332 $schema = DBICTest::Schema->compose_namespace('DBICTest');
333 }
a258bfc7 334
2bf79155 335 if( $args{storage_type}) {
d7a58a29 336 $schema->storage_type($args{storage_type});
337 }
a258bfc7 338
579ca3f7 339 if ( !$args{no_connect} ) {
481df957 340 $schema = $schema->connect($self->_database(%args));
3943fd63 341 }
a258bfc7 342
17e7d7f0 343 if ( !$args{no_deploy} ) {
89cf6a70 344 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
345 __PACKAGE__->populate_schema( $schema )
346 if( !$args{no_populate} );
17e7d7f0 347 }
65d35121 348
349 populate_weakregistry ( $weak_registry, $schema->storage )
350 if $INC{'Test/Builder.pm'} and $schema->storage;
351
17e7d7f0 352 return $schema;
353}
354
65d35121 355END {
356 assert_empty_weakregistry($weak_registry, 'quiet');
357}
358
17e7d7f0 359=head2 deploy_schema
360
361 DBICTest->deploy_schema( $schema );
362
8273e845 363This method does one of two things to the schema. It can either call
364the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
365variable is set, otherwise the default is to read in the t/lib/sqlite.sql
366file and execute the SQL within. Either way you end up with a fresh set
17e7d7f0 367of tables for testing.
368
369=cut
370
371sub deploy_schema {
372 my $self = shift;
89cf6a70 373 my $schema = shift;
374 my $args = shift || {};
17e7d7f0 375
f8200928 376 local $schema->storage->{debug}
377 if ($ENV{TRAVIS}||'') eq 'true';
378
8273e845 379 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
06e15b8e 380 $schema->deploy($args);
17e7d7f0 381 } else {
de306d4b 382 my $filename = Path::Class::File->new(__FILE__)->dir
383 ->file('sqlite.sql')->stringify;
384 my $sql = do { local (@ARGV, $/) = $filename ; <> };
ebf846e8 385 for my $chunk ( split (/;\s*\n+/, $sql) ) {
386 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 387 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
ebf846e8 388 }
389 }
17e7d7f0 390 }
89cf6a70 391 return;
17e7d7f0 392}
393
394=head2 populate_schema
395
396 DBICTest->populate_schema( $schema );
397
8273e845 398After you deploy your schema you can use this method to populate
17e7d7f0 399the tables with test data.
400
401=cut
402
403sub populate_schema {
404 my $self = shift;
405 my $schema = shift;
406
f8200928 407 local $schema->storage->{debug}
408 if ($ENV{TRAVIS}||'') eq 'true';
409
972015a7 410 $schema->populate('Genre', [
411 [qw/genreid name/],
412 [qw/1 emo /],
413 ]);
414
17e7d7f0 415 $schema->populate('Artist', [
77211009 416 [ qw/artistid name/ ],
417 [ 1, 'Caterwauler McCrae' ],
418 [ 2, 'Random Boy Band' ],
419 [ 3, 'We Are Goth' ],
17e7d7f0 420 ]);
421
422 $schema->populate('CD', [
972015a7 423 [ qw/cdid artist title year genreid/ ],
424 [ 1, 1, "Spoonful of bees", 1999, 1 ],
17e7d7f0 425 [ 2, 1, "Forkful of bees", 2001 ],
426 [ 3, 1, "Caterwaulin' Blues", 1997 ],
427 [ 4, 2, "Generic Manufactured Singles", 2001 ],
428 [ 5, 3, "Come Be Depressed With Us", 1998 ],
429 ]);
430
431 $schema->populate('LinerNotes', [
432 [ qw/liner_id notes/ ],
433 [ 2, "Buy Whiskey!" ],
434 [ 4, "Buy Merch!" ],
435 [ 5, "Kill Yourself!" ],
436 ]);
437
438 $schema->populate('Tag', [
439 [ qw/tagid cd tag/ ],
440 [ 1, 1, "Blue" ],
441 [ 2, 2, "Blue" ],
442 [ 3, 3, "Blue" ],
443 [ 4, 5, "Blue" ],
444 [ 5, 2, "Cheesy" ],
445 [ 6, 4, "Cheesy" ],
446 [ 7, 5, "Cheesy" ],
447 [ 8, 2, "Shiny" ],
448 [ 9, 4, "Shiny" ],
449 ]);
450
451 $schema->populate('TwoKeys', [
452 [ qw/artist cd/ ],
453 [ 1, 1 ],
454 [ 1, 2 ],
455 [ 2, 2 ],
456 ]);
457
458 $schema->populate('FourKeys', [
3bd6e3e0 459 [ qw/foo bar hello goodbye sensors/ ],
460 [ 1, 2, 3, 4, 'online' ],
461 [ 5, 4, 3, 6, 'offline' ],
17e7d7f0 462 ]);
463
464 $schema->populate('OneKey', [
465 [ qw/id artist cd/ ],
466 [ 1, 1, 1 ],
467 [ 2, 1, 2 ],
468 [ 3, 2, 2 ],
469 ]);
470
471 $schema->populate('SelfRef', [
472 [ qw/id name/ ],
473 [ 1, 'First' ],
474 [ 2, 'Second' ],
475 ]);
476
477 $schema->populate('SelfRefAlias', [
478 [ qw/self_ref alias/ ],
479 [ 1, 2 ]
480 ]);
481
482 $schema->populate('ArtistUndirectedMap', [
483 [ qw/id1 id2/ ],
484 [ 1, 2 ]
485 ]);
486
487 $schema->populate('Producer', [
488 [ qw/producerid name/ ],
489 [ 1, 'Matt S Trout' ],
490 [ 2, 'Bob The Builder' ],
491 [ 3, 'Fred The Phenotype' ],
492 ]);
493
494 $schema->populate('CD_to_Producer', [
495 [ qw/cd producer/ ],
496 [ 1, 1 ],
497 [ 1, 2 ],
498 [ 1, 3 ],
499 ]);
8273e845 500
8871d4ad 501 $schema->populate('TreeLike', [
61177e44 502 [ qw/id parent name/ ],
972015a7 503 [ 1, undef, 'root' ],
8871d4ad 504 [ 2, 1, 'foo' ],
505 [ 3, 2, 'bar' ],
506 [ 6, 2, 'blop' ],
507 [ 4, 3, 'baz' ],
508 [ 5, 4, 'quux' ],
509 [ 7, 3, 'fong' ],
510 ]);
4b8dcc58 511
17e7d7f0 512 $schema->populate('Track', [
513 [ qw/trackid cd position title/ ],
514 [ 4, 2, 1, "Stung with Success"],
515 [ 5, 2, 2, "Stripy"],
516 [ 6, 2, 3, "Sticky Honey"],
517 [ 7, 3, 1, "Yowlin"],
518 [ 8, 3, 2, "Howlin"],
519 [ 9, 3, 3, "Fowlin"],
520 [ 10, 4, 1, "Boring Name"],
521 [ 11, 4, 2, "Boring Song"],
522 [ 12, 4, 3, "No More Ideas"],
523 [ 13, 5, 1, "Sad"],
524 [ 14, 5, 2, "Under The Weather"],
525 [ 15, 5, 3, "Suicidal"],
526 [ 16, 1, 1, "The Bees Knees"],
527 [ 17, 1, 2, "Apiary"],
528 [ 18, 1, 3, "Beehind You"],
529 ]);
4b8dcc58 530
ae515736 531 $schema->populate('Event', [
ff8a6e3b 532 [ qw/id starts_at created_on varchar_date varchar_datetime skip_inflation/ ],
533 [ 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 534 ]);
535
17e7d7f0 536 $schema->populate('Link', [
54e0bd06 537 [ qw/id url title/ ],
538 [ 1, '', 'aaa' ]
17e7d7f0 539 ]);
e673f011 540
17e7d7f0 541 $schema->populate('Bookmark', [
542 [ qw/id link/ ],
543 [ 1, 1 ]
544 ]);
78060df8 545
546 $schema->populate('Collection', [
547 [ qw/collectionid name/ ],
548 [ 1, "Tools" ],
549 [ 2, "Body Parts" ],
550 ]);
8273e845 551
78060df8 552 $schema->populate('TypedObject', [
553 [ qw/objectid type value/ ],
554 [ 1, "pointy", "Awl" ],
555 [ 2, "round", "Bearing" ],
556 [ 3, "pointy", "Knife" ],
557 [ 4, "pointy", "Tooth" ],
558 [ 5, "round", "Head" ],
559 ]);
89cf6a70 560 $schema->populate('CollectionObject', [
561 [ qw/collection object/ ],
562 [ 1, 1 ],
563 [ 1, 2 ],
564 [ 1, 3 ],
565 [ 2, 4 ],
566 [ 2, 5 ],
567 ]);
78060df8 568
569 $schema->populate('Owners', [
bed3a173 570 [ qw/id name/ ],
78060df8 571 [ 1, "Newton" ],
572 [ 2, "Waltham" ],
573 ]);
574
575 $schema->populate('BooksInLibrary', [
cda5e082 576 [ qw/id owner title source price/ ],
577 [ 1, 1, "Programming Perl", "Library", 23 ],
578 [ 2, 1, "Dynamical Systems", "Library", 37 ],
579 [ 3, 2, "Best Recipe Cookbook", "Library", 65 ],
78060df8 580 ]);
1c339d71 581}
4b8dcc58 582
510ca912 5831;