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