2cfb22a6533a9a143a1b9f6f878c76b46cc6778b
[openssl.git] / test / testlib / OpenSSL / Test.pm
1 # Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
2 #
3 # Licensed under the OpenSSL license (the "License").  You may not use
4 # this file except in compliance with the License.  You can obtain a copy
5 # in the file LICENSE in the source distribution or at
6 # https://www.openssl.org/source/license.html
7
8 package OpenSSL::Test;
9
10 use strict;
11 use warnings;
12
13 use Test::More 0.96;
14
15 use Exporter;
16 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
17 $VERSION = "0.8";
18 @ISA = qw(Exporter);
19 @EXPORT = (@Test::More::EXPORT, qw(setup indir app perlapp test perltest run));
20 @EXPORT_OK = (@Test::More::EXPORT_OK, qw(bldtop_dir bldtop_file
21                                          srctop_dir srctop_file
22                                          pipe with cmdstr quotify));
23
24 =head1 NAME
25
26 OpenSSL::Test - a private extension of Test::More
27
28 =head1 SYNOPSIS
29
30   use OpenSSL::Test;
31
32   setup("my_test_name");
33
34   ok(run(app(["openssl", "version"])), "check for openssl presence");
35
36   indir "subdir" => sub {
37     ok(run(test(["sometest", "arg1"], stdout => "foo.txt")),
38        "run sometest with output to foo.txt");
39   };
40
41 =head1 DESCRIPTION
42
43 This module is a private extension of L<Test::More> for testing OpenSSL.
44 In addition to the Test::More functions, it also provides functions that
45 easily find the diverse programs within a OpenSSL build tree, as well as
46 some other useful functions.
47
48 This module I<depends> on the environment variables C<$TOP> or C<$SRCTOP>
49 and C<$BLDTOP>.  Without one of the combinations it refuses to work.
50 See L</ENVIRONMENT> below.
51
52 =cut
53
54 use File::Copy;
55 use File::Spec::Functions qw/file_name_is_absolute curdir canonpath splitdir
56                              catdir catfile splitpath catpath devnull abs2rel
57                              rel2abs/;
58 use File::Path 2.00 qw/rmtree mkpath/;
59
60
61 # The name of the test.  This is set by setup() and is used in the other
62 # functions to verify that setup() has been used.
63 my $test_name = undef;
64
65 # Directories we want to keep track of TOP, APPS, TEST and RESULTS are the
66 # ones we're interested in, corresponding to the environment variables TOP
67 # (mandatory), BIN_D, TEST_D, UTIL_D and RESULT_D.
68 my %directories = ();
69
70 # The environment variables that gave us the contents in %directories.  These
71 # get modified whenever we change directories, so that subprocesses can use
72 # the values of those environment variables as well
73 my @direnv = ();
74
75 # A bool saying if we shall stop all testing if the current recipe has failing
76 # tests or not.  This is set by setup() if the environment variable STOPTEST
77 # is defined with a non-empty value.
78 my $end_with_bailout = 0;
79
80 # A set of hooks that is affected by with() and may be used in diverse places.
81 # All hooks are expected to be CODE references.
82 my %hooks = (
83
84     # exit_checker is used by run() directly after completion of a command.
85     # it receives the exit code from that command and is expected to return
86     # 1 (for success) or 0 (for failure).  This is the value that will be
87     # returned by run().
88     # NOTE: When run() gets the option 'capture => 1', this hook is ignored.
89     exit_checker => sub { return shift == 0 ? 1 : 0 },
90
91     );
92
93 # Debug flag, to be set manually when needed
94 my $debug = 0;
95
96 # Declare some utility functions that are defined at the end
97 sub bldtop_file;
98 sub bldtop_dir;
99 sub srctop_file;
100 sub srctop_dir;
101 sub quotify;
102
103 # Declare some private functions that are defined at the end
104 sub __env;
105 sub __cwd;
106 sub __apps_file;
107 sub __results_file;
108 sub __fixup_cmd;
109 sub __build_cmd;
110
111 =head2 Main functions
112
113 The following functions are exported by default when using C<OpenSSL::Test>.
114
115 =cut
116
117 =over 4
118
119 =item B<setup "NAME">
120
121 C<setup> is used for initial setup, and it is mandatory that it's used.
122 If it's not used in a OpenSSL test recipe, the rest of the recipe will
123 most likely refuse to run.
124
125 C<setup> checks for environment variables (see L</ENVIRONMENT> below),
126 checks that C<$TOP/Configure> or C<$SRCTOP/Configure> exists, C<chdir>
127 into the results directory (defined by the C<$RESULT_D> environment
128 variable if defined, otherwise C<$BLDTOP/test> or C<$TOP/test>, whichever
129 is defined).
130
131 =back
132
133 =cut
134
135 sub setup {
136     my $old_test_name = $test_name;
137     $test_name = shift;
138
139     BAIL_OUT("setup() must receive a name") unless $test_name;
140     warn "setup() detected test name change.  Innocuous, so we continue...\n"
141         if $old_test_name && $old_test_name ne $test_name;
142
143     return if $old_test_name;
144
145     BAIL_OUT("setup() needs \$TOP or \$SRCTOP and \$BLDTOP to be defined")
146         unless $ENV{TOP} || ($ENV{SRCTOP} && $ENV{BLDTOP});
147     BAIL_OUT("setup() found both \$TOP and \$SRCTOP or \$BLDTOP...")
148         if $ENV{TOP} && ($ENV{SRCTOP} || $ENV{BLDTOP});
149
150     __env();
151
152     BAIL_OUT("setup() expects the file Configure in the source top directory")
153         unless -f srctop_file("Configure");
154
155     __cwd($directories{RESULTS});
156 }
157
158 =over 4
159
160 =item B<indir "SUBDIR" =E<gt> sub BLOCK, OPTS>
161
162 C<indir> is used to run a part of the recipe in a different directory than
163 the one C<setup> moved into, usually a subdirectory, given by SUBDIR.
164 The part of the recipe that's run there is given by the codeblock BLOCK.
165
166 C<indir> takes some additional options OPTS that affect the subdirectory:
167
168 =over 4
169
170 =item B<create =E<gt> 0|1>
171
172 When set to 1 (or any value that perl preceives as true), the subdirectory
173 will be created if it doesn't already exist.  This happens before BLOCK
174 is executed.
175
176 =item B<cleanup =E<gt> 0|1>
177
178 When set to 1 (or any value that perl preceives as true), the subdirectory
179 will be cleaned out and removed.  This happens both before and after BLOCK
180 is executed.
181
182 =back
183
184 An example:
185
186   indir "foo" => sub {
187       ok(run(app(["openssl", "version"]), stdout => "foo.txt"));
188       if (ok(open(RESULT, "foo.txt"), "reading foo.txt")) {
189           my $line = <RESULT>;
190           close RESULT;
191           is($line, qr/^OpenSSL 1\./,
192              "check that we're using OpenSSL 1.x.x");
193       }
194   }, create => 1, cleanup => 1;
195
196 =back
197
198 =cut
199
200 sub indir {
201     my $subdir = shift;
202     my $codeblock = shift;
203     my %opts = @_;
204
205     my $reverse = __cwd($subdir,%opts);
206     BAIL_OUT("FAILURE: indir, \"$subdir\" wasn't possible to move into")
207         unless $reverse;
208
209     $codeblock->();
210
211     __cwd($reverse);
212
213     if ($opts{cleanup}) {
214         rmtree($subdir, { safe => 0 });
215     }
216 }
217
218 =over 4
219
220 =item B<app ARRAYREF, OPTS>
221
222 =item B<test ARRAYREF, OPTS>
223
224 Both of these functions take a reference to a list that is a command and
225 its arguments, and some additional options (described further on).
226
227 C<app> expects to find the given command (the first item in the given list
228 reference) as an executable in C<$BIN_D> (if defined, otherwise C<$TOP/apps>
229 or C<$BLDTOP/apps>).
230
231 C<test> expects to find the given command (the first item in the given list
232 reference) as an executable in C<$TEST_D> (if defined, otherwise C<$TOP/test>
233 or C<$BLDTOP/test>).
234
235 Both return a CODEREF to be used by C<run>, C<pipe> or C<cmdstr>.
236
237 The options that both C<app> and C<test> can take are in the form of hash
238 values:
239
240 =over 4
241
242 =item B<stdin =E<gt> PATH>
243
244 =item B<stdout =E<gt> PATH>
245
246 =item B<stderr =E<gt> PATH>
247
248 In all three cases, the corresponding standard input, output or error is
249 redirected from (for stdin) or to (for the others) a file given by the
250 string PATH, I<or>, if the value is C<undef>, C</dev/null> or similar.
251
252 =back
253
254 =item B<perlapp ARRAYREF, OPTS>
255
256 =item B<perltest ARRAYREF, OPTS>
257
258 Both these functions function the same way as B<app> and B<test>, except
259 that they expect the command to be a perl script.  Also, they support one
260 more option:
261
262 =over 4
263
264 =item B<interpreter_args =E<gt> ARRAYref>
265
266 The array reference is a set of arguments for perl rather than the script.
267 Take care so that none of them can be seen as a script!  Flags and their
268 eventual arguments only!
269
270 =back
271
272 An example:
273
274   ok(run(perlapp(["foo.pl", "arg1"],
275                  interpreter_args => [ "-I", srctop_dir("test") ])));
276
277 =back
278
279 =cut
280
281 sub app {
282     my $cmd = shift;
283     my %opts = @_;
284     return sub { my $num = shift;
285                  return __build_cmd($num, \&__apps_file, $cmd, %opts); }
286 }
287
288 sub test {
289     my $cmd = shift;
290     my %opts = @_;
291     return sub { my $num = shift;
292                  return __build_cmd($num, \&__test_file, $cmd, %opts); }
293 }
294
295 sub perlapp {
296     my $cmd = shift;
297     my %opts = @_;
298     return sub { my $num = shift;
299                  return __build_cmd($num, \&__perlapps_file, $cmd, %opts); }
300 }
301
302 sub perltest {
303     my $cmd = shift;
304     my %opts = @_;
305     return sub { my $num = shift;
306                  return __build_cmd($num, \&__perltest_file, $cmd, %opts); }
307 }
308
309 =over 4
310
311 =item B<run CODEREF, OPTS>
312
313 This CODEREF is expected to be the value return by C<app> or C<test>,
314 anything else will most likely cause an error unless you know what you're
315 doing.
316
317 C<run> executes the command returned by CODEREF and return either the
318 resulting output (if the option C<capture> is set true) or a boolean indicating
319 if the command succeeded or not.
320
321 The options that C<run> can take are in the form of hash values:
322
323 =over 4
324
325 =item B<capture =E<gt> 0|1>
326
327 If true, the command will be executed with a perl backtick, and C<run> will
328 return the resulting output as an array of lines.  If false or not given,
329 the command will be executed with C<system()>, and C<run> will return 1 if
330 the command was successful or 0 if it wasn't.
331
332 =back
333
334 For further discussion on what is considered a successful command or not, see
335 the function C<with> further down.
336
337 =back
338
339 =cut
340
341 sub run {
342     my ($cmd, $display_cmd) = shift->(0);
343     my %opts = @_;
344
345     return () if !$cmd;
346
347     my $prefix = "";
348     if ( $^O eq "VMS" ) {       # VMS
349         $prefix = "pipe ";
350     }
351
352     my @r = ();
353     my $r = 0;
354     my $e = 0;
355
356     # In non-verbose, we want to shut up the command interpreter, in case
357     # it has something to complain about.  On VMS, it might complain both
358     # on stdout and stderr
359     my $save_STDOUT;
360     my $save_STDERR;
361     if ($ENV{HARNESS_ACTIVE} && !$ENV{HARNESS_VERBOSE}) {
362         open $save_STDOUT, '>&', \*STDOUT or die "Can't dup STDOUT: $!";
363         open $save_STDERR, '>&', \*STDERR or die "Can't dup STDERR: $!";
364         open STDOUT, ">", devnull();
365         open STDERR, ">", devnull();
366     }
367
368     # The dance we do with $? is the same dance the Unix shells appear to
369     # do.  For example, a program that gets aborted (and therefore signals
370     # SIGABRT = 6) will appear to exit with the code 134.  We mimic this
371     # to make it easier to compare with a manual run of the command.
372     if ($opts{capture}) {
373         @r = `$prefix$cmd`;
374         $e = ($? & 0x7f) ? ($? & 0x7f)|0x80 : ($? >> 8);
375     } else {
376         system("$prefix$cmd");
377         $e = ($? & 0x7f) ? ($? & 0x7f)|0x80 : ($? >> 8);
378         $r = $hooks{exit_checker}->($e);
379     }
380
381     if ($ENV{HARNESS_ACTIVE} && !$ENV{HARNESS_VERBOSE}) {
382         close STDOUT;
383         close STDERR;
384         open STDOUT, '>&', $save_STDOUT or die "Can't restore STDOUT: $!";
385         open STDERR, '>&', $save_STDERR or die "Can't restore STDERR: $!";
386     }
387
388     print STDERR "$prefix$display_cmd => $e\n"
389         if !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE};
390
391     # At this point, $? stops being interesting, and unfortunately,
392     # there are Test::More versions that get picky if we leave it
393     # non-zero.
394     $? = 0;
395
396     if ($opts{capture}) {
397         return @r;
398     } else {
399         return $r;
400     }
401 }
402
403 END {
404     my $tb = Test::More->builder;
405     my $failure = scalar(grep { $_ == 0; } $tb->summary);
406     if ($failure && $end_with_bailout) {
407         BAIL_OUT("Stoptest!");
408     }
409 }
410
411 =head2 Utility functions
412
413 The following functions are exported on request when using C<OpenSSL::Test>.
414
415   # To only get the bldtop_file and srctop_file functions.
416   use OpenSSL::Test qw/bldtop_file srctop_file/;
417
418   # To only get the bldtop_file function in addition to the default ones.
419   use OpenSSL::Test qw/:DEFAULT bldtop_file/;
420
421 =cut
422
423 # Utility functions, exported on request
424
425 =over 4
426
427 =item B<bldtop_dir LIST>
428
429 LIST is a list of directories that make up a path from the top of the OpenSSL
430 build directory (as indicated by the environment variable C<$TOP> or
431 C<$BLDTOP>).
432 C<bldtop_dir> returns the resulting directory as a string, adapted to the local
433 operating system.
434
435 =back
436
437 =cut
438
439 sub bldtop_dir {
440     return __bldtop_dir(@_);    # This caters for operating systems that have
441                                 # a very distinct syntax for directories.
442 }
443
444 =over 4
445
446 =item B<bldtop_file LIST, FILENAME>
447
448 LIST is a list of directories that make up a path from the top of the OpenSSL
449 build directory (as indicated by the environment variable C<$TOP> or
450 C<$BLDTOP>) and FILENAME is the name of a file located in that directory path.
451 C<bldtop_file> returns the resulting file path as a string, adapted to the local
452 operating system.
453
454 =back
455
456 =cut
457
458 sub bldtop_file {
459     return __bldtop_file(@_);
460 }
461
462 =over 4
463
464 =item B<srctop_dir LIST>
465
466 LIST is a list of directories that make up a path from the top of the OpenSSL
467 source directory (as indicated by the environment variable C<$TOP> or
468 C<$SRCTOP>).
469 C<srctop_dir> returns the resulting directory as a string, adapted to the local
470 operating system.
471
472 =back
473
474 =cut
475
476 sub srctop_dir {
477     return __srctop_dir(@_);    # This caters for operating systems that have
478                                 # a very distinct syntax for directories.
479 }
480
481 =over 4
482
483 =item B<srctop_file LIST, FILENAME>
484
485 LIST is a list of directories that make up a path from the top of the OpenSSL
486 source directory (as indicated by the environment variable C<$TOP> or
487 C<$SRCTOP>) and FILENAME is the name of a file located in that directory path.
488 C<srctop_file> returns the resulting file path as a string, adapted to the local
489 operating system.
490
491 =back
492
493 =cut
494
495 sub srctop_file {
496     return __srctop_file(@_);
497 }
498
499 =over 4
500
501 =item B<pipe LIST>
502
503 LIST is a list of CODEREFs returned by C<app> or C<test>, from which C<pipe>
504 creates a new command composed of all the given commands put together in a
505 pipe.  C<pipe> returns a new CODEREF in the same manner as C<app> or C<test>,
506 to be passed to C<run> for execution.
507
508 =back
509
510 =cut
511
512 sub pipe {
513     my @cmds = @_;
514     return
515         sub {
516             my @cs  = ();
517             my @dcs = ();
518             my @els = ();
519             my $counter = 0;
520             foreach (@cmds) {
521                 my ($c, $dc, @el) = $_->(++$counter);
522
523                 return () if !$c;
524
525                 push @cs, $c;
526                 push @dcs, $dc;
527                 push @els, @el;
528             }
529             return (
530                 join(" | ", @cs),
531                 join(" | ", @dcs),
532                 @els
533                 );
534     };
535 }
536
537 =over 4
538
539 =item B<with HASHREF, CODEREF>
540
541 C<with> will temporarly install hooks given by the HASHREF and then execute
542 the given CODEREF.  Hooks are usually expected to have a coderef as value.
543
544 The currently available hoosk are:
545
546 =over 4
547
548 =item B<exit_checker =E<gt> CODEREF>
549
550 This hook is executed after C<run> has performed its given command.  The
551 CODEREF receives the exit code as only argument and is expected to return
552 1 (if the exit code indicated success) or 0 (if the exit code indicated
553 failure).
554
555 =back
556
557 =back
558
559 =cut
560
561 sub with {
562     my $opts = shift;
563     my %opts = %{$opts};
564     my $codeblock = shift;
565
566     my %saved_hooks = ();
567
568     foreach (keys %opts) {
569         $saved_hooks{$_} = $hooks{$_}   if exists($hooks{$_});
570         $hooks{$_} = $opts{$_};
571     }
572
573     $codeblock->();
574
575     foreach (keys %saved_hooks) {
576         $hooks{$_} = $saved_hooks{$_};
577     }
578 }
579
580 =over 4
581
582 =item B<cmdstr CODEREF, OPTS>
583
584 C<cmdstr> takes a CODEREF from C<app> or C<test> and simply returns the
585 command as a string.
586
587 C<cmdstr> takes some additiona options OPTS that affect the string returned:
588
589 =over 4
590
591 =item B<display =E<gt> 0|1>
592
593 When set to 0, the returned string will be with all decorations, such as a
594 possible redirect of stderr to the null device.  This is suitable if the
595 string is to be used directly in a recipe.
596
597 When set to 1, the returned string will be without extra decorations.  This
598 is suitable for display if that is desired (doesn't confuse people with all
599 internal stuff), or if it's used to pass a command down to a subprocess.
600
601 Default: 0
602
603 =back
604
605 =back
606
607 =cut
608
609 sub cmdstr {
610     my ($cmd, $display_cmd) = shift->(0);
611     my %opts = @_;
612
613     if ($opts{display}) {
614         return $display_cmd;
615     } else {
616         return $cmd;
617     }
618 }
619
620 =over 4
621
622 =item B<quotify LIST>
623
624 LIST is a list of strings that are going to be used as arguments for a
625 command, and makes sure to inject quotes and escapes as necessary depending
626 on the content of each string.
627
628 This can also be used to put quotes around the executable of a command.
629 I<This must never ever be done on VMS.>
630
631 =back
632
633 =cut
634
635 sub quotify {
636     # Unix setup (default if nothing else is mentioned)
637     my $arg_formatter =
638         sub { $_ = shift; /\s|[\{\}\\\$\[\]\*\?\|\&:;<>]/ ? "'$_'" : $_ };
639
640     if ( $^O eq "VMS") {        # VMS setup
641         $arg_formatter = sub {
642             $_ = shift;
643             if (/\s|["[:upper:]]/) {
644                 s/"/""/g;
645                 '"'.$_.'"';
646             } else {
647                 $_;
648             }
649         };
650     } elsif ( $^O eq "MSWin32") { # MSWin setup
651         $arg_formatter = sub {
652             $_ = shift;
653             if (/\s|["\|\&\*\;<>]/) {
654                 s/(["\\])/\\$1/g;
655                 '"'.$_.'"';
656             } else {
657                 $_;
658             }
659         };
660     }
661
662     return map { $arg_formatter->($_) } @_;
663 }
664
665 ######################################################################
666 # private functions.  These are never exported.
667
668 =head1 ENVIRONMENT
669
670 OpenSSL::Test depends on some environment variables.
671
672 =over 4
673
674 =item B<TOP>
675
676 This environment variable is mandatory.  C<setup> will check that it's
677 defined and that it's a directory that contains the file C<Configure>.
678 If this isn't so, C<setup> will C<BAIL_OUT>.
679
680 =item B<BIN_D>
681
682 If defined, its value should be the directory where the openssl application
683 is located.  Defaults to C<$TOP/apps> (adapted to the operating system).
684
685 =item B<TEST_D>
686
687 If defined, its value should be the directory where the test applications
688 are located.  Defaults to C<$TOP/test> (adapted to the operating system).
689
690 =item B<STOPTEST>
691
692 If defined, it puts testing in a different mode, where a recipe with
693 failures will result in a C<BAIL_OUT> at the end of its run.
694
695 =back
696
697 =cut
698
699 sub __env {
700     $directories{SRCTOP}  = $ENV{SRCTOP} || $ENV{TOP};
701     $directories{BLDTOP}  = $ENV{BLDTOP} || $ENV{TOP};
702     $directories{BLDAPPS} = $ENV{BIN_D}  || __bldtop_dir("apps");
703     $directories{SRCAPPS} =                 __srctop_dir("apps");
704     $directories{BLDTEST} = $ENV{TEST_D} || __bldtop_dir("test");
705     $directories{SRCTEST} =                 __srctop_dir("test");
706     $directories{RESULTS} = $ENV{RESULT_D} || $directories{BLDTEST};
707
708     push @direnv, "TOP"       if $ENV{TOP};
709     push @direnv, "SRCTOP"    if $ENV{SRCTOP};
710     push @direnv, "BLDTOP"    if $ENV{BLDTOP};
711     push @direnv, "BIN_D"     if $ENV{BIN_D};
712     push @direnv, "TEST_D"    if $ENV{TEST_D};
713     push @direnv, "RESULT_D"  if $ENV{RESULT_D};
714
715     $end_with_bailout     = $ENV{STOPTEST} ? 1 : 0;
716 };
717
718 sub __srctop_file {
719     BAIL_OUT("Must run setup() first") if (! $test_name);
720
721     my $f = pop;
722     return catfile($directories{SRCTOP},@_,$f);
723 }
724
725 sub __srctop_dir {
726     BAIL_OUT("Must run setup() first") if (! $test_name);
727
728     return catdir($directories{SRCTOP},@_);
729 }
730
731 sub __bldtop_file {
732     BAIL_OUT("Must run setup() first") if (! $test_name);
733
734     my $f = pop;
735     return catfile($directories{BLDTOP},@_,$f);
736 }
737
738 sub __bldtop_dir {
739     BAIL_OUT("Must run setup() first") if (! $test_name);
740
741     return catdir($directories{BLDTOP},@_);
742 }
743
744 sub __exeext {
745     my $ext = "";
746     if ($^O eq "VMS" ) {        # VMS
747         $ext = ".exe";
748     } elsif ($^O eq "MSWin32") { # Windows
749         $ext = ".exe";
750     }
751     return $ENV{"EXE_EXT"} || $ext;
752 }
753
754 sub __test_file {
755     BAIL_OUT("Must run setup() first") if (! $test_name);
756
757     my $f = pop;
758     $f = catfile($directories{BLDTEST},@_,$f . __exeext());
759     $f = catfile($directories{SRCTEST},@_,$f) unless -x $f;
760     return $f;
761 }
762
763 sub __perltest_file {
764     BAIL_OUT("Must run setup() first") if (! $test_name);
765
766     my $f = pop;
767     $f = catfile($directories{BLDTEST},@_,$f);
768     $f = catfile($directories{SRCTEST},@_,$f) unless -f $f;
769     return ($^X, $f);
770 }
771
772 sub __apps_file {
773     BAIL_OUT("Must run setup() first") if (! $test_name);
774
775     my $f = pop;
776     $f = catfile($directories{BLDAPPS},@_,$f . __exeext());
777     $f = catfile($directories{SRCAPPS},@_,$f) unless -x $f;
778     return $f;
779 }
780
781 sub __perlapps_file {
782     BAIL_OUT("Must run setup() first") if (! $test_name);
783
784     my $f = pop;
785     $f = catfile($directories{BLDAPPS},@_,$f);
786     $f = catfile($directories{SRCAPPS},@_,$f) unless -f $f;
787     return ($^X, $f);
788 }
789
790 sub __results_file {
791     BAIL_OUT("Must run setup() first") if (! $test_name);
792
793     my $f = pop;
794     return catfile($directories{RESULTS},@_,$f);
795 }
796
797 sub __cwd {
798     my $dir = catdir(shift);
799     my %opts = @_;
800     my $abscurdir = rel2abs(curdir());
801     my $absdir = rel2abs($dir);
802     my $reverse = abs2rel($abscurdir, $absdir);
803
804     # PARANOIA: if we're not moving anywhere, we do nothing more
805     if ($abscurdir eq $absdir) {
806         return $reverse;
807     }
808
809     # Do not support a move to a different volume for now.  Maybe later.
810     BAIL_OUT("FAILURE: \"$dir\" moves to a different volume, not supported")
811         if $reverse eq $abscurdir;
812
813     # If someone happened to give a directory that leads back to the current,
814     # it's extremely silly to do anything more, so just simulate that we did
815     # move.
816     # In this case, we won't even clean it out, for safety's sake.
817     return "." if $reverse eq "";
818
819     $dir = canonpath($dir);
820     if ($opts{create}) {
821         mkpath($dir);
822     }
823
824     # Should we just bail out here as well?  I'm unsure.
825     return undef unless chdir($dir);
826
827     if ($opts{cleanup}) {
828         rmtree(".", { safe => 0, keep_root => 1 });
829     }
830
831     # For each of these directory variables, figure out where they are relative
832     # to the directory we want to move to if they aren't absolute (if they are,
833     # they don't change!)
834     my @dirtags = sort keys %directories;
835     foreach (@dirtags) {
836         if (!file_name_is_absolute($directories{$_})) {
837             my $newpath = abs2rel(rel2abs($directories{$_}), rel2abs($dir));
838             $directories{$_} = $newpath;
839         }
840     }
841
842     # Treat each environment variable that was used to get us the values in
843     # %directories the same was as the paths in %directories, so any sub
844     # process can use their values properly as well
845     foreach (@direnv) {
846         if (!file_name_is_absolute($ENV{$_})) {
847             my $newpath = abs2rel(rel2abs($ENV{$_}), rel2abs($dir));
848             $ENV{$_} = $newpath;
849         }
850     }
851
852     if ($debug) {
853         print STDERR "DEBUG: __cwd(), directories and files:\n";
854         print STDERR "  \$directories{BLDTEST} = \"$directories{BLDTEST}\"\n";
855         print STDERR "  \$directories{SRCTEST} = \"$directories{SRCTEST}\"\n";
856         print STDERR "  \$directories{RESULTS} = \"$directories{RESULTS}\"\n";
857         print STDERR "  \$directories{BLDAPPS} = \"$directories{BLDAPPS}\"\n";
858         print STDERR "  \$directories{SRCAPPS} = \"$directories{SRCAPPS}\"\n";
859         print STDERR "  \$directories{SRCTOP}  = \"$directories{SRCTOP}\"\n";
860         print STDERR "  \$directories{BLDTOP}  = \"$directories{BLDTOP}\"\n";
861         print STDERR "\n";
862         print STDERR "  current directory is \"",curdir(),"\"\n";
863         print STDERR "  the way back is \"$reverse\"\n";
864     }
865
866     return $reverse;
867 }
868
869 sub __fixup_cmd {
870     my $prog = shift;
871     my $exe_shell = shift;
872
873     my $prefix = __bldtop_file("util", "shlib_wrap.sh")." ";
874
875     if (defined($exe_shell)) {
876         $prefix = "$exe_shell ";
877     } elsif ($^O eq "VMS" ) {   # VMS
878         $prefix = ($prog =~ /^(?:[\$a-z0-9_]+:)?[<\[]/i ? "mcr " : "mcr []");
879     } elsif ($^O eq "MSWin32") { # Windows
880         $prefix = "";
881     }
882
883     # We test both with and without extension.  The reason
884     # is that we might be passed a complete file spec, with
885     # extension.
886     if ( ! -x $prog ) {
887         my $prog = "$prog";
888         if ( ! -x $prog ) {
889             $prog = undef;
890         }
891     }
892
893     if (defined($prog)) {
894         # Make sure to quotify the program file on platforms that may
895         # have spaces or similar in their path name.
896         # To our knowledge, VMS is the exception where quotifying should
897         # never happem.
898         ($prog) = quotify($prog) unless $^O eq "VMS";
899         return $prefix.$prog;
900     }
901
902     print STDERR "$prog not found\n";
903     return undef;
904 }
905
906 sub __build_cmd {
907     BAIL_OUT("Must run setup() first") if (! $test_name);
908
909     my $num = shift;
910     my $path_builder = shift;
911     # Make a copy to not destroy the caller's array
912     my @cmdarray = ( @{$_[0]} ); shift;
913     my %opts = @_;
914
915     # We do a little dance, as $path_builder might return a list of
916     # more than one.  If so, only the first is to be considered a
917     # program to fix up, the rest is part of the arguments.  This
918     # happens for perl scripts, where $path_builder will return
919     # a list of two, $^X and the script name.
920     # Also, if $path_builder returned more than one, we don't apply
921     # the EXE_SHELL environment variable.
922     my @prog = ($path_builder->(shift @cmdarray));
923     my $first = shift @prog;
924     my $exe_shell = @prog ? undef : $ENV{EXE_SHELL};
925     my $cmd = __fixup_cmd($first, $exe_shell);
926     if (@prog) {
927         if ( ! -f $prog[0] ) {
928             print STDERR "$prog[0] not found\n";
929             $cmd = undef;
930         }
931     }
932     my @args = (@prog, @cmdarray);
933     if (defined($opts{interpreter_args})) {
934         unshift @args, @{$opts{interpreter_args}};
935     }
936
937     return () if !$cmd;
938
939     my $arg_str = "";
940     my $null = devnull();
941
942
943     $arg_str = " ".join(" ", quotify @args) if @args;
944
945     my $fileornull = sub { $_[0] ? $_[0] : $null; };
946     my $stdin = "";
947     my $stdout = "";
948     my $stderr = "";
949     my $saved_stderr = undef;
950     $stdin = " < ".$fileornull->($opts{stdin})  if exists($opts{stdin});
951     $stdout= " > ".$fileornull->($opts{stdout}) if exists($opts{stdout});
952     $stderr=" 2> ".$fileornull->($opts{stderr}) if exists($opts{stderr});
953
954     my $display_cmd = "$cmd$arg_str$stdin$stdout$stderr";
955
956     $stderr=" 2> ".$null
957         unless $stderr || !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE};
958
959     $cmd .= "$arg_str$stdin$stdout$stderr";
960
961     if ($debug) {
962         print STDERR "DEBUG[__build_cmd]: \$cmd = \"$cmd\"\n";
963         print STDERR "DEBUG[__build_cmd]: \$display_cmd = \"$display_cmd\"\n";
964     }
965
966     return ($cmd, $display_cmd);
967 }
968
969 =head1 SEE ALSO
970
971 L<Test::More>, L<Test::Harness>
972
973 =head1 AUTHORS
974
975 Richard Levitte E<lt>levitte@openssl.orgE<gt> with assitance and
976 inspiration from Andy Polyakov E<lt>appro@openssl.org<gt>.
977
978 =cut
979
980 1;