Test suite wide leaktesting
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest.pm
CommitLineData
8273e845 1package # hide from PAUSE
c6d74d3e 2 DBICTest;
1c339d71 3
4use strict;
5use warnings;
39c9c72d 6use DBICTest::RunMode;
1c339d71 7use DBICTest::Schema;
65d35121 8use DBICTest::Util qw/populate_weakregistry assert_empty_weakregistry/;
a258bfc7 9use Carp;
de306d4b 10use Path::Class::File ();
17e7d7f0 11
12=head1 NAME
13
14DBICTest - 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;
8273e845 21
17e7d7f0 22 my $schema = DBICTest->init_schema();
23
24=head1 DESCRIPTION
25
8273e845 26This module provides the basic utilities to write tests against
17e7d7f0 27DBIx::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,
2bf79155 36 storage_type=>'::DBI::Replicated',
cb6ec758 37 storage_type_args=>{
d7a58a29 38 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
cb6ec758 39 },
17e7d7f0 40 );
41
8273e845 42This method removes the test SQLite database in t/var/DBIxClass.db
17e7d7f0 43and then creates a new, empty database.
44
8273e845 45This method will call deploy_schema() by default, unless the
17e7d7f0 46no_deploy flag is set.
47
8273e845 48Also, by default, this method will call populate_schema() by
17e7d7f0 49default, unless the no_deploy or no_populate flags are set.
50
51=cut
1c339d71 52
857d66ca 53sub has_custom_dsn {
d7a58a29 54 return $ENV{"DBICTEST_DSN"} ? 1:0;
857d66ca 55}
56
57sub _sqlite_dbfilename {
de306d4b 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;
bcb3e850 61}
62
63sub _sqlite_dbname {
481df957 64 my $self = shift;
65 my %args = @_;
bcb3e850 66 return $self->_sqlite_dbfilename if $args{sqlite_use_file} or $ENV{"DBICTEST_SQLITE_USE_FILE"};
d7a58a29 67 return ":memory:";
857d66ca 68}
69
579ca3f7 70sub _database {
17e7d7f0 71 my $self = shift;
481df957 72 my %args = @_;
17e7d7f0 73
a258bfc7 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);
17e7d7f0 81
a258bfc7 82 for ($db_file, "${db_file}-journal") {
83 next unless -e $_;
84 unlink ($_) or carp (
70c28808 85 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
a258bfc7 86 );
87 }
17e7d7f0 88
a258bfc7 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)
d9c17594 104 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
a258bfc7 105 $dbh->{Callbacks} = {
d9c17594 106 connect => sub { $guard_cb->('connect') },
107 disconnect => sub { $guard_cb->('disconnect') },
108 DESTROY => sub { $guard_cb->('DESTROY') },
a258bfc7 109 };
110 }
111 },
112 %args,
113 });
579ca3f7 114}
115
d9c17594 116sub __mk_disconnect_guard {
e0b2dc74 117 return if DBIx::Class::_ENV_::PEEPEENESS(); # leaks handles, delaying DESTROY, can't work right
d12d8272 118
d9c17594 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
65d35121 185my $weak_registry = {};
186
579ca3f7 187sub init_schema {
188 my $self = shift;
189 my %args = @_;
190
191 my $schema;
d7a58a29 192
640ac94c 193 if ($args{compose_connection}) {
194 $schema = DBICTest::Schema->compose_connection(
481df957 195 'DBICTest', $self->_database(%args)
640ac94c 196 );
197 } else {
198 $schema = DBICTest::Schema->compose_namespace('DBICTest');
199 }
a258bfc7 200
2bf79155 201 if( $args{storage_type}) {
d7a58a29 202 $schema->storage_type($args{storage_type});
203 }
a258bfc7 204
579ca3f7 205 if ( !$args{no_connect} ) {
481df957 206 $schema = $schema->connect($self->_database(%args));
3943fd63 207 }
a258bfc7 208
17e7d7f0 209 if ( !$args{no_deploy} ) {
89cf6a70 210 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
211 __PACKAGE__->populate_schema( $schema )
212 if( !$args{no_populate} );
17e7d7f0 213 }
65d35121 214
215 populate_weakregistry ( $weak_registry, $schema->storage )
216 if $INC{'Test/Builder.pm'} and $schema->storage;
217
17e7d7f0 218 return $schema;
219}
220
65d35121 221END {
222 assert_empty_weakregistry($weak_registry, 'quiet');
223}
224
17e7d7f0 225=head2 deploy_schema
226
227 DBICTest->deploy_schema( $schema );
228
8273e845 229This method does one of two things to the schema. It can either call
230the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
231variable is set, otherwise the default is to read in the t/lib/sqlite.sql
232file and execute the SQL within. Either way you end up with a fresh set
17e7d7f0 233of tables for testing.
234
235=cut
236
237sub deploy_schema {
238 my $self = shift;
89cf6a70 239 my $schema = shift;
240 my $args = shift || {};
17e7d7f0 241
8273e845 242 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
06e15b8e 243 $schema->deploy($args);
17e7d7f0 244 } else {
de306d4b 245 my $filename = Path::Class::File->new(__FILE__)->dir
246 ->file('sqlite.sql')->stringify;
247 my $sql = do { local (@ARGV, $/) = $filename ; <> };
ebf846e8 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
856e2d17 250 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
ebf846e8 251 }
252 }
17e7d7f0 253 }
89cf6a70 254 return;
17e7d7f0 255}
256
257=head2 populate_schema
258
259 DBICTest->populate_schema( $schema );
260
8273e845 261After you deploy your schema you can use this method to populate
17e7d7f0 262the tables with test data.
263
264=cut
265
266sub populate_schema {
267 my $self = shift;
268 my $schema = shift;
269
972015a7 270 $schema->populate('Genre', [
271 [qw/genreid name/],
272 [qw/1 emo /],
273 ]);
274
17e7d7f0 275 $schema->populate('Artist', [
77211009 276 [ qw/artistid name/ ],
277 [ 1, 'Caterwauler McCrae' ],
278 [ 2, 'Random Boy Band' ],
279 [ 3, 'We Are Goth' ],
17e7d7f0 280 ]);
281
282 $schema->populate('CD', [
972015a7 283 [ qw/cdid artist title year genreid/ ],
284 [ 1, 1, "Spoonful of bees", 1999, 1 ],
17e7d7f0 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', [
3bd6e3e0 319 [ qw/foo bar hello goodbye sensors/ ],
320 [ 1, 2, 3, 4, 'online' ],
321 [ 5, 4, 3, 6, 'offline' ],
17e7d7f0 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 ]);
8273e845 360
8871d4ad 361 $schema->populate('TreeLike', [
61177e44 362 [ qw/id parent name/ ],
972015a7 363 [ 1, undef, 'root' ],
8871d4ad 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 ]);
4b8dcc58 371
17e7d7f0 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 ]);
4b8dcc58 390
ae515736 391 $schema->populate('Event', [
ff8a6e3b 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'],
ae515736 394 ]);
395
17e7d7f0 396 $schema->populate('Link', [
54e0bd06 397 [ qw/id url title/ ],
398 [ 1, '', 'aaa' ]
17e7d7f0 399 ]);
e673f011 400
17e7d7f0 401 $schema->populate('Bookmark', [
402 [ qw/id link/ ],
403 [ 1, 1 ]
404 ]);
78060df8 405
406 $schema->populate('Collection', [
407 [ qw/collectionid name/ ],
408 [ 1, "Tools" ],
409 [ 2, "Body Parts" ],
410 ]);
8273e845 411
78060df8 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 ]);
89cf6a70 420 $schema->populate('CollectionObject', [
421 [ qw/collection object/ ],
422 [ 1, 1 ],
423 [ 1, 2 ],
424 [ 1, 3 ],
425 [ 2, 4 ],
426 [ 2, 5 ],
427 ]);
78060df8 428
429 $schema->populate('Owners', [
bed3a173 430 [ qw/id name/ ],
78060df8 431 [ 1, "Newton" ],
432 [ 2, "Waltham" ],
433 ]);
434
435 $schema->populate('BooksInLibrary', [
cda5e082 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 ],
78060df8 440 ]);
1c339d71 441}
4b8dcc58 442
510ca912 4431;