diff --git a/contrib/atf/atf-c/atf-c.3 b/contrib/atf/atf-c/atf-c.3 index d7aa8c382dff..c38e068bb380 100644 --- a/contrib/atf/atf-c/atf-c.3 +++ b/contrib/atf/atf-c/atf-c.3 @@ -1,793 +1,810 @@ .\" Copyright (c) 2008 The NetBSD Foundation, Inc. .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND .\" CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, .\" INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF .\" MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. .\" IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY .\" DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE .\" GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER .\" IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR .\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN .\" IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -.Dd April 5, 2017 +.Dd February 23, 2021 .Dt ATF-C 3 .Os .Sh NAME .Nm atf-c , .Nm ATF_CHECK , .Nm ATF_CHECK_MSG , .Nm ATF_CHECK_EQ , .Nm ATF_CHECK_EQ_MSG , .Nm ATF_CHECK_MATCH , .Nm ATF_CHECK_MATCH_MSG , .Nm ATF_CHECK_STREQ , .Nm ATF_CHECK_STREQ_MSG , +.Nm ATF_CHECK_INTEQ , +.Nm ATF_CHECK_INTEQ_MSG , .Nm ATF_CHECK_ERRNO , .Nm ATF_REQUIRE , .Nm ATF_REQUIRE_MSG , .Nm ATF_REQUIRE_EQ , .Nm ATF_REQUIRE_EQ_MSG , .Nm ATF_REQUIRE_MATCH , .Nm ATF_REQUIRE_MATCH_MSG , .Nm ATF_REQUIRE_STREQ , .Nm ATF_REQUIRE_STREQ_MSG , +.Nm ATF_REQUIRE_INTEQ , +.Nm ATF_REQUIRE_INTEQ_MSG , .Nm ATF_REQUIRE_ERRNO , .Nm ATF_TC , .Nm ATF_TC_BODY , .Nm ATF_TC_BODY_NAME , .Nm ATF_TC_CLEANUP , .Nm ATF_TC_CLEANUP_NAME , .Nm ATF_TC_HEAD , .Nm ATF_TC_HEAD_NAME , .Nm ATF_TC_NAME , .Nm ATF_TC_WITH_CLEANUP , .Nm ATF_TC_WITHOUT_HEAD , .Nm ATF_TP_ADD_TC , .Nm ATF_TP_ADD_TCS , .Nm atf_tc_get_config_var , .Nm atf_tc_get_config_var_wd , .Nm atf_tc_get_config_var_as_bool , .Nm atf_tc_get_config_var_as_bool_wd , .Nm atf_tc_get_config_var_as_long , .Nm atf_tc_get_config_var_as_long_wd , .Nm atf_no_error , .Nm atf_tc_expect_death , .Nm atf_tc_expect_exit , .Nm atf_tc_expect_fail , .Nm atf_tc_expect_pass , .Nm atf_tc_expect_signal , .Nm atf_tc_expect_timeout , .Nm atf_tc_fail , .Nm atf_tc_fail_nonfatal , .Nm atf_tc_pass , .Nm atf_tc_skip , .Nm atf_utils_cat_file , .Nm atf_utils_compare_file , .Nm atf_utils_copy_file , .Nm atf_utils_create_file , .Nm atf_utils_file_exists , .Nm atf_utils_fork , .Nm atf_utils_free_charpp , .Nm atf_utils_grep_file , .Nm atf_utils_grep_string , .Nm atf_utils_readline , .Nm atf_utils_redirect , .Nm atf_utils_wait .Nd C API to write ATF-based test programs .Sh SYNOPSIS .In atf-c.h .\" NO_CHECK_STYLE_BEGIN .Fn ATF_CHECK "expression" .Fn ATF_CHECK_MSG "expression" "fail_msg_fmt" ... .Fn ATF_CHECK_EQ "expected_expression" "actual_expression" .Fn ATF_CHECK_EQ_MSG "expected_expression" "actual_expression" "fail_msg_fmt" ... .Fn ATF_CHECK_MATCH "regexp" "string" .Fn ATF_CHECK_MATCH_MSG "regexp" "string" "fail_msg_fmt" ... -.Fn ATF_CHECK_STREQ "string_1" "string_2" -.Fn ATF_CHECK_STREQ_MSG "string_1" "string_2" "fail_msg_fmt" ... +.Fn ATF_CHECK_STREQ "expected_string" "actual_string" +.Fn ATF_CHECK_STREQ_MSG "expected_string" "actual_string" "fail_msg_fmt" ... +.Fn ATF_CHECK_INTEQ "expected_int" "actual_int" +.Fn ATF_CHECK_INTEQ_MSG "expected_int" "actual_int" "fail_msg_fmt" ... .Fn ATF_CHECK_ERRNO "expected_errno" "bool_expression" .Fn ATF_REQUIRE "expression" .Fn ATF_REQUIRE_MSG "expression" "fail_msg_fmt" ... .Fn ATF_REQUIRE_EQ "expected_expression" "actual_expression" .Fn ATF_REQUIRE_EQ_MSG "expected_expression" "actual_expression" "fail_msg_fmt" ... .Fn ATF_REQUIRE_MATCH "regexp" "string" .Fn ATF_REQUIRE_MATCH_MSG "regexp" "string" "fail_msg_fmt" ... .Fn ATF_REQUIRE_STREQ "expected_string" "actual_string" .Fn ATF_REQUIRE_STREQ_MSG "expected_string" "actual_string" "fail_msg_fmt" ... +.Fn ATF_REQUIRE_INTEQ "expected_int" "actual_int" +.Fn ATF_REQUIRE_INTEQ_MSG "expected_int" "actual_int" "fail_msg_fmt" ... .Fn ATF_REQUIRE_ERRNO "expected_errno" "bool_expression" .\" NO_CHECK_STYLE_END .Fn ATF_TC "name" .Fn ATF_TC_BODY "name" "tc" .Fn ATF_TC_BODY_NAME "name" .Fn ATF_TC_CLEANUP "name" "tc" .Fn ATF_TC_CLEANUP_NAME "name" .Fn ATF_TC_HEAD "name" "tc" .Fn ATF_TC_HEAD_NAME "name" .Fn ATF_TC_NAME "name" .Fn ATF_TC_WITH_CLEANUP "name" .Fn ATF_TC_WITHOUT_HEAD "name" .Fn ATF_TP_ADD_TC "tp_name" "tc_name" .Fn ATF_TP_ADD_TCS "tp_name" .Fn atf_tc_get_config_var "tc" "varname" .Fn atf_tc_get_config_var_wd "tc" "variable_name" "default_value" .Fn atf_tc_get_config_var_as_bool "tc" "variable_name" .Fn atf_tc_get_config_var_as_bool_wd "tc" "variable_name" "default_value" .Fn atf_tc_get_config_var_as_long "tc" "variable_name" .Fn atf_tc_get_config_var_as_long_wd "tc" "variable_name" "default_value" .Fn atf_no_error .Fn atf_tc_expect_death "reason" "..." .Fn atf_tc_expect_exit "exitcode" "reason" "..." .Fn atf_tc_expect_fail "reason" "..." .Fn atf_tc_expect_pass .Fn atf_tc_expect_signal "signo" "reason" "..." .Fn atf_tc_expect_timeout "reason" "..." .Fn atf_tc_fail "reason" .Fn atf_tc_fail_nonfatal "reason" .Fn atf_tc_pass .Fn atf_tc_skip "reason" .Ft void .Fo atf_utils_cat_file .Fa "const char *file" .Fa "const char *prefix" .Fc .Ft bool .Fo atf_utils_compare_file .Fa "const char *file" .Fa "const char *contents" .Fc .Ft void .Fo atf_utils_copy_file .Fa "const char *source" .Fa "const char *destination" .Fc .Ft void .Fo atf_utils_create_file .Fa "const char *file" .Fa "const char *contents" .Fa "..." .Fc .Ft void .Fo atf_utils_file_exists .Fa "const char *file" .Fc .Ft pid_t .Fo atf_utils_fork .Fa "void" .Fc .Ft void .Fo atf_utils_free_charpp .Fa "char **argv" .Fc .Ft bool .Fo atf_utils_grep_file .Fa "const char *regexp" .Fa "const char *file" .Fa "..." .Fc .Ft bool .Fo atf_utils_grep_string .Fa "const char *regexp" .Fa "const char *str" .Fa "..." .Fc .Ft char * .Fo atf_utils_readline .Fa "int fd" .Fc .Ft void .Fo atf_utils_redirect .Fa "const int fd" .Fa "const char *file" .Fc .Ft void .Fo atf_utils_wait .Fa "const pid_t pid" .Fa "const int expected_exit_status" .Fa "const char *expected_stdout" .Fa "const char *expected_stderr" .Fc .Sh DESCRIPTION ATF provides a C programming interface to implement test programs. C-based test programs follow this template: .Bd -literal -offset indent \&... C-specific includes go here ... #include ATF_TC(tc1); ATF_TC_HEAD(tc1, tc) { ... first test case's header ... } ATF_TC_BODY(tc1, tc) { ... first test case's body ... } ATF_TC_WITH_CLEANUP(tc2); ATF_TC_HEAD(tc2, tc) { ... second test case's header ... } ATF_TC_BODY(tc2, tc) { ... second test case's body ... } ATF_TC_CLEANUP(tc2, tc) { ... second test case's cleanup ... } ATF_TC_WITHOUT_HEAD(tc3); ATF_TC_BODY(tc3, tc) { ... third test case's body ... } \&... additional test cases ... ATF_TP_ADD_TCS(tp) { ATF_TP_ADD_TC(tcs, tc1); ATF_TP_ADD_TC(tcs, tc2); ATF_TP_ADD_TC(tcs, tc3); ... add additional test cases ... return atf_no_error(); } .Ed .Ss Definition of test cases Test cases have an identifier and are composed of three different parts: the header, the body and an optional cleanup routine, all of which are described in .Xr atf-test-case 4 . To define test cases, one can use the .Fn ATF_TC , .Fn ATF_TC_WITH_CLEANUP or the .Fn ATF_TC_WITHOUT_HEAD macros, which take a single parameter specifying the test case's name. .Fn ATF_TC , requires to define a head and a body for the test case, .Fn ATF_TC_WITH_CLEANUP requires to define a head, a body and a cleanup for the test case and .Fn ATF_TC_WITHOUT_HEAD requires only a body for the test case. It is important to note that these .Em do not set the test case up for execution when the program is run. In order to do so, a later registration is needed with the .Fn ATF_TP_ADD_TC macro detailed in .Sx Program initialization . .Pp Later on, one must define the three parts of the body by means of three functions. Their headers are given by the .Fn ATF_TC_HEAD , .Fn ATF_TC_BODY and .Fn ATF_TC_CLEANUP macros, all of which take the test case name provided to the .Fn ATF_TC .Fn ATF_TC_WITH_CLEANUP , or .Fn ATF_TC_WITHOUT_HEAD macros and the name of the variable that will hold a pointer to the test case data. Following each of these, a block of code is expected, surrounded by the opening and closing brackets. .Ss Program initialization The library provides a way to easily define the test program's .Fn main function. You should never define one on your own, but rely on the library to do it for you. This is done by using the .Fn ATF_TP_ADD_TCS macro, which is passed the name of the object that will hold the test cases, i.e., the test program instance. This name can be whatever you want as long as it is a valid variable identifier. .Pp After the macro, you are supposed to provide the body of a function, which should only use the .Fn ATF_TP_ADD_TC macro to register the test cases the test program will execute and return a success error code. The first parameter of this macro matches the name you provided in the former call. The success status can be returned using the .Fn atf_no_error function. .Ss Header definitions The test case's header can define the meta-data by using the .Fn atf_tc_set_md_var method, which takes three parameters: the first one points to the test case data, the second one specifies the meta-data variable to be set and the third one specifies its value. Both of them are strings. .Ss Configuration variables The test case has read-only access to the current configuration variables by means of the .Ft bool .Fn atf_tc_has_config_var , .Ft const char * .Fn atf_tc_get_config_var , .Ft const char * .Fn atf_tc_get_config_var_wd , .Ft bool .Fn atf_tc_get_config_var_as_bool , .Ft bool .Fn atf_tc_get_config_var_as_bool_wd , .Ft long .Fn atf_tc_get_config_var_as_long , and the .Ft long .Fn atf_tc_get_config_var_as_long_wd functions, which can be called in any of the three parts of a test case. .Pp The .Sq _wd variants take a default value for the variable which is returned if the variable is not defined. The other functions without the .Sq _wd suffix .Em require the variable to be defined. .Ss Access to the source directory It is possible to get the path to the test case's source directory from any of its three components by querying the .Sq srcdir configuration variable. .Ss Requiring programs Aside from the .Va require.progs meta-data variable available in the header only, one can also check for additional programs in the test case's body by using the .Fn atf_tc_require_prog function, which takes the base name or full path of a single binary. Relative paths are forbidden. If it is not found, the test case will be automatically skipped. .Ss Test case finalization The test case finalizes either when the body reaches its end, at which point the test is assumed to have .Em passed , unless any non-fatal errors were raised using .Fn atf_tc_fail_nonfatal , or at any explicit call to .Fn atf_tc_pass , .Fn atf_tc_fail or .Fn atf_tc_skip . These three functions terminate the execution of the test case immediately. The cleanup routine will be processed afterwards in a completely automated way, regardless of the test case's termination reason. .Pp .Fn atf_tc_pass does not take any parameters. .Fn atf_tc_fail , .Fn atf_tc_fail_nonfatal and .Fn atf_tc_skip take a format string and a variable list of parameters, which describe, in a user-friendly manner, why the test case failed or was skipped, respectively. It is very important to provide a clear error message in both cases so that the user can quickly know why the test did not pass. .Ss Expectations Everything explained in the previous section changes when the test case expectations are redefined by the programmer. .Pp Each test case has an internal state called .Sq expect that describes what the test case expectations are at any point in time. The value of this property can change during execution by any of: .Bl -tag -width indent .It Fn atf_tc_expect_death "reason" "..." Expects the test case to exit prematurely regardless of the nature of the exit. .It Fn atf_tc_expect_exit "exitcode" "reason" "..." Expects the test case to exit cleanly. If .Va exitcode is not .Sq -1 , the runtime engine will validate that the exit code of the test case matches the one provided in this call. Otherwise, the exact value will be ignored. .It Fn atf_tc_expect_fail "reason" "..." Any failure (be it fatal or non-fatal) raised in this mode is recorded. However, such failures do not report the test case as failed; instead, the test case finalizes cleanly and is reported as .Sq expected failure ; this report includes the provided .Fa reason as part of it. If no error is raised while running in this mode, then the test case is reported as .Sq failed . .Pp This mode is useful to reproduce actual known bugs in tests. Whenever the developer fixes the bug later on, the test case will start reporting a failure, signaling the developer that the test case must be adjusted to the new conditions. In this situation, it is useful, for example, to set .Fa reason as the bug number for tracking purposes. .It Fn atf_tc_expect_pass This is the normal mode of execution. In this mode, any failure is reported as such to the user and the test case is marked as .Sq failed . .It Fn atf_tc_expect_signal "signo" "reason" "..." Expects the test case to terminate due to the reception of a signal. If .Va signo is not .Sq -1 , the runtime engine will validate that the signal that terminated the test case matches the one provided in this call. Otherwise, the exact value will be ignored. .It Fn atf_tc_expect_timeout "reason" "..." Expects the test case to execute for longer than its timeout. .El .Ss Helper macros for common checks The library provides several macros that are very handy in multiple situations. These basically check some condition after executing a given statement or processing a given expression and, if the condition is not met, they report the test case as failed. .Pp The .Sq REQUIRE variant of the macros immediately abort the test case as soon as an error condition is detected by calling the .Fn atf_tc_fail function. Use this variant whenever it makes no sense to continue the execution of a test case when the checked condition is not met. The .Sq CHECK variant, on the other hand, reports a failure as soon as it is encountered using the .Fn atf_tc_fail_nonfatal function, but the execution of the test case continues as if nothing had happened. Use this variant whenever the checked condition is important as a result of the test case, but there are other conditions that can be subsequently checked on the same run without aborting. .Pp Additionally, the .Sq MSG variants take an extra set of parameters to explicitly specify the failure message. This failure message is formatted according to the .Xr printf 3 formatters. .Pp .Fn ATF_CHECK , .Fn ATF_CHECK_MSG , .Fn ATF_REQUIRE and .Fn ATF_REQUIRE_MSG take an expression and fail if the expression evaluates to false. .Pp .Fn ATF_CHECK_EQ , .Fn ATF_CHECK_EQ_MSG , .Fn ATF_REQUIRE_EQ and .Fn ATF_REQUIRE_EQ_MSG take two expressions and fail if the two evaluated values are not equal. The common style is to put the expected value in the first parameter and the -actual value in the second parameter. +observed value in the second parameter. .Pp .Fn ATF_CHECK_MATCH , .Fn ATF_CHECK_MATCH_MSG , .Fn ATF_REQUIRE_MATCH and .Fn ATF_REQUIRE_MATCH_MSG take a regular expression and a string and fail if the regular expression does not match the given string. Note that the regular expression is not anchored, so it will match anywhere in the string. .Pp .Fn ATF_CHECK_STREQ , .Fn ATF_CHECK_STREQ_MSG , .Fn ATF_REQUIRE_STREQ and .Fn ATF_REQUIRE_STREQ_MSG take two strings and fail if the two are not equal character by character. The common style is to put the expected string in the first parameter and the -actual string in the second parameter. +observed string in the second parameter. +.Pp +.Fn ATF_CHECK_INTEQ , +.Fn ATF_CHECK_INTEQ_MSG , +.Fn ATF_REQUIRE_INTEQ +and +.Fn ATF_REQUIRE_INTQ_MSG +take two integers and fail if the two are not equal. +The common style is to put the expected integer in the first parameter and the +observed integer in the second parameter. .Pp .Fn ATF_CHECK_ERRNO and .Fn ATF_REQUIRE_ERRNO take, first, the error code that the check is expecting to find in the .Va errno variable and, second, a boolean expression that, if evaluates to true, means that a call failed and .Va errno has to be checked against the first value. .Ss Utility functions The following functions are provided as part of the .Nm API to simplify the creation of a variety of tests. In particular, these are useful to write tests for command-line interfaces. .Pp .Ft void .Fo atf_utils_cat_file .Fa "const char *file" .Fa "const char *prefix" .Fc .Bd -ragged -offset indent Prints the contents of .Fa file to the standard output, prefixing every line with the string in .Fa prefix . .Ed .Pp .Ft bool .Fo atf_utils_compare_file .Fa "const char *file" .Fa "const char *contents" .Fc .Bd -ragged -offset indent Returns true if the given .Fa file matches exactly the expected inlined .Fa contents . .Ed .Pp .Ft void .Fo atf_utils_copy_file .Fa "const char *source" .Fa "const char *destination" .Fc .Bd -ragged -offset indent Copies the file .Fa source to .Fa destination . The permissions of the file are preserved during the code. .Ed .Pp .Ft void .Fo atf_utils_create_file .Fa "const char *file" .Fa "const char *contents" .Fa "..." .Fc .Bd -ragged -offset indent Creates .Fa file with the text given in .Fa contents , which is a formatting string that uses the rest of the variable arguments. .Ed .Pp .Ft void .Fo atf_utils_file_exists .Fa "const char *file" .Fc .Bd -ragged -offset indent Checks if .Fa file exists. .Ed .Pp .Ft pid_t .Fo atf_utils_fork .Fa "void" .Fc .Bd -ragged -offset indent Forks a process and redirects the standard output and standard error of the child to files for later validation with .Fn atf_utils_wait . Fails the test case if the fork fails, so this does not return an error. .Ed .Pp .Ft void .Fo atf_utils_free_charpp .Fa "char **argv" .Fc .Bd -ragged -offset indent Frees a dynamically-allocated array of dynamically-allocated strings. .Ed .Pp .Ft bool .Fo atf_utils_grep_file .Fa "const char *regexp" .Fa "const char *file" .Fa "..." .Fc .Bd -ragged -offset indent Searches for the .Fa regexp , which is a formatting string representing the regular expression, in the .Fa file . The variable arguments are used to construct the regular expression. .Ed .Pp .Ft bool .Fo atf_utils_grep_string .Fa "const char *regexp" .Fa "const char *str" .Fa "..." .Fc .Bd -ragged -offset indent Searches for the .Fa regexp , which is a formatting string representing the regular expression, in the literal string .Fa str . The variable arguments are used to construct the regular expression. .Ed .Pp .Ft char * .Fo atf_utils_readline .Fa "int fd" .Fc .Bd -ragged -offset indent Reads a line from the file descriptor .Fa fd . The line, if any, is returned as a dynamically-allocated buffer that must be released with .Xr free 3 . If there was nothing to read, returns .Sq NULL . .Ed .Pp .Ft void .Fo atf_utils_redirect .Fa "const int fd" .Fa "const char *file" .Fc .Bd -ragged -offset indent Redirects the given file descriptor .Fa fd to .Fa file . This function exits the process in case of an error and does not properly mark the test case as failed. As a result, it should only be used in subprocesses of the test case; specially those spawned by .Fn atf_utils_fork . .Ed .Pp .Ft void .Fo atf_utils_wait .Fa "const pid_t pid" .Fa "const int expected_exit_status" .Fa "const char *expected_stdout" .Fa "const char *expected_stderr" .Fc .Bd -ragged -offset indent Waits and validates the result of a subprocess spawned with .Fn atf_utils_fork . The validation involves checking that the subprocess exited cleanly and returned the code specified in .Fa expected_exit_status and that its standard output and standard error match the strings given in .Fa expected_stdout and .Fa expected_stderr . .Pp If any of the .Fa expected_stdout or .Fa expected_stderr strings are prefixed with .Sq save: , then they specify the name of the file into which to store the stdout or stderr of the subprocess, and no comparison is performed. .Ed .Sh ENVIRONMENT The following variables are recognized by .Nm but should not be overridden other than for testing purposes: .Pp .Bl -tag -width ATFXBUILDXCXXFLAGSXX -compact .It Va ATF_BUILD_CC Path to the C compiler. .It Va ATF_BUILD_CFLAGS C compiler flags. .It Va ATF_BUILD_CPP Path to the C/C++ preprocessor. .It Va ATF_BUILD_CPPFLAGS C/C++ preprocessor flags. .It Va ATF_BUILD_CXX Path to the C++ compiler. .It Va ATF_BUILD_CXXFLAGS C++ compiler flags. .El .Sh EXAMPLES The following shows a complete test program with a single test case that validates the addition operator: .Bd -literal -offset indent #include ATF_TC(addition); ATF_TC_HEAD(addition, tc) { atf_tc_set_md_var(tc, "descr", "Sample tests for the addition operator"); } ATF_TC_BODY(addition, tc) { ATF_CHECK_EQ(0, 0 + 0); ATF_CHECK_EQ(1, 0 + 1); ATF_CHECK_EQ(1, 1 + 0); ATF_CHECK_EQ(2, 1 + 1); ATF_CHECK_EQ(300, 100 + 200); } ATF_TC(string_formatting); ATF_TC_HEAD(string_formatting, tc) { atf_tc_set_md_var(tc, "descr", "Sample tests for the snprintf"); } ATF_TC_BODY(string_formatting, tc) { char buf[1024]; snprintf(buf, sizeof(buf), "a %s", "string"); ATF_CHECK_STREQ_MSG("a string", buf, "%s is not working"); } ATF_TC(open_failure); ATF_TC_HEAD(open_failure, tc) { atf_tc_set_md_var(tc, "descr", "Sample tests for the open function"); } ATF_TC_BODY(open_failure, tc) { ATF_CHECK_ERRNO(ENOENT, open("non-existent", O_RDONLY) == -1); } ATF_TC(known_bug); ATF_TC_HEAD(known_bug, tc) { atf_tc_set_md_var(tc, "descr", "Reproduces a known bug"); } ATF_TC_BODY(known_bug, tc) { atf_tc_expect_fail("See bug number foo/bar"); ATF_CHECK_EQ(3, 1 + 1); atf_tc_expect_pass(); ATF_CHECK_EQ(3, 1 + 2); } ATF_TP_ADD_TCS(tp) { ATF_TP_ADD_TC(tp, addition); ATF_TP_ADD_TC(tp, string_formatting); ATF_TP_ADD_TC(tp, open_failure); ATF_TP_ADD_TC(tp, known_bug); return atf_no_error(); } .Ed .Sh SEE ALSO .Xr atf-test-program 1 , .Xr atf-test-case 4 diff --git a/contrib/atf/atf-c/macros.h b/contrib/atf/atf-c/macros.h index 485a159acecb..1784fc47435d 100644 --- a/contrib/atf/atf-c/macros.h +++ b/contrib/atf/atf-c/macros.h @@ -1,212 +1,231 @@ /* Copyright (c) 2008 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if !defined(ATF_C_MACROS_H) #define ATF_C_MACROS_H #include #include #include #include #include #include #define ATF_TC_NAME(tc) \ (atfu_ ## tc ## _tc) #define ATF_TC_PACK_NAME(tc) \ (atfu_ ## tc ## _tc_pack) #define ATF_TC_WITHOUT_HEAD(tc) \ static void atfu_ ## tc ## _body(const atf_tc_t *); \ static atf_tc_t atfu_ ## tc ## _tc; \ static atf_tc_pack_t atfu_ ## tc ## _tc_pack = { \ .m_ident = #tc, \ .m_head = NULL, \ .m_body = atfu_ ## tc ## _body, \ .m_cleanup = NULL, \ } #define ATF_TC(tc) \ static void atfu_ ## tc ## _head(atf_tc_t *); \ static void atfu_ ## tc ## _body(const atf_tc_t *); \ static atf_tc_t atfu_ ## tc ## _tc; \ static atf_tc_pack_t atfu_ ## tc ## _tc_pack = { \ .m_ident = #tc, \ .m_head = atfu_ ## tc ## _head, \ .m_body = atfu_ ## tc ## _body, \ .m_cleanup = NULL, \ } #define ATF_TC_WITH_CLEANUP(tc) \ static void atfu_ ## tc ## _head(atf_tc_t *); \ static void atfu_ ## tc ## _body(const atf_tc_t *); \ static void atfu_ ## tc ## _cleanup(const atf_tc_t *); \ static atf_tc_t atfu_ ## tc ## _tc; \ static atf_tc_pack_t atfu_ ## tc ## _tc_pack = { \ .m_ident = #tc, \ .m_head = atfu_ ## tc ## _head, \ .m_body = atfu_ ## tc ## _body, \ .m_cleanup = atfu_ ## tc ## _cleanup, \ } #define ATF_TC_HEAD(tc, tcptr) \ static \ void \ atfu_ ## tc ## _head(atf_tc_t *tcptr ATF_DEFS_ATTRIBUTE_UNUSED) #define ATF_TC_HEAD_NAME(tc) \ (atfu_ ## tc ## _head) #define ATF_TC_BODY(tc, tcptr) \ static \ void \ atfu_ ## tc ## _body(const atf_tc_t *tcptr ATF_DEFS_ATTRIBUTE_UNUSED) #define ATF_TC_BODY_NAME(tc) \ (atfu_ ## tc ## _body) #define ATF_TC_CLEANUP(tc, tcptr) \ static \ void \ atfu_ ## tc ## _cleanup(const atf_tc_t *tcptr ATF_DEFS_ATTRIBUTE_UNUSED) #define ATF_TC_CLEANUP_NAME(tc) \ (atfu_ ## tc ## _cleanup) #define ATF_TP_ADD_TCS(tps) \ static atf_error_t atfu_tp_add_tcs(atf_tp_t *); \ int atf_tp_main(int, char **, atf_error_t (*)(atf_tp_t *)); \ \ int \ main(int argc, char **argv) \ { \ return atf_tp_main(argc, argv, atfu_tp_add_tcs); \ } \ static \ atf_error_t \ atfu_tp_add_tcs(atf_tp_t *tps) #define ATF_TP_ADD_TC(tp, tc) \ do { \ atf_error_t atfu_err; \ char **atfu_config = atf_tp_get_config(tp); \ if (atfu_config == NULL) \ return atf_no_memory_error(); \ atfu_err = atf_tc_init_pack(&atfu_ ## tc ## _tc, \ &atfu_ ## tc ## _tc_pack, \ (const char *const *)atfu_config); \ atf_utils_free_charpp(atfu_config); \ if (atf_is_error(atfu_err)) \ return atfu_err; \ atfu_err = atf_tp_add_tc(tp, &atfu_ ## tc ## _tc); \ if (atf_is_error(atfu_err)) \ return atfu_err; \ } while (0) #define ATF_REQUIRE_MSG(expression, fmt, ...) \ do { \ if (!(expression)) \ atf_tc_fail_requirement(__FILE__, __LINE__, fmt, ##__VA_ARGS__); \ } while(0) #define ATF_CHECK_MSG(expression, fmt, ...) \ do { \ if (!(expression)) \ atf_tc_fail_check(__FILE__, __LINE__, fmt, ##__VA_ARGS__); \ } while(0) #define ATF_REQUIRE(expression) \ do { \ if (!(expression)) \ atf_tc_fail_requirement(__FILE__, __LINE__, "%s", \ #expression " not met"); \ } while(0) #define ATF_CHECK(expression) \ do { \ if (!(expression)) \ atf_tc_fail_check(__FILE__, __LINE__, "%s", \ #expression " not met"); \ } while(0) #define ATF_REQUIRE_EQ(expected, actual) \ ATF_REQUIRE_MSG((expected) == (actual), "%s != %s", #expected, #actual) #define ATF_CHECK_EQ(expected, actual) \ ATF_CHECK_MSG((expected) == (actual), "%s != %s", #expected, #actual) #define ATF_REQUIRE_EQ_MSG(expected, actual, fmt, ...) \ ATF_REQUIRE_MSG((expected) == (actual), "%s != %s: " fmt, \ #expected, #actual, ##__VA_ARGS__) #define ATF_CHECK_EQ_MSG(expected, actual, fmt, ...) \ ATF_CHECK_MSG((expected) == (actual), "%s != %s: " fmt, \ #expected, #actual, ##__VA_ARGS__) #define ATF_REQUIRE_STREQ(expected, actual) \ ATF_REQUIRE_MSG(strcmp(expected, actual) == 0, "%s != %s (%s != %s)", \ #expected, #actual, expected, actual) #define ATF_CHECK_STREQ(expected, actual) \ ATF_CHECK_MSG(strcmp(expected, actual) == 0, "%s != %s (%s != %s)", \ #expected, #actual, expected, actual) #define ATF_REQUIRE_STREQ_MSG(expected, actual, fmt, ...) \ ATF_REQUIRE_MSG(strcmp(expected, actual) == 0, \ "%s != %s (%s != %s): " fmt, \ #expected, #actual, expected, actual, ##__VA_ARGS__) #define ATF_CHECK_STREQ_MSG(expected, actual, fmt, ...) \ ATF_CHECK_MSG(strcmp(expected, actual) == 0, \ "%s != %s (%s != %s): " fmt, \ #expected, #actual, expected, actual, ##__VA_ARGS__) +#define ATF_REQUIRE_INTEQ(expected, actual) \ + ATF_REQUIRE_MSG((expected) == (actual), "%s != %s (%jd != %jd)", \ + #expected, #actual, (intmax_t)(expected), \ + (intmax_t)(actual)) + +#define ATF_CHECK_INTEQ(expected, actual) \ + ATF_CHECK_MSG((expected) == (actual), "%s != %s (%jd != %jd)", #expected, \ + #actual, (intmax_t)(expected), (intmax_t)(actual)) + +#define ATF_REQUIRE_INTEQ_MSG(expected, actual, fmt, ...) \ + ATF_REQUIRE_MSG((expected) == (actual), "%s != %s (%jd != %jd): " fmt, \ + #expected, #actual, (intmax_t)(expected), \ + (intmax_t)(actual), ##__VA_ARGS__) + +#define ATF_CHECK_INTEQ_MSG(expected, actual, fmt, ...) \ + ATF_CHECK_MSG((expected) == (actual), "%s != %s (%jd != %jd): " fmt, \ + #expected, #actual, (intmax_t)(expected), \ + (intmax_t)(actual), ##__VA_ARGS__) + #define ATF_REQUIRE_MATCH(regexp, string) \ ATF_REQUIRE_MSG(atf_utils_grep_string("%s", string, regexp), \ "'%s' not matched in '%s'", regexp, string); #define ATF_CHECK_MATCH(regexp, string) \ ATF_CHECK_MSG(atf_utils_grep_string("%s", string, regexp), \ "'%s' not matched in '%s'", regexp, string); #define ATF_REQUIRE_MATCH_MSG(regexp, string, fmt, ...) \ ATF_REQUIRE_MSG(atf_utils_grep_string("%s", string, regexp), \ "'%s' not matched in '%s': " fmt, regexp, string, \ ##__VA_ARGS__); #define ATF_CHECK_MATCH_MSG(regexp, string, fmt, ...) \ ATF_CHECK_MSG(atf_utils_grep_string("%s", string, regexp), \ "'%s' not matched in '%s': " fmt, regexp, string, \ ##__VA_ARGS__); #define ATF_CHECK_ERRNO(exp_errno, bool_expr) \ atf_tc_check_errno(__FILE__, __LINE__, exp_errno, #bool_expr, bool_expr) #define ATF_REQUIRE_ERRNO(exp_errno, bool_expr) \ atf_tc_require_errno(__FILE__, __LINE__, exp_errno, #bool_expr, bool_expr) #endif /* !defined(ATF_C_MACROS_H) */ diff --git a/contrib/atf/atf-c/tc.c b/contrib/atf/atf-c/tc.c index 69b31123f3a3..84a8beb4fa13 100644 --- a/contrib/atf/atf-c/tc.c +++ b/contrib/atf/atf-c/tc.c @@ -1,1279 +1,1273 @@ /* Copyright (c) 2008 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "atf-c/tc.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "atf-c/defs.h" #include "atf-c/detail/env.h" #include "atf-c/detail/fs.h" #include "atf-c/detail/map.h" #include "atf-c/detail/sanity.h" #include "atf-c/detail/text.h" #include "atf-c/error.h" /* --------------------------------------------------------------------- * Auxiliary functions. * --------------------------------------------------------------------- */ enum expect_type { EXPECT_PASS, EXPECT_FAIL, EXPECT_EXIT, EXPECT_SIGNAL, EXPECT_DEATH, EXPECT_TIMEOUT, }; struct context { const atf_tc_t *tc; const char *resfile; int resfilefd; size_t fail_count; enum expect_type expect; atf_dynstr_t expect_reason; size_t expect_previous_fail_count; size_t expect_fail_count; int expect_exitcode; int expect_signo; }; static void context_init(struct context *, const atf_tc_t *, const char *); static void context_set_resfile(struct context *, const char *); static void context_close_resfile(struct context *); static void check_fatal_error(atf_error_t); static void report_fatal_error(const char *, ...) ATF_DEFS_ATTRIBUTE_NORETURN; static atf_error_t write_resfile(const int, const char *, const int, const atf_dynstr_t *); static void create_resfile(struct context *, const char *, const int, atf_dynstr_t *); static void error_in_expect(struct context *, const char *, ...) ATF_DEFS_ATTRIBUTE_NORETURN; static void validate_expect(struct context *); static void expected_failure(struct context *, atf_dynstr_t *) ATF_DEFS_ATTRIBUTE_NORETURN; static void fail_requirement(struct context *, atf_dynstr_t *) ATF_DEFS_ATTRIBUTE_NORETURN; static void fail_check(struct context *, atf_dynstr_t *); static void pass(struct context *) ATF_DEFS_ATTRIBUTE_NORETURN; static void skip(struct context *, atf_dynstr_t *) ATF_DEFS_ATTRIBUTE_NORETURN; static void format_reason_ap(atf_dynstr_t *, const char *, const size_t, const char *, va_list); static void format_reason_fmt(atf_dynstr_t *, const char *, const size_t, const char *, ...); static void errno_test(struct context *, const char *, const size_t, const int, const char *, const bool, void (*)(struct context *, atf_dynstr_t *)); static atf_error_t check_prog_in_dir(const char *, void *); static atf_error_t check_prog(struct context *, const char *); /* No prototype in header for this one, it's a little sketchy (internal). */ void atf_tc_set_resultsfile(const char *); static void context_init(struct context *ctx, const atf_tc_t *tc, const char *resfile) { ctx->tc = tc; ctx->resfilefd = -1; context_set_resfile(ctx, resfile); ctx->fail_count = 0; ctx->expect = EXPECT_PASS; check_fatal_error(atf_dynstr_init(&ctx->expect_reason)); ctx->expect_previous_fail_count = 0; ctx->expect_fail_count = 0; ctx->expect_exitcode = 0; ctx->expect_signo = 0; } static void context_set_resfile(struct context *ctx, const char *resfile) { atf_error_t err; context_close_resfile(ctx); ctx->resfile = resfile; if (strcmp(resfile, "/dev/stdout") == 0) ctx->resfilefd = STDOUT_FILENO; else if (strcmp(resfile, "/dev/stderr") == 0) ctx->resfilefd = STDERR_FILENO; else ctx->resfilefd = open(resfile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (ctx->resfilefd == -1) { err = atf_libc_error(errno, "Cannot create results file '%s'", resfile); check_fatal_error(err); } ctx->resfile = resfile; } static void context_close_resfile(struct context *ctx) { if (ctx->resfilefd == -1) return; if (ctx->resfilefd != STDOUT_FILENO && ctx->resfilefd != STDERR_FILENO) close(ctx->resfilefd); ctx->resfilefd = -1; ctx->resfile = NULL; } static void check_fatal_error(atf_error_t err) { if (atf_is_error(err)) { char buf[1024]; atf_error_format(err, buf, sizeof(buf)); fprintf(stderr, "FATAL ERROR: %s\n", buf); atf_error_free(err); abort(); } } static void report_fatal_error(const char *msg, ...) { va_list ap; fprintf(stderr, "FATAL ERROR: "); va_start(ap, msg); vfprintf(stderr, msg, ap); va_end(ap); fprintf(stderr, "\n"); abort(); } /** Writes to a results file. * * The results file is supposed to be already open. * * This function returns an error code instead of exiting in case of error * because the caller needs to clean up the reason object before terminating. */ static atf_error_t write_resfile(const int fd, const char *result, const int arg, const atf_dynstr_t *reason) { static char NL[] = "\n", CS[] = ": "; char buf[64]; const char *r; struct iovec iov[5]; ssize_t ret; int count = 0; INV(arg == -1 || reason != NULL); #define UNCONST(a) ((void *)(uintptr_t)(const void *)(a)) iov[count].iov_base = UNCONST(result); iov[count++].iov_len = strlen(result); if (reason != NULL) { if (arg != -1) { iov[count].iov_base = buf; iov[count++].iov_len = snprintf(buf, sizeof(buf), "(%d)", arg); } iov[count].iov_base = CS; iov[count++].iov_len = sizeof(CS) - 1; r = atf_dynstr_cstring(reason); iov[count].iov_base = UNCONST(r); iov[count++].iov_len = strlen(r); } #undef UNCONST iov[count].iov_base = NL; iov[count++].iov_len = sizeof(NL) - 1; while ((ret = writev(fd, iov, count)) == -1 && errno == EINTR) continue; /* Retry. */ if (ret != -1) return atf_no_error(); return atf_libc_error( errno, "Failed to write results file; result %s, reason %s", result, reason == NULL ? "null" : atf_dynstr_cstring(reason)); } /** Creates a results file. * * The input reason is released in all cases. * * An error in this function is considered to be fatal, hence why it does * not return any error code. */ static void create_resfile(struct context *ctx, const char *result, const int arg, atf_dynstr_t *reason) { atf_error_t err; /* * We'll attempt to truncate the results file, but only if it's not pointed * at stdout/stderr. We could just blindly ftruncate() here, but it may * be that stdout/stderr have been redirected to a file that we want to * validate expectations on, for example. Kyua will want the truncation, * but it will also redirect the results directly to some file and we'll * have no issue here. */ if (ctx->resfilefd != STDOUT_FILENO && ctx->resfilefd != STDERR_FILENO && ftruncate(ctx->resfilefd, 0) != -1) lseek(ctx->resfilefd, 0, SEEK_SET); err = write_resfile(ctx->resfilefd, result, arg, reason); if (reason != NULL) atf_dynstr_fini(reason); check_fatal_error(err); } /** Fails a test case if validate_expect fails. */ static void error_in_expect(struct context *ctx, const char *fmt, ...) { atf_dynstr_t reason; va_list ap; va_start(ap, fmt); format_reason_ap(&reason, NULL, 0, fmt, ap); va_end(ap); ctx->expect = EXPECT_PASS; /* Ensure fail_requirement really fails. */ fail_requirement(ctx, &reason); } /** Ensures that the "expect" state is correct. * * Call this function before modifying the current value of expect. */ static void validate_expect(struct context *ctx) { if (ctx->expect == EXPECT_DEATH) { error_in_expect(ctx, "Test case was expected to terminate abruptly " "but it continued execution"); } else if (ctx->expect == EXPECT_EXIT) { error_in_expect(ctx, "Test case was expected to exit cleanly but it " "continued execution"); } else if (ctx->expect == EXPECT_FAIL) { if (ctx->expect_fail_count == ctx->expect_previous_fail_count) error_in_expect(ctx, "Test case was expecting a failure but none " "were raised"); else INV(ctx->expect_fail_count > ctx->expect_previous_fail_count); } else if (ctx->expect == EXPECT_PASS) { /* Nothing to validate. */ } else if (ctx->expect == EXPECT_SIGNAL) { error_in_expect(ctx, "Test case was expected to receive a termination " "signal but it continued execution"); } else if (ctx->expect == EXPECT_TIMEOUT) { error_in_expect(ctx, "Test case was expected to hang but it continued " "execution"); } else UNREACHABLE; } static void expected_failure(struct context *ctx, atf_dynstr_t *reason) { check_fatal_error(atf_dynstr_prepend_fmt(reason, "%s: ", atf_dynstr_cstring(&ctx->expect_reason))); create_resfile(ctx, "expected_failure", -1, reason); context_close_resfile(ctx); exit(EXIT_SUCCESS); } static void fail_requirement(struct context *ctx, atf_dynstr_t *reason) { if (ctx->expect == EXPECT_FAIL) { expected_failure(ctx, reason); } else if (ctx->expect == EXPECT_PASS) { create_resfile(ctx, "failed", -1, reason); context_close_resfile(ctx); exit(EXIT_FAILURE); } else { error_in_expect(ctx, "Test case raised a failure but was not " "expecting one; reason was %s", atf_dynstr_cstring(reason)); } UNREACHABLE; } static void fail_check(struct context *ctx, atf_dynstr_t *reason) { if (ctx->expect == EXPECT_FAIL) { fprintf(stderr, "*** Expected check failure: %s: %s\n", atf_dynstr_cstring(&ctx->expect_reason), atf_dynstr_cstring(reason)); ctx->expect_fail_count++; } else if (ctx->expect == EXPECT_PASS) { fprintf(stderr, "*** Check failed: %s\n", atf_dynstr_cstring(reason)); ctx->fail_count++; } else { error_in_expect(ctx, "Test case raised a failure but was not " "expecting one; reason was %s", atf_dynstr_cstring(reason)); } atf_dynstr_fini(reason); } static void pass(struct context *ctx) { if (ctx->expect == EXPECT_FAIL) { error_in_expect(ctx, "Test case was expecting a failure but got " "a pass instead"); } else if (ctx->expect == EXPECT_PASS) { create_resfile(ctx, "passed", -1, NULL); context_close_resfile(ctx); exit(EXIT_SUCCESS); } else { error_in_expect(ctx, "Test case asked to explicitly pass but was " "not expecting such condition"); } UNREACHABLE; } static void skip(struct context *ctx, atf_dynstr_t *reason) { - if (ctx->expect == EXPECT_PASS) { - create_resfile(ctx, "skipped", -1, reason); - context_close_resfile(ctx); - exit(EXIT_SUCCESS); - } else { - error_in_expect(ctx, "Can only skip a test case when running in " - "expect pass mode"); - } - UNREACHABLE; + create_resfile(ctx, "skipped", -1, reason); + context_close_resfile(ctx); + exit(EXIT_SUCCESS); } /** Formats a failure/skip reason message. * * The formatted reason is stored in out_reason. out_reason is initialized * in this function and is supposed to be released by the caller. In general, * the reason will eventually be fed to create_resfile, which will release * it. * * Errors in this function are fatal. Rationale being: reasons are used to * create results files; if we can't format the reason correctly, the result * of the test program will be bogus. So it's better to just exit with a * fatal error. */ static void format_reason_ap(atf_dynstr_t *out_reason, const char *source_file, const size_t source_line, const char *reason, va_list ap) { atf_error_t err; if (source_file != NULL) { err = atf_dynstr_init_fmt(out_reason, "%s:%zd: ", source_file, source_line); } else { PRE(source_line == 0); err = atf_dynstr_init(out_reason); } if (!atf_is_error(err)) { va_list ap2; va_copy(ap2, ap); err = atf_dynstr_append_ap(out_reason, reason, ap2); va_end(ap2); } check_fatal_error(err); } static void format_reason_fmt(atf_dynstr_t *out_reason, const char *source_file, const size_t source_line, const char *reason, ...) { va_list ap; va_start(ap, reason); format_reason_ap(out_reason, source_file, source_line, reason, ap); va_end(ap); } static void errno_test(struct context *ctx, const char *file, const size_t line, const int exp_errno, const char *expr_str, const bool expr_result, void (*fail_func)(struct context *, atf_dynstr_t *)) { const int actual_errno = errno; if (expr_result) { if (exp_errno != actual_errno) { atf_dynstr_t reason; format_reason_fmt(&reason, file, line, "Expected errno %d, got %d, " "in %s", exp_errno, actual_errno, expr_str); fail_func(ctx, &reason); } } else { atf_dynstr_t reason; format_reason_fmt(&reason, file, line, "Expected true value in %s", expr_str); fail_func(ctx, &reason); } } struct prog_found_pair { const char *prog; bool found; }; static atf_error_t check_prog_in_dir(const char *dir, void *data) { struct prog_found_pair *pf = data; atf_error_t err; if (pf->found) err = atf_no_error(); else { atf_fs_path_t p; err = atf_fs_path_init_fmt(&p, "%s/%s", dir, pf->prog); if (atf_is_error(err)) goto out_p; err = atf_fs_eaccess(&p, atf_fs_access_x); if (!atf_is_error(err)) pf->found = true; else { atf_error_free(err); INV(!pf->found); err = atf_no_error(); } out_p: atf_fs_path_fini(&p); } return err; } static atf_error_t check_prog(struct context *ctx, const char *prog) { atf_error_t err; atf_fs_path_t p; err = atf_fs_path_init_fmt(&p, "%s", prog); if (atf_is_error(err)) goto out; if (atf_fs_path_is_absolute(&p)) { err = atf_fs_eaccess(&p, atf_fs_access_x); if (atf_is_error(err)) { atf_dynstr_t reason; atf_error_free(err); atf_fs_path_fini(&p); format_reason_fmt(&reason, NULL, 0, "The required program %s could " "not be found", prog); skip(ctx, &reason); } } else { const char *path = atf_env_get("PATH"); struct prog_found_pair pf; atf_fs_path_t bp; err = atf_fs_path_branch_path(&p, &bp); if (atf_is_error(err)) goto out_p; if (strcmp(atf_fs_path_cstring(&bp), ".") != 0) { atf_fs_path_fini(&bp); atf_fs_path_fini(&p); report_fatal_error("Relative paths are not allowed when searching " "for a program (%s)", prog); UNREACHABLE; } pf.prog = prog; pf.found = false; err = atf_text_for_each_word(path, ":", check_prog_in_dir, &pf); if (atf_is_error(err)) goto out_bp; if (!pf.found) { atf_dynstr_t reason; atf_fs_path_fini(&bp); atf_fs_path_fini(&p); format_reason_fmt(&reason, NULL, 0, "The required program %s could " "not be found in the PATH", prog); fail_requirement(ctx, &reason); } out_bp: atf_fs_path_fini(&bp); } out_p: atf_fs_path_fini(&p); out: return err; } /* --------------------------------------------------------------------- * The "atf_tc" type. * --------------------------------------------------------------------- */ struct atf_tc_impl { const char *m_ident; atf_map_t m_vars; atf_map_t m_config; atf_tc_head_t m_head; atf_tc_body_t m_body; atf_tc_cleanup_t m_cleanup; }; /* * Constructors/destructors. */ atf_error_t atf_tc_init(atf_tc_t *tc, const char *ident, atf_tc_head_t head, atf_tc_body_t body, atf_tc_cleanup_t cleanup, const char *const *config) { atf_error_t err; tc->pimpl = malloc(sizeof(struct atf_tc_impl)); if (tc->pimpl == NULL) { err = atf_no_memory_error(); goto err; } tc->pimpl->m_ident = ident; tc->pimpl->m_head = head; tc->pimpl->m_body = body; tc->pimpl->m_cleanup = cleanup; err = atf_map_init_charpp(&tc->pimpl->m_config, config); if (atf_is_error(err)) goto err; err = atf_map_init(&tc->pimpl->m_vars); if (atf_is_error(err)) goto err_vars; err = atf_tc_set_md_var(tc, "ident", ident); if (atf_is_error(err)) goto err_map; if (cleanup != NULL) { err = atf_tc_set_md_var(tc, "has.cleanup", "true"); if (atf_is_error(err)) goto err_map; } /* XXX Should the head be able to return error codes? */ if (tc->pimpl->m_head != NULL) tc->pimpl->m_head(tc); if (strcmp(atf_tc_get_md_var(tc, "ident"), ident) != 0) { report_fatal_error("Test case head modified the read-only 'ident' " "property"); UNREACHABLE; } INV(!atf_is_error(err)); return err; err_map: atf_map_fini(&tc->pimpl->m_vars); err_vars: atf_map_fini(&tc->pimpl->m_config); err: return err; } atf_error_t atf_tc_init_pack(atf_tc_t *tc, const atf_tc_pack_t *pack, const char *const *config) { return atf_tc_init(tc, pack->m_ident, pack->m_head, pack->m_body, pack->m_cleanup, config); } void atf_tc_fini(atf_tc_t *tc) { atf_map_fini(&tc->pimpl->m_vars); free(tc->pimpl); } /* * Getters. */ const char * atf_tc_get_ident(const atf_tc_t *tc) { return tc->pimpl->m_ident; } const char * atf_tc_get_config_var(const atf_tc_t *tc, const char *name) { const char *val; atf_map_citer_t iter; PRE(atf_tc_has_config_var(tc, name)); iter = atf_map_find_c(&tc->pimpl->m_config, name); val = atf_map_citer_data(iter); INV(val != NULL); return val; } const char * atf_tc_get_config_var_wd(const atf_tc_t *tc, const char *name, const char *defval) { const char *val; if (!atf_tc_has_config_var(tc, name)) val = defval; else val = atf_tc_get_config_var(tc, name); return val; } bool atf_tc_get_config_var_as_bool(const atf_tc_t *tc, const char *name) { bool val; const char *strval; atf_error_t err; strval = atf_tc_get_config_var(tc, name); err = atf_text_to_bool(strval, &val); if (atf_is_error(err)) { atf_error_free(err); atf_tc_fail("Configuration variable %s does not have a valid " "boolean value; found %s", name, strval); } return val; } bool atf_tc_get_config_var_as_bool_wd(const atf_tc_t *tc, const char *name, const bool defval) { bool val; if (!atf_tc_has_config_var(tc, name)) val = defval; else val = atf_tc_get_config_var_as_bool(tc, name); return val; } long atf_tc_get_config_var_as_long(const atf_tc_t *tc, const char *name) { long val; const char *strval; atf_error_t err; strval = atf_tc_get_config_var(tc, name); err = atf_text_to_long(strval, &val); if (atf_is_error(err)) { atf_error_free(err); atf_tc_fail("Configuration variable %s does not have a valid " "long value; found %s", name, strval); } return val; } long atf_tc_get_config_var_as_long_wd(const atf_tc_t *tc, const char *name, const long defval) { long val; if (!atf_tc_has_config_var(tc, name)) val = defval; else val = atf_tc_get_config_var_as_long(tc, name); return val; } const char * atf_tc_get_md_var(const atf_tc_t *tc, const char *name) { const char *val; atf_map_citer_t iter; PRE(atf_tc_has_md_var(tc, name)); iter = atf_map_find_c(&tc->pimpl->m_vars, name); val = atf_map_citer_data(iter); INV(val != NULL); return val; } char ** atf_tc_get_md_vars(const atf_tc_t *tc) { return atf_map_to_charpp(&tc->pimpl->m_vars); } bool atf_tc_has_config_var(const atf_tc_t *tc, const char *name) { atf_map_citer_t end, iter; iter = atf_map_find_c(&tc->pimpl->m_config, name); end = atf_map_end_c(&tc->pimpl->m_config); return !atf_equal_map_citer_map_citer(iter, end); } bool atf_tc_has_md_var(const atf_tc_t *tc, const char *name) { atf_map_citer_t end, iter; iter = atf_map_find_c(&tc->pimpl->m_vars, name); end = atf_map_end_c(&tc->pimpl->m_vars); return !atf_equal_map_citer_map_citer(iter, end); } /* * Modifiers. */ atf_error_t atf_tc_set_md_var(atf_tc_t *tc, const char *name, const char *fmt, ...) { atf_error_t err; char *value; va_list ap; va_start(ap, fmt); err = atf_text_format_ap(&value, fmt, ap); va_end(ap); if (!atf_is_error(err)) err = atf_map_insert(&tc->pimpl->m_vars, name, value, true); else free(value); return err; } /* --------------------------------------------------------------------- * Free functions, as they should be publicly but they can't. * --------------------------------------------------------------------- */ static void _atf_tc_fail(struct context *, const char *, va_list) ATF_DEFS_ATTRIBUTE_NORETURN; static void _atf_tc_fail_nonfatal(struct context *, const char *, va_list); static void _atf_tc_fail_check(struct context *, const char *, const size_t, const char *, va_list); static void _atf_tc_fail_requirement(struct context *, const char *, const size_t, const char *, va_list) ATF_DEFS_ATTRIBUTE_NORETURN; static void _atf_tc_pass(struct context *) ATF_DEFS_ATTRIBUTE_NORETURN; static void _atf_tc_require_prog(struct context *, const char *); static void _atf_tc_skip(struct context *, const char *, va_list) ATF_DEFS_ATTRIBUTE_NORETURN; static void _atf_tc_check_errno(struct context *, const char *, const size_t, const int, const char *, const bool); static void _atf_tc_require_errno(struct context *, const char *, const size_t, const int, const char *, const bool); static void _atf_tc_expect_pass(struct context *); static void _atf_tc_expect_fail(struct context *, const char *, va_list); static void _atf_tc_expect_exit(struct context *, const int, const char *, va_list); static void _atf_tc_expect_signal(struct context *, const int, const char *, va_list); static void _atf_tc_expect_death(struct context *, const char *, va_list); static void _atf_tc_fail(struct context *ctx, const char *fmt, va_list ap) { va_list ap2; atf_dynstr_t reason; va_copy(ap2, ap); format_reason_ap(&reason, NULL, 0, fmt, ap2); va_end(ap2); fail_requirement(ctx, &reason); UNREACHABLE; } static void _atf_tc_fail_nonfatal(struct context *ctx, const char *fmt, va_list ap) { va_list ap2; atf_dynstr_t reason; va_copy(ap2, ap); format_reason_ap(&reason, NULL, 0, fmt, ap2); va_end(ap2); fail_check(ctx, &reason); } static void _atf_tc_fail_check(struct context *ctx, const char *file, const size_t line, const char *fmt, va_list ap) { va_list ap2; atf_dynstr_t reason; va_copy(ap2, ap); format_reason_ap(&reason, file, line, fmt, ap2); va_end(ap2); fail_check(ctx, &reason); } static void _atf_tc_fail_requirement(struct context *ctx, const char *file, const size_t line, const char *fmt, va_list ap) { va_list ap2; atf_dynstr_t reason; va_copy(ap2, ap); format_reason_ap(&reason, file, line, fmt, ap2); va_end(ap2); fail_requirement(ctx, &reason); UNREACHABLE; } static void _atf_tc_pass(struct context *ctx) { pass(ctx); UNREACHABLE; } static void _atf_tc_require_prog(struct context *ctx, const char *prog) { check_fatal_error(check_prog(ctx, prog)); } static void _atf_tc_skip(struct context *ctx, const char *fmt, va_list ap) { atf_dynstr_t reason; va_list ap2; va_copy(ap2, ap); format_reason_ap(&reason, NULL, 0, fmt, ap2); va_end(ap2); skip(ctx, &reason); } static void _atf_tc_check_errno(struct context *ctx, const char *file, const size_t line, const int exp_errno, const char *expr_str, const bool expr_result) { errno_test(ctx, file, line, exp_errno, expr_str, expr_result, fail_check); } static void _atf_tc_require_errno(struct context *ctx, const char *file, const size_t line, const int exp_errno, const char *expr_str, const bool expr_result) { errno_test(ctx, file, line, exp_errno, expr_str, expr_result, fail_requirement); } static void _atf_tc_expect_pass(struct context *ctx) { validate_expect(ctx); ctx->expect = EXPECT_PASS; } static void _atf_tc_expect_fail(struct context *ctx, const char *reason, va_list ap) { va_list ap2; validate_expect(ctx); ctx->expect = EXPECT_FAIL; atf_dynstr_fini(&ctx->expect_reason); va_copy(ap2, ap); check_fatal_error(atf_dynstr_init_ap(&ctx->expect_reason, reason, ap2)); va_end(ap2); ctx->expect_previous_fail_count = ctx->expect_fail_count; } static void _atf_tc_expect_exit(struct context *ctx, const int exitcode, const char *reason, va_list ap) { va_list ap2; atf_dynstr_t formatted; validate_expect(ctx); ctx->expect = EXPECT_EXIT; va_copy(ap2, ap); check_fatal_error(atf_dynstr_init_ap(&formatted, reason, ap2)); va_end(ap2); create_resfile(ctx, "expected_exit", exitcode, &formatted); } static void _atf_tc_expect_signal(struct context *ctx, const int signo, const char *reason, va_list ap) { va_list ap2; atf_dynstr_t formatted; validate_expect(ctx); ctx->expect = EXPECT_SIGNAL; va_copy(ap2, ap); check_fatal_error(atf_dynstr_init_ap(&formatted, reason, ap2)); va_end(ap2); create_resfile(ctx, "expected_signal", signo, &formatted); } static void _atf_tc_expect_death(struct context *ctx, const char *reason, va_list ap) { va_list ap2; atf_dynstr_t formatted; validate_expect(ctx); ctx->expect = EXPECT_DEATH; va_copy(ap2, ap); check_fatal_error(atf_dynstr_init_ap(&formatted, reason, ap2)); va_end(ap2); create_resfile(ctx, "expected_death", -1, &formatted); } static void _atf_tc_expect_timeout(struct context *ctx, const char *reason, va_list ap) { va_list ap2; atf_dynstr_t formatted; validate_expect(ctx); ctx->expect = EXPECT_TIMEOUT; va_copy(ap2, ap); check_fatal_error(atf_dynstr_init_ap(&formatted, reason, ap2)); va_end(ap2); create_resfile(ctx, "expected_timeout", -1, &formatted); } static void _atf_tc_set_resultsfile(struct context *ctx, const char *file) { context_set_resfile(ctx, file); } /* --------------------------------------------------------------------- * Free functions. * --------------------------------------------------------------------- */ static struct context Current; atf_error_t atf_tc_run(const atf_tc_t *tc, const char *resfile) { context_init(&Current, tc, resfile); tc->pimpl->m_body(tc); validate_expect(&Current); if (Current.fail_count > 0) { atf_dynstr_t reason; format_reason_fmt(&reason, NULL, 0, "%d checks failed; see output for " "more details", Current.fail_count); fail_requirement(&Current, &reason); } else if (Current.expect_fail_count > 0) { atf_dynstr_t reason; format_reason_fmt(&reason, NULL, 0, "%d checks failed as expected; " "see output for more details", Current.expect_fail_count); expected_failure(&Current, &reason); } else { pass(&Current); } UNREACHABLE; return atf_no_error(); } atf_error_t atf_tc_cleanup(const atf_tc_t *tc) { if (tc->pimpl->m_cleanup != NULL) tc->pimpl->m_cleanup(tc); return atf_no_error(); /* XXX */ } /* --------------------------------------------------------------------- * Free functions that depend on Current. * --------------------------------------------------------------------- */ /* * All the functions below provide delegates to other internal functions * (prefixed by _) that take the current test case as an argument to * prevent them from accessing global state. This is to keep the side- * effects of the internal functions clearer and easier to understand. * * The public API should never have hid the fact that it needs access to * the current test case (other than maybe in the macros), but changing it * is hard. TODO: Revisit in the future. */ void atf_tc_fail(const char *fmt, ...) { va_list ap; PRE(Current.tc != NULL); va_start(ap, fmt); _atf_tc_fail(&Current, fmt, ap); va_end(ap); } void atf_tc_fail_nonfatal(const char *fmt, ...) { va_list ap; PRE(Current.tc != NULL); va_start(ap, fmt); _atf_tc_fail_nonfatal(&Current, fmt, ap); va_end(ap); } void atf_tc_fail_check(const char *file, const size_t line, const char *fmt, ...) { va_list ap; PRE(Current.tc != NULL); va_start(ap, fmt); _atf_tc_fail_check(&Current, file, line, fmt, ap); va_end(ap); } void atf_tc_fail_requirement(const char *file, const size_t line, const char *fmt, ...) { va_list ap; PRE(Current.tc != NULL); va_start(ap, fmt); _atf_tc_fail_requirement(&Current, file, line, fmt, ap); va_end(ap); } void atf_tc_pass(void) { PRE(Current.tc != NULL); _atf_tc_pass(&Current); } void atf_tc_require_prog(const char *prog) { PRE(Current.tc != NULL); _atf_tc_require_prog(&Current, prog); } void atf_tc_skip(const char *fmt, ...) { va_list ap; PRE(Current.tc != NULL); va_start(ap, fmt); _atf_tc_skip(&Current, fmt, ap); va_end(ap); } void atf_tc_check_errno(const char *file, const size_t line, const int exp_errno, const char *expr_str, const bool expr_result) { PRE(Current.tc != NULL); _atf_tc_check_errno(&Current, file, line, exp_errno, expr_str, expr_result); } void atf_tc_require_errno(const char *file, const size_t line, const int exp_errno, const char *expr_str, const bool expr_result) { PRE(Current.tc != NULL); _atf_tc_require_errno(&Current, file, line, exp_errno, expr_str, expr_result); } void atf_tc_expect_pass(void) { PRE(Current.tc != NULL); _atf_tc_expect_pass(&Current); } void atf_tc_expect_fail(const char *reason, ...) { va_list ap; PRE(Current.tc != NULL); va_start(ap, reason); _atf_tc_expect_fail(&Current, reason, ap); va_end(ap); } void atf_tc_expect_exit(const int exitcode, const char *reason, ...) { va_list ap; PRE(Current.tc != NULL); va_start(ap, reason); _atf_tc_expect_exit(&Current, exitcode, reason, ap); va_end(ap); } void atf_tc_expect_signal(const int signo, const char *reason, ...) { va_list ap; PRE(Current.tc != NULL); va_start(ap, reason); _atf_tc_expect_signal(&Current, signo, reason, ap); va_end(ap); } void atf_tc_expect_death(const char *reason, ...) { va_list ap; PRE(Current.tc != NULL); va_start(ap, reason); _atf_tc_expect_death(&Current, reason, ap); va_end(ap); } void atf_tc_expect_timeout(const char *reason, ...) { va_list ap; PRE(Current.tc != NULL); va_start(ap, reason); _atf_tc_expect_timeout(&Current, reason, ap); va_end(ap); } /* Internal! */ void atf_tc_set_resultsfile(const char *file) { PRE(Current.tc != NULL); _atf_tc_set_resultsfile(&Current, file); } diff --git a/contrib/atf/atf-sh/atf-check.cpp b/contrib/atf/atf-sh/atf-check.cpp index 38ab527aab54..4cb1e33a005a 100644 --- a/contrib/atf/atf-sh/atf-check.cpp +++ b/contrib/atf/atf-sh/atf-check.cpp @@ -1,943 +1,943 @@ // Copyright (c) 2008 The NetBSD Foundation, Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND // CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER // IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN // IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. extern "C" { #include #include #include #include #include #include } #include #include #include #include #include #include #include #include #include #include #include "atf-c++/check.hpp" #include "atf-c++/detail/application.hpp" #include "atf-c++/detail/auto_array.hpp" #include "atf-c++/detail/env.hpp" #include "atf-c++/detail/exceptions.hpp" #include "atf-c++/detail/fs.hpp" #include "atf-c++/detail/process.hpp" #include "atf-c++/detail/sanity.hpp" #include "atf-c++/detail/text.hpp" static const useconds_t seconds_in_useconds = (1000 * 1000); static const useconds_t mseconds_in_useconds = 1000; static const useconds_t useconds_in_nseconds = 1000; // ------------------------------------------------------------------------ // Auxiliary functions. // ------------------------------------------------------------------------ namespace { enum status_check_t { sc_exit, sc_ignore, sc_signal, }; struct status_check { status_check_t type; bool negated; int value; status_check(const status_check_t& p_type, const bool p_negated, const int p_value) : type(p_type), negated(p_negated), value(p_value) { } }; enum output_check_t { oc_ignore, oc_inline, oc_file, oc_empty, oc_match, oc_save }; struct output_check { output_check_t type; bool negated; std::string value; output_check(const output_check_t& p_type, const bool p_negated, const std::string& p_value) : type(p_type), negated(p_negated), value(p_value) { } }; class temp_file : public std::ostream { std::auto_ptr< atf::fs::path > m_path; int m_fd; public: temp_file(const char* pattern) : std::ostream(NULL), m_fd(-1) { const atf::fs::path file = atf::fs::path( atf::env::get("TMPDIR", "/tmp")) / pattern; atf::auto_array< char > buf(new char[file.str().length() + 1]); std::strcpy(buf.get(), file.c_str()); m_fd = ::mkstemp(buf.get()); if (m_fd == -1) throw atf::system_error("atf_check::temp_file::temp_file(" + file.str() + ")", "mkstemp(3) failed", errno); m_path.reset(new atf::fs::path(buf.get())); } ~temp_file(void) { close(); try { remove(*m_path); } catch (const atf::system_error&) { // Ignore deletion errors. } } const atf::fs::path& get_path(void) const { return *m_path; } void write(const std::string& text) { if (::write(m_fd, text.c_str(), text.size()) == -1) throw atf::system_error("atf_check", "write(2) failed", errno); } void close(void) { if (m_fd != -1) { flush(); ::close(m_fd); m_fd = -1; } } }; } // anonymous namespace static useconds_t get_monotonic_useconds(void) { struct timespec ts; useconds_t res; int rc; rc = clock_gettime(CLOCK_MONOTONIC, &ts); if (rc != 0) throw std::runtime_error("clock_gettime: " + std::string(strerror(errno))); res = ts.tv_sec * seconds_in_useconds; res += ts.tv_nsec / useconds_in_nseconds; return res; } static bool timo_expired(useconds_t timeout) { if (get_monotonic_useconds() >= timeout) return true; return false; } static int parse_exit_code(const std::string& str) { try { const int value = atf::text::to_type< int >(str); if (value < 0 || value > 255) throw std::runtime_error("Unused reason"); return value; } catch (const std::runtime_error&) { throw atf::application::usage_error("Invalid exit code for -s option; " "must be an integer in range 0-255"); } } static struct name_number { const char *name; int signo; } signal_names_to_numbers[] = { { "hup", SIGHUP }, { "int", SIGINT }, { "quit", SIGQUIT }, { "trap", SIGTRAP }, { "abrt", SIGABRT }, { "kill", SIGKILL }, { "segv", SIGSEGV }, { "pipe", SIGPIPE }, { "alrm", SIGALRM }, { "term", SIGTERM }, { "usr1", SIGUSR1 }, { "usr2", SIGUSR2 }, { NULL, INT_MIN }, }; static int signal_name_to_number(const std::string& str) { struct name_number* iter = signal_names_to_numbers; int signo = INT_MIN; while (signo == INT_MIN && iter->name != NULL) { if (str == iter->name || str == std::string("sig") + iter->name) signo = iter->signo; else iter++; } return signo; } static int parse_signal(const std::string& str) { const int signo = signal_name_to_number(str); if (signo == INT_MIN) { try { return atf::text::to_type< int >(str); } catch (const std::runtime_error&) { throw atf::application::usage_error("Invalid signal name or number " "in -s option"); } } INV(signo != INT_MIN); return signo; } static status_check parse_status_check_arg(const std::string& arg) { const std::string::size_type delimiter = arg.find(':'); bool negated = (arg.compare(0, 4, "not-") == 0); const std::string action_str = arg.substr(0, delimiter); const std::string action = negated ? action_str.substr(4) : action_str; const std::string value_str = ( delimiter == std::string::npos ? "" : arg.substr(delimiter + 1)); int value; status_check_t type; if (action == "eq") { // Deprecated; use exit instead. TODO: Remove after 0.10. type = sc_exit; if (negated) throw atf::application::usage_error("Cannot negate eq checker"); negated = false; value = parse_exit_code(value_str); } else if (action == "exit") { type = sc_exit; if (value_str.empty()) value = INT_MIN; else value = parse_exit_code(value_str); } else if (action == "ignore") { if (negated) throw atf::application::usage_error("Cannot negate ignore checker"); type = sc_ignore; value = INT_MIN; } else if (action == "ne") { // Deprecated; use not-exit instead. TODO: Remove after 0.10. type = sc_exit; if (negated) throw atf::application::usage_error("Cannot negate ne checker"); negated = true; value = parse_exit_code(value_str); } else if (action == "signal") { type = sc_signal; if (value_str.empty()) value = INT_MIN; else value = parse_signal(value_str); } else throw atf::application::usage_error("Invalid status checker"); return status_check(type, negated, value); } static output_check parse_output_check_arg(const std::string& arg) { const std::string::size_type delimiter = arg.find(':'); const bool negated = (arg.compare(0, 4, "not-") == 0); const std::string action_str = arg.substr(0, delimiter); const std::string action = negated ? action_str.substr(4) : action_str; output_check_t type; if (action == "empty") type = oc_empty; else if (action == "file") type = oc_file; else if (action == "ignore") { if (negated) throw atf::application::usage_error("Cannot negate ignore checker"); type = oc_ignore; } else if (action == "inline") type = oc_inline; else if (action == "match") type = oc_match; else if (action == "save") { if (negated) throw atf::application::usage_error("Cannot negate save checker"); type = oc_save; } else throw atf::application::usage_error("Invalid output checker"); return output_check(type, negated, arg.substr(delimiter + 1)); } static void parse_repeat_check_arg(const std::string& arg, useconds_t *m_timo, useconds_t *m_interval) { const std::string::size_type delimiter = arg.find(':'); const bool has_interval = (delimiter != std::string::npos); const std::string timo_str = arg.substr(0, delimiter); long l; char *end; // There is no reason this couldn't be a non-integer number of seconds, // this was just easy to do for now. errno = 0; l = strtol(timo_str.c_str(), &end, 10); if (errno == ERANGE) throw atf::application::usage_error("Bogus timeout in seconds"); else if (errno != 0) throw atf::application::usage_error("Timeout must be a number"); if (*end != 0) throw atf::application::usage_error("Timeout must be a number"); *m_timo = get_monotonic_useconds() + (l * seconds_in_useconds); // 50 milliseconds is chosen arbitrarily. There is a tradeoff between // longer and shorter poll times. A shorter poll time makes for faster // tests. A longer poll time makes for lower CPU overhead for the polled // operation. 50ms is chosen with these tradeoffs in mind: on // microcontrollers, the hope is that we can still avoid meaningful CPU use // with a small test every 50ms. And on typical fast x86 hardware, our // tests can be much more precise with time wasted than they typically are // without this feature. *m_interval = 50 * mseconds_in_useconds; if (!has_interval) return; const std::string intv_str = arg.substr(delimiter + 1, std::string::npos); // Same -- this could be non-integer milliseconds. errno = 0; l = strtol(intv_str.c_str(), &end, 10); if (errno == ERANGE) throw atf::application::usage_error( "Bogus repeat interval in milliseconds"); else if (errno != 0) throw atf::application::usage_error( "Repeat interval must be a number"); if (*end != 0) throw atf::application::usage_error( "Repeat interval must be a number"); *m_interval = l * mseconds_in_useconds; } static std::string flatten_argv(char* const* argv) { std::string cmdline; char* const* arg = &argv[0]; while (*arg != NULL) { if (arg != &argv[0]) cmdline += ' '; cmdline += *arg; arg++; } return cmdline; } static std::auto_ptr< atf::check::check_result > execute(const char* const* argv) { // TODO: This should go to stderr... but fixing it now may be hard as test // cases out there might be relying on stderr being silent. std::cout << "Executing command [ "; for (int i = 0; argv[i] != NULL; ++i) std::cout << argv[i] << " "; std::cout << "]\n"; std::cout.flush(); atf::process::argv_array argva(argv); return atf::check::exec(argva); } static std::auto_ptr< atf::check::check_result > execute_with_shell(char* const* argv) { const std::string cmd = flatten_argv(argv); const std::string shell = atf::env::get("ATF_SHELL", ATF_SHELL); const char* sh_argv[4]; sh_argv[0] = shell.c_str(); sh_argv[1] = "-c"; sh_argv[2] = cmd.c_str(); sh_argv[3] = NULL; return execute(sh_argv); } static void cat_file(const atf::fs::path& path) { std::ifstream stream(path.c_str()); if (!stream) throw std::runtime_error("Failed to open " + path.str()); stream >> std::noskipws; std::istream_iterator< char > begin(stream), end; std::ostream_iterator< char > out(std::cerr); std::copy(begin, end, out); stream.close(); } static bool grep_file(const atf::fs::path& path, const std::string& regexp) { std::ifstream stream(path.c_str()); if (!stream) throw std::runtime_error("Failed to open " + path.str()); bool found = false; std::string line; while (!found && !std::getline(stream, line).fail()) { if (atf::text::match(line, regexp)) found = true; } stream.close(); return found; } static bool file_empty(const atf::fs::path& p) { atf::fs::file_info f(p); return (f.get_size() == 0); } static bool compare_files(const atf::fs::path& p1, const atf::fs::path& p2) { bool equal = false; std::ifstream f1(p1.c_str()); if (!f1) throw std::runtime_error("Failed to open " + p1.str()); std::ifstream f2(p2.c_str()); if (!f2) - throw std::runtime_error("Failed to open " + p1.str()); + throw std::runtime_error("Failed to open " + p2.str()); for (;;) { char buf1[512], buf2[512]; f1.read(buf1, sizeof(buf1)); if (f1.bad()) throw std::runtime_error("Failed to read from " + p1.str()); f2.read(buf2, sizeof(buf2)); if (f2.bad()) - throw std::runtime_error("Failed to read from " + p1.str()); + throw std::runtime_error("Failed to read from " + p2.str()); if ((f1.gcount() == 0) && (f2.gcount() == 0)) { equal = true; break; } if ((f1.gcount() != f2.gcount()) || (std::memcmp(buf1, buf2, f1.gcount()) != 0)) { break; } } return equal; } static void print_diff(const atf::fs::path& p1, const atf::fs::path& p2) { const atf::process::status s = atf::process::exec(atf::fs::path("diff"), atf::process::argv_array("diff", "-u", p1.c_str(), p2.c_str(), NULL), atf::process::stream_connect(STDOUT_FILENO, STDERR_FILENO), atf::process::stream_inherit()); if (!s.exited()) std::cerr << "Failed to run diff(3)\n"; if (s.exitstatus() != 1) std::cerr << "Error while running diff(3)\n"; } static std::string decode(const std::string& s) { size_t i; std::string res; res.reserve(s.length()); i = 0; while (i < s.length()) { char c = s[i++]; if (c == '\\') { switch (s[i++]) { case 'a': c = '\a'; break; case 'b': c = '\b'; break; case 'c': break; case 'e': c = 033; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = '\v'; break; case '\\': break; case '0': { int count = 3; c = 0; while (--count >= 0 && (unsigned)(s[i] - '0') < 8) c = (c << 3) + (s[i++] - '0'); break; } default: --i; break; } } res.push_back(c); } return res; } static bool run_status_check(const status_check& sc, const atf::check::check_result& cr) { bool result; if (sc.type == sc_exit) { if (cr.exited() && sc.value != INT_MIN) { const int status = cr.exitcode(); if (!sc.negated && sc.value != status) { std::cerr << "Fail: incorrect exit status: " << status << ", expected: " << sc.value << "\n"; result = false; } else if (sc.negated && sc.value == status) { std::cerr << "Fail: incorrect exit status: " << status << ", expected: " << "anything else\n"; result = false; } else result = true; } else if (cr.exited() && sc.value == INT_MIN) { result = true; } else { std::cerr << "Fail: program did not exit cleanly\n"; result = false; } } else if (sc.type == sc_ignore) { result = true; } else if (sc.type == sc_signal) { if (cr.signaled() && sc.value != INT_MIN) { const int status = cr.termsig(); if (!sc.negated && sc.value != status) { std::cerr << "Fail: incorrect signal received: " << status << ", expected: " << sc.value << "\n"; result = false; } else if (sc.negated && sc.value == status) { std::cerr << "Fail: incorrect signal received: " << status << ", expected: " << "anything else\n"; result = false; } else result = true; } else if (cr.signaled() && sc.value == INT_MIN) { result = true; } else { std::cerr << "Fail: program did not receive a signal\n"; result = false; } } else { UNREACHABLE; result = false; } if (result == false) { std::cerr << "stdout:\n"; cat_file(atf::fs::path(cr.stdout_path())); std::cerr << "\n"; std::cerr << "stderr:\n"; cat_file(atf::fs::path(cr.stderr_path())); std::cerr << "\n"; } return result; } static bool run_status_checks(const std::vector< status_check >& checks, const atf::check::check_result& result) { bool ok = false; for (std::vector< status_check >::const_iterator iter = checks.begin(); !ok && iter != checks.end(); iter++) { ok |= run_status_check(*iter, result); } return ok; } static bool run_output_check(const output_check oc, const atf::fs::path& path, const std::string& stdxxx) { bool result; if (oc.type == oc_empty) { const bool is_empty = file_empty(path); if (!oc.negated && !is_empty) { std::cerr << "Fail: " << stdxxx << " not empty\n"; print_diff(atf::fs::path("/dev/null"), path); result = false; } else if (oc.negated && is_empty) { std::cerr << "Fail: " << stdxxx << " is empty\n"; result = false; } else result = true; } else if (oc.type == oc_file) { const bool equals = compare_files(path, atf::fs::path(oc.value)); if (!oc.negated && !equals) { std::cerr << "Fail: " << stdxxx << " does not match golden " "output\n"; print_diff(atf::fs::path(oc.value), path); result = false; } else if (oc.negated && equals) { std::cerr << "Fail: " << stdxxx << " matches golden output\n"; cat_file(atf::fs::path(oc.value)); result = false; } else result = true; } else if (oc.type == oc_ignore) { result = true; } else if (oc.type == oc_inline) { temp_file temp("atf-check.XXXXXX"); temp.write(decode(oc.value)); temp.close(); const bool equals = compare_files(path, temp.get_path()); if (!oc.negated && !equals) { std::cerr << "Fail: " << stdxxx << " does not match expected " "value\n"; print_diff(temp.get_path(), path); result = false; } else if (oc.negated && equals) { std::cerr << "Fail: " << stdxxx << " matches expected value\n"; cat_file(temp.get_path()); result = false; } else result = true; } else if (oc.type == oc_match) { const bool matches = grep_file(path, oc.value); if (!oc.negated && !matches) { std::cerr << "Fail: regexp " + oc.value + " not in " << stdxxx << "\n"; cat_file(path); result = false; } else if (oc.negated && matches) { std::cerr << "Fail: regexp " + oc.value + " is in " << stdxxx << "\n"; cat_file(path); result = false; } else result = true; } else if (oc.type == oc_save) { INV(!oc.negated); std::ifstream ifs(path.c_str(), std::fstream::binary); ifs >> std::noskipws; std::istream_iterator< char > begin(ifs), end; std::ofstream ofs(oc.value.c_str(), std::fstream::binary | std::fstream::trunc); std::ostream_iterator obegin(ofs); std::copy(begin, end, obegin); result = true; } else { UNREACHABLE; result = false; } return result; } static bool run_output_checks(const std::vector< output_check >& checks, const atf::fs::path& path, const std::string& stdxxx) { bool ok = true; for (std::vector< output_check >::const_iterator iter = checks.begin(); iter != checks.end(); iter++) { ok &= run_output_check(*iter, path, stdxxx); } return ok; } // ------------------------------------------------------------------------ // The "atf_check" application. // ------------------------------------------------------------------------ namespace { class atf_check : public atf::application::app { bool m_rflag; bool m_xflag; useconds_t m_timo; useconds_t m_interval; std::vector< status_check > m_status_checks; std::vector< output_check > m_stdout_checks; std::vector< output_check > m_stderr_checks; static const char* m_description; bool run_output_checks(const atf::check::check_result&, const std::string&) const; std::string specific_args(void) const; options_set specific_options(void) const; void process_option(int, const char*); void process_option_s(const std::string&); public: atf_check(void); int main(void); }; } // anonymous namespace const char* atf_check::m_description = "atf-check executes given command and analyzes its results."; atf_check::atf_check(void) : app(m_description, "atf-check(1)"), m_rflag(false), m_xflag(false) { } bool atf_check::run_output_checks(const atf::check::check_result& r, const std::string& stdxxx) const { if (stdxxx == "stdout") { return ::run_output_checks(m_stdout_checks, atf::fs::path(r.stdout_path()), "stdout"); } else if (stdxxx == "stderr") { return ::run_output_checks(m_stderr_checks, atf::fs::path(r.stderr_path()), "stderr"); } else { UNREACHABLE; return false; } } std::string atf_check::specific_args(void) const { return ""; } atf_check::options_set atf_check::specific_options(void) const { using atf::application::option; options_set opts; opts.insert(option('s', "qual:value", "Handle status. Qualifier " "must be one of: ignore exit: signal:")); opts.insert(option('o', "action:arg", "Handle stdout. Action must be " "one of: empty ignore file: inline: match:regexp " "save:")); opts.insert(option('e', "action:arg", "Handle stderr. Action must be " "one of: empty ignore file: inline: match:regexp " "save:")); opts.insert(option('r', "timeout[:interval]", "Repeat failed check until " "the timeout expires.")); opts.insert(option('x', "", "Execute command as a shell command")); return opts; } void atf_check::process_option(int ch, const char* arg) { switch (ch) { case 's': m_status_checks.push_back(parse_status_check_arg(arg)); break; case 'o': m_stdout_checks.push_back(parse_output_check_arg(arg)); break; case 'e': m_stderr_checks.push_back(parse_output_check_arg(arg)); break; case 'r': m_rflag = true; parse_repeat_check_arg(arg, &m_timo, &m_interval); break; case 'x': m_xflag = true; break; default: UNREACHABLE; } } int atf_check::main(void) { if (m_argc < 1) throw atf::application::usage_error("No command specified"); int status = EXIT_FAILURE; if (m_status_checks.empty()) m_status_checks.push_back(status_check(sc_exit, false, EXIT_SUCCESS)); else if (m_status_checks.size() > 1) { // TODO: Remove this restriction. throw atf::application::usage_error("Cannot specify -s more than once"); } if (m_stdout_checks.empty()) m_stdout_checks.push_back(output_check(oc_empty, false, "")); if (m_stderr_checks.empty()) m_stderr_checks.push_back(output_check(oc_empty, false, "")); do { std::auto_ptr< atf::check::check_result > r = m_xflag ? execute_with_shell(m_argv) : execute(m_argv); if ((run_status_checks(m_status_checks, *r) == false) || (run_output_checks(*r, "stderr") == false) || (run_output_checks(*r, "stdout") == false)) status = EXIT_FAILURE; else status = EXIT_SUCCESS; if (m_rflag && status == EXIT_FAILURE) { if (timo_expired(m_timo)) break; usleep(m_interval); } } while (m_rflag && status == EXIT_FAILURE); return status; } int main(int argc, char* const* argv) { return atf_check().run(argc, argv); } diff --git a/contrib/atf/atf-sh/atf-sh.3 b/contrib/atf/atf-sh/atf-sh.3 index 5d1119b2b5dc..c3080c296826 100644 --- a/contrib/atf/atf-sh/atf-sh.3 +++ b/contrib/atf/atf-sh/atf-sh.3 @@ -1,384 +1,384 @@ .\" Copyright (c) 2008 The NetBSD Foundation, Inc. .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND .\" CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, .\" INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF .\" MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. .\" IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY .\" DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE .\" GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER .\" IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR .\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN .\" IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -.Dd June 08, 2017 +.Dd January 27, 2021 .Dt ATF-SH 3 .Os .Sh NAME .Nm atf_add_test_case , .Nm atf_check , .Nm atf_check_equal , .Nm atf_check_not_equal , .Nm atf_config_get , .Nm atf_config_has , .Nm atf_expect_death , .Nm atf_expect_exit , .Nm atf_expect_fail , .Nm atf_expect_pass , .Nm atf_expect_signal , .Nm atf_expect_timeout , .Nm atf_fail , .Nm atf_get , .Nm atf_get_srcdir , .Nm atf_init_test_cases , .Nm atf_pass , .Nm atf_require_prog , .Nm atf_set , .Nm atf_skip , .Nm atf_test_case .Nd POSIX shell API to write ATF-based test programs .Sh SYNOPSIS .Nm atf_add_test_case .Qq name .Nm atf_check .Qq command .Nm atf_check_equal .Qq expected_expression .Qq actual_expression .Nm atf_check_not_equal .Qq expected_expression .Qq actual_expression .Nm atf_config_get .Qq var_name .Nm atf_config_has .Qq var_name .Nm atf_expect_death .Qq reason .Qq ... .Nm atf_expect_exit .Qq exitcode .Qq reason .Qq ... .Nm atf_expect_fail .Qq reason .Qq ... .Nm atf_expect_pass .Qq .Nm atf_expect_signal .Qq signo .Qq reason .Qq ... .Nm atf_expect_timeout .Qq reason .Qq ... .Nm atf_fail .Qq reason .Nm atf_get .Qq var_name .Nm atf_get_srcdir .Nm atf_init_test_cases .Qq name .Nm atf_pass .Nm atf_require_prog .Qq prog_name .Nm atf_set .Qq var_name .Qq value .Nm atf_skip .Qq reason .Nm atf_test_case .Qq name .Qq cleanup .Sh DESCRIPTION ATF provides a simple but powerful interface to easily write test programs in the POSIX shell language. These are extremely helpful given that they are trivial to write due to the language simplicity and the great deal of available external tools, so they are often ideal to test other applications at the user level. .Pp Test programs written using this library must be run using the .Xr atf-sh 1 interpreter by putting the following on their very first line: .Bd -literal -offset indent #! /usr/bin/env atf-sh .Ed .Pp Shell-based test programs always follow this template: .Bd -literal -offset indent atf_test_case tc1 tc1_head() { ... first test case's header ... } tc1_body() { ... first test case's body ... } atf_test_case tc2 cleanup tc2_head() { ... second test case's header ... } tc2_body() { ... second test case's body ... } tc2_cleanup() { ... second test case's cleanup ... } \&... additional test cases ... atf_init_test_cases() { atf_add_test_case tc1 atf_add_test_case tc2 ... add additional test cases ... } .Ed .Ss Definition of test cases Test cases have an identifier and are composed of three different parts: the header, the body and an optional cleanup routine, all of which are described in .Xr atf-test-case 4 . To define test cases, one can use the .Nm atf_test_case function, which takes a first parameter specifying the test case's name and instructs the library to set things up to accept it as a valid test case. The second parameter is optional and, if provided, must be .Sq cleanup ; providing this parameter allows defining a cleanup routine for the test case. It is important to note that this function .Em does not set the test case up for execution when the program is run. In order to do so, a later registration is needed through the .Nm atf_add_test_case function detailed in .Sx Program initialization . .Pp Later on, one must define the three parts of the body by providing two or three functions (remember that the cleanup routine is optional). These functions are named after the test case's identifier, and are .Nm \*(Ltid\*(Gt_head , .Nm \*(Ltid\*(Gt_body and .Nm \*(Ltid\*(Gt_cleanup . None of these take parameters when executed. .Ss Program initialization The test program must define an .Nm atf_init_test_cases function, which is in charge of registering the test cases that will be executed at run time by using the .Nm atf_add_test_case function, which takes the name of a test case as its single parameter. This main function should not do anything else, except maybe sourcing auxiliary source files that define extra variables and functions. .Ss Configuration variables The test case has read-only access to the current configuration variables through the .Nm atf_config_has and .Nm atf_config_get methods. The former takes a single parameter specifying a variable name and returns a boolean indicating whether the variable is defined or not. The latter can take one or two parameters. If it takes only one, it specifies the variable from which to get the value, and this variable must be defined. If it takes two, the second one specifies a default value to be returned if the variable is not available. .Ss Access to the source directory It is possible to get the path to the test case's source directory from anywhere in the test program by using the .Nm atf_get_srcdir function. It is interesting to note that this can be used inside .Nm atf_init_test_cases to silently include additional helper files from the source directory. .Ss Requiring programs Aside from the .Va require.progs meta-data variable available in the header only, one can also check for additional programs in the test case's body by using the .Nm atf_require_prog function, which takes the base name or full path of a single binary. Relative paths are forbidden. If it is not found, the test case will be automatically skipped. .Ss Test case finalization The test case finalizes either when the body reaches its end, at which point the test is assumed to have .Em passed , or at any explicit call to .Nm atf_pass , .Nm atf_fail or .Nm atf_skip . These three functions terminate the execution of the test case immediately. The cleanup routine will be processed afterwards in a completely automated way, regardless of the test case's termination reason. .Pp .Nm atf_pass does not take any parameters. .Nm atf_fail and .Nm atf_skip take a single string parameter that describes why the test case failed or was skipped, respectively. It is very important to provide a clear error message in both cases so that the user can quickly know why the test did not pass. .Ss Expectations Everything explained in the previous section changes when the test case expectations are redefined by the programmer. .Pp Each test case has an internal state called .Sq expect that describes what the test case expectations are at any point in time. The value of this property can change during execution by any of: .Bl -tag -width indent .It Nm atf_expect_death Qo reason Qc Qo ... Qc Expects the test case to exit prematurely regardless of the nature of the exit. .It Nm atf_expect_exit Qo exitcode Qc Qo reason Qc Qo ... Qc Expects the test case to exit cleanly. If .Va exitcode is not .Sq -1 , the runtime engine will validate that the exit code of the test case matches the one provided in this call. Otherwise, the exact value will be ignored. .It Nm atf_expect_fail Qo reason Qc Any failure raised in this mode is recorded, but such failures do not report the test case as failed; instead, the test case finalizes cleanly and is reported as .Sq expected failure ; this report includes the provided .Fa reason as part of it. If no error is raised while running in this mode, then the test case is reported as .Sq failed . .Pp This mode is useful to reproduce actual known bugs in tests. Whenever the developer fixes the bug later on, the test case will start reporting a failure, signaling the developer that the test case must be adjusted to the new conditions. In this situation, it is useful, for example, to set .Fa reason as the bug number for tracking purposes. .It Nm atf_expect_pass This is the normal mode of execution. In this mode, any failure is reported as such to the user and the test case is marked as .Sq failed . .It Nm atf_expect_signal Qo signo Qc Qo reason Qc Qo ... Qc Expects the test case to terminate due to the reception of a signal. If .Va signo is not .Sq -1 , the runtime engine will validate that the signal that terminated the test case matches the one provided in this call. Otherwise, the exact value will be ignored. .It Nm atf_expect_timeout Qo reason Qc Qo ... Qc Expects the test case to execute for longer than its timeout. .El .Ss Helper functions for common checks .Bl -tag -width indent .It Nm atf_check Qo [options] Qc Qo command Qc Qo [args] Qc Executes a command, performs checks on its exit code and its output, and fails the test case if any of the checks is not successful. This function is particularly useful in integration tests that verify the correct functioning of a binary. .Pp Internally, this function is just a wrapper over the .Xr atf-check 1 tool (whose manual page provides all details on the calling syntax). You should always use the .Nm atf_check function instead of the .Xr atf-check 1 tool in your scripts; the latter is not even in the path. .It Nm atf_check_equal Qo expected_expression Qc Qo actual_expression Qc This function takes two expressions, evaluates them and, if their results differ, aborts the test case with an appropriate failure message. The common style is to put the expected value in the first parameter and the actual value in the second parameter. .It Nm atf_check_not_equal Qo expected_expression Qc Qo actual_expression Qc This function takes two expressions, evaluates them and, if their results are equal, aborts the test case with an appropriate failure message. The common style is to put the expected value in the first parameter and the actual value in the second parameter. .El .Sh EXAMPLES The following shows a complete test program with a single test case that validates the addition operator: .Bd -literal -offset indent atf_test_case addition addition_head() { atf_set "descr" "Sample tests for the addition operator" } addition_body() { atf_check_equal 0 $((0 + 0)) atf_check_equal 1 $((0 + 1)) atf_check_equal 1 $((1 + 0)) atf_check_equal 2 $((1 + 1)) atf_check_equal 300 $((100 + 200)) } atf_init_test_cases() { atf_add_test_case addition } .Ed .Pp This other example shows how to include a file with extra helper functions in the test program: .Bd -literal -offset indent \&... definition of test cases ... atf_init_test_cases() { . $(atf_get_srcdir)/helper_functions.sh atf_add_test_case foo1 atf_add_test_case foo2 } .Ed .Pp This example demonstrates the use of the very useful .Nm atf_check function: .Bd -literal -offset indent # Check for silent output -atf_check -s exit:0 -o empty -e empty 'true' +atf_check -s exit:0 -o empty -e empty true # Check for silent output and failure -atf_check -s exit:1 -o empty -e empty 'false' +atf_check -s exit:1 -o empty -e empty false # Check for known stdout and silent stderr echo foo >expout -atf_check -s exit:0 -o file:expout -e empty 'echo foo' +atf_check -s exit:0 -o file:expout -e empty echo foo # Generate a file for later inspection -atf_check -s exit:0 -o save:stdout -e empty 'ls' +atf_check -s exit:0 -o save:stdout -e empty ls grep foo ls || atf_fail "foo file not found in listing" # Or just do the match along the way -atf_check -s exit:0 -o match:"^foo$" -e empty 'ls' +atf_check -s exit:0 -o match:"^foo$" -e empty ls .Ed .Sh SEE ALSO .Xr atf-check 1 , .Xr atf-sh 1 , .Xr atf-test-program 1 , .Xr atf-test-case 4