Port taint-related fixes from b5ce6748, 4fb8d74c and 652d9b76
[dbsrgits/DBIx-Class.git] / t / storage / debug.t
1 use strict;
2 use warnings;
3 no warnings 'once';
4
5 use Test::More;
6 use Test::Exception;
7 use lib qw(t/lib);
8 use DBICTest;
9 use DBIC::DebugObj;
10 use DBIC::SqlMakerTest;
11 use Path::Class qw/file/;
12
13 plan skip_all => "Test is finicky under -T before 5.10"
14   if "$]" < 5.010 and ${^TAINT};
15
16 BEGIN { delete @ENV{qw(DBIC_TRACE DBIC_TRACE_PROFILE DBICTEST_SQLITE_USE_FILE)} }
17
18 my $schema = DBICTest->init_schema();
19
20 my $lfn = file("t/var/sql-$$.log");
21 unlink $lfn or die $!
22   if -e $lfn;
23
24 # make sure we are testing the vanilla debugger and not ::PrettyPrint
25 $schema->storage->debugobj(DBIx::Class::Storage::Statistics->new);
26
27 ok ( $schema->storage->debug(1), 'debug' );
28 $schema->storage->debugfh($lfn->openw);
29 $schema->storage->debugfh->autoflush(1);
30 $schema->resultset('CD')->count;
31
32 my @loglines = $lfn->slurp;
33 is (@loglines, 1, 'one line of log');
34 like($loglines[0], qr/^SELECT COUNT/, 'File log via debugfh success');
35
36 $schema->storage->debugfh(undef);
37
38 {
39   local $ENV{DBIC_TRACE} = "=$lfn";
40   unlink $lfn;
41
42   $schema->resultset('CD')->count;
43
44   my $schema2 = DBICTest->init_schema(no_deploy => 1);
45   $schema2->storage->_do_query('SELECT 1'); # _do_query() logs via standard mechanisms
46
47   my @loglines = $lfn->slurp;
48   is(@loglines, 2, '2 lines of log');
49   like($loglines[0], qr/^SELECT COUNT/, 'Env log from schema1 success');
50   like($loglines[1], qr/^SELECT 1:/, 'Env log from schema2 success');
51
52   $schema->storage->debugobj->debugfh(undef)
53 }
54
55 END {
56   unlink $lfn if $lfn;
57 }
58
59 open(STDERRCOPY, '>&STDERR');
60 close(STDERR);
61 dies_ok {
62   $schema->resultset('CD')->search({})->count;
63 } 'Died on closed FH';
64
65 open(STDERR, '>&STDERRCOPY');
66
67 # test trace output correctness for bind params
68 {
69     my ($sql, @bind);
70     $schema->storage->debugobj(DBIC::DebugObj->new(\$sql, \@bind));
71
72     my @cds = $schema->resultset('CD')->search( { artist => 1, cdid => { -between => [ 1, 3 ] }, } );
73     is_same_sql_bind(
74         $sql, \@bind,
75         "SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track FROM cd me WHERE ( artist = ? AND (cdid BETWEEN ? AND ?) )",
76         [qw/'1' '1' '3'/],
77         'got correct SQL with all bind parameters (debugcb)'
78     );
79
80     @cds = $schema->resultset('CD')->search( { artist => 1, cdid => { -between => [ 1, 3 ] }, } );
81     is_same_sql_bind(
82         $sql, \@bind,
83         "SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track FROM cd me WHERE ( artist = ? AND (cdid BETWEEN ? AND ?) )", ["'1'", "'1'", "'3'"],
84         'got correct SQL with all bind parameters (debugobj)'
85     );
86 }
87
88 done_testing;