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