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