]> git.ipfire.org Git - thirdparty/openssl.git/blame - util/perl/OpenSSL/Test.pm
Following the license change, modify the boilerplates in util/, tools/
[thirdparty/openssl.git] / util / perl / OpenSSL / Test.pm
CommitLineData
71bb86f0 1# Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
ac3d0e13 2#
9059ab42 3# Licensed under the Apache License 2.0 (the "License"). You may not use
ac3d0e13
RS
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
aec27d4d
RL
8package OpenSSL::Test;
9
10use strict;
11use warnings;
12
fd99c6b5
RL
13use Test::More 0.96;
14
aec27d4d
RL
15use Exporter;
16use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
42e0ccdf 17$VERSION = "0.8";
aec27d4d 18@ISA = qw(Exporter);
9ddf67f3 19@EXPORT = (@Test::More::EXPORT, qw(setup run indir cmd app fuzz test
208d721a 20 perlapp perltest subtest));
42e0ccdf
RL
21@EXPORT_OK = (@Test::More::EXPORT_OK, qw(bldtop_dir bldtop_file
22 srctop_dir srctop_file
fa92c69a 23 data_file data_dir
efe749c8
RL
24 pipe with cmdstr quotify
25 openssl_versions));
aec27d4d 26
f5098edb 27=head1 NAME
aec27d4d 28
f5098edb 29OpenSSL::Test - a private extension of Test::More
aec27d4d 30
f5098edb 31=head1 SYNOPSIS
aec27d4d 32
f5098edb 33 use OpenSSL::Test;
aec27d4d 34
f5098edb 35 setup("my_test_name");
aec27d4d 36
f5098edb 37 ok(run(app(["openssl", "version"])), "check for openssl presence");
caadc543 38
f5098edb
RL
39 indir "subdir" => sub {
40 ok(run(test(["sometest", "arg1"], stdout => "foo.txt")),
41 "run sometest with output to foo.txt");
42 };
aec27d4d 43
f5098edb 44=head1 DESCRIPTION
aec27d4d 45
f5098edb
RL
46This module is a private extension of L<Test::More> for testing OpenSSL.
47In addition to the Test::More functions, it also provides functions that
48easily find the diverse programs within a OpenSSL build tree, as well as
49some other useful functions.
aec27d4d 50
42e0ccdf
RL
51This module I<depends> on the environment variables C<$TOP> or C<$SRCTOP>
52and C<$BLDTOP>. Without one of the combinations it refuses to work.
53See L</ENVIRONMENT> below.
aec27d4d 54
6c6a2ae6
RL
55With each test recipe, a parallel data directory with (almost) the same name
56as the recipe is possible in the source directory tree. For example, for a
57recipe C<$SRCTOP/test/recipes/99-foo.t>, there could be a directory
58C<$SRCTOP/test/recipes/99-foo_data/>.
59
f5098edb 60=cut
aec27d4d 61
f5098edb
RL
62use File::Copy;
63use File::Spec::Functions qw/file_name_is_absolute curdir canonpath splitdir
64 catdir catfile splitpath catpath devnull abs2rel
65 rel2abs/;
4500a4cd 66use File::Path 2.00 qw/rmtree mkpath/;
6c6a2ae6 67use File::Basename;
aec27d4d 68
208d721a 69my $level = 0;
aec27d4d 70
f5098edb
RL
71# The name of the test. This is set by setup() and is used in the other
72# functions to verify that setup() has been used.
73my $test_name = undef;
aec27d4d 74
f5098edb
RL
75# Directories we want to keep track of TOP, APPS, TEST and RESULTS are the
76# ones we're interested in, corresponding to the environment variables TOP
42e0ccdf 77# (mandatory), BIN_D, TEST_D, UTIL_D and RESULT_D.
f5098edb 78my %directories = ();
aec27d4d 79
d1094383
RL
80# The environment variables that gave us the contents in %directories. These
81# get modified whenever we change directories, so that subprocesses can use
82# the values of those environment variables as well
83my @direnv = ();
84
f5098edb
RL
85# A bool saying if we shall stop all testing if the current recipe has failing
86# tests or not. This is set by setup() if the environment variable STOPTEST
87# is defined with a non-empty value.
88my $end_with_bailout = 0;
aec27d4d 89
f5098edb
RL
90# A set of hooks that is affected by with() and may be used in diverse places.
91# All hooks are expected to be CODE references.
92my %hooks = (
aec27d4d 93
f5098edb
RL
94 # exit_checker is used by run() directly after completion of a command.
95 # it receives the exit code from that command and is expected to return
089a45c5 96 # 1 (for success) or 0 (for failure). This is the status value that run()
46f4e1be 97 # will give back (through the |statusvar| reference and as returned value
089a45c5 98 # when capture => 1 doesn't apply).
f5098edb 99 exit_checker => sub { return shift == 0 ? 1 : 0 },
aec27d4d 100
f5098edb 101 );
aec27d4d 102
a00c84f6
RL
103# Debug flag, to be set manually when needed
104my $debug = 0;
105
f5098edb 106=head2 Main functions
aec27d4d 107
f5098edb 108The following functions are exported by default when using C<OpenSSL::Test>.
aec27d4d 109
f5098edb 110=cut
aec27d4d 111
f5098edb 112=over 4
aec27d4d 113
f5098edb 114=item B<setup "NAME">
aec27d4d 115
f5098edb
RL
116C<setup> is used for initial setup, and it is mandatory that it's used.
117If it's not used in a OpenSSL test recipe, the rest of the recipe will
118most likely refuse to run.
119
120C<setup> checks for environment variables (see L</ENVIRONMENT> below),
42e0ccdf
RL
121checks that C<$TOP/Configure> or C<$SRCTOP/Configure> exists, C<chdir>
122into the results directory (defined by the C<$RESULT_D> environment
123variable if defined, otherwise C<$BLDTOP/test> or C<$TOP/test>, whichever
124is defined).
f5098edb
RL
125
126=back
127
128=cut
aec27d4d
RL
129
130sub setup {
fa657fc8 131 my $old_test_name = $test_name;
aec27d4d
RL
132 $test_name = shift;
133
134 BAIL_OUT("setup() must receive a name") unless $test_name;
fa657fc8
RL
135 warn "setup() detected test name change. Innocuous, so we continue...\n"
136 if $old_test_name && $old_test_name ne $test_name;
137
138 return if $old_test_name;
139
42e0ccdf
RL
140 BAIL_OUT("setup() needs \$TOP or \$SRCTOP and \$BLDTOP to be defined")
141 unless $ENV{TOP} || ($ENV{SRCTOP} && $ENV{BLDTOP});
142 BAIL_OUT("setup() found both \$TOP and \$SRCTOP or \$BLDTOP...")
143 if $ENV{TOP} && ($ENV{SRCTOP} || $ENV{BLDTOP});
aec27d4d 144
f5098edb 145 __env();
caadc543 146
fa657fc8
RL
147 BAIL_OUT("setup() expects the file Configure in the source top directory")
148 unless -f srctop_file("Configure");
aec27d4d
RL
149
150 __cwd($directories{RESULTS});
aec27d4d
RL
151}
152
f5098edb
RL
153=over 4
154
155=item B<indir "SUBDIR" =E<gt> sub BLOCK, OPTS>
156
157C<indir> is used to run a part of the recipe in a different directory than
158the one C<setup> moved into, usually a subdirectory, given by SUBDIR.
159The part of the recipe that's run there is given by the codeblock BLOCK.
160
161C<indir> takes some additional options OPTS that affect the subdirectory:
162
163=over 4
164
165=item B<create =E<gt> 0|1>
166
167When set to 1 (or any value that perl preceives as true), the subdirectory
168will be created if it doesn't already exist. This happens before BLOCK
169is executed.
170
171=item B<cleanup =E<gt> 0|1>
172
173When set to 1 (or any value that perl preceives as true), the subdirectory
174will be cleaned out and removed. This happens both before and after BLOCK
175is executed.
176
177=back
178
179An example:
180
181 indir "foo" => sub {
182 ok(run(app(["openssl", "version"]), stdout => "foo.txt"));
183 if (ok(open(RESULT, "foo.txt"), "reading foo.txt")) {
184 my $line = <RESULT>;
185 close RESULT;
186 is($line, qr/^OpenSSL 1\./,
187 "check that we're using OpenSSL 1.x.x");
188 }
189 }, create => 1, cleanup => 1;
190
191=back
192
193=cut
194
aec27d4d
RL
195sub indir {
196 my $subdir = shift;
197 my $codeblock = shift;
198 my %opts = @_;
199
200 my $reverse = __cwd($subdir,%opts);
201 BAIL_OUT("FAILURE: indir, \"$subdir\" wasn't possible to move into")
202 unless $reverse;
203
204 $codeblock->();
205
206 __cwd($reverse);
207
208 if ($opts{cleanup}) {
4500a4cd 209 rmtree($subdir, { safe => 0 });
aec27d4d
RL
210 }
211}
212
f5098edb 213=over 4
aec27d4d 214
9ddf67f3 215=item B<cmd ARRAYREF, OPTS>
aec27d4d 216
9ddf67f3
RL
217This functions build up a platform dependent command based on the
218input. It takes a reference to a list that is the executable or
219script and its arguments, and some additional options (described
28e0f6eb
RL
220further on). Where necessary, the command will be wrapped in a
221suitable environment to make sure the correct shared libraries are
222used (currently only on Unix).
aec27d4d 223
9ddf67f3 224It returns a CODEREF to be used by C<run>, C<pipe> or C<cmdstr>.
aec27d4d 225
9ddf67f3 226The options that C<cmd> can take are in the form of hash values:
aec27d4d 227
f5098edb 228=over 4
aec27d4d 229
f5098edb 230=item B<stdin =E<gt> PATH>
aec27d4d 231
f5098edb 232=item B<stdout =E<gt> PATH>
aec27d4d 233
f5098edb 234=item B<stderr =E<gt> PATH>
aec27d4d 235
f5098edb
RL
236In all three cases, the corresponding standard input, output or error is
237redirected from (for stdin) or to (for the others) a file given by the
238string PATH, I<or>, if the value is C<undef>, C</dev/null> or similar.
aec27d4d 239
f5098edb 240=back
aec27d4d 241
9ddf67f3
RL
242=item B<app ARRAYREF, OPTS>
243
244=item B<test ARRAYREF, OPTS>
245
246Both of these are specific applications of C<cmd>, with just a couple
247of small difference:
248
249C<app> expects to find the given command (the first item in the given list
250reference) as an executable in C<$BIN_D> (if defined, otherwise C<$TOP/apps>
251or C<$BLDTOP/apps>).
252
253C<test> expects to find the given command (the first item in the given list
254reference) as an executable in C<$TEST_D> (if defined, otherwise C<$TOP/test>
255or C<$BLDTOP/test>).
256
257Also, for both C<app> and C<test>, the command may be prefixed with
258the content of the environment variable C<$EXE_SHELL>, which is useful
259in case OpenSSL has been cross compiled.
260
a00c84f6
RL
261=item B<perlapp ARRAYREF, OPTS>
262
263=item B<perltest ARRAYREF, OPTS>
264
9ddf67f3
RL
265These are also specific applications of C<cmd>, where the interpreter
266is predefined to be C<perl>, and they expect the script to be
267interpreted to reside in the same location as C<app> and C<test>.
268
269C<perlapp> and C<perltest> will also take the following option:
b8fcd4f0
RL
270
271=over 4
272
273=item B<interpreter_args =E<gt> ARRAYref>
274
9ddf67f3
RL
275The array reference is a set of arguments for the interpreter rather
276than the script. Take care so that none of them can be seen as a
277script! Flags and their eventual arguments only!
b8fcd4f0
RL
278
279=back
280
281An example:
282
283 ok(run(perlapp(["foo.pl", "arg1"],
284 interpreter_args => [ "-I", srctop_dir("test") ])));
a00c84f6 285
f5098edb 286=back
aec27d4d 287
9ddf67f3
RL
288=begin comment
289
290One might wonder over the complexity of C<apps>, C<fuzz>, C<test>, ...
291with all the lazy evaluations and all that. The reason for this is that
292we want to make sure the directory in which those programs are found are
293correct at the time these commands are used. Consider the following code
294snippet:
295
296 my $cmd = app(["openssl", ...]);
297
298 indir "foo", sub {
299 ok(run($cmd), "Testing foo")
300 };
301
302If there wasn't this lazy evaluation, the directory where C<openssl> is
303found would be incorrect at the time C<run> is called, because it was
304calculated before we moved into the directory "foo".
305
306=end comment
307
f5098edb 308=cut
aec27d4d 309
9ddf67f3
RL
310sub cmd {
311 my $cmd = shift;
312 my %opts = @_;
313 return sub {
314 my $num = shift;
315 # Make a copy to not destroy the caller's array
316 my @cmdargs = ( @$cmd );
317 my @prog = __wrap_cmd(shift @cmdargs, $opts{exe_shell} // ());
318
319 return __decorate_cmd($num, [ @prog, quotify(@cmdargs) ],
320 %opts);
321 }
322}
323
aec27d4d
RL
324sub app {
325 my $cmd = shift;
326 my %opts = @_;
9ddf67f3
RL
327 return sub {
328 my @cmdargs = ( @{$cmd} );
329 my @prog = __fixup_prg(__apps_file(shift @cmdargs, __exeext()));
330 return cmd([ @prog, @cmdargs ],
331 exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift);
332 }
aec27d4d
RL
333}
334
90d28f05
BL
335sub fuzz {
336 my $cmd = shift;
337 my %opts = @_;
9ddf67f3
RL
338 return sub {
339 my @cmdargs = ( @{$cmd} );
340 my @prog = __fixup_prg(__fuzz_file(shift @cmdargs, __exeext()));
341 return cmd([ @prog, @cmdargs ],
342 exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift);
343 }
90d28f05
BL
344}
345
aec27d4d
RL
346sub test {
347 my $cmd = shift;
348 my %opts = @_;
9ddf67f3
RL
349 return sub {
350 my @cmdargs = ( @{$cmd} );
351 my @prog = __fixup_prg(__test_file(shift @cmdargs, __exeext()));
352 return cmd([ @prog, @cmdargs ],
353 exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift);
354 }
aec27d4d
RL
355}
356
a00c84f6
RL
357sub perlapp {
358 my $cmd = shift;
359 my %opts = @_;
9ddf67f3
RL
360 return sub {
361 my @interpreter_args = defined $opts{interpreter_args} ?
362 @{$opts{interpreter_args}} : ();
363 my @interpreter = __fixup_prg($^X);
364 my @cmdargs = ( @{$cmd} );
365 my @prog = __apps_file(shift @cmdargs, undef);
366 return cmd([ @interpreter, @interpreter_args,
367 @prog, @cmdargs ], %opts) -> (shift);
368 }
a00c84f6
RL
369}
370
371sub perltest {
372 my $cmd = shift;
373 my %opts = @_;
9ddf67f3
RL
374 return sub {
375 my @interpreter_args = defined $opts{interpreter_args} ?
376 @{$opts{interpreter_args}} : ();
377 my @interpreter = __fixup_prg($^X);
378 my @cmdargs = ( @{$cmd} );
379 my @prog = __test_file(shift @cmdargs, undef);
380 return cmd([ @interpreter, @interpreter_args,
381 @prog, @cmdargs ], %opts) -> (shift);
382 }
a00c84f6
RL
383}
384
f5098edb 385=over 4
aec27d4d 386
f5098edb
RL
387=item B<run CODEREF, OPTS>
388
9ddf67f3
RL
389CODEREF is expected to be the value return by C<cmd> or any of its
390derivatives, anything else will most likely cause an error unless you
391know what you're doing.
f5098edb
RL
392
393C<run> executes the command returned by CODEREF and return either the
9ddf67f3
RL
394resulting output (if the option C<capture> is set true) or a boolean
395indicating if the command succeeded or not.
f5098edb
RL
396
397The options that C<run> can take are in the form of hash values:
398
399=over 4
400
401=item B<capture =E<gt> 0|1>
402
403If true, the command will be executed with a perl backtick, and C<run> will
404return the resulting output as an array of lines. If false or not given,
405the command will be executed with C<system()>, and C<run> will return 1 if
406the command was successful or 0 if it wasn't.
407
f75f007c
RL
408=item B<prefix =E<gt> EXPR>
409
410If specified, EXPR will be used as a string to prefix the output from the
411command. This is useful if the output contains lines starting with C<ok >
412or C<not ok > that can disturb Test::Harness.
413
34a6a9b1
RL
414=item B<statusvar =E<gt> VARREF>
415
416If used, B<VARREF> must be a reference to a scalar variable. It will be
417assigned a boolean indicating if the command succeeded or not. This is
418particularly useful together with B<capture>.
419
f5098edb
RL
420=back
421
422For further discussion on what is considered a successful command or not, see
423the function C<with> further down.
424
425=back
426
427=cut
aec27d4d
RL
428
429sub run {
b843cdb1 430 my ($cmd, $display_cmd) = shift->(0);
aec27d4d
RL
431 my %opts = @_;
432
433 return () if !$cmd;
434
435 my $prefix = "";
436 if ( $^O eq "VMS" ) { # VMS
437 $prefix = "pipe ";
aec27d4d
RL
438 }
439
440 my @r = ();
441 my $r = 0;
442 my $e = 0;
2ef157af 443
34a6a9b1
RL
444 die "OpenSSL::Test::run(): statusvar value not a scalar reference"
445 if $opts{statusvar} && ref($opts{statusvar}) ne "SCALAR";
446
78e91586
RL
447 # In non-verbose, we want to shut up the command interpreter, in case
448 # it has something to complain about. On VMS, it might complain both
449 # on stdout and stderr
81b538e5
RL
450 my $save_STDOUT;
451 my $save_STDERR;
78e91586 452 if ($ENV{HARNESS_ACTIVE} && !$ENV{HARNESS_VERBOSE}) {
81b538e5
RL
453 open $save_STDOUT, '>&', \*STDOUT or die "Can't dup STDOUT: $!";
454 open $save_STDERR, '>&', \*STDERR or die "Can't dup STDERR: $!";
78e91586
RL
455 open STDOUT, ">", devnull();
456 open STDERR, ">", devnull();
457 }
458
208d721a
RL
459 $ENV{HARNESS_OSSL_LEVEL} = $level + 1;
460
2ef157af
RL
461 # The dance we do with $? is the same dance the Unix shells appear to
462 # do. For example, a program that gets aborted (and therefore signals
463 # SIGABRT = 6) will appear to exit with the code 134. We mimic this
464 # to make it easier to compare with a manual run of the command.
f75f007c
RL
465 if ($opts{capture} || defined($opts{prefix})) {
466 my $pipe;
93f725a3 467 local $_;
f75f007c
RL
468
469 open($pipe, '-|', "$prefix$cmd") or die "Can't start command: $!";
470 while(<$pipe>) {
471 my $l = ($opts{prefix} // "") . $_;
472 if ($opts{capture}) {
473 push @r, $l;
474 } else {
475 print STDOUT $l;
476 }
477 }
478 close $pipe;
aec27d4d 479 } else {
71bb86f0 480 $ENV{HARNESS_OSSL_PREFIX} = "# ";
aec27d4d 481 system("$prefix$cmd");
71bb86f0 482 delete $ENV{HARNESS_OSSL_PREFIX};
34a6a9b1
RL
483 }
484 $e = ($? & 0x7f) ? ($? & 0x7f)|0x80 : ($? >> 8);
485 $r = $hooks{exit_checker}->($e);
486 if ($opts{statusvar}) {
487 ${$opts{statusvar}} = $r;
aec27d4d
RL
488 }
489
78e91586
RL
490 if ($ENV{HARNESS_ACTIVE} && !$ENV{HARNESS_VERBOSE}) {
491 close STDOUT;
492 close STDERR;
81b538e5
RL
493 open STDOUT, '>&', $save_STDOUT or die "Can't restore STDOUT: $!";
494 open STDERR, '>&', $save_STDERR or die "Can't restore STDERR: $!";
78e91586 495 }
78e91586 496
349232d1 497 print STDERR "$prefix$display_cmd => $e\n"
3eefcea1
RL
498 if !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE};
499
aec27d4d
RL
500 # At this point, $? stops being interesting, and unfortunately,
501 # there are Test::More versions that get picky if we leave it
502 # non-zero.
503 $? = 0;
504
aec27d4d
RL
505 if ($opts{capture}) {
506 return @r;
507 } else {
508 return $r;
509 }
510}
511
f5098edb
RL
512END {
513 my $tb = Test::More->builder;
514 my $failure = scalar(grep { $_ == 0; } $tb->summary);
515 if ($failure && $end_with_bailout) {
516 BAIL_OUT("Stoptest!");
517 }
518}
519
520=head2 Utility functions
521
522The following functions are exported on request when using C<OpenSSL::Test>.
523
42e0ccdf
RL
524 # To only get the bldtop_file and srctop_file functions.
525 use OpenSSL::Test qw/bldtop_file srctop_file/;
f5098edb 526
42e0ccdf
RL
527 # To only get the bldtop_file function in addition to the default ones.
528 use OpenSSL::Test qw/:DEFAULT bldtop_file/;
f5098edb
RL
529
530=cut
531
532# Utility functions, exported on request
533
534=over 4
535
42e0ccdf 536=item B<bldtop_dir LIST>
f5098edb
RL
537
538LIST is a list of directories that make up a path from the top of the OpenSSL
42e0ccdf
RL
539build directory (as indicated by the environment variable C<$TOP> or
540C<$BLDTOP>).
541C<bldtop_dir> returns the resulting directory as a string, adapted to the local
f5098edb
RL
542operating system.
543
544=back
545
546=cut
547
42e0ccdf
RL
548sub bldtop_dir {
549 return __bldtop_dir(@_); # This caters for operating systems that have
f5098edb
RL
550 # a very distinct syntax for directories.
551}
552
553=over 4
554
42e0ccdf 555=item B<bldtop_file LIST, FILENAME>
f5098edb
RL
556
557LIST is a list of directories that make up a path from the top of the OpenSSL
42e0ccdf
RL
558build directory (as indicated by the environment variable C<$TOP> or
559C<$BLDTOP>) and FILENAME is the name of a file located in that directory path.
560C<bldtop_file> returns the resulting file path as a string, adapted to the local
f5098edb
RL
561operating system.
562
563=back
564
565=cut
566
42e0ccdf
RL
567sub bldtop_file {
568 return __bldtop_file(@_);
569}
570
571=over 4
572
573=item B<srctop_dir LIST>
574
575LIST is a list of directories that make up a path from the top of the OpenSSL
576source directory (as indicated by the environment variable C<$TOP> or
577C<$SRCTOP>).
578C<srctop_dir> returns the resulting directory as a string, adapted to the local
579operating system.
580
581=back
582
583=cut
584
585sub srctop_dir {
586 return __srctop_dir(@_); # This caters for operating systems that have
587 # a very distinct syntax for directories.
588}
589
590=over 4
591
592=item B<srctop_file LIST, FILENAME>
593
594LIST is a list of directories that make up a path from the top of the OpenSSL
595source directory (as indicated by the environment variable C<$TOP> or
596C<$SRCTOP>) and FILENAME is the name of a file located in that directory path.
597C<srctop_file> returns the resulting file path as a string, adapted to the local
598operating system.
599
600=back
601
602=cut
603
604sub srctop_file {
605 return __srctop_file(@_);
f5098edb
RL
606}
607
608=over 4
609
708a6a17
RL
610=item B<data_dir LIST>
611
612LIST is a list of directories that make up a path from the data directory
613associated with the test (see L</DESCRIPTION> above).
614C<data_dir> returns the resulting directory as a string, adapted to the local
615operating system.
616
617=back
618
619=cut
620
621sub data_dir {
622 return __data_dir(@_);
623}
624
625=over 4
626
6c6a2ae6
RL
627=item B<data_file LIST, FILENAME>
628
629LIST is a list of directories that make up a path from the data directory
630associated with the test (see L</DESCRIPTION> above) and FILENAME is the name
631of a file located in that directory path. C<data_file> returns the resulting
632file path as a string, adapted to the local operating system.
633
634=back
635
636=cut
637
638sub data_file {
639 return __data_file(@_);
640}
641
642=over 4
643
f5098edb
RL
644=item B<pipe LIST>
645
646LIST is a list of CODEREFs returned by C<app> or C<test>, from which C<pipe>
647creates a new command composed of all the given commands put together in a
648pipe. C<pipe> returns a new CODEREF in the same manner as C<app> or C<test>,
649to be passed to C<run> for execution.
650
651=back
652
653=cut
654
aec27d4d
RL
655sub pipe {
656 my @cmds = @_;
657 return
658 sub {
659 my @cs = ();
660 my @dcs = ();
661 my @els = ();
662 my $counter = 0;
663 foreach (@cmds) {
664 my ($c, $dc, @el) = $_->(++$counter);
665
666 return () if !$c;
667
668 push @cs, $c;
669 push @dcs, $dc;
670 push @els, @el;
671 }
672 return (
673 join(" | ", @cs),
674 join(" | ", @dcs),
675 @els
676 );
677 };
678}
679
f5098edb
RL
680=over 4
681
682=item B<with HASHREF, CODEREF>
683
46f4e1be 684C<with> will temporarily install hooks given by the HASHREF and then execute
f5098edb
RL
685the given CODEREF. Hooks are usually expected to have a coderef as value.
686
687The currently available hoosk are:
688
689=over 4
690
691=item B<exit_checker =E<gt> CODEREF>
692
693This hook is executed after C<run> has performed its given command. The
694CODEREF receives the exit code as only argument and is expected to return
6951 (if the exit code indicated success) or 0 (if the exit code indicated
696failure).
697
698=back
699
700=back
701
702=cut
703
704sub with {
705 my $opts = shift;
706 my %opts = %{$opts};
707 my $codeblock = shift;
708
709 my %saved_hooks = ();
710
711 foreach (keys %opts) {
712 $saved_hooks{$_} = $hooks{$_} if exists($hooks{$_});
713 $hooks{$_} = $opts{$_};
714 }
715
716 $codeblock->();
717
718 foreach (keys %saved_hooks) {
719 $hooks{$_} = $saved_hooks{$_};
720 }
721}
722
723=over 4
724
cb2ceb18 725=item B<cmdstr CODEREF, OPTS>
f5098edb
RL
726
727C<cmdstr> takes a CODEREF from C<app> or C<test> and simply returns the
728command as a string.
729
46f4e1be 730C<cmdstr> takes some additional options OPTS that affect the string returned:
cb2ceb18
RL
731
732=over 4
733
734=item B<display =E<gt> 0|1>
735
736When set to 0, the returned string will be with all decorations, such as a
737possible redirect of stderr to the null device. This is suitable if the
738string is to be used directly in a recipe.
739
740When set to 1, the returned string will be without extra decorations. This
741is suitable for display if that is desired (doesn't confuse people with all
742internal stuff), or if it's used to pass a command down to a subprocess.
743
744Default: 0
745
746=back
747
f5098edb
RL
748=back
749
750=cut
751
752sub cmdstr {
b843cdb1 753 my ($cmd, $display_cmd) = shift->(0);
cb2ceb18 754 my %opts = @_;
f5098edb 755
cb2ceb18
RL
756 if ($opts{display}) {
757 return $display_cmd;
758 } else {
759 return $cmd;
760 }
f5098edb
RL
761}
762
763=over 4
764
765=item B<quotify LIST>
766
767LIST is a list of strings that are going to be used as arguments for a
768command, and makes sure to inject quotes and escapes as necessary depending
769on the content of each string.
770
771This can also be used to put quotes around the executable of a command.
772I<This must never ever be done on VMS.>
773
774=back
775
776=cut
aec27d4d
RL
777
778sub quotify {
779 # Unix setup (default if nothing else is mentioned)
780 my $arg_formatter =
5845f7de
RL
781 sub { $_ = shift;
782 ($_ eq '' || /\s|[\{\}\\\$\[\]\*\?\|\&:;<>]/) ? "'$_'" : $_ };
aec27d4d
RL
783
784 if ( $^O eq "VMS") { # VMS setup
785 $arg_formatter = sub {
786 $_ = shift;
5845f7de 787 if ($_ eq '' || /\s|["[:upper:]]/) {
aec27d4d
RL
788 s/"/""/g;
789 '"'.$_.'"';
790 } else {
791 $_;
792 }
793 };
794 } elsif ( $^O eq "MSWin32") { # MSWin setup
795 $arg_formatter = sub {
796 $_ = shift;
5845f7de 797 if ($_ eq '' || /\s|["\|\&\*\;<>]/) {
aec27d4d
RL
798 s/(["\\])/\\$1/g;
799 '"'.$_.'"';
800 } else {
801 $_;
802 }
803 };
804 }
805
806 return map { $arg_formatter->($_) } @_;
807}
808
efe749c8
RL
809=over 4
810
811=item B<openssl_versions>
812
3a63dbef
RL
813Returns a list of two version numbers, the first representing the build
814version, the second representing the library version. See opensslv.h for
815more information on those numbers.
efe749c8 816
2dc37bc2 817=back
efe749c8
RL
818
819=cut
820
821my @versions = ();
822sub openssl_versions {
823 unless (@versions) {
824 my %lines =
825 map { s/\R$//;
3a63dbef
RL
826 /^(.*): (.*)$/;
827 $1 => $2 }
efe749c8
RL
828 run(test(['versions']), capture => 1);
829 @versions = ( $lines{'Build version'}, $lines{'Library version'} );
830 }
831 return @versions;
832}
833
f5098edb
RL
834######################################################################
835# private functions. These are never exported.
836
837=head1 ENVIRONMENT
838
839OpenSSL::Test depends on some environment variables.
840
841=over 4
842
843=item B<TOP>
844
845This environment variable is mandatory. C<setup> will check that it's
846defined and that it's a directory that contains the file C<Configure>.
847If this isn't so, C<setup> will C<BAIL_OUT>.
848
849=item B<BIN_D>
850
851If defined, its value should be the directory where the openssl application
852is located. Defaults to C<$TOP/apps> (adapted to the operating system).
853
854=item B<TEST_D>
855
856If defined, its value should be the directory where the test applications
857are located. Defaults to C<$TOP/test> (adapted to the operating system).
858
f5098edb
RL
859=item B<STOPTEST>
860
861If defined, it puts testing in a different mode, where a recipe with
862failures will result in a C<BAIL_OUT> at the end of its run.
863
864=back
865
866=cut
867
868sub __env {
6c6a2ae6
RL
869 (my $recipe_datadir = basename($0)) =~ s/\.t$/_data/i;
870
42e0ccdf
RL
871 $directories{SRCTOP} = $ENV{SRCTOP} || $ENV{TOP};
872 $directories{BLDTOP} = $ENV{BLDTOP} || $ENV{TOP};
fbd361ea
RL
873 $directories{BLDAPPS} = $ENV{BIN_D} || __bldtop_dir("apps");
874 $directories{SRCAPPS} = __srctop_dir("apps");
90d28f05
BL
875 $directories{BLDFUZZ} = __bldtop_dir("fuzz");
876 $directories{SRCFUZZ} = __srctop_dir("fuzz");
fbd361ea
RL
877 $directories{BLDTEST} = $ENV{TEST_D} || __bldtop_dir("test");
878 $directories{SRCTEST} = __srctop_dir("test");
6c6a2ae6
RL
879 $directories{SRCDATA} = __srctop_dir("test", "recipes",
880 $recipe_datadir);
fbd361ea 881 $directories{RESULTS} = $ENV{RESULT_D} || $directories{BLDTEST};
f5098edb 882
d1094383
RL
883 push @direnv, "TOP" if $ENV{TOP};
884 push @direnv, "SRCTOP" if $ENV{SRCTOP};
885 push @direnv, "BLDTOP" if $ENV{BLDTOP};
886 push @direnv, "BIN_D" if $ENV{BIN_D};
887 push @direnv, "TEST_D" if $ENV{TEST_D};
888 push @direnv, "RESULT_D" if $ENV{RESULT_D};
889
f5098edb
RL
890 $end_with_bailout = $ENV{STOPTEST} ? 1 : 0;
891};
892
28e0f6eb
RL
893# __srctop_file and __srctop_dir are helpers to build file and directory
894# names on top of the source directory. They depend on $SRCTOP, and
895# therefore on the proper use of setup() and when needed, indir().
896# __bldtop_file and __bldtop_dir do the same thing but relative to $BLDTOP.
897# __srctop_file and __bldtop_file take the same kind of argument as
898# File::Spec::Functions::catfile.
899# Similarly, __srctop_dir and __bldtop_dir take the same kind of argument
900# as File::Spec::Functions::catdir
42e0ccdf
RL
901sub __srctop_file {
902 BAIL_OUT("Must run setup() first") if (! $test_name);
903
904 my $f = pop;
905 return catfile($directories{SRCTOP},@_,$f);
906}
907
908sub __srctop_dir {
909 BAIL_OUT("Must run setup() first") if (! $test_name);
910
911 return catdir($directories{SRCTOP},@_);
912}
913
914sub __bldtop_file {
f5098edb
RL
915 BAIL_OUT("Must run setup() first") if (! $test_name);
916
917 my $f = pop;
42e0ccdf 918 return catfile($directories{BLDTOP},@_,$f);
f5098edb
RL
919}
920
42e0ccdf 921sub __bldtop_dir {
4ada8be2
AP
922 BAIL_OUT("Must run setup() first") if (! $test_name);
923
42e0ccdf 924 return catdir($directories{BLDTOP},@_);
4ada8be2
AP
925}
926
28e0f6eb
RL
927# __exeext is a function that returns the platform dependent file extension
928# for executable binaries, or the value of the environment variable $EXE_EXT
929# if that one is defined.
d8a52304
RL
930sub __exeext {
931 my $ext = "";
932 if ($^O eq "VMS" ) { # VMS
933 $ext = ".exe";
934 } elsif ($^O eq "MSWin32") { # Windows
935 $ext = ".exe";
936 }
937 return $ENV{"EXE_EXT"} || $ext;
938}
939
28e0f6eb
RL
940# __test_file, __apps_file and __fuzz_file return the full path to a file
941# relative to the test/, apps/ or fuzz/ directory in the build tree or the
942# source tree, depending on where the file is found. Note that when looking
943# in the build tree, the file name with an added extension is looked for, if
944# an extension is given. The intent is to look for executable binaries (in
945# the build tree) or possibly scripts (in the source tree).
946# These functions all take the same arguments as File::Spec::Functions::catfile,
947# *plus* a mandatory extension argument. This extension argument can be undef,
948# and is ignored in such a case.
f5098edb
RL
949sub __test_file {
950 BAIL_OUT("Must run setup() first") if (! $test_name);
951
9ddf67f3 952 my $e = pop || "";
3732f12c 953 my $f = pop;
9b9a8a71
RL
954 my $out = catfile($directories{BLDTEST},@_,$f . $e);
955 $out = catfile($directories{SRCTEST},@_,$f) unless -f $out;
956 return $out;
a00c84f6
RL
957}
958
f5098edb
RL
959sub __apps_file {
960 BAIL_OUT("Must run setup() first") if (! $test_name);
961
9ddf67f3 962 my $e = pop || "";
3732f12c 963 my $f = pop;
9b9a8a71
RL
964 my $out = catfile($directories{BLDAPPS},@_,$f . $e);
965 $out = catfile($directories{SRCAPPS},@_,$f) unless -f $out;
966 return $out;
f5098edb
RL
967}
968
90d28f05
BL
969sub __fuzz_file {
970 BAIL_OUT("Must run setup() first") if (! $test_name);
971
9ddf67f3 972 my $e = pop || "";
90d28f05 973 my $f = pop;
9b9a8a71
RL
974 my $out = catfile($directories{BLDFUZZ},@_,$f . $e);
975 $out = catfile($directories{SRCFUZZ},@_,$f) unless -f $out;
976 return $out;
90d28f05
BL
977}
978
6c6a2ae6
RL
979sub __data_file {
980 BAIL_OUT("Must run setup() first") if (! $test_name);
981
982 my $f = pop;
983 return catfile($directories{SRCDATA},@_,$f);
984}
985
708a6a17
RL
986sub __data_dir {
987 BAIL_OUT("Must run setup() first") if (! $test_name);
988
989 return catdir($directories{SRCDATA},@_);
990}
991
f5098edb
RL
992sub __results_file {
993 BAIL_OUT("Must run setup() first") if (! $test_name);
994
995 my $f = pop;
996 return catfile($directories{RESULTS},@_,$f);
997}
998
28e0f6eb
RL
999# __cwd DIR
1000# __cwd DIR, OPTS
1001#
1002# __cwd changes directory to DIR (string) and changes all the relative
1003# entries in %directories accordingly. OPTS is an optional series of
1004# hash style arguments to alter __cwd's behavior:
1005#
1006# create = 0|1 The directory we move to is created if 1, not if 0.
1007# cleanup = 0|1 The directory we move from is removed if 1, not if 0.
1008
f5098edb 1009sub __cwd {
11b3313c 1010 my $dir = catdir(shift);
f5098edb
RL
1011 my %opts = @_;
1012 my $abscurdir = rel2abs(curdir());
1013 my $absdir = rel2abs($dir);
1014 my $reverse = abs2rel($abscurdir, $absdir);
1015
1016 # PARANOIA: if we're not moving anywhere, we do nothing more
1017 if ($abscurdir eq $absdir) {
1018 return $reverse;
1019 }
1020
1021 # Do not support a move to a different volume for now. Maybe later.
1022 BAIL_OUT("FAILURE: \"$dir\" moves to a different volume, not supported")
1023 if $reverse eq $abscurdir;
1024
1025 # If someone happened to give a directory that leads back to the current,
1026 # it's extremely silly to do anything more, so just simulate that we did
1027 # move.
1028 # In this case, we won't even clean it out, for safety's sake.
1029 return "." if $reverse eq "";
1030
1031 $dir = canonpath($dir);
1032 if ($opts{create}) {
1033 mkpath($dir);
1034 }
1035
3da9eeb1
RL
1036 # We are recalculating the directories we keep track of, but need to save
1037 # away the result for after having moved into the new directory.
1038 my %tmp_directories = ();
1039 my %tmp_ENV = ();
f5098edb
RL
1040
1041 # For each of these directory variables, figure out where they are relative
1042 # to the directory we want to move to if they aren't absolute (if they are,
1043 # they don't change!)
42e0ccdf 1044 my @dirtags = sort keys %directories;
f5098edb
RL
1045 foreach (@dirtags) {
1046 if (!file_name_is_absolute($directories{$_})) {
1047 my $newpath = abs2rel(rel2abs($directories{$_}), rel2abs($dir));
3da9eeb1 1048 $tmp_directories{$_} = $newpath;
f5098edb
RL
1049 }
1050 }
1051
d1094383
RL
1052 # Treat each environment variable that was used to get us the values in
1053 # %directories the same was as the paths in %directories, so any sub
1054 # process can use their values properly as well
1055 foreach (@direnv) {
1056 if (!file_name_is_absolute($ENV{$_})) {
1057 my $newpath = abs2rel(rel2abs($ENV{$_}), rel2abs($dir));
3da9eeb1 1058 $tmp_ENV{$_} = $newpath;
d1094383
RL
1059 }
1060 }
1061
3da9eeb1
RL
1062 # Should we just bail out here as well? I'm unsure.
1063 return undef unless chdir($dir);
1064
1065 if ($opts{cleanup}) {
1066 rmtree(".", { safe => 0, keep_root => 1 });
1067 }
1068
768a3eca 1069 # We put back new values carefully. Doing the obvious
46f4e1be 1070 # %directories = ( %tmp_directories )
768a3eca
RL
1071 # will clear out any value that happens to be an absolute path
1072 foreach (keys %tmp_directories) {
1073 $directories{$_} = $tmp_directories{$_};
1074 }
3da9eeb1
RL
1075 foreach (keys %tmp_ENV) {
1076 $ENV{$_} = $tmp_ENV{$_};
1077 }
1078
a00c84f6 1079 if ($debug) {
f5098edb 1080 print STDERR "DEBUG: __cwd(), directories and files:\n";
fbd361ea
RL
1081 print STDERR " \$directories{BLDTEST} = \"$directories{BLDTEST}\"\n";
1082 print STDERR " \$directories{SRCTEST} = \"$directories{SRCTEST}\"\n";
6c6a2ae6 1083 print STDERR " \$directories{SRCDATA} = \"$directories{SRCDATA}\"\n";
f5098edb 1084 print STDERR " \$directories{RESULTS} = \"$directories{RESULTS}\"\n";
fbd361ea
RL
1085 print STDERR " \$directories{BLDAPPS} = \"$directories{BLDAPPS}\"\n";
1086 print STDERR " \$directories{SRCAPPS} = \"$directories{SRCAPPS}\"\n";
42e0ccdf
RL
1087 print STDERR " \$directories{SRCTOP} = \"$directories{SRCTOP}\"\n";
1088 print STDERR " \$directories{BLDTOP} = \"$directories{BLDTOP}\"\n";
f5098edb
RL
1089 print STDERR "\n";
1090 print STDERR " current directory is \"",curdir(),"\"\n";
1091 print STDERR " the way back is \"$reverse\"\n";
1092 }
1093
1094 return $reverse;
1095}
1096
9ddf67f3
RL
1097# __wrap_cmd CMD
1098# __wrap_cmd CMD, EXE_SHELL
1099#
1100# __wrap_cmd "wraps" CMD (string) with a beginning command that makes sure
1101# the command gets executed with an appropriate environment. If EXE_SHELL
1102# is given, it is used as the beginning command.
1103#
1104# __wrap_cmd returns a list that should be used to build up a larger list
1105# of command tokens, or be joined together like this:
1106#
1107# join(" ", __wrap_cmd($cmd))
1108sub __wrap_cmd {
1109 my $cmd = shift;
ec307bcc 1110 my $exe_shell = shift;
f5098edb 1111
9ddf67f3 1112 my @prefix = ( __bldtop_file("util", "shlib_wrap.sh") );
f5098edb 1113
9ddf67f3
RL
1114 if(defined($exe_shell)) {
1115 @prefix = ( $exe_shell );
1116 } elsif ($^O eq "VMS" || $^O eq "MSWin32") {
1117 # VMS and Windows don't use any wrapper script for the moment
1118 @prefix = ();
1119 }
1120
1121 return (@prefix, $cmd);
1122}
1123
1124# __fixup_prg PROG
1125#
1126# __fixup_prg does whatever fixup is needed to execute an executable binary
1127# given by PROG (string).
1128#
1129# __fixup_prg returns a string with the possibly prefixed program path spec.
1130sub __fixup_prg {
1131 my $prog = shift;
1132
1133 my $prefix = "";
1134
1135 if ($^O eq "VMS" ) {
c10d1bc8 1136 $prefix = ($prog =~ /^(?:[\$a-z0-9_]+:)?[<\[]/i ? "mcr " : "mcr []");
f5098edb
RL
1137 }
1138
a00c84f6
RL
1139 if (defined($prog)) {
1140 # Make sure to quotify the program file on platforms that may
1141 # have spaces or similar in their path name.
1142 # To our knowledge, VMS is the exception where quotifying should
69687aa8 1143 # never happen.
a00c84f6
RL
1144 ($prog) = quotify($prog) unless $^O eq "VMS";
1145 return $prefix.$prog;
f5098edb
RL
1146 }
1147
1148 print STDERR "$prog not found\n";
1149 return undef;
1150}
1151
28e0f6eb
RL
1152# __decorate_cmd NUM, CMDARRAYREF
1153#
1154# __decorate_cmd takes a command number NUM and a command token array
1155# CMDARRAYREF, builds up a command string from them and decorates it
1156# with necessary redirections.
1157# __decorate_cmd returns a list of two strings, one with the command
1158# string to actually be used, the other to be displayed for the user.
1159# The reason these strings might differ is that we redirect stderr to
1160# the null device unless we're verbose and unless the user has
1161# explicitly specified a stderr redirection.
9ddf67f3 1162sub __decorate_cmd {
f5098edb
RL
1163 BAIL_OUT("Must run setup() first") if (! $test_name);
1164
1165 my $num = shift;
9ddf67f3 1166 my $cmd = shift;
b8fcd4f0 1167 my %opts = @_;
a00c84f6 1168
9ddf67f3 1169 my $cmdstr = join(" ", @$cmd);
f5098edb 1170 my $null = devnull();
f5098edb
RL
1171 my $fileornull = sub { $_[0] ? $_[0] : $null; };
1172 my $stdin = "";
1173 my $stdout = "";
1174 my $stderr = "";
1175 my $saved_stderr = undef;
1176 $stdin = " < ".$fileornull->($opts{stdin}) if exists($opts{stdin});
1177 $stdout= " > ".$fileornull->($opts{stdout}) if exists($opts{stdout});
1178 $stderr=" 2> ".$fileornull->($opts{stderr}) if exists($opts{stderr});
1179
9ddf67f3 1180 my $display_cmd = "$cmdstr$stdin$stdout$stderr";
b843cdb1
RL
1181
1182 $stderr=" 2> ".$null
1183 unless $stderr || !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE};
1184
9ddf67f3 1185 $cmdstr .= "$stdin$stdout$stderr";
f5098edb 1186
a00c84f6 1187 if ($debug) {
9ddf67f3
RL
1188 print STDERR "DEBUG[__decorate_cmd]: \$cmdstr = \"$cmdstr\"\n";
1189 print STDERR "DEBUG[__decorate_cmd]: \$display_cmd = \"$display_cmd\"\n";
a00c84f6
RL
1190 }
1191
9ddf67f3 1192 return ($cmdstr, $display_cmd);
f5098edb
RL
1193}
1194
1195=head1 SEE ALSO
1196
1197L<Test::More>, L<Test::Harness>
1198
1199=head1 AUTHORS
1200
e3713c36 1201Richard Levitte E<lt>levitte@openssl.orgE<gt> with assistance and
f5098edb
RL
1202inspiration from Andy Polyakov E<lt>appro@openssl.org<gt>.
1203
1204=cut
1205
208d721a
RL
1206no warnings 'redefine';
1207sub subtest {
1208 $level++;
1209
1210 Test::More::subtest @_;
1211
1212 $level--;
1213};
1214
aec27d4d 12151;