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