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

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

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