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