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