2
0

Test.pm 35 KB

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