Merge branch 'master' into dq2eb
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest.pm
1 package # hide from PAUSE
2     DBICTest;
3
4 use strict;
5 use warnings;
6
7 use lib 't/dqlib';
8
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)
16 BEGIN {
17   if ($INC{'Test/Builder.pm'}) {
18     local $| = 1;
19     print "#\n";
20   }
21 }
22
23 use Module::Runtime 'module_notional_filename';
24 BEGIN {
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 }
41
42 use DBICTest::RunMode;
43 use DBICTest::Schema;
44 use DBICTest::Util::LeakTracer qw/populate_weakregistry assert_empty_weakregistry/;
45 use DBICTest::Util 'local_umask';
46 use Carp;
47 use Path::Class::File ();
48 use File::Spec;
49 use Fcntl qw/:DEFAULT :flock/;
50
51 =head1 NAME
52
53 DBICTest - 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;
60
61   my $schema = DBICTest->init_schema();
62
63 =head1 DESCRIPTION
64
65 This module provides the basic utilities to write tests against
66 DBIx::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,
75     storage_type=>'::DBI::Replicated',
76     storage_type_args=>{
77       balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
78     },
79   );
80
81 This method removes the test SQLite database in t/var/DBIxClass.db
82 and then creates a new, empty database.
83
84 This method will call deploy_schema() by default, unless the
85 no_deploy flag is set.
86
87 Also, by default, this method will call populate_schema() by
88 default, unless the no_deploy or no_populate flags are set.
89
90 =cut
91
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
96 our ($global_lock_fh, $global_exclusive_lock);
97 sub import {
98     my $self = shift;
99
100     my $tmpdir = DBICTest::RunMode->tmpdir;
101     my $lockpath = $tmpdir->file('.dbictest_global.lock');
102
103     {
104       my $u = local_umask(0); # so that the file opens as 666, and any user can lock
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;
111 Unable to open %s: %s
112 Process EUID/EGID: %s / %s
113 TmpDir UID/GID:    %s / %s
114 TmpDir StatMode:   %o
115 TmpDir X-tests:    -e:%s -d:%s -f:%s -r:%s -w:%s -x:%s -o:%s
116 TmpFile X-tests:   -e:%s -d:%s -f:%s -r:%s -w:%s -x:%s -o:%s
117 EOE
118       };
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
136 END {
137     if ($global_lock_fh) {
138         # delay destruction even more
139     }
140 }
141
142 {
143     my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
144     $dir->mkpath unless -d "$dir";
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
168 sub _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
182 sub has_custom_dsn {
183     return $ENV{"DBICTEST_DSN"} ? 1:0;
184 }
185
186 sub _sqlite_dbname {
187     my $self = shift;
188     my %args = @_;
189     return $self->_sqlite_dbfilename if (
190       defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
191     );
192     return ":memory:";
193 }
194
195 sub _database {
196     my $self = shift;
197     my %args = @_;
198
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);
206
207     for ($db_file, "${db_file}-journal") {
208       next unless -e $_;
209       unlink ($_) or carp (
210         "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
211       );
212     }
213
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
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         }
234
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)
238         if (my $guard_cb = __mk_disconnect_guard($db_file)) {
239           $dbh->{Callbacks} = {
240             connect => sub { $guard_cb->('connect') },
241             disconnect => sub { $guard_cb->('disconnect') },
242             DESTROY => sub { $guard_cb->('DESTROY') },
243           };
244         }
245       },
246       %args,
247     });
248 }
249
250 sub __mk_disconnect_guard {
251   return if DBIx::Class::_ENV_::PEEPEENESS; # leaks handles, delaying DESTROY, can't work right
252
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
319 my $weak_registry = {};
320
321 sub init_schema {
322     my $self = shift;
323     my %args = @_;
324
325     my $schema;
326
327     if ($args{compose_connection}) {
328       $schema = DBICTest::Schema->compose_connection(
329                   'DBICTest', $self->_database(%args)
330                 );
331     } else {
332       $schema = DBICTest::Schema->compose_namespace('DBICTest');
333     }
334
335     if( $args{storage_type}) {
336       $schema->storage_type($args{storage_type});
337     }
338
339     if ( !$args{no_connect} ) {
340       $schema = $schema->connect($self->_database(%args));
341     }
342
343     if ( !$args{no_deploy} ) {
344         __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
345         __PACKAGE__->populate_schema( $schema )
346          if( !$args{no_populate} );
347     }
348
349     populate_weakregistry ( $weak_registry, $schema->storage )
350       if $INC{'Test/Builder.pm'} and $schema->storage;
351
352     return $schema;
353 }
354
355 END {
356     assert_empty_weakregistry($weak_registry, 'quiet');
357 }
358
359 =head2 deploy_schema
360
361   DBICTest->deploy_schema( $schema );
362
363 This method does one of two things to the schema.  It can either call
364 the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
365 variable is set, otherwise the default is to read in the t/lib/sqlite.sql
366 file and execute the SQL within. Either way you end up with a fresh set
367 of tables for testing.
368
369 =cut
370
371 sub deploy_schema {
372     my $self = shift;
373     my $schema = shift;
374     my $args = shift || {};
375
376     local $schema->storage->{debug}
377       if ($ENV{TRAVIS}||'') eq 'true';
378
379     if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
380         $schema->deploy($args);
381     } else {
382         my $filename = Path::Class::File->new(__FILE__)->dir
383           ->file('sqlite.sql')->stringify;
384         my $sql = do { local (@ARGV, $/) = $filename ; <> };
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
387             $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
388           }
389         }
390     }
391     return;
392 }
393
394 =head2 populate_schema
395
396   DBICTest->populate_schema( $schema );
397
398 After you deploy your schema you can use this method to populate
399 the tables with test data.
400
401 =cut
402
403 sub populate_schema {
404     my $self = shift;
405     my $schema = shift;
406
407     local $schema->storage->{debug}
408       if ($ENV{TRAVIS}||'') eq 'true';
409
410     $schema->populate('Genre', [
411       [qw/genreid name/],
412       [qw/1       emo  /],
413     ]);
414
415     $schema->populate('Artist', [
416         [ qw/artistid name/ ],
417         [ 1, 'Caterwauler McCrae' ],
418         [ 2, 'Random Boy Band' ],
419         [ 3, 'We Are Goth' ],
420     ]);
421
422     $schema->populate('CD', [
423         [ qw/cdid artist title year genreid/ ],
424         [ 1, 1, "Spoonful of bees", 1999, 1 ],
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', [
459         [ qw/foo bar hello goodbye sensors/ ],
460         [ 1, 2, 3, 4, 'online' ],
461         [ 5, 4, 3, 6, 'offline' ],
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     ]);
500
501     $schema->populate('TreeLike', [
502         [ qw/id parent name/ ],
503         [ 1, undef, 'root' ],
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     ]);
511
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     ]);
530
531     $schema->populate('Event', [
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'],
534     ]);
535
536     $schema->populate('Link', [
537         [ qw/id url title/ ],
538         [ 1, '', 'aaa' ]
539     ]);
540
541     $schema->populate('Bookmark', [
542         [ qw/id link/ ],
543         [ 1, 1 ]
544     ]);
545
546     $schema->populate('Collection', [
547         [ qw/collectionid name/ ],
548         [ 1, "Tools" ],
549         [ 2, "Body Parts" ],
550     ]);
551
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     ]);
560     $schema->populate('CollectionObject', [
561         [ qw/collection object/ ],
562         [ 1, 1 ],
563         [ 1, 2 ],
564         [ 1, 3 ],
565         [ 2, 4 ],
566         [ 2, 5 ],
567     ]);
568
569     $schema->populate('Owners', [
570         [ qw/id name/ ],
571         [ 1, "Newton" ],
572         [ 2, "Waltham" ],
573     ]);
574
575     $schema->populate('BooksInLibrary', [
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 ],
580     ]);
581 }
582
583 1;