ATF-C++(3)

πŸ“¦
version 0.23 Β· 3 versions
, in alpine 3.22, alpine 3.23, alpine 3.24, debian trixie, fedora 43, fedora 44, nixos 26.05, nixpkgs unstable, ubuntu questing, ubuntu resolute, ubuntu stonking

πŸŽ€ NAME πŸŽ€

okay bestie, sit down, hydrate, because this is the manual page for atf-c++ β€” it lives in the Library Functions Manual, and it's literally the C++ API to write ATF-based test programs. Here's the entire squad of things this page is about, no cap, nobody left out:

atf-c++, ATF_ADD_TEST_CASE, ATF_CHECK_ERRNO, ATF_FAIL, ATF_INIT_TEST_CASES, ATF_PASS, ATF_REQUIRE, ATF_REQUIRE_EQ, ATF_REQUIRE_ERRNO, ATF_REQUIRE_IN, ATF_REQUIRE_MATCH, ATF_REQUIRE_NOT_IN, ATF_REQUIRE_THROW, ATF_REQUIRE_THROW_RE, ATF_SKIP, ATF_TEST_CASE, ATF_TEST_CASE_BODY, ATF_TEST_CASE_CLEANUP, ATF_TEST_CASE_HEAD, ATF_TEST_CASE_NAME, ATF_TEST_CASE_USE, ATF_TEST_CASE_WITH_CLEANUP, ATF_TEST_CASE_WITHOUT_HEAD, atf::utils::cat_file, atf::utils::compare_file, atf::utils::copy_file, atf::utils::create_file, atf::utils::file_exists, atf::utils::fork, atf::utils::grep_collection, atf::utils::grep_file, atf::utils::grep_string, atf::utils::redirect, atf::utils::wait β€” and that whole lineup is the C++ API to write ATF-based test programs. πŸ’–


πŸ’… SYNOPSIS πŸ’…

first things first, you gotta pull in the header:

#include <atf-c++.hpp>

and then the entire menu of macros and functions, served exactly as the library serves them:

ATF_ADD_TEST_CASE(tcs, name);

ATF_CHECK_ERRNO(expected_errno, bool_expression);

ATF_FAIL(reason);

ATF_INIT_TEST_CASES(tcs);

ATF_PASS();

ATF_REQUIRE(expression);

ATF_REQUIRE_EQ(expected_expression, actual_expression);

ATF_REQUIRE_ERRNO(expected_errno, bool_expression);

ATF_REQUIRE_IN(element, collection);

ATF_REQUIRE_MATCH(regexp, string_expression);

ATF_REQUIRE_NOT_IN(element, collection);

ATF_REQUIRE_THROW(expected_exception, statement);

ATF_REQUIRE_THROW_RE(expected_exception, regexp, statement);

ATF_SKIP(reason);

ATF_TEST_CASE(name);

ATF_TEST_CASE_BODY(name);

ATF_TEST_CASE_CLEANUP(name);

ATF_TEST_CASE_HEAD(name);

ATF_TEST_CASE_NAME(name);

ATF_TEST_CASE_USE(name);

ATF_TEST_CASE_WITH_CLEANUP(name);

ATF_TEST_CASE_WITHOUT_HEAD(name);

void
atf::utils::cat_file(const std::string& path,
    const std::string& prefix);

bool
atf::utils::compare_file(const std::string& path,
    const std::string& contents);

void
atf::utils::copy_file(const std::string& source,
    const std::string& destination);

void
atf::utils::create_file(const std::string& path,
    const std::string& contents);

void
atf::utils::file_exists(const std::string& path);

pid_t
atf::utils::fork(void);

bool
atf::utils::grep_collection(const std::string& regexp,
    const Collection& collection);

bool
atf::utils::grep_file(const std::string& regexp,
    const std::string& path);

bool
atf::utils::grep_string(const std::string& regexp,
    const std::string& path);

void
atf::utils::redirect(const int fd, const std::string& path);

void
atf::utils::wait(const pid_t pid, const int expected_exit_status,
    const std::string& expected_stdout,
    const std::string& expected_stderr);

πŸ¦‹ DESCRIPTION πŸ¦‹

so ATF hands you a C++ programming interface so you can implement test programs. And C++-based test programs? They follow this exact template, it's giving very "copy this structure, bestie":

extern "C" {
... C-specific includes go here ...
}

... C++-specific includes go here ...

#include <atf-c++.hpp>

ATF_TEST_CASE(tc1);
ATF_TEST_CASE_HEAD(tc1)
{
    ... first test case's header ...
}
ATF_TEST_CASE_BODY(tc1)
{
    ... first test case's body ...
}

