Annotation of wikisrc/tutorials/atf.mdwn, revision 1.10

1.5       jmmv        1: [[!meta title="Creating atf-based tests for NetBSD src"]]
                      2: [[!toc ]]
                      3: 
1.10    ! jmmv        4: # Introduction
        !             5: 
1.7       jmmv        6: This quick tutorial provides a guideline on how to start creating new test
1.1       jmmv        7: programs and/or test cases, how these tests are tied to the NetBSD source tree
1.7       jmmv        8: and includes a short reference of the most commonly used functions.
1.1       jmmv        9: 
                     10: You should start by reading the
                     11: [tests(7)](http://netbsd.gw.com/cgi-bin/man-cgi?tests++NetBSD-current) manual
1.7       jmmv       12: page, which provides a user-level overview on how to run the tests included in
                     13: NetBSD.  While reading this tutorial, you may also want to refer to these pages
                     14: on a need-to-know basis:
1.1       jmmv       15: [atf-run(1)](http://netbsd.gw.com/cgi-bin/man-cgi?atf-run++NetBSD-current),
                     16: [atf-report(1)](http://netbsd.gw.com/cgi-bin/man-cgi?atf-report++NetBSD-current),
                     17: [atf-test-program(1)](http://netbsd.gw.com/cgi-bin/man-cgi?atf-test-program++NetBSD-current),
1.7       jmmv       18: [atf-c-api(3)](http://netbsd.gw.com/cgi-bin/man-cgi?atf-c-api++NetBSD-current),
                     19: [atf-sh-api(3)](http://netbsd.gw.com/cgi-bin/man-cgi?atf-sh-api++NetBSD-current)
1.1       jmmv       20: and
1.7       jmmv       21: [atf-check(1)](http://netbsd.gw.com/cgi-bin/man-cgi?atf-check++NetBSD-current).
1.1       jmmv       22: 
                     23: **IMPORTANT: Do not take anything for granted, SPECIALLY if you have previously
                     24: worked with and/or have seen src/regress/.  Your assumptions are most likely
1.2       jmmv       25: incorrect.**
1.1       jmmv       26: 
1.5       jmmv       27: # Test programs vs. test cases
1.1       jmmv       28: 
                     29: So, what is what and how do you organize your tests?
                     30: 
                     31: A **test case** is a piece of code that exercises a particular functionality of
                     32: another piece of code.  Commonly, test cases validate the outcome of a
                     33: particular source function or class method, the validity of the execution of a
                     34: command with a particular combination of flags/arguments, etc.  Test cases are
                     35: supposed to be very concise, in the sense that they should just be testing *one
                     36: behavior*.
                     37: 
                     38: A **test program** is a binary that collects and exposes a group of test cases.
                     39: Typically, these test programs expose conceptually-related tests or all the
                     40: tests for a particular source file.
                     41: 
                     42: In general, having many test programs with **just one test case** in them is
                     43: **wrong** and smells from the previous layout of src/regress/.  Think about some
                     44: other organization.  And don't blame atf for this separation: this is extremely
                     45: common in (almost?) all other test frameworks and, when used wisely, becomes an
                     46: invaluable classification.
                     47: 
                     48: For example, suppose you have the following fictitious source files for the ls
                     49: tool:
                     50: 
                     51: * bin/ls/fs.c: Provides the list_files() and stat_files() functions.
                     52: 
                     53: * bin/ls/ui.c: Provides the format_columns() function.
                     54: 
                     55: * bin/ls/main.c: The main method for ls.
                     56: 
                     57: Then, you could define the following test programs and test cases:
                     58: 
                     59: * bin/ls/fs_test.c: Provides test cases for list_files and stat_files.  These
                     60:   would be named list_files__empty_directory, list_files__one_file,
                     61:   list_files__multiple_files, stat_files__directory, stat_files__symlink, etc.
                     62: 
                     63: * bin/ls/ui_test.c: Provides test cases for the format_columns function.  These
                     64:   would be named format_columns__no_files, format_columns__multiple_files, etc.
                     65: 
                     66: * bin/ls/integration_test.sh: Provides "black box" test cases for the binary
                     67:   itself.  These would be named lflag, lflag_and_Fflag, no_flags, no_files, etc.
                     68: 
1.2       jmmv       69: Try to keep your test case names as descriptive as possible so that they do not
                     70: require comments to explain what they intend to test.
                     71: 
1.5       jmmv       72: # Test case parts
1.3       jmmv       73: 
1.5       jmmv       74: ## The head
1.3       jmmv       75: 
                     76: The *head* is used **for the sole purpose** to define meta-data properties for
                     77: the test case.  (Eventually, this would not be specified programmatically, but
                     78: is how we deal with the information right now.)
                     79: 
                     80: The following properties are commonly useful:
                     81: 
                     82: * descr: A textual description of the purpose of the test case.
                     83: 
1.7       jmmv       84: * require.user: Set to 'root' to tell the atf runtime that this test requires
                     85:   root privileges.  The test will later be skipped if you are running atf as
1.10    ! jmmv       86:   non-root, and the test will be executed otherwise.  Please do not use this
        !            87:   unless absolutely necessary!  You can most likely make your tests run as a
        !            88:   regular user if you use puffs and rump.
1.3       jmmv       89: 
                     90: * use.fs: Set to 'true' if the test case creates temporary files in the "current
1.7       jmmv       91:   directory".  If set to false, the atf runtime will set the "current directory"
                     92:   to an unwritable directory, which will disallow the creation of the temporary
1.10    ! jmmv       93:   files and will make your test mysteriously fail.
1.3       jmmv       94: 
1.5       jmmv       95: ## The body
1.3       jmmv       96: 
                     97: The *body* is the actual meat of the test case.  This is just a regular function
                     98: that executes any code you want and calls special atf functions to report
                     99: failures; see below.
                    100: 
                    101: In particular, be aware that the atf run-time **isolates** the execution of
                    102: every test case to prevent side-effects (such as temporary file leftovers,
                    103: in-memory data corruption, etc.).  In particular:
                    104: 
                    105: * A test case is **always executed as a subprocess** that is separate from the
1.9       jmmv      106:   head.  This implies that you cannot pass any in-memory state between the
                    107:   parts.
1.3       jmmv      108: 
                    109: * The current working directory of a test case is changed to a temporary
                    110:   location that gets cleaned up later on automatically.  (Set the use.fs
                    111:   property to true in the head if you need to write to this temporary
                    112:   directory.)
                    113: 
                    114: * The environment of the test case is "sanitized" to get rid of variables that
                    115:   can cause side-effects; e.g. LC_ALL, TZ, etc.
                    116: 
1.7       jmmv      117: # Running the test programs
                    118: 
                    119: Do:
                    120: 
                    121:     $ cd /usr/tests/
                    122:     $ atf-run | atf-report
                    123: 
                    124: Why?
1.2       jmmv      125: 
                    126: Test programs get installed into the /usr/tests/ hierarchy.  The main reason for
                    127: doing that is to allow *any* user to test his system and to be able to convince
                    128: himself that everything is working correctly.
                    129: 
                    130: Imagine that you install NetBSD-current on a public-facing machine that has some
                    131: particular hardware only supported in the bleeding-edge source tree.  In this
                    132: scenario, you, as the administrator, could just go into /usr/tests/, run the
                    133: tests and know immediately if everything is working correctly in your
                    134: software+hardware combination or not.  No need to rely on promises from the
                    135: vendor, no need to deal with a source tree, no need to have a compiler
                    136: installed...
                    137: 
                    138: So, that's the theory.  Now, how does this map to our source tree?
                    139: 
                    140: At the moment, the source test programs are located somewhere under src/tests/.
                    141: Say, for example, that you have the src/tests/bin/ls/ui_test.c source file.
                    142: This Makefile in src/tests/bin/ls/ will take this source file and generate a
                    143: ui_test binary.  The Makefile will also generate an Atffile.  Both files (the
                    144: ui_test binary and the Atffile) will later be installed to /usr/tests/bin/ls/
1.1       jmmv      145: 
1.7       jmmv      146: ## Executing a single test
                    147: 
                    148: In general, you **do not want to run a test program by hand**.  If you do so,
                    149: you do not take advantage of any of the isolation provided by the atf runtime.
                    150: This means that the test program will probably leave some temporary files behind
                    151: or will raise some false negatives.
                    152: 
                    153: To run a test, use atf-run.  In general:
                    154: 
                    155:     $ atf-run | atf-report  # To run all the test programs in a directory.
                    156:     $ atf-run some_test | atf-report  # To run only the some_test program.
                    157: 
                    158: The only "legitimate" case in which you should be running test cases by hand is
                    159: to debug them:
                    160: 
                    161:     $ gdb --args ./some_test the_broken_test_case
                    162: 
                    163: ... but be sure to clean up any leftover files if you do that.
                    164: 
                    165: ## Executing tests during development
                    166: 
                    167: When you are in a subdirectory of src/tests/, you can generally run "make test"
                    168: to execute the tests of that particular subdirectory.  This assumes that the
                    169: tests have been installed into the destdir.
                    170: 
                    171: Please note that this is only provided for convenience but it is completely
1.10    ! jmmv      172: unsupported.  Tests run this way may fail mysteriously, and that is perfectly
1.7       jmmv      173: fine as long as they work from their canonical locations in /usr/tests.
                    174: 
1.5       jmmv      175: # Adding a new test
1.1       jmmv      176: 
                    177: To add a new *test case* to the source tree, look for any test program in
                    178: src/tests/ that can assimilate it.  If you find such a program, just add the
1.2       jmmv      179: test case to it: no other changes are required so your life is easy.  Otherwise,
                    180: you will have to create a new test program.
1.1       jmmv      181: 
                    182: To add a new *test program* to the source tree:
                    183: 
                    184: 1. Locate the appropriate subdirectory in which to put your test program.  It is
                    185: OK (and **expected**) to have multiple test programs into the same directory.
                    186: **Restrain yourself from creating one directory per test program.**
                    187: 
                    188: If the subdirectory exists:
                    189: 
                    190: 1. Choose a sane name for the test program; the name must not be so specific
                    191:    that it restricts the addition of future test cases into it.
                    192: 
                    193: 1. Create the test program source file using one of the templates below.
                    194:    E.g. src/tests/tutorial/sample_test.c.
                    195: 
                    196: 1. Add the new test program to the Makefile.
                    197: 
                    198: If the subdirectory does not exist:
                    199: 
                    200: 1. Do the same as above.
                    201: 
                    202: 1. Create the Makefile for the directory using the templates below.
                    203: 
                    204: 1. Edit the parent Makefile to recurse into the new subdirectory.
                    205: 
                    206: 1. Edit src/etc/mtree/NetBSD.base.dist to register the new subdirectory.  Your
                    207:    test will be installed under /usr/tests/.
                    208: 
                    209: 1. Edit src/distrib/sets/lists/tests/mi to register the new test program.  Do
                    210:    not forget to add .debug entries if your test program is a C/C++ binary.
                    211: 
1.5       jmmv      212: ## Makefile template
1.1       jmmv      213: 
1.7       jmmv      214: Follow this template to create your Makefile:
1.1       jmmv      215: 
                    216:     .include <bsd.own.mk>
                    217: 
                    218:     # This must always be defined.
                    219:     TESTSDIR= ${TESTSBASE}/bin/ls
                    220: 
1.7       jmmv      221:     # These correspond to the test programs you have in the directory.
1.1       jmmv      222:     TESTS_C+= c1_test c2_test  # Correspond to c1_test.c and c2_test.c.
                    223:     TESTS_SH+= sh1_test sh2_test  # Correspond to sh1_test.c and sh2_test.c
                    224: 
                    225:     # Define only if your tests need any data files.
                    226:     FILESDIR= ${TESTSDIR}
                    227:     FILES= testdata1.txt testdata2.bin  # Any necessary data files.
                    228: 
                    229:     .include <bsd.test.mk>
                    230: 
1.5       jmmv      231: ## Atffile template
1.2       jmmv      232: 
1.7       jmmv      233: *Atffiles are automatically generated by bsd.test.mk, so in general you will not
                    234: have to deal with them.*
                    235: 
1.2       jmmv      236: What is an Atffile?  An Atffile is the atf-run counterpart of a "Makefile".
                    237: Given that atf tests *do not rely on a toolchain*, they cannot use make(1) to
                    238: script their execution as the old tests in src/regress/ did.
                    239: 
                    240: The Atffiles, in general, just provide a list of test programs in a particular
                    241: directory and the list of the subdirectories to descend into.
                    242: 
1.7       jmmv      243: If you have to provide an Atffile explicitly because the automatic generation
                    244: does not suit your needs, follow this format:
1.2       jmmv      245: 
                    246:     Content-Type: application/X-atf-atffile; version="1"
                    247: 
                    248:     prop: test-suite = NetBSD
                    249: 
                    250:     tp: first_test
                    251:     tp: second_test
                    252:     tp-glob: optional_*_test
                    253:     tp: subdir1
                    254:     tp: subdir2
                    255: 
1.5       jmmv      256: # C test programs
1.1       jmmv      257: 
1.5       jmmv      258: ## Template
1.1       jmmv      259: 
1.7       jmmv      260: The following code snippet provides a C test program with two test cases.  The
                    261: specific details as to how this works follow later:
1.2       jmmv      262: 
1.1       jmmv      263:     #include <atf-c.h>
                    264: 
                    265:     ATF_TC(tc, my_test_case);
                    266:     ATF_TC_HEAD(tc, my_test_case)
                    267:     {
                    268:         atf_tc_set_md_var(tc, "descr", "This test case ensures that...");
                    269:     }
                    270:     ATF_TC_BODY(tc, my_test_case)
                    271:     {
1.7       jmmv      272:         ATF_CHECK(true); /* Success; continue execution. */
                    273:         ATF_CHECK(false); /* Failure; continue execution. */
1.1       jmmv      274: 
1.7       jmmv      275:         ATF_CHECK_EQ(5, 2 + 2); /* Failure; continue execution. */
                    276:         ATF_REQUIRE_EQ(5, 2 + 2); /* Failure; abort execution. */
1.1       jmmv      277: 
                    278:         if (!condition)
1.7       jmmv      279:             atf_tc_fail("Condition not met!"); /* Abort execution. */
1.1       jmmv      280:     }
                    281: 
1.9       jmmv      282:     ATF_TC(tc, another_test_case);
                    283:     ATF_TC_HEAD(tc, another_test_case)
                    284:     {
                    285:         atf_tc_set_md_var(tc, "descr", "This test case ensures that...");
                    286:     }
1.2       jmmv      287:     ATF_TC_BODY(tc, another_test_case)
                    288:     {
                    289:         /* Do more tests here... */
                    290:     }
                    291: 
1.1       jmmv      292:     ATF_TP_ADD_TCS(tp)
                    293:     {
                    294:         ATF_TP_ADD_TC(tp, my_test_case);
1.2       jmmv      295:         ATF_TP_ADD_TC(tp, another_test_case);
1.1       jmmv      296:     }
                    297: 
1.7       jmmv      298: This program needs to be built with the Makefile shown below.  Once built, the
                    299: program automatically gains a main() method that provides a consistent user
                    300: interface to all test programs.  You are simply not inteded to provide your own
                    301: main method, nor to deal with the command-line of the invocation.
1.2       jmmv      302: 
1.5       jmmv      303: ## How to build
1.1       jmmv      304: 
                    305: To build a C test program, append the name of the test program (without the .c
                    306: extension) to the TESTS_C variable in the Makefile.
                    307: 
                    308: For example:
                    309: 
                    310:     .include <bsd.own.mk>
                    311: 
                    312:     TESTSDIR= ${TESTSBASE}/bin/ls
                    313: 
                    314:     TESTS_C+= fs_test ui_test
                    315: 
                    316:     .include <bsd.test.mk>
                    317: 
1.5       jmmv      318: ## Common functions
1.3       jmmv      319: 
                    320: The following functions are commonly used from within a test case body:
                    321: 
1.10    ! jmmv      322: * ATF_REQUIRE(boolean_expression): Checks if the given boolean expression is
        !           323:   true and, if not, aborts exectuion and markts the test as failed.  Similarly
        !           324:   ATF_CHECK performs the same test but does not abort execution: it records the
        !           325:   failure but keeps processing the test case.  For an explanation on when to use
        !           326:   which, refer to the FAQ question below.
        !           327: 
        !           328: * ATF_REQUIRE_EQ(expected_expression, actual_expression): Checks if the two
        !           329:   expressions match and, if not, aborts marking the test as failed.  Similarly,
        !           330:   ATF_CHECK_EQ records the error but does not abort execution.
1.3       jmmv      331: 
1.10    ! jmmv      332: * ATF_REQUIRE_STREQ(expected_string, actual_string): Same as ATF_REQUIRE_EQ but
1.3       jmmv      333:   performs string comparisons with strcmp.
                    334: 
                    335: * atf_tc_skip(const char *format, ...): Marks the test case as skipped with the
                    336:   provided reason and exits.
                    337: 
                    338: * atf_tc_fail(const char *format, ...): Marks the test case as failed with the
                    339:   provided reason and exits.
                    340: 
                    341: * atf_tc_pass(void): Explicitly marks the test case as passed.  This is
                    342:   *implied* when the test case function ends, so you should not use this in
                    343:   general.
                    344: 
                    345: * atf_expect_fail(const char *format, ...): Tells the atf runtime that the code
                    346:   following this call is expected to raise one or more failures (be it with
1.10    ! jmmv      347:   atf_tc_fail, ATF_REQUIRE_*, etc.).  Use this to mark a block of code that is
1.3       jmmv      348:   known to be broken (e.g. a test that reproduces a known bug).  Use the string
                    349:   parameter to provide an explanation about why the code is broken; if possible,
                    350:   provide a PR number.  Lastly, to terminate the "expected failure" code block
                    351:   and reset the runtime to the default functionality, use the atf_expect_pass()
                    352:   function.
                    353: 
                    354: * atf_expect_death(const char *format, ...): Same as atf_expect_fail but expects
                    355:   an abrupt termination of the test case, be it due to a call to exit() or to
                    356:   the reception of a signal.
                    357: 
                    358: * atf_expect_exit(int exitcode, const char *fomat, ...): Same as atf_expect_fail
                    359:   but expects the test case to exit with a specific exitcode.  Provide -1 to
                    360:   indicate any exit code.
                    361: 
                    362: * atf_expect_signal(int signo, const char *fomat, ...): Same as atf_expect_fail
                    363:   but expects the test case to receive a specific signal.  Provide -1 to
                    364:   indicate any signal.
                    365: 
                    366: * atf_expect_timeout(const char *reason, ...): Same as atf_expect_fail but
                    367:   expects the test case to get stuck and time out.
                    368: 
1.8       jmmv      369: * atf_tc_get_config_var("srcdir"): Returns the path to the directory containing
                    370:   the test program binary.  This must be used to locate any data/auxiliary files
                    371:   stored alongside the binary.
                    372: 
1.10    ! jmmv      373: * RL(integer_expression, integer): Used to evaluate a call to a libc function
        !           374:   that updates errno when it returns an error and to provide correct error
        !           375:   reporting.  The integer expression is the call to such function, and the
        !           376:   literal integer provides the expected return value when there is an error.
        !           377:   For example: RL(open("foo", O_RDONLY), -1).  This would fail the test case if
        !           378:   open returns -1, and would record the correct error message returned by libc.
        !           379: 
1.5       jmmv      380: # Shell test programs
1.1       jmmv      381: 
1.5       jmmv      382: ## Template
1.1       jmmv      383: 
1.7       jmmv      384: The following code snippet provides a shell test program with two test cases.
                    385: The details on how this works are provided later:
1.2       jmmv      386: 
1.1       jmmv      387:     atf_test_case my_test_case
                    388:     my_test_case_head() {
                    389:         atf_set "descr" "This test case ensures that..."
                    390:     }
                    391:     my_test_case_body() {
                    392:         touch file1 file2
                    393: 
                    394:         cat >expout <<EOF
                    395:     file1
                    396:     file2
                    397:     EOF
1.7       jmmv      398:         # The following call validates that the 'ls' command returns an
                    399:         # exit code of 0, that its stdout matches exactly the contents
                    400:         # previously stored in the 'expout' file and that its stderr is
                    401:         # completely empty.  See atf-check(1) for details, which is the
                    402:         # auxiliary tool invoked by the atf_check wrapper function.
1.1       jmmv      403:         atf_check -s eq:0 -o file:expout -e empty 'ls'
                    404: 
                    405:         atf_check_equal 4 $((2 + 2))
                    406: 
                    407:         if [ 'a' != 'b' ]; then
                    408:             atf_fail "Condition not met!"  # Explicit failure.
                    409:         fi
                    410:     }
                    411: 
1.2       jmmv      412:     atf_test_case another_test_case
1.9       jmmv      413:     another_test_case_head() {
                    414:         atf_set "descr" "This test case ensures that..."
                    415:     }
1.2       jmmv      416:     another_test_case_body() {
                    417:         # Do more tests...
                    418:     }
                    419: 
1.1       jmmv      420:     atf_init_test_cases() {
                    421:         atf_add_test_case my_test_case
1.2       jmmv      422:         atf_add_test_case another_test_case
1.1       jmmv      423:     }
                    424: 
1.7       jmmv      425: This program needs to be built with the Makefile shown below.  The program
                    426: automatically gains an entry point that provides a consistent user interface to
                    427: all test programs.  You are simply not inteded to provide your own "main
                    428: method", nor to deal with the command-line of the invocation.
1.2       jmmv      429: 
1.5       jmmv      430: ## How to build
1.1       jmmv      431: 
                    432: To build a shell test program, append the name of the test program (without the
                    433: .sh extension) to the TESTS_SH variable in the Makefile.
                    434: 
                    435: For example:
                    436: 
                    437:     .include <bsd.own.mk>
                    438: 
                    439:     TESTSDIR= ${TESTSBASE}/bin/ls
                    440: 
                    441:     TESTS_SH+= integration_test something_else_test
                    442: 
                    443:     .include <bsd.test.mk>
                    444: 
                    445: If you want to run the test program yourself, you should know that shell-based
                    446: test programs are processed with the atf-sh interpreter.  atf-sh is just a thin
                    447: wrapper over /bin/sh that loads the shared atf code and then delegates execution
                    448: to your source file.
                    449: 
1.5       jmmv      450: ## Common functions
1.3       jmmv      451: 
                    452: The following functions are commonly used from within a test case body:
                    453: 
                    454: * atf_check: This is probably the most useful function for shell-based tests.
                    455:   It may need some experience to get it right, but it allows, in one line, to
                    456:   check the execution of a command.  Where check means: validate exit code,
                    457:   stdout and stderr.  This is just a wrapper over atf-check, so please refer to
                    458:   [atf-check(1)](http://netbsd.gw.com/cgi-bin/man-cgi?atf-check++NetBSD-current)
                    459:   for more details.
                    460: 
                    461: * atf_check_equal value1 value2: Check that the two values are equal and, if
                    462:   not, abort execution.
                    463: 
                    464: * atf_expect_*: Same as their C counterparts; see above.
                    465: 
                    466: * atf_fail reason: Explicitly marks the test case as failed and aborts it.
                    467: 
                    468: * atf_skip reason: Explicitly marks the test case as skipped and exits.
                    469: 
                    470: * atf_pass: Explicitly markts the test case as passed and exits.
                    471: 
                    472: * atf_get_srcdir: Prints the path to the directory where the test case lives.
                    473:   Use as $(atf_get_srcdir)/my-static-data-file.
                    474: 
1.5       jmmv      475: # FAQ
1.1       jmmv      476: 
1.5       jmmv      477: ## How do I atfify a plain test program?
1.1       jmmv      478: 
                    479: Let's suppose you have a program to exercise a particular piece of code.
                    480: Conceptually this implements a test but it does not use atf at all.  For
                    481: example:
                    482: 
                    483:     #include <err.h>
                    484:     #include <stdio.h>
                    485:     #include <stdlib.h>
                    486:     #include <string.h>
                    487: 
                    488:     /* This test program exercises the snprintf function. */
                    489: 
                    490:     int main(void)
                    491:     {
                    492:         char buf[1024];
                    493: 
                    494:         printf("Testing integers");
                    495:         snprintf(buf, sizeof(buf), "%d", 3);
                    496:         if (strcmp(buf, "3") != 0)
                    497:             errx(EXIT_FAILURE, "%d failed");
                    498:         snprintf(buf, sizeof(buf), "a %d b", 5);
                    499:         if (strcmp(buf, "a 5 b") != 0)
                    500:             errx(EXIT_FAILURE, "%d failed");
                    501: 
                    502:         printf("Testing strings");
                    503:         snprintf(buf, sizeof(buf), "%s", "foo");
                    504:         if (strcmp(buf, "foo") != 0)
                    505:             errx(EXIT_FAILURE, "%s failed");
                    506:         snprintf(buf, sizeof(buf), "a %s b", "bar");
                    507:         if (strcmp(buf, "a bar b") != 0)
                    508:             errx(EXIT_FAILURE, "%s failed");
                    509: 
                    510:         return EXIT_SUCCESS;
                    511:     }
                    512: 
                    513: To convert this program into an atf test program, use the template above and
                    514: keep this in mind:
                    515: 
                    516: * Split the whole main function into separate test cases.  In this scenario, the
                    517:   calls to printf(3) delimit a good granularity for the test cases: one for the
                    518:   integer formatter, one for the string formatter, etc.
                    519: 
                    520: * Use the ATF_CHECK* and/or atf_tc_fail functions to do the comparisons and
1.7       jmmv      521:   report errors.  Neither errx nor any other error reporting and program
                    522:   termination functions (read: err, errx, warn, warnx, exit, abor) are to be
                    523:   used at all.
1.1       jmmv      524: 
                    525: The result would look like:
                    526: 
                    527:     #include <atf-c.h>
                    528:     #include <stdio.h>
                    529: 
                    530:     ATF_TC(tc, integer_formatter);
                    531:     ATF_TC_HEAD(tc, integer_formatter)
                    532:     {
                    533:         atf_tc_set_md_var(tc, "descr", "Validates the %d formatter");
                    534:     }
                    535:     ATF_TC_BODY(tc, integer_formatter)
                    536:     {
                    537:         char buf[1024];
                    538: 
                    539:         snprintf(buf, sizeof(1024), "%d", 3);
                    540:         ATF_CHECK_STREQ("3", buf);
                    541: 
                    542:         snprintf(buf, sizeof(1024), "a %d b", 5);
                    543:         ATF_CHECK_STREQ("a 5 b", buf);
                    544:     }
                    545: 
                    546:     ATF_TC(tc, string_formatter);
                    547:     ATF_TC_HEAD(tc, string_formatter)
                    548:     {
                    549:         atf_tc_set_md_var(tc, "descr", "Validates the %s formatter");
                    550:     }
                    551:     ATF_TC_BODY(tc, string_formatter)
                    552:     {
                    553:         char buf[1024];
                    554: 
                    555:         snprintf(buf, sizeof(1024), "%s", "foo");
                    556:         ATF_CHECK_STREQ("foo", buf);
                    557: 
                    558:         snprintf(buf, sizeof(1024), "a %s b", "bar");
                    559:         ATF_CHECK_STREQ("a bar b", buf);
                    560:     }
                    561: 
                    562:     ATF_TP_ADD_TCS(tp)
                    563:     {
                    564:         ATF_TP_ADD_TC(tp, integer_formatter);
                    565:         ATF_TP_ADD_TC(tp, string_formatter);
                    566:     }
                    567: 
                    568: Which can later be invoked as any of:
                    569: 
1.7       jmmv      570:     $ atf-run snprintf_test | atf-report  # Normal execution method.
                    571:     $ ./snprintf_test integer_formatter  # For DEBUGGING only.
                    572:     $ ./snprintf_test string_formatter  # For DEBUGGING only.
1.1       jmmv      573: 
1.5       jmmv      574: ## How do I write a test case for an unfixed PR?
1.3       jmmv      575: 
                    576: Use the "expectations" mechanism to define part of the test case as faulty,
1.7       jmmv      577: crashy, etc.  This is for two reasons:
                    578: 
1.10    ! jmmv      579: * As long as the bug still exists, the test case will be reported as an
        !           580:   "expected failure".  Such expected failures do not count towards the success
        !           581:   or failure of the whole test suite.
1.7       jmmv      582: 
                    583: * When the bug gets fixed, the bug will not trigger any more in the test case,
                    584:   and thus the expectation of failure will not be met any more.  At this point
                    585:   the test case will start raising a regular failure, which is usually addressed
1.10    ! jmmv      586:   by just removing the expect_* calls (but add a comment with the PR number!).
1.7       jmmv      587: 
                    588: For example, suppose we have PR lib/1 that reports a condition in which
                    589: snprintf() does the wrong formatting when using %s, and PR lib/2 that mentions
1.3       jmmv      590: that another snprintf() call using %d with number 5 causes a segfault.  We could
                    591: do:
                    592: 
                    593:     #include <atf-c.h>
                    594:     #include <signal.h>
                    595:     #include <stdio.h>
                    596: 
1.9       jmmv      597:     ATF_TC(tc, integer_formatter);
                    598:     ATF_TC_HEAD(tc, integer_formatter)
                    599:     {
                    600:         atf_tc_set_md_var(tc, "descr", "Tests the %d formatter for snprintf");
                    601:     }
1.3       jmmv      602:     ATF_TC_BODY(tc, integer_formatter)
                    603:     {
                    604:         char buf[1024];
                    605: 
                    606:         snprintf(buf, sizeof(buf), "Hello %d\n", 1);
                    607:         ATF_CHECK_STREQ("Hello 1", buf);
                    608: 
1.7       jmmv      609:         atf_tc_expect_signal(SIGSEGV, "PR lib/2: %%d with 5 causes a crash");
1.3       jmmv      610:         snprintf(buf, sizeof(buf), "Hello %d\n", 5);
                    611:         atf_tc_expect_pass();
                    612:         ATF_CHECK_STREQ("Hello 5", buf);
                    613:     }
                    614: 
1.9       jmmv      615:     ATF_TC(tc, string_formatter);
                    616:     ATF_TC_HEAD(tc, string_formatter)
                    617:     {
                    618:         atf_tc_set_md_var(tc, "descr", "Tests the %s formatter for snprintf");
                    619:     }
1.3       jmmv      620:     ATF_TC_BODY(tc, string_formatter)
                    621:     {
                    622:         char buf[1024];
                    623: 
                    624:         snprintf(buf, sizeof(buf), "Hello %s\n", "world!");
1.7       jmmv      625:         atf_tc_expect_failure("PR lib/1: %%s does not work");
1.3       jmmv      626:         ATF_CHECK_STREQ("Hello world!", buf);
                    627:         atf_tc_expect_pass();
                    628:     }
                    629: 
                    630:     ATF_TP_ADD_TCS(tp)
                    631:     {
                    632:         ATF_TP_ADD_TC(tp, integer_formatter);
                    633:         ATF_TP_ADD_TC(tp, string_formatter);
                    634:     }
                    635: 
1.5       jmmv      636: ## Do I need to remove temporary files?
1.1       jmmv      637: 
                    638: No.  atf-run does this automatically for you, because it runs every test program
                    639: in its own temporary subdirectory.
1.7       jmmv      640: 
                    641: ## When do I use ATF_CHECK and when ATF_REQUIRE?
                    642: 
                    643: ATF_CHECK logs errors but does not abort the execution of the test program.
                    644: ATF_REQUIRE logs errors in a similar way but immediately terminates the
                    645: execution.
                    646: 
                    647: You can use this distinction in the following way: use ATF_REQUIRE to check the
                    648: code that "prepares" your test case.  Use ATF_CHECK to do the actual
                    649: functionality tests once all the set up has been performed.  For example:
                    650: 
                    651:     ATF_TC_BODY(getline) {
                    652:         FILE *f;
                    653:         char buf[1024];
                    654: 
                    655:         /* Opening the file is not part of the functionality under test, but it
                    656:          * must succeed before we actually test the relevant code. */
                    657:         ATF_REQUIRE((f = fopen("foo")) != NULL);
                    658: 
                    659:         ATF_CHECK(getline(f, buf, sizeof(buf)) > 0);
                    660:         ATF_CHECK_STREQ("line 1", buf);
                    661: 
                    662:         ATF_CHECK(getline(f, buf, sizeof(buf)) > 0);
                    663:         ATF_CHECK_STREQ("line 2", buf);
                    664:     }

CVSweb for NetBSD wikisrc <wikimaster@NetBSD.org> software: FreeBSD-CVSweb