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