2
0

Test.pm 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. # Copyright 2016-2020 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. use Cwd qw/getcwd abs_path/;
  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 perceives 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 perceives 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 numbers, the first representing the build version,
  591. the second representing the library version. See opensslv.h for more
  592. 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. /^(.*): (0x[[:xdigit:]]{8})$/;
  601. die "Weird line: $_" unless defined $1;
  602. $1 => hex($2) }
  603. run(test(['versions']), capture => 1);
  604. @versions = ( $lines{'Build version'}, $lines{'Library version'} );
  605. }
  606. return @versions;
  607. }
  608. ######################################################################
  609. # private functions. These are never exported.
  610. =head1 ENVIRONMENT
  611. OpenSSL::Test depends on some environment variables.
  612. =over 4
  613. =item B<TOP>
  614. This environment variable is mandatory. C<setup> will check that it's
  615. defined and that it's a directory that contains the file C<Configure>.
  616. If this isn't so, C<setup> will C<BAIL_OUT>.
  617. =item B<BIN_D>
  618. If defined, its value should be the directory where the openssl application
  619. is located. Defaults to C<$TOP/apps> (adapted to the operating system).
  620. =item B<TEST_D>
  621. If defined, its value should be the directory where the test applications
  622. are located. Defaults to C<$TOP/test> (adapted to the operating system).
  623. =item B<STOPTEST>
  624. If defined, it puts testing in a different mode, where a recipe with
  625. failures will result in a C<BAIL_OUT> at the end of its run.
  626. =back
  627. =cut
  628. sub __env {
  629. (my $recipe_datadir = basename($0)) =~ s/\.t$/_data/i;
  630. $directories{SRCTOP} = abs_path($ENV{SRCTOP} || $ENV{TOP});
  631. $directories{BLDTOP} = abs_path($ENV{BLDTOP} || $ENV{TOP});
  632. $directories{BLDAPPS} = $ENV{BIN_D} || __bldtop_dir("apps");
  633. $directories{SRCAPPS} = __srctop_dir("apps");
  634. $directories{BLDFUZZ} = __bldtop_dir("fuzz");
  635. $directories{SRCFUZZ} = __srctop_dir("fuzz");
  636. $directories{BLDTEST} = $ENV{TEST_D} || __bldtop_dir("test");
  637. $directories{SRCTEST} = __srctop_dir("test");
  638. $directories{SRCDATA} = __srctop_dir("test", "recipes",
  639. $recipe_datadir);
  640. $directories{RESULTS} = $ENV{RESULT_D} || $directories{BLDTEST};
  641. push @direnv, "TOP" if $ENV{TOP};
  642. push @direnv, "SRCTOP" if $ENV{SRCTOP};
  643. push @direnv, "BLDTOP" if $ENV{BLDTOP};
  644. push @direnv, "BIN_D" if $ENV{BIN_D};
  645. push @direnv, "TEST_D" if $ENV{TEST_D};
  646. push @direnv, "RESULT_D" if $ENV{RESULT_D};
  647. $end_with_bailout = $ENV{STOPTEST} ? 1 : 0;
  648. };
  649. # __srctop_file and __srctop_dir are helpers to build file and directory
  650. # names on top of the source directory. They depend on $SRCTOP, and
  651. # therefore on the proper use of setup() and when needed, indir().
  652. # __bldtop_file and __bldtop_dir do the same thing but relative to $BLDTOP.
  653. # __srctop_file and __bldtop_file take the same kind of argument as
  654. # File::Spec::Functions::catfile.
  655. # Similarly, __srctop_dir and __bldtop_dir take the same kind of argument
  656. # as File::Spec::Functions::catdir
  657. sub __srctop_file {
  658. BAIL_OUT("Must run setup() first") if (! $test_name);
  659. my $f = pop;
  660. return abs2rel(catfile($directories{SRCTOP},@_,$f),getcwd);
  661. }
  662. sub __srctop_dir {
  663. BAIL_OUT("Must run setup() first") if (! $test_name);
  664. return abs2rel(catdir($directories{SRCTOP},@_), getcwd);
  665. }
  666. sub __bldtop_file {
  667. BAIL_OUT("Must run setup() first") if (! $test_name);
  668. my $f = pop;
  669. return abs2rel(catfile($directories{BLDTOP},@_,$f), getcwd);
  670. }
  671. sub __bldtop_dir {
  672. BAIL_OUT("Must run setup() first") if (! $test_name);
  673. return abs2rel(catdir($directories{BLDTOP},@_), getcwd);
  674. }
  675. # __exeext is a function that returns the platform dependent file extension
  676. # for executable binaries, or the value of the environment variable $EXE_EXT
  677. # if that one is defined.
  678. sub __exeext {
  679. my $ext = "";
  680. if ($^O eq "VMS" ) { # VMS
  681. $ext = ".exe";
  682. } elsif ($^O eq "MSWin32") { # Windows
  683. $ext = ".exe";
  684. }
  685. return $ENV{"EXE_EXT"} || $ext;
  686. }
  687. # __test_file, __apps_file and __fuzz_file return the full path to a file
  688. # relative to the test/, apps/ or fuzz/ directory in the build tree or the
  689. # source tree, depending on where the file is found. Note that when looking
  690. # in the build tree, the file name with an added extension is looked for, if
  691. # an extension is given. The intent is to look for executable binaries (in
  692. # the build tree) or possibly scripts (in the source tree).
  693. # These functions all take the same arguments as File::Spec::Functions::catfile,
  694. # *plus* a mandatory extension argument. This extension argument can be undef,
  695. # and is ignored in such a case.
  696. sub __test_file {
  697. BAIL_OUT("Must run setup() first") if (! $test_name);
  698. my $e = pop || "";
  699. my $f = pop;
  700. my $out = catfile($directories{BLDTEST},@_,$f . $e);
  701. $out = catfile($directories{SRCTEST},@_,$f) unless -f $out;
  702. return $out;
  703. }
  704. sub __apps_file {
  705. BAIL_OUT("Must run setup() first") if (! $test_name);
  706. my $e = pop || "";
  707. my $f = pop;
  708. my $out = catfile($directories{BLDAPPS},@_,$f . $e);
  709. $out = catfile($directories{SRCAPPS},@_,$f) unless -f $out;
  710. return $out;
  711. }
  712. sub __fuzz_file {
  713. BAIL_OUT("Must run setup() first") if (! $test_name);
  714. my $e = pop || "";
  715. my $f = pop;
  716. my $out = catfile($directories{BLDFUZZ},@_,$f . $e);
  717. $out = catfile($directories{SRCFUZZ},@_,$f) unless -f $out;
  718. return $out;
  719. }
  720. sub __data_file {
  721. BAIL_OUT("Must run setup() first") if (! $test_name);
  722. my $f = pop;
  723. return catfile($directories{SRCDATA},@_,$f);
  724. }
  725. sub __data_dir {
  726. BAIL_OUT("Must run setup() first") if (! $test_name);
  727. return catdir($directories{SRCDATA},@_);
  728. }
  729. sub __results_file {
  730. BAIL_OUT("Must run setup() first") if (! $test_name);
  731. my $f = pop;
  732. return catfile($directories{RESULTS},@_,$f);
  733. }
  734. # __cwd DIR
  735. # __cwd DIR, OPTS
  736. #
  737. # __cwd changes directory to DIR (string) and changes all the relative
  738. # entries in %directories accordingly. OPTS is an optional series of
  739. # hash style arguments to alter __cwd's behavior:
  740. #
  741. # create = 0|1 The directory we move to is created if 1, not if 0.
  742. # cleanup = 0|1 The directory we move from is removed if 1, not if 0.
  743. sub __cwd {
  744. my $dir = catdir(shift);
  745. my %opts = @_;
  746. my $abscurdir = rel2abs(curdir());
  747. my $absdir = rel2abs($dir);
  748. my $reverse = abs2rel($abscurdir, $absdir);
  749. # PARANOIA: if we're not moving anywhere, we do nothing more
  750. if ($abscurdir eq $absdir) {
  751. return $reverse;
  752. }
  753. # Do not support a move to a different volume for now. Maybe later.
  754. BAIL_OUT("FAILURE: \"$dir\" moves to a different volume, not supported")
  755. if $reverse eq $abscurdir;
  756. # If someone happened to give a directory that leads back to the current,
  757. # it's extremely silly to do anything more, so just simulate that we did
  758. # move.
  759. # In this case, we won't even clean it out, for safety's sake.
  760. return "." if $reverse eq "";
  761. $dir = canonpath($dir);
  762. if ($opts{create}) {
  763. mkpath($dir);
  764. }
  765. # We are recalculating the directories we keep track of, but need to save
  766. # away the result for after having moved into the new directory.
  767. my %tmp_directories = ();
  768. my %tmp_ENV = ();
  769. # For each of these directory variables, figure out where they are relative
  770. # to the directory we want to move to if they aren't absolute (if they are,
  771. # they don't change!)
  772. my @dirtags = sort keys %directories;
  773. foreach (@dirtags) {
  774. if (!file_name_is_absolute($directories{$_})) {
  775. my $newpath = abs2rel(rel2abs($directories{$_}), rel2abs($dir));
  776. $tmp_directories{$_} = $newpath;
  777. }
  778. }
  779. # Treat each environment variable that was used to get us the values in
  780. # %directories the same was as the paths in %directories, so any sub
  781. # process can use their values properly as well
  782. foreach (@direnv) {
  783. if (!file_name_is_absolute($ENV{$_})) {
  784. my $newpath = abs2rel(rel2abs($ENV{$_}), rel2abs($dir));
  785. $tmp_ENV{$_} = $newpath;
  786. }
  787. }
  788. # Should we just bail out here as well? I'm unsure.
  789. return undef unless chdir($dir);
  790. if ($opts{cleanup}) {
  791. rmtree(".", { safe => 0, keep_root => 1 });
  792. }
  793. # We put back new values carefully. Doing the obvious
  794. # %directories = ( %tmp_directories )
  795. # will clear out any value that happens to be an absolute path
  796. foreach (keys %tmp_directories) {
  797. $directories{$_} = $tmp_directories{$_};
  798. }
  799. foreach (keys %tmp_ENV) {
  800. $ENV{$_} = $tmp_ENV{$_};
  801. }
  802. if ($debug) {
  803. print STDERR "DEBUG: __cwd(), directories and files:\n";
  804. print STDERR " \$directories{BLDTEST} = \"$directories{BLDTEST}\"\n";
  805. print STDERR " \$directories{SRCTEST} = \"$directories{SRCTEST}\"\n";
  806. print STDERR " \$directories{SRCDATA} = \"$directories{SRCDATA}\"\n";
  807. print STDERR " \$directories{RESULTS} = \"$directories{RESULTS}\"\n";
  808. print STDERR " \$directories{BLDAPPS} = \"$directories{BLDAPPS}\"\n";
  809. print STDERR " \$directories{SRCAPPS} = \"$directories{SRCAPPS}\"\n";
  810. print STDERR " \$directories{SRCTOP} = \"$directories{SRCTOP}\"\n";
  811. print STDERR " \$directories{BLDTOP} = \"$directories{BLDTOP}\"\n";
  812. print STDERR "\n";
  813. print STDERR " current directory is \"",curdir(),"\"\n";
  814. print STDERR " the way back is \"$reverse\"\n";
  815. }
  816. return $reverse;
  817. }
  818. # __wrap_cmd CMD
  819. # __wrap_cmd CMD, EXE_SHELL
  820. #
  821. # __wrap_cmd "wraps" CMD (string) with a beginning command that makes sure
  822. # the command gets executed with an appropriate environment. If EXE_SHELL
  823. # is given, it is used as the beginning command.
  824. #
  825. # __wrap_cmd returns a list that should be used to build up a larger list
  826. # of command tokens, or be joined together like this:
  827. #
  828. # join(" ", __wrap_cmd($cmd))
  829. sub __wrap_cmd {
  830. my $cmd = shift;
  831. my $exe_shell = shift;
  832. my @prefix = ( __bldtop_file("util", "shlib_wrap.sh") );
  833. if(defined($exe_shell)) {
  834. @prefix = ( $exe_shell );
  835. } elsif ($^O eq "VMS" || $^O eq "MSWin32") {
  836. # VMS and Windows don't use any wrapper script for the moment
  837. @prefix = ();
  838. }
  839. return (@prefix, $cmd);
  840. }
  841. # __fixup_prg PROG
  842. #
  843. # __fixup_prg does whatever fixup is needed to execute an executable binary
  844. # given by PROG (string).
  845. #
  846. # __fixup_prg returns a string with the possibly prefixed program path spec.
  847. sub __fixup_prg {
  848. my $prog = shift;
  849. my $prefix = "";
  850. if ($^O eq "VMS" ) {
  851. $prefix = ($prog =~ /^(?:[\$a-z0-9_]+:)?[<\[]/i ? "mcr " : "mcr []");
  852. }
  853. if (defined($prog)) {
  854. # Make sure to quotify the program file on platforms that may
  855. # have spaces or similar in their path name.
  856. # To our knowledge, VMS is the exception where quotifying should
  857. # never happen.
  858. ($prog) = quotify($prog) unless $^O eq "VMS";
  859. return $prefix.$prog;
  860. }
  861. print STDERR "$prog not found\n";
  862. return undef;
  863. }
  864. # __decorate_cmd NUM, CMDARRAYREF
  865. #
  866. # __decorate_cmd takes a command number NUM and a command token array
  867. # CMDARRAYREF, builds up a command string from them and decorates it
  868. # with necessary redirections.
  869. # __decorate_cmd returns a list of two strings, one with the command
  870. # string to actually be used, the other to be displayed for the user.
  871. # The reason these strings might differ is that we redirect stderr to
  872. # the null device unless we're verbose and unless the user has
  873. # explicitly specified a stderr redirection.
  874. sub __decorate_cmd {
  875. BAIL_OUT("Must run setup() first") if (! $test_name);
  876. my $num = shift;
  877. my $cmd = shift;
  878. my %opts = @_;
  879. my $cmdstr = join(" ", @$cmd);
  880. my $null = devnull();
  881. my $fileornull = sub { $_[0] ? $_[0] : $null; };
  882. my $stdin = "";
  883. my $stdout = "";
  884. my $stderr = "";
  885. my $saved_stderr = undef;
  886. $stdin = " < ".$fileornull->($opts{stdin}) if exists($opts{stdin});
  887. $stdout= " > ".$fileornull->($opts{stdout}) if exists($opts{stdout});
  888. $stderr=" 2> ".$fileornull->($opts{stderr}) if exists($opts{stderr});
  889. my $display_cmd = "$cmdstr$stdin$stdout$stderr";
  890. $stderr=" 2> ".$null
  891. unless $stderr || !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE};
  892. $cmdstr .= "$stdin$stdout$stderr";
  893. if ($debug) {
  894. print STDERR "DEBUG[__decorate_cmd]: \$cmdstr = \"$cmdstr\"\n";
  895. print STDERR "DEBUG[__decorate_cmd]: \$display_cmd = \"$display_cmd\"\n";
  896. }
  897. return ($cmdstr, $display_cmd);
  898. }
  899. =head1 SEE ALSO
  900. L<Test::More>, L<Test::Harness>
  901. =head1 AUTHORS
  902. Richard Levitte E<lt>levitte@openssl.orgE<gt> with assistance and
  903. inspiration from Andy Polyakov E<lt>appro@openssl.org<gt>.
  904. =cut
  905. no warnings 'redefine';
  906. sub subtest {
  907. $level++;
  908. Test::More::subtest @_;
  909. $level--;
  910. };
  911. 1;