Test.pm 33 KB

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