blib/lib/Apache/TestUtil.pm untested

filter: Statementstmt 0.0% 0 / 280 Branchbran 0.0% 0 / 118 Conditioncond 0.0% 0 / 60 MC/DCmcdc 0.0% 0 / 37 Subroutinesub 0.0% 0 / 49 Podpod 0.0% 0 / 33 totaltotal 0.0% 0 / 577 CC 58 SCAR 34.4
CC
58
Cov
0%
t_is_equal
156.0
t_file_watch_for
42.0
struct_as_string
42.0
CRAP 31.2
1 # Licensed to the Apache Software Foundation (ASF) under one or more
2 # contributor license agreements. See the NOTICE file distributed with
3 # this work for additional information regarding copyright ownership.
4 # The ASF licenses this file to You under the Apache License, Version 2.0
5 # (the "License"); you may not use this file except in compliance with
6 # the License. You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16 package Apache::TestUtil;
17  
18 use strict;
19 use warnings FATAL => 'all';
20  
21 use File::Find ();
22 use File::Path ();
23 use Exporter ();
24 use Carp ();
25 use Config;
26 use File::Basename qw(dirname);
27 use File::Spec::Functions qw(catfile catdir file_name_is_absolute tmpdir);
28 use Symbol ();
29 use Fcntl qw(SEEK_END);
30  
31 use Apache::Test ();
32 use Apache::TestConfig ();
33  
34 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %CLEAN);
35  
36 $VERSION = '0.02';
37 @ISA = qw(Exporter);
38  
39 @EXPORT = qw(t_cmp t_debug t_append_file t_write_file t_open_file
40 t_mkdir t_rmtree t_is_equal t_filepath_cmp t_write_test_lib
41 t_server_log_error_is_expected t_server_log_warn_is_expected
42 t_client_log_error_is_expected t_client_log_warn_is_expected
43 );
44  
45 @EXPORT_OK = qw(t_write_perl_script t_write_shell_script t_chown
46 t_catfile_apache t_catfile t_file_watch_for
47 t_start_error_log_watch t_finish_error_log_watch
48 t_start_file_watch t_read_file_watch t_finish_file_watch);
49  
50 %CLEAN = ();
51  
52 $Apache::TestUtil::DEBUG_OUTPUT = \*STDOUT;
53  
54 # 5.005's Data::Dumper has problems to dump certain datastructures
55 use constant HAS_DUMPER => eval { $] >= 5.006 && require Data::Dumper; };
56 use constant INDENT => 4;
57  
58 {
59 my %files;
60 sub t_start_file_watch (;$) {
61 my $name = defined $_[0] ? $_[0] : 'error_log';
62 $name = File::Spec->catfile(Apache::Test::vars->{t_logs}, $name)
63 unless (File::Spec->file_name_is_absolute($name));
64  
65 if (open my $fh, '<', $name) {
66 seek $fh, 0, SEEK_END;
67 $files{$name} = $fh;
68 }
69 else {
70 delete $files{$name};
71 }
72  
73 return;
74 }
75  
76 sub t_finish_file_watch (;$) {
77 my $name = defined $_[0] ? $_[0] : 'error_log';
78 $name = File::Spec->catfile(Apache::Test::vars->{t_logs}, $name)
79 unless (File::Spec->file_name_is_absolute($name));
80  
81 my $fh = delete $files{$name};
82 unless (defined $fh) {
83 open $fh, '<', $name or return;
84 return readline $fh;
85 }
86  
87 return readline $fh;
88 }
89  
90 sub t_read_file_watch (;$) {
91 my $name = defined $_[0] ? $_[0] : 'error_log';
92 $name = File::Spec->catfile(Apache::Test::vars->{t_logs}, $name)
93 unless (File::Spec->file_name_is_absolute($name));
94  
95 my $fh = $files{$name};
96 unless (defined $fh) {
97 open $fh, '<', $name or return;
98 $files{$name} = $fh;
99 }
100  
101 return readline $fh;
102 }
103  
104 sub t_file_watch_for ($$$) {
105 my ($name, $re, $timeout) = @_;
106 local $/ = "\n";
107 $re = qr/$re/ unless ref $re;
108 $timeout *= 10;
109 my $buf = '';
110 my @acc;
111 while ($timeout >= 0) {
112 my $line = t_read_file_watch $name;
113 unless (defined $line) { # EOF
114 select undef, undef, undef, 0.1;
115 $timeout--;
116 next;
117 }
118 $buf .= $line;
119 next unless $buf =~ /\n$/; # incomplete line
120  
121 # found a complete line
122 $line = $buf;
123 $buf = '';
124  
125 push @acc, $line;
126 return wantarray ? @acc : $line if $line =~ $re;
127 }
128 return;
129 }
130  
131 sub t_start_error_log_watch {
132 t_start_file_watch;
133 }
134  
135 sub t_finish_error_log_watch {
136 local $/ = "\n";
137 return my @lines = t_finish_file_watch;
138 }
139 }
140  
141 # because of the prototype and recursive call to itself a forward
142 # declaration is needed
143 sub t_is_equal ($$);
144  
145 # compare any two datastructures (must pass references for non-scalars)
146 # undef()'s are valid args
147 sub t_is_equal ($$) {
148 my ($a, $b) = @_;
149 return 0 unless @_ == 2;
150  
151 # this was added in Apache::Test::VERSION 1.12 - remove deprecated
152 # logic sometime around 1.15 or mid September, 2004.
153 if (UNIVERSAL::isa($a, 'Regexp')) {
154 my @warning = ("WARNING!!! t_is_equal() argument order has changed.",
155 "use of a regular expression as the first argument",
156 "is deprecated. support will be removed soon.");
157 t_debug(@warning);
158 ($a, $b) = ($b, $a);
159 }
160  
161 if (defined $a && defined $b) {
162 my $ref_a = ref $a;
163 my $ref_b = ref $b;
164 if (!$ref_a && !$ref_b) {
165 return $a eq $b;
166 }
167 elsif ($ref_a eq 'ARRAY' && $ref_b eq 'ARRAY') {
168 return 0 unless @$a == @$b;
169 for my $i (0..$#$a) {
170 t_is_equal($a->[$i], $b->[$i]) || return 0;
171 }
172 }
173 elsif ($ref_a eq 'HASH' && $ref_b eq 'HASH') {
174 return 0 unless (keys %$a) == (keys %$b);
175 for my $key (sort keys %$a) {
176 return 0 unless exists $b->{$key};
177 t_is_equal($a->{$key}, $b->{$key}) || return 0;
178 }
179 }
180 elsif ($ref_b eq 'Regexp') {
181 return $a =~ $b;
182 }
183 else {
184 # try to compare the references
185 return $a eq $b;
186 }
187 }
188 else {
189 # undef == undef! a valid test
190 return (defined $a || defined $b) ? 0 : 1;
191 }
192 return 1;
193 }
194  
195  
196  
197 sub t_cmp ($$;$) {
198 Carp::carp(join(":", (caller)[1..2]) .
199 ' usage: $res = t_cmp($received, $expected, [$comment])')
200 if @_ < 2 || @_ > 3;
201  
202 my ($received, $expected) = @_;
203  
204 # this was added in Apache::Test::VERSION 1.12 - remove deprecated
205 # logic sometime around 1.15 or mid September, 2004.
206 if (UNIVERSAL::isa($_[0], 'Regexp')) {
207 my @warning = ("WARNING!!! t_cmp() argument order has changed.",
208 "use of a regular expression as the first argument",
209 "is deprecated. support will be removed soon.");
210 t_debug(@warning);
211 ($received, $expected) = ($expected, $received);
212 }
213  
214 t_debug("testing : " . pop) if @_ == 3;
215 t_debug("expected: " . struct_as_string(0, $expected));
216 t_debug("received: " . struct_as_string(0, $received));
217 return t_is_equal($received, $expected);
218 }
219  
220 # Essentially t_cmp, but on Win32, first converts pathnames
221 # to their DOS long name.
222 sub t_filepath_cmp ($$;$) {
223 my @a = (shift, shift);
224 if (Apache::TestConfig::WIN32) {
225 $a[0] = Win32::GetLongPathName($a[0]) if defined $a[0] && -e $a[0];
226 $a[1] = Win32::GetLongPathName($a[1]) if defined $a[1] && -e $a[1];
227 }
228 return @_ == 1 ? t_cmp($a[0], $a[1], $_[0]) : t_cmp($a[0], $a[1]);
229 }
230  
231  
232 *expand = HAS_DUMPER ?
233 sub { map { ref $_ ? Data::Dumper::Dumper($_) : $_ } @_ } :
234 sub { @_ };
235  
236 sub t_debug {
237 my $out = $Apache::TestUtil::DEBUG_OUTPUT;
238 print $out map {"# $_\n"} map {split /\n/} grep {defined} expand(@_);
239 }
240  
241 sub t_open_file {
242 my $file = shift;
243  
244 die "must pass a filename" unless defined $file;
245  
246 # create the parent dir if it doesn't exist yet
247 makepath(dirname $file);
248  
249 my $fh = Symbol::gensym();
250 open $fh, ">$file" or die "can't open $file: $!";
251 t_debug("writing file: $file");
252 $CLEAN{files}{$file}++;
253  
254 return $fh;
255 }
256  
257 sub _temp_package_dir {
258 return catdir(tmpdir(), 'apache_test');
259 }
260  
261 sub t_write_test_lib {
262 my $file = shift;
263  
264 die "must pass a filename" unless defined $file;
265  
266 t_write_file(catdir(_temp_package_dir(), $file), @_);
267 }
268  
269 sub t_write_file {
270 my $file = shift;
271  
272 die "must pass a filename" unless defined $file;
273  
274 # create the parent dir if it doesn't exist yet
275 makepath(dirname $file);
276  
277 my $fh = Symbol::gensym();
278 open $fh, ">$file" or die "can't open $file: $!";
279 t_debug("writing file: $file");
280 print $fh join '', @_ if @_;
281 close $fh;
282 $CLEAN{files}{$file}++;
283 }
284  
285 sub t_append_file {
286 my $file = shift;
287  
288 die "must pass a filename" unless defined $file;
289  
290 # create the parent dir if it doesn't exist yet
291 makepath(dirname $file);
292  
293 # add to the cleanup list only if we created it now
294 $CLEAN{files}{$file}++ unless -e $file;
295  
296 my $fh = Symbol::gensym();
297 open $fh, ">>$file" or die "can't open $file: $!";
298 print $fh join '', @_ if @_;
299 close $fh;
300 }
301  
302 sub t_write_shell_script {
303 my $file = shift;
304  
305 my $code = join '', @_;
306 my($ext, $shebang);
307  
308 if (Apache::TestConfig::WIN32()) {
309 $code =~ s/echo$/echo./mg; #required to echo newline
310 $ext = 'bat';
311 $shebang = "\@echo off\nREM this is a bat";
312 }
313 else {
314 $ext = 'sh';
315 $shebang = '#!/bin/sh';
316 }
317  
318 $file .= ".$ext";
319 t_write_file($file, "$shebang\n", $code);
320 $ext;
321 }
322  
323 sub t_write_perl_script {
324 my $file = shift;
325  
326 my $shebang = "#!$Config{perlpath}\n";
327 my $warning = Apache::TestConfig->thaw->genwarning($file);
328 t_write_file($file, $shebang, $warning, @_);
329 chmod 0755, $file;
330 }
331  
332  
333 sub t_mkdir {
334 my $dir = shift;
335 makepath($dir);
336 }
337  
338 # returns a list of dirs successfully created
339 sub makepath {
340 my($path) = @_;
341  
342 return if !defined($path) || -e $path;
343 my $full_path = $path;
344  
345 # remember which dirs were created and should be cleaned up
346 while (1) {
347 $CLEAN{dirs}{$path} = 1;
348 $path = dirname $path;
349 last if -e $path;
350 }
351  
352 return File::Path::mkpath($full_path, 0, 0755);
353 }
354  
355 sub t_rmtree {
356 die "must pass a dirname" unless defined $_[0];
357 File::Path::rmtree((@_ > 1 ? \@_ : $_[0]), 0, 1);
358 }
359  
360 #chown a file or directory to the test User/Group
361 #noop if chown is unsupported
362  
363 sub t_chown {
364 my $file = shift;
365 my $config = Apache::Test::config();
366 my($uid, $gid);
367  
368 eval {
369 #XXX cache this lookup
370 ($uid, $gid) = (getpwnam($config->{vars}->{user}))[2,3];
371 };
372  
373 if ($@) {
374 if ($@ =~ /^The getpwnam function is unimplemented/) {
375 #ok if unsupported, e.g. win32
376 return 1;
377 }
378 else {
379 die $@;
380 }
381 }
382  
383 CORE::chown($uid, $gid, $file) || die "chown $file: $!";
384 }
385  
386 # $string = struct_as_string($indent_level, $var);
387 #
388 # return any nested datastructure via Data::Dumper or ala Data::Dumper
389 # as a string. undef() is a valid arg.
390 #
391 # $indent_level should be 0 (used for nice indentation during
392 # recursive datastructure traversal)
393 sub struct_as_string{
394 return "???" unless @_ == 2;
395 my $level = shift;
396  
397 return "undef" unless defined $_[0];
398 my $pad = ' ' x (($level + 1) * INDENT);
399 my $spad = ' ' x ($level * INDENT);
400  
401 if (HAS_DUMPER) {
402 local $Data::Dumper::Terse = 1;
403 $Data::Dumper::Terse = $Data::Dumper::Terse; # warn
404 my $data = Data::Dumper::Dumper(@_);
405 $data =~ s/\n$//; # \n is handled by the caller
406 return $data;
407 }
408 else {
409 if (ref($_[0]) eq 'ARRAY') {
410 my @data = ();
411 for my $i (0..$#{ $_[0] }) {
412 push @data,
413 struct_as_string($level+1, $_[0]->[$i]);
414 }
415 return join "\n", "[", map({"$pad$_,"} @data), "$spad\]";
416 } elsif ( ref($_[0])eq 'HASH') {
417 my @data = ();
418 for my $key (keys %{ $_[0] }) {
419 push @data,
420 "$key => " .
421 struct_as_string($level+1, $_[0]->{$key});
422 }
423 return join "\n", "{", map({"$pad$_,"} @data), "$spad\}";
424 } else {
425 return $_[0];
426 }
427 }
428 }
429  
430 my $banner_format =
431 "\n*** The following %s expected and harmless ***\n";
432  
433 sub is_expected_banner {
434 my $type = shift;
435 my $count = @_ ? shift : 1;
436 sprintf $banner_format, $count == 1
437 ? "$type entry is"
438 : "$count $type entries are";
439 }
440  
441 sub t_server_log_is_expected {
442 print STDERR is_expected_banner(@_);
443 }
444  
445 sub t_client_log_is_expected {
446 my $vars = Apache::Test::config()->{vars};
447 my $log_file = catfile $vars->{serverroot}, "logs", "error_log";
448  
449 my $fh = Symbol::gensym();
450 open $fh, ">>$log_file" or die "Can't open $log_file: $!";
451 my $oldfh = select($fh); $| = 1; select($oldfh);
452 print $fh is_expected_banner(@_);
453 close $fh;
454 }
455  
456 sub t_server_log_error_is_expected { t_server_log_is_expected("error", @_);}
457 sub t_server_log_warn_is_expected { t_server_log_is_expected("warn", @_); }
458 sub t_client_log_error_is_expected { t_client_log_is_expected("error", @_);}
459 sub t_client_log_warn_is_expected { t_client_log_is_expected("warn", @_); }
460  
461 END {
462 # remove files that were created via this package
463 for (grep {-e $_ && -f _ } keys %{ $CLEAN{files} } ) {
464 t_debug("removing file: $_");
465 unlink $_;
466 }
467  
468 # remove dirs that were created via this package
469 for (grep {-e $_ && -d _ } keys %{ $CLEAN{dirs} } ) {
470 t_debug("removing dir tree: $_");
471 t_rmtree($_);
472 }
473 }
474  
475 # essentially File::Spec->catfile, but on Win32
476 # returns the long path name, if the file is absolute
477 sub t_catfile {
478 my $f = catfile(@_);
479 return $f unless file_name_is_absolute($f);
480 return Apache::TestConfig::WIN32 && -e $f ?
481 Win32::GetLongPathName($f) : $f;
482 }
483  
484 # Apache uses a Unix-style specification for files, with
485 # forward slashes for directory separators. This is
486 # essentially File::Spec::Unix->catfile, but on Win32
487 # returns the long path name, if the file is absolute
488 sub t_catfile_apache {
489 my $f = File::Spec::Unix->catfile(@_);
490 return $f unless file_name_is_absolute($f);
491 return Apache::TestConfig::WIN32 && -e $f ?
492 Win32::GetLongPathName($f) : $f;
493 }
494  
495 1;
496 __END__