home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / TestUtil.pm < prev    next >
Encoding:
Perl POD Document  |  2003-04-29  |  16.9 KB  |  633 lines

  1. package Apache::TestUtil;
  2.  
  3. use strict;
  4. use warnings FATAL => 'all';
  5.  
  6. use File::Find ();
  7. use File::Path ();
  8. use Exporter ();
  9. use Carp ();
  10. use Config;
  11. use File::Basename qw(dirname);
  12. use File::Spec::Functions qw(catfile);
  13. use Symbol ();
  14.  
  15. use Apache::Test ();
  16. use Apache::TestConfig ();
  17.  
  18. use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %CLEAN);
  19.  
  20. $VERSION = '0.01';
  21. @ISA     = qw(Exporter);
  22.  
  23. @EXPORT = qw(t_cmp t_debug t_append_file t_write_file t_open_file
  24.     t_mkdir t_rmtree t_is_equal
  25.     t_server_log_error_is_expected t_server_log_warn_is_expected
  26.     t_client_log_error_is_expected t_client_log_warn_is_expected
  27. );
  28.  
  29. @EXPORT_OK = qw(t_write_perl_script t_write_shell_script t_chown);
  30.  
  31. %CLEAN = ();
  32.  
  33. # 5.005's Data::Dumper has problems to dump certain datastructures
  34. use constant HAS_DUMPER => eval { $] >= 5.6 && require Data::Dumper; };
  35. use constant INDENT     => 4;
  36.  
  37. sub t_cmp {
  38.     Carp::carp(join(":", (caller)[1..2]) . 
  39.         ' usage: $res = t_cmp($expected, $received, [$comment])')
  40.             if @_ < 2 || @_ > 3;
  41.  
  42.     t_debug("testing : " . pop) if @_ == 3;
  43.     t_debug("expected: " . struct_as_string(0, $_[0]));
  44.     t_debug("received: " . struct_as_string(0, $_[1]));
  45.     return t_is_equal(@_);
  46. }
  47.  
  48. *expand = HAS_DUMPER ?
  49.     sub { map { ref $_ ? Data::Dumper::Dumper($_) : $_ } @_ } :
  50.     sub { @_ };
  51.  
  52. sub t_debug {
  53.     print map {"# $_\n"} map {split /\n/} grep {defined} expand(@_);
  54. }
  55.  
  56. sub t_open_file {
  57.     my $file = shift;
  58.  
  59.     die "must pass a filename" unless defined $file;
  60.  
  61.     # create the parent dir if it doesn't exist yet
  62.     makepath(dirname $file);
  63.  
  64.     my $fh = Symbol::gensym();
  65.     open $fh, ">$file" or die "can't open $file: $!";
  66.     t_debug("writing file: $file");
  67.     $CLEAN{files}{$file}++;
  68.  
  69.     return $fh;
  70. }
  71.  
  72. sub t_write_file {
  73.     my $file = shift;
  74.  
  75.     die "must pass a filename" unless defined $file;
  76.  
  77.     # create the parent dir if it doesn't exist yet
  78.     makepath(dirname $file);
  79.  
  80.     my $fh = Symbol::gensym();
  81.     open $fh, ">$file" or die "can't open $file: $!";
  82.     t_debug("writing file: $file");
  83.     print $fh join '', @_ if @_;
  84.     close $fh;
  85.     $CLEAN{files}{$file}++;
  86. }
  87.  
  88. sub t_append_file {
  89.     my $file = shift;
  90.  
  91.     die "must pass a filename" unless defined $file;
  92.  
  93.     # create the parent dir if it doesn't exist yet
  94.     makepath(dirname $file);
  95.  
  96.     # add to the cleanup list only if we created it now
  97.     $CLEAN{files}{$file}++ unless -e $file;
  98.  
  99.     my $fh = Symbol::gensym();
  100.     open $fh, ">>$file" or die "can't open $file: $!";
  101.     print $fh join '', @_ if @_;
  102.     close $fh;
  103. }
  104.  
  105. sub t_write_shell_script {
  106.     my $file = shift;
  107.  
  108.     my $code = join '', @_;
  109.     my($ext, $shebang);
  110.  
  111.     if (Apache::TestConfig::WIN32()) {
  112.         $code =~ s/echo$/echo./mg; #required to echo newline
  113.         $ext = 'bat';
  114.         $shebang = "\@echo off\nREM this is a bat";
  115.     }
  116.     else {
  117.         $ext = 'sh';
  118.         $shebang = '#!/bin/sh';
  119.     }
  120.  
  121.     $file .= ".$ext";
  122.     t_write_file($file, "$shebang\n", $code);
  123.     $ext;
  124. }
  125.  
  126. sub t_write_perl_script {
  127.     my $file = shift;
  128.  
  129.     my $shebang = "#!$Config{perlpath}\n";
  130.     my $warning = Apache::TestConfig->thaw->genwarning($file);
  131.     t_write_file($file, $shebang, $warning, @_);
  132.     chmod 0755, $file;
  133. }
  134.  
  135.  
  136. sub t_mkdir {
  137.     my $dir = shift;
  138.     makepath($dir);
  139. }
  140.  
  141. # returns a list of dirs successfully created
  142. sub makepath {
  143.     my($path) = @_;
  144.  
  145.     return if !defined($path) || -e $path;
  146.     my $full_path = $path;
  147.  
  148.     # remember which dirs were created and should be cleaned up
  149.     while (1) {
  150.         $CLEAN{dirs}{$path} = 1;
  151.         $path = dirname $path;
  152.         last if -e $path;
  153.     }
  154.  
  155.     return File::Path::mkpath($full_path, 0, 0755);
  156. }
  157.  
  158. sub t_rmtree {
  159.     die "must pass a dirname" unless defined $_[0];
  160.     File::Path::rmtree((@_ > 1 ? \@_ : $_[0]), 0, 1);
  161. }
  162.  
  163. #chown a file or directory to the test User/Group
  164. #noop if chown is unsupported
  165.  
  166. sub t_chown {
  167.     my $file = shift;
  168.     my $config = Apache::Test::config();
  169.     my($uid, $gid);
  170.  
  171.     eval {
  172.         #XXX cache this lookup
  173.         ($uid, $gid) = (getpwnam($config->{vars}->{user}))[2,3];
  174.     };
  175.  
  176.     if ($@) {
  177.         if ($@ =~ /^The getpwnam function is unimplemented/) {
  178.             #ok if unsupported, e.g. win32
  179.             return 1;
  180.         }
  181.         else {
  182.             die $@;
  183.         }
  184.     }
  185.  
  186.     CORE::chown($uid, $gid, $file) || die "chown $file: $!";
  187. }
  188.  
  189. # $string = struct_as_string($indent_level, $var);
  190. #
  191. # return any nested datastructure via Data::Dumper or ala Data::Dumper
  192. # as a string. undef() is a valid arg.
  193. #
  194. # $indent_level should be 0 (used for nice indentation during
  195. # recursive datastructure traversal)
  196. sub struct_as_string{
  197.     return "???"   unless @_ == 2;
  198.     my $level = shift;
  199.  
  200.     return "undef" unless defined $_[0];
  201.     my $pad  = ' ' x (($level + 1) * INDENT);
  202.     my $spad = ' ' x ($level       * INDENT);
  203.  
  204.     if (HAS_DUMPER) {
  205.         local $Data::Dumper::Terse = 1;
  206.         $Data::Dumper::Terse = $Data::Dumper::Terse; # warn
  207.         my $data = Data::Dumper::Dumper(@_);
  208.         $data =~ s/\n$//; # \n is handled by the caller
  209.         return $data;
  210.     }
  211.     else {
  212.         if (ref($_[0]) eq 'ARRAY') {
  213.             my @data = ();
  214.             for my $i (0..$#{ $_[0] }) {
  215.                 push @data,
  216.                     struct_as_string($level+1, $_[0]->[$i]);
  217.             }
  218.             return join "\n", "[", map({"$pad$_,"} @data), "$spad\]";
  219.         } elsif ( ref($_[0])eq 'HASH') {
  220.             my @data = ();
  221.             for my $key (keys %{ $_[0] }) {
  222.                 push @data,
  223.                     "$key => " .
  224.                     struct_as_string($level+1, $_[0]->{$key});
  225.             }
  226.             return join "\n", "{", map({"$pad$_,"} @data), "$spad\}";
  227.         } else {
  228.             return $_[0];
  229.         }
  230.     }
  231. }
  232.  
  233. # compare any two datastructures (must pass references for non-scalars)
  234. # undef()'s are valid args
  235. sub t_is_equal {
  236.     my ($a, $b) = @_;
  237.     return 0 unless @_ == 2;
  238.  
  239.     if (defined $a && defined $b) {
  240.         my $ref_a = ref $a;
  241.         my $ref_b = ref $b;
  242.         if (!$ref_a && !$ref_b) {
  243.             return $a eq $b;
  244.         }
  245.         elsif ($ref_a eq 'ARRAY' && $ref_b eq 'ARRAY') {
  246.             return 0 unless @$a == @$b;
  247.             for my $i (0..$#$a) {
  248.                 t_is_equal($a->[$i], $b->[$i]) || return 0;
  249.             }
  250.         }
  251.         elsif ($ref_a eq 'HASH' && $ref_b eq 'HASH') {
  252.             return 0 unless (keys %$a) == (keys %$b);
  253.             for my $key (sort keys %$a) {
  254.                 return 0 unless exists $b->{$key};
  255.                 t_is_equal($a->{$key}, $b->{$key}) || return 0;
  256.             }
  257.         }
  258.         elsif ($ref_a eq 'Regexp') {
  259.             return $b =~ $a;
  260.         }
  261.         else {
  262.             # try to compare the references
  263.             return $a eq $b;
  264.         }
  265.     }
  266.     else {
  267.         # undef == undef! a valid test
  268.         return (defined $a || defined $b) ? 0 : 1;
  269.     }
  270.     return 1;
  271. }
  272.  
  273. my $banner_format = 
  274.     "\n*** The following %s entry is expected and it is harmless ***\n";
  275. sub t_server_log_is_expected { printf STDERR $banner_format, $_[0]; }
  276.  
  277. sub t_client_log_is_expected {
  278.     my $vars = Apache::Test::config()->{vars};
  279.     my $log_file = catfile $vars->{serverroot}, "logs", "error_log";
  280.  
  281.     my $fh = Symbol::gensym();
  282.     open $fh, ">>$log_file" or die "Can't open $log_file: $!";
  283.     my $oldfh = select($fh); $| = 1; select($oldfh);
  284.     printf $fh $banner_format, $_[0];
  285.     close $fh;
  286. }
  287.  
  288. sub t_server_log_error_is_expected { t_server_log_is_expected("error");}
  289. sub t_server_log_warn_is_expected  { t_server_log_is_expected("warn"); }
  290. sub t_client_log_error_is_expected { t_client_log_is_expected("error");}
  291. sub t_client_log_warn_is_expected  { t_client_log_is_expected("warn"); }
  292.  
  293. END {
  294.     # remove files that were created via this package
  295.     for (grep {-e $_ && -f _ } keys %{ $CLEAN{files} } ) {
  296.         t_debug("removing file: $_");
  297.         unlink $_;
  298.     }
  299.  
  300.     # remove dirs that were created via this package
  301.     for (grep {-e $_ && -d _ } keys %{ $CLEAN{dirs} } ) {
  302.         t_debug("removing dir tree: $_");
  303.         t_rmtree($_);
  304.     }
  305. }
  306.  
  307. 1;
  308. __END__
  309.  
  310.  
  311. =head1 NAME
  312.  
  313. Apache::TestUtil - Utility functions for writing tests
  314.  
  315. =head1 SYNOPSIS
  316.  
  317.   use Apache::Test;
  318.   use Apache::TestUtil;
  319.  
  320.   ok t_cmp("foo", "foo", "sanity check");
  321.   t_write_file("filename", @content);
  322.   my $fh = t_open_file($filename);
  323.   t_mkdir("/foo/bar");
  324.   t_rmtree("/foo/bar");
  325.   t_is_equal($a, $b);
  326.  
  327. =head1 DESCRIPTION
  328.  
  329. C<Apache::TestUtil> automatically exports a number of functions useful
  330. in writing tests.
  331.  
  332. All the files and directories created using the functions from this
  333. package will be automatically destroyed at the end of the program
  334. execution (via END block). You should not use these functions other
  335. than from within tests which should cleanup all the created
  336. directories and files at the end of the test.
  337.  
  338. =head1 FUNCTIONS
  339.  
  340. =over
  341.  
  342. =item t_cmp()
  343.  
  344.   t_cmp($expected, $received, $comment);
  345.  
  346. t_cmp() prints the values of I<$comment>, I<$expected> and
  347. I<$received>. e.g.:
  348.  
  349.   t_cmp(1, 1, "1 == 1?");
  350.  
  351. prints:
  352.  
  353.   # testing : 1 == 1?
  354.   # expected: 1
  355.   # received: 1
  356.  
  357. then it returns the result of comparison of the I<$expected> and the
  358. I<$received> variables. Usually, the return value of this function is
  359. fed directly to the ok() function, like this:
  360.  
  361.   ok t_cmp(1, 1, "1 == 1?");
  362.  
  363. the third argument (I<$comment>) is optional, mostly useful for
  364. telling what the comparison is trying to do.
  365.  
  366. It is valid to use C<undef> as an expected value. Therefore:
  367.  
  368.   my $foo;
  369.   t_cmp(undef, $foo, "undef == undef?");
  370.  
  371. will return a I<true> value.
  372.  
  373. You can compare any two data-structures with t_cmp(). Just make sure
  374. that if you pass non-scalars, you have to pass their references. The
  375. datastructures can be deeply nested. For example you can compare:
  376.  
  377.   t_cmp({1 => [2..3,{5..8}], 4 => [5..6]},
  378.         {1 => [2..3,{5..8}], 4 => [5..6]},
  379.         "hash of array of hashes");
  380.  
  381. You can also compare the second argument against the first as a
  382. regex. Use the C<qr//> function in the first argument. For example:
  383.  
  384.   t_cmp(qr/^abc/, "abcd", "regex compare");
  385.  
  386. will do:
  387.  
  388.   "abcd" =~ /^abc/;
  389.  
  390. This function is exported by default.
  391.  
  392. =item t_debug()
  393.  
  394.   t_debug("testing feature foo");
  395.   t_debug("test", [1..3], 5, {a=>[1..5]});
  396.  
  397. t_debug() prints out any datastructure while prepending C<#> at the
  398. beginning of each line, to make the debug printouts comply with
  399. C<Test::Harness>'s requirements. This function should be always used
  400. for debug prints, since if in the future the debug printing will
  401. change (e.g. redirected into a file) your tests won't need to be
  402. changed.
  403.  
  404. This function is exported by default.
  405.  
  406. =item t_write_file()
  407.  
  408.   t_write_file($filename, @lines);
  409.  
  410. t_write_file() creates a new file at I<$filename> or overwrites the
  411. existing file with the content passed in I<@lines>. If only the
  412. I<$filename> is passed, an empty file will be created.
  413.  
  414. If parent directories of C<$filename> don't exist they will be
  415. automagically created.
  416.  
  417. The generated file will be automatically deleted at the end of the
  418. program's execution.
  419.  
  420. This function is exported by default.
  421.  
  422. =item t_append_file()
  423.  
  424.   t_append_file($filename, @lines);
  425.  
  426. t_append_file() is similar to t_write_file(), but it doesn't clobber
  427. existing files and appends C<@lines> to the end of the file. If the
  428. file doesn't exist it will create it.
  429.  
  430. If parent directories of C<$filename> don't exist they will be
  431. automagically created.
  432.  
  433. The generated file will be registered to be automatically deleted at
  434. the end of the program's execution, only if the file was created by
  435. t_append_file().
  436.  
  437. This function is exported by default.
  438.  
  439. =item t_write_shell_script()
  440.  
  441.   Apache::TestUtil::t_write_shell_script($filename, @lines);
  442.  
  443. Similar to t_write_file() but creates a portable shell/batch
  444. script. The created filename is constructed from C<$filename> and an
  445. appropriate extension automatically selected according to the platform
  446. the code is running under.
  447.  
  448. It returns the extension of the created file.
  449.  
  450. =item t_write_perl_script()
  451.  
  452.   Apache::TestUtil::t_write_perl_script($filename, @lines);
  453.  
  454. Similar to t_write_file() but creates a executable Perl script with
  455. correctly set shebang line.
  456.  
  457. =item t_open_file()
  458.  
  459.   my $fh = t_open_file($filename);
  460.  
  461. t_open_file() opens a file I<$filename> for writing and returns the
  462. file handle to the opened file.
  463.  
  464. If parent directories of C<$filename> don't exist they will be
  465. automagically created.
  466.  
  467. The generated file will be automatically deleted at the end of the
  468. program's execution.
  469.  
  470. This function is exported by default.
  471.  
  472. =item t_mkdir()
  473.  
  474.   t_mkdir($dirname);
  475.  
  476. t_mkdir() creates a directory I<$dirname>. The operation will fail if
  477. the parent directory doesn't exist.
  478.  
  479. If parent directories of C<$dirname> don't exist they will be
  480. automagically created.
  481.  
  482. The generated directory will be automatically deleted at the end of
  483. the program's execution.
  484.  
  485. This function is exported by default.
  486.  
  487. =item t_rmtree()
  488.  
  489.   t_rmtree(@dirs);
  490.  
  491. t_rmtree() deletes the whole directories trees passed in I<@dirs>.
  492.  
  493. This function is exported by default.
  494.  
  495. =item t_chown()
  496.  
  497.   Apache::TestUtil::t_chown($file);
  498.  
  499. Change ownership of $file to the test's I<User>/I<Group>.  This
  500. function is noop on platforms where chown(2) is unsupported
  501. (e.g. Win32).
  502.  
  503. =item t_is_equal()
  504.  
  505.   t_is_equal($a, $b);
  506.  
  507. t_is_equal() compares any two datastructures and returns 1 if they are
  508. exactly the same, otherwise 0. The datastructures can be nested
  509. hashes, arrays, scalars, undefs or a combination of any of these.  See
  510. t_cmp() for an example.
  511.  
  512. If C<$a> is a regex reference, the regex comparison C<$b =~ $a> is
  513. performed. For example:
  514.  
  515.   t_is_equal(qr{^Apache}, $server_version);
  516.  
  517. If comparing non-scalars make sure to pass the references to the
  518. datastructures.
  519.  
  520. This function is exported by default.
  521.  
  522. =item t_server_log_error_is_expected()
  523.  
  524. If the handler's execution results in an error or a warning logged to
  525. the I<error_log> file which is expected, it's a good idea to have a
  526. disclaimer printed before the error itself, so one can tell real
  527. problems with tests from expected errors. For example when testing how
  528. the package behaves under error conditions the I<error_log> file might
  529. be loaded with errors, most of which are expected.
  530.  
  531. For example if a handler is about to generate a run-time error, this
  532. function can be used as:
  533.  
  534.   use Apache::TestUtil;
  535.   ...
  536.   sub handler {
  537.       my $r = shift;
  538.       ...
  539.       t_server_log_error_is_expected();
  540.       die "failed because ...";
  541.   }
  542.  
  543. After running this handler the I<error_log> file will include:
  544.  
  545.   *** The following error entry is expected and it is harmless ***
  546.   [Tue Apr 01 14:00:21 2003] [error] failed because ...
  547.  
  548. If the error is generated at compile time, the logging must be done in
  549. the BEGIN block at the very beginning of the file:
  550.  
  551.   BEGIN {
  552.       use Apache::TestUtil;
  553.       t_server_log_error_is_expected();
  554.   }
  555.   use DOES_NOT_exist;
  556.  
  557. After attempting to run this handler the I<error_log> file will
  558. include:
  559.  
  560.   *** The following error entry is expected and it is harmless ***
  561.   [Tue Apr 01 14:04:49 2003] [error] Can't locate "DOES_NOT_exist.pm"
  562.   in @INC (@INC contains: ...
  563.  
  564. Also see C<t_server_log_warn_is_expected()> which is similar but used
  565. for warnings.
  566.  
  567. This function is exported by default.
  568.  
  569. =item t_server_log_warn_is_expected()
  570.  
  571. C<t_server_log_warn_is_expected()> generates a disclaimer for expected
  572. warnings.
  573.  
  574. See the explanation for C<t_server_log_error_is_expected()> for more
  575. details.
  576.  
  577. This function is exported by default.
  578.  
  579. =item t_client_log_error_is_expected()
  580.  
  581. C<t_client_log_error_is_expected()> generates a disclaimer for
  582. expected errors. But in contrast to
  583. C<t_server_log_error_is_expected()> called by the client side of the
  584. script.
  585.  
  586. See the explanation for C<t_server_log_error_is_expected()> for more
  587. details.
  588.  
  589. For example the following client script fails to find the handler:
  590.  
  591.   use Apache::Test;
  592.   use Apache::TestUtil;
  593.   use Apache::TestRequest qw(GET);
  594.   
  595.   plan tests => 1;
  596.   
  597.   t_client_log_error_is_expected();
  598.   my $url = "/error_document/cannot_be_found";
  599.   my $res = GET($url);
  600.   ok t_cmp(404, $res->code, "test 404");
  601.  
  602. After running this test the I<error_log> file will include an entry
  603. similar to the following snippet:
  604.  
  605.   *** The following error entry is expected and it is harmless ***
  606.   [Tue Apr 01 14:02:55 2003] [error] [client 127.0.0.1] 
  607.   File does not exist: /tmp/test/t/htdocs/error
  608.  
  609. This function is exported by default.
  610.  
  611. =item t_client_log_warn_is_expected()
  612.  
  613. C<t_client_log_warn_is_expected()> generates a disclaimer for expected
  614. warnings on the client side.
  615.  
  616. See the explanation for C<t_client_log_error_is_expected()> for more
  617. details.
  618.  
  619. This function is exported by default.
  620.  
  621. =back
  622.  
  623. =head1 AUTHOR
  624.  
  625. Stas Bekman <stas@stason.org>
  626.  
  627. =head1 SEE ALSO
  628.  
  629. perl(1)
  630.  
  631. =cut
  632.  
  633.