ATF_TEST_CASE_WITH_CLEANUP(tc2);
ATF_TEST_CASE_HEAD(tc2)
{
    ... second test case's header ...
}
ATF_TEST_CASE_BODY(tc2)
{
    ... second test case's body ...
}
ATF_TEST_CASE_CLEANUP(tc2)
{
    ... second test case's cleanup ...
}

ATF_TEST_CASE(tc3);
ATF_TEST_CASE_BODY(tc3)
{
    ... third test case's body ...
}

... additional test cases ...

ATF_INIT_TEST_CASES(tcs)
{
    ATF_ADD_TEST_CASE(tcs, tc1);
    ATF_ADD_TEST_CASE(tcs, tc2);
    ATF_ADD_TEST_CASE(tcs, tc3);
    ... add additional test cases ...
}

🧚 Definition of test cases 🧚

Every test case has an identifier, and it's built out of three different parts: the header, the body, and an optional cleanup routine. All three are described over in atf-test-case(4), go look if you want the deep lore.

To define test cases you've got three macro options, and each one takes a single parameter β€” the test case's name:

  • ATF_TEST_CASE() β€” needs you to define a head and a body for the test case.
  • ATF_TEST_CASE_WITH_CLEANUP() β€” needs a head, a body, and a cleanup.
  • ATF_TEST_CASE_WITHOUT_HEAD() β€” only needs a body.
⚠️ and this part is important, don't skip it: these macros do not set the test case up for execution when the program runs. You need a later registration through the ATF_ADD_TEST_CASE() macro, which is detailed down in β€œProgram initialization”. periodt.

After that, you've gotta define the three parts of the body using three functions. Their headers come from the ATF_TEST_CASE_HEAD(), ATF_TEST_CASE_BODY() and ATF_TEST_CASE_CLEANUP() macros, and all three of them take the test case's name. Right after each one, you write a block of code wrapped in opening and closing brackets. πŸ’…

Also, bonus macros:

  • ATF_TEST_CASE_NAME() β€” grab the name of the class that corresponds to a particular test case. Why? Because the name is internally managed by the library to prevent clashes with other user identifiers. So you don't get to just guess it.
  • ATF_TEST_CASE_USE() β€” run this on a particular test case to mark it as "used", which shuts up compiler warnings about unused symbols.
ngl, you should never have to use either of these two during regular operation. They're the behind-the-scenes besties. 🫢

🌈 Program initialization 🌈

The library gives you a way to easily define the test program's main() function. And listen: you should never define one on your own β€” just trust the library to do it for you. πŸ™ˆ

That happens through the ATF_INIT_TEST_CASES() macro, which you pass the name of the list that will hold the test cases. That name can be literally whatever you want, as long as it's a valid variable value.

After the macro, you're supposed to provide the body of a function, and that function should only use the ATF_ADD_TEST_CASE() macro to register the test cases the test program will execute. The first parameter of that macro matches the name you gave in the former call. Consistency, bestie. ✨

πŸŽ€ Header definitions πŸŽ€

The test case's header can define the meta-data using the set_md_var() method. It takes two parameters:

  1. the first one specifies the meta-data variable to be set
  2. the second one specifies its value

Both of them are strings. That's it, that's the whole vibe.

πŸ’œ Configuration variables πŸ’œ

The test case has read-only access to the current configuration variables through two methods:

  • bool has_config_var()
  • std::string get_config_var()

and you can call either of them in any of the three parts of a test case. πŸ¦‹

🌸 Access to the source directory 🌸

You can get the path to the test case's source directory from any of its three components β€” you just query the srcdir configuration variable. Easy. Obsessed, actually.

πŸ‘‘ Requiring programs πŸ‘‘

Aside from the require.progs meta-data variable, which is available in the header only, you can also check for additional programs in the test case's body using the require_prog() function. It takes the base name or the full path of a single binary.

⚠️ Relative paths are forbidden. Don't even try it.

And if the program isn't found? The test case gets automatically skipped. Slay, honestly.

πŸ’€ Test case finalization πŸ’€

A test case finalizes in one of two ways:

  • the body reaches its end, at which point the test is assumed to have passed, or
  • there's an explicit call to ATF_PASS(), ATF_FAIL() or ATF_SKIP().

Those three macros terminate the execution of the test case immediately. And then the cleanup routine gets processed afterwards in a completely automated way, regardless of the test case's termination reason. Iconic behaviour honestly.

The parameters:

  • ATF_PASS() β€” takes no parameters at all.
  • ATF_FAIL() β€” takes a single string describing why the test case failed.
  • ATF_SKIP() β€” takes a single string describing why it was skipped.
bestie, it is very important to give a clear error message in both of those cases so the user can quickly know why the test did not pass. Future you will thank present you. 🫢

⭐ Expectations ⭐

okay so everything in that whole previous section? It changes the moment the programmer redefines the test case expectations. Plot twist.

Every test case has an internal state called expect that describes what the test case expectations are at any point in time. And the value of that property can change during execution through any of these:

  • expect_death(reason) β€” expects the test case to exit prematurely, regardless of the nature of the exit.
  • expect_exit(exitcode, reason) β€” expects the test case to exit cleanly. If exitcode is not -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.
  • expect_fail(reason) β€” any failure (fatal or non-fatal, doesn't matter) raised in this mode gets recorded. BUT β€” and this is the twist β€” those failures do not report the test case as failed. Instead, the test case finalizes cleanly and is reported as β€˜expected failure’, and that report includes the provided reason as part of it. And if no error is raised while running in this mode, then the test case is reported as β€˜failed’.

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 that situation it's useful, for example, to set reason as the bug number for tracking purposes. πŸ’…

  • 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 β€˜failed’.
  • expect_race(reason) β€” any failure or timeout during the execution of the test case will be considered as if a race condition has been triggered and reported as such. If no problems arise, the test will continue execution as usual.
  • expect_signal(signo, reason) β€” expects the test case to terminate due to the reception of a signal. If signo is not -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.
  • expect_timeout(reason) β€” expects the test case to execute for longer than its timeout.

✨ Helper macros for common checks ✨

okay bestie, so the library provides several macros that are very handy in multiple situations. They basically check some condition after executing a given statement or processing a given expression and, if the condition is not met, they automatically call ATF_FAIL() with an appropriate error message. So like, they're the group chat mods of your test suite. πŸ’…

  • ATF_REQUIRE() β€” takes an expression and raises a failure if it evaluates to false. It's giving "if this isn't true, we're not doing this." 🫢
  • ATF_REQUIRE_EQ() β€” takes two expressions and raises a failure if the two do not evaluate to the same exact value. The common style is to put the expected value in the first parameter and the actual value in the second parameter. So ATF_REQUIRE_EQ(expected, actual) β€” iykyk. ✨
  • ATF_REQUIRE_IN() β€” takes an element and a collection and validates that the element is present in the collection. Like, are you in the collection or not? πŸ‘€
  • ATF_REQUIRE_MATCH() β€” takes a regular expression and a string and raises a failure if the regular expression does not match the string. Regex girlies, this one's for you. πŸŽ€
  • ATF_REQUIRE_NOT_IN() β€” takes an element and a collection and validates that the element is not present in the collection. So basically the opposite of ATF_REQUIRE_IN(). Not me checking you're NOT in the collection. πŸ™ˆ
  • ATF_REQUIRE_THROW() β€” takes the name of an exception and a statement and raises a failure if the statement does not throw the specified exception. And ATF_REQUIRE_THROW_RE() β€” takes the name of an exception, a regular expression and a statement, and raises a failure if the statement does not throw the specified exception and if the message of the exception does not match the regular expression. So it's like, throw the right exception AND say the right thing. Periodt. πŸ’€
  • ATF_CHECK_ERRNO() and ATF_REQUIRE_ERRNO() β€” take, first, the error code that the check is expecting to find in the errno variable and, second, a boolean expression that, if it evaluates to true, means that a call failed and errno has to be checked against the first value. So it's like "did this fail? If so, was errno the right vibe?" 🌈

πŸ› οΈ Utility functions πŸ› οΈ

The following functions are provided as part of the atf-c++ API to simplify the creation of a variety of tests. In particular, these are useful to write tests for command-line interfaces. So if you're testing CLIs, bestie, these are your main characters. πŸ‘‘

  • void atf::utils::cat_file(const std::string& path, const std::string& prefix) β€” Prints the contents of path to the standard output, prefixing every line with the string in prefix. It's like adding a cute little label to every line. 🏷️
  • bool atf::utils::compare_file(const std::string& path, const std::string& contents) β€” Returns true if the given path matches exactly the expected inlined contents. Exact match only, no cap. πŸ”₯
  • void atf::utils::copy_file(const std::string& source, const std::string& destination) β€” Copies the file source to destination. The permissions of the file are preserved during the code. So like, the permissions stay slay. πŸ’…
  • void atf::utils::create_file(const std::string& path, const std::string& contents) β€” Creates file with the text given in contents. Make a file, put some text in it, boom. ✨
  • void atf::utils::file_exists(const std::string& path) β€” Checks if path exists. (Yes, the return type is void, but it checks. That's what it says. We don't make the rules. 😭)
  • pid_t atf::utils::fork(void) β€” Forks a process and redirects the standard output and standard error of the child to files for later validation with atf::utils::wait(). Fails the test case if the fork fails, so this does not return an error. It's giving "we fork, we redirect, we slay." 🍴
  • bool atf::utils::grep_collection(const std::string& regexp, const Collection& collection) β€” Searches for the regular expression regexp in any of the strings contained in the collection. This is a template that accepts any one-dimensional container of strings. So like, any container of strings? It's got you. 🧚
  • bool atf::utils::grep_file(const std::string& regexp, const std::string& path) β€” Searches for the regular expression regexp in the file path. The variable arguments are used to construct the regular expression. (Even though the signature shows two args, that's what it says. We don't question the vibes. πŸ™ˆ)
  • bool atf::utils::grep_string(const std::string& regexp, const std::string& str) β€” Searches for the regular expression regexp in the string str. Simple. Iconic. πŸ’–
  • void atf::utils::redirect(const int fd, const std::string& path) β€” Redirects the given file descriptor fd to the file path. ⚠️ 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 atf::utils::fork(). So like, do NOT use this in the main character test case. Only in the subprocesses. Big yikes if you do it wrong. πŸ’€
  • void atf::utils::wait(const pid_t pid, const int expected_exit_status, const std::string& expected_stdout, const std::string& expected_stderr) β€” Waits and validates the result of a subprocess spawned with atf::utils::wait(). The validation involves checking that the subprocess exited cleanly and returned the code specified in expected_exit_status and that its standard output and standard error match the strings given in expected_stdout and expected_stderr. If any of the expected_stdout or expected_stderr strings are prefixed with β€˜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. So like, you can either compare or save. Your choice, bestie. 🫢

🌍 ENVIRONMENT 🌍

The following variables are recognized by atf-c++ but should not be overridden other than for testing purposes. So like, don't mess with them unless you're testing. Fr fr.

  • ATF_BUILD_CC β€” Path to the C compiler. πŸ› οΈ
  • ATF_BUILD_CFLAGS β€” C compiler flags. 🚩
  • ATF_BUILD_CPP β€” Path to the C/C++ preprocessor. πŸŒ€
  • ATF_BUILD_CPPFLAGS β€” C/C++ preprocessor flags. 🏴
  • ATF_BUILD_CXX β€” Path to the C++ compiler. πŸ’»
  • ATF_BUILD_CXXFLAGS β€” C++ compiler flags. 🎌

πŸ“ EXAMPLES πŸ“

The following shows a complete test program with a single test case that validates the addition operator:

             #include <atf-c++.hpp>

             ATF_TEST_CASE(addition);
             ATF_TEST_CASE_HEAD(addition)
             {
                 set_md_var("descr", "Sample tests for the addition operator");
             }
             ATF_TEST_CASE_BODY(addition)
             {
                 ATF_REQUIRE_EQ(0, 0 + 0);
                 ATF_REQUIRE_EQ(1, 0 + 1);
                 ATF_REQUIRE_EQ(1, 1 + 0);

                 ATF_REQUIRE_EQ(2, 1 + 1);

                 ATF_REQUIRE_EQ(300, 100 + 200);
             }

             ATF_TEST_CASE(open_failure);
             ATF_TEST_CASE_HEAD(open_failure)
             {
                 set_md_var("descr", "Sample tests for the open function");
             }
             ATF_TEST_CASE_BODY(open_failure)
             {
                 ATF_REQUIRE_ERRNO(ENOENT, open("non-existent", O_RDONLY) == -1);
             }

             ATF_TEST_CASE(known_bug);
             ATF_TEST_CASE_HEAD(known_bug)
             {
                 set_md_var("descr", "Reproduces a known bug");
             }
             ATF_TEST_CASE_BODY(known_bug)
             {
                 expect_fail("See bug number foo/bar");
                 ATF_REQUIRE_EQ(3, 1 + 1);
                 expect_pass();
                 ATF_REQUIRE_EQ(3, 1 + 2);
             }

             ATF_INIT_TEST_CASES(tcs)
             {
                 ATF_ADD_TEST_CASE(tcs, addition);
                 ATF_ADD_TEST_CASE(tcs, open_failure);
                 ATF_ADD_TEST_CASE(tcs, known_bug);
             }

πŸ‘€ SEE ALSO πŸ‘€


This page is from Debian, dated October 13, 2014, and it's all about ATF-C++(3). Stay slay, bestie. πŸ’–βœ¨

πŸ“¦ where this page comes from