Institute a central "load this first in testing" package
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest / Util.pm
1 package DBICTest::Util;
2
3 use warnings;
4 use strict;
5
6 use ANFANG;
7
8 use constant DEBUG_TEST_CONCURRENCY_LOCKS =>
9   ( ($ENV{DBICTEST_DEBUG_CONCURRENCY_LOCKS}||'') =~ /^(\d+)$/ )[0]
10     ||
11   0
12 ;
13
14 use Config;
15 use Carp qw(cluck confess croak);
16 use Fcntl ':flock';
17 use Scalar::Util qw(blessed refaddr);
18 use DBIx::Class::_Util qw( scope_guard parent_dir );
19
20 use base 'Exporter';
21 our @EXPORT_OK = qw(
22   dbg stacktrace
23   local_umask find_co_root
24   visit_namespaces
25   check_customcond_args
26   await_flock DEBUG_TEST_CONCURRENCY_LOCKS
27 );
28
29 if (DEBUG_TEST_CONCURRENCY_LOCKS) {
30   require DBI;
31   my $oc = DBI->can('connect');
32   no warnings 'redefine';
33   *DBI::connect = sub {
34     DBICTest::Util::dbg("Connecting to $_[1]");
35     goto $oc;
36   }
37 }
38
39 sub dbg ($) {
40   require Time::HiRes;
41   printf STDERR "\n%.06f  %5s %-78s %s\n",
42     scalar Time::HiRes::time(),
43     $$,
44     $_[0],
45     $0,
46   ;
47 }
48
49 # File locking is hard. Really hard. By far the best lock implementation
50 # I've seen is part of the guts of File::Temp. However it is sadly not
51 # reusable. Since I am not aware of folks doing NFS parallel testing,
52 # nor are we known to work on VMS, I am just going to punt this and
53 # use the portable-ish flock() provided by perl itself. If this does
54 # not work for you - patches more than welcome.
55 #
56 # This figure esentially means "how long can a single test hold a
57 # resource before everyone else gives up waiting and aborts" or
58 # in other words "how long does the longest test-group legitimally run?"
59 my $lock_timeout_minutes = 15;  # yes, that's long, I know
60 my $wait_step_seconds = 0.25;
61
62 sub await_flock ($$) {
63   my ($fh, $locktype) = @_;
64
65   my ($res, $tries);
66   while(
67     ! ( $res = flock( $fh, $locktype | LOCK_NB ) )
68       and
69     ++$tries <= $lock_timeout_minutes * 60 / $wait_step_seconds
70   ) {
71     select( undef, undef, undef, $wait_step_seconds );
72
73     # "say something" every 10 cycles to work around RT#108390
74     # jesus christ our tooling is such a crock of shit :(
75     print "#\n" if not $tries % 10;
76   }
77
78   return $res;
79 }
80
81
82 sub local_umask ($) {
83   return unless defined $Config{d_umask};
84
85   croak 'Calling local_umask() in void context makes no sense'
86     if ! defined wantarray;
87
88   my $old_umask = umask($_[0]);
89   die "Setting umask failed: $!" unless defined $old_umask;
90
91   scope_guard(sub {
92     local ($@, $!, $?);
93
94     eval {
95       defined(umask $old_umask) or die "nope";
96       1;
97     } or cluck (
98       "Unable to reset old umask '$old_umask': " . ($! || 'Unknown error')
99     );
100   });
101 }
102
103 # Try to determine the root of a checkout/untar if possible
104 # OR throws an exception
105 my $co_root;
106 sub find_co_root () {
107
108   $co_root ||= do {
109
110     my @mod_parts = split /::/, (__PACKAGE__ . '.pm');
111     my $inc_key = join ('/', @mod_parts);  # %INC stores paths with / regardless of OS
112
113     # a bit convoluted, but what we do here essentially is:
114     #  - get the file name of this particular module
115     #  - do 'cd ..' as many times as necessary to get to t/lib/../..
116
117     my $root = $INC{$inc_key}
118       or croak "\$INC{'$inc_key'} seems to be missing, this can't happen...";
119
120     $root = parent_dir $root
121       for 1 .. @mod_parts + 2;
122
123     # do the check twice so that the exception is more informative in the
124     # very unlikely case of realpath returning garbage
125     # (Paththools are in really bad shape - handholding all the way down)
126     for my $call_realpath (0,1) {
127
128       require Cwd and $root = ( Cwd::realpath($root) . '/' )
129         if $call_realpath;
130
131       croak "Unable to find root of DBIC checkout/untar: '${root}Makefile.PL' does not exist"
132         unless -f "${root}Makefile.PL";
133     }
134
135     $root;
136   }
137 }
138
139
140 sub stacktrace {
141   my $frame = shift;
142   $frame++;
143   my (@stack, @frame);
144
145   while (@frame = CORE::caller($frame++)) {
146     push @stack, [@frame[3,1,2]];
147   }
148
149   return undef unless @stack;
150
151   $stack[0][0] = '';
152   return join "\tinvoked as ", map { sprintf ("%s at %s line %d\n", @$_ ) } @stack;
153 }
154
155 sub check_customcond_args ($) {
156   my $args = shift;
157
158   confess "Expecting a hashref"
159     unless ref $args eq 'HASH';
160
161   for (qw(rel_name foreign_relname self_alias foreign_alias)) {
162     confess "Custom condition argument '$_' must be a plain string"
163       if length ref $args->{$_} or ! length $args->{$_};
164   }
165
166   confess "Current and legacy rel_name arguments do not match"
167     if $args->{rel_name} ne $args->{foreign_relname};
168
169   confess "Custom condition argument 'self_resultsource' must be a rsrc instance"
170     unless defined blessed $args->{self_resultsource} and $args->{self_resultsource}->isa('DBIx::Class::ResultSource');
171
172   confess "Passed resultsource has no record of the supplied rel_name - likely wrong \$rsrc"
173     unless ref $args->{self_resultsource}->relationship_info($args->{rel_name});
174
175   my $struct_cnt = 0;
176
177   if (defined $args->{self_result_object} or defined $args->{self_rowobj} ) {
178     $struct_cnt++;
179     for (qw(self_result_object self_rowobj)) {
180       confess "Custom condition argument '$_' must be a result instance"
181         unless defined blessed $args->{$_} and $args->{$_}->isa('DBIx::Class::Row');
182     }
183
184     confess "Current and legacy self_result_object arguments do not match"
185       if refaddr($args->{self_result_object}) != refaddr($args->{self_rowobj});
186   }
187
188   if (defined $args->{foreign_values}) {
189     $struct_cnt++;
190
191     confess "Custom condition argument 'foreign_values' must be a hash reference"
192       unless ref $args->{foreign_values} eq 'HASH';
193   }
194
195   confess "Data structures supplied on both ends of a relationship"
196     if $struct_cnt == 2;
197
198   $args;
199 }
200
201 sub visit_namespaces {
202   my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
203
204   my $visited_count = 1;
205
206   # A package and a namespace are subtly different things
207   $args->{package} ||= 'main';
208   $args->{package} = 'main' if $args->{package} =~ /^ :: (?: main )? $/x;
209   $args->{package} =~ s/^:://;
210
211   if ( $args->{action}->($args->{package}) ) {
212     my $ns =
213       ( ($args->{package} eq 'main') ? '' :  $args->{package} )
214         .
215       '::'
216     ;
217
218     $visited_count += visit_namespaces( %$args, package => $_ ) for
219       grep
220         # this happens sometimes on %:: traversal
221         { $_ ne '::main' }
222         map
223           { $_ =~ /^(.+?)::$/ ? "$ns$1" : () }
224           do { no strict 'refs'; keys %$ns }
225     ;
226   }
227
228   return $visited_count;
229 }
230
231 1;