blob: 442fb087ba573c045d4328b66a9cf19296b3c768 [file] [log] [blame]
Cyril Hrubisafb61682014-01-13 19:08:02 +01001LTP Test Writing Guidelines
2===========================
3
4This document describes LTP guidelines and LTP test interface and is intended
5for anybody who want to write or modify a LTP testcase. It's not a definitive
6guide and it's not, by any means, a substitute for common sense.
7
8
91. General Rules
10----------------
11
121.1 Simplicity
13~~~~~~~~~~~~~~
14
15For all it's worth keep the testcases simple or better as simple as possible.
Cyril Hrubis187e3232014-02-13 14:58:07 +010016The kernel and libc are tricky beasts and the complexity imposed by their
Alexey Kodanev683d16e2014-03-27 17:28:18 +040017interfaces is quite high. Concentrate on the interface you want to test and
Cyril Hrubis187e3232014-02-13 14:58:07 +010018follow the UNIX philosophy. It's a good idea to make the test as
19self-contained as possible too (it should not depend on tools or libraries
20that are not widely available).
Cyril Hrubisafb61682014-01-13 19:08:02 +010021
22Do not reinvent the wheel
23
24* Use LTP standard interface
Jiri Jaburek44e1ed82014-06-23 09:49:08 -070025* Do not add custom PASS/FAIL reporting functions
26* Do not write Makefiles from scratch,
Cyril Hrubisafb61682014-01-13 19:08:02 +010027 use LTP build system instead, etc.
28* ...
29
301.2 Code duplication
31~~~~~~~~~~~~~~~~~~~~
32
33Copy & paste is a good servant but very poor master. If you are about to copy a
34large part of the code from one testcase to another, think what would happen if
35you find bug in the code that has been copied all around the tree. What about
36moving it to a library instead?
37
38The same goes for short but complicated parts, whenever you are about to copy &
39paste a syscall wrapper that packs arguments accordingly to machine
40architecture or similarly complicated code, put it into a header instead.
41
421.3 Coding style
43~~~~~~~~~~~~~~~~
44
Cyril Hrubis33463792014-03-12 17:13:30 +0100451.3.1 C coding style
46^^^^^^^^^^^^^^^^^^^^
47
Cyril Hrubisafb61682014-01-13 19:08:02 +010048LTP adopted Linux kernel coding style. If you aren't familiar with its rules
49locate 'linux/Documentation/CodingStyle' in the kernel sources and read it,
50it's a well written introduction.
51
52There is also a checkpatch (see 'linux/scripts/checkpatch.pl') script that can
53be used to check your patches before the submission.
54
55NOTE: If checkpatch does not report any problems, the code still may be wrong
56 as the tool only looks for common mistakes.
57
Cyril Hrubis33463792014-03-12 17:13:30 +0100581.3.2 Shell coding style
59^^^^^^^^^^^^^^^^^^^^^^^^
60
61When writing testcases in shell write in portable shell only, it's a good idea
62to try to run the test using alternative shell (alternative to bash, for
63example dash) too.
64
65Here are some common sense style rules for shell
66
67* Keep lines under 80 chars
68
69* Use tabs for indentation
70
Jiri Jaburek44e1ed82014-06-23 09:49:08 -070071* Keep things simple, avoid unnecessary subshells
Cyril Hrubis33463792014-03-12 17:13:30 +010072
73* Don't do confusing things (i.e. don't name your functions like common shell
74 commands, etc.)
75
76* Quote variables
77
78* Be consistent
Cyril Hrubisafb61682014-01-13 19:08:02 +010079
801.4 Commenting code
81~~~~~~~~~~~~~~~~~~~
82
83Comments can sometimes save you day but they can easily do more harm than
84good. There has been several cases where comments and actual implementation
85were drifting slowly apart which yielded into API misuses and hard to find
86bugs. Remember there is only one thing worse than no documentation, wrong
87documentation.
88
89Generally everybody should write code that is obvious (which unfortunately
90isn't always possible). If there is a code that needs to be commented keep it
91short and to the point. Never ever comment the obvious.
92
93In case of LTP testcases it's customary to add a paragraph with highlevel test
94description somewhere at the beginning of the file (usually right under the GPL
95header). This helps other people to understand the overall goal of the test
96before they dive into the technical details.
97
Jiri Jaburek44e1ed82014-06-23 09:49:08 -0700981.5 Backwards compatibility
99~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cyril Hrubisafb61682014-01-13 19:08:02 +0100100
101LTP test should be as backward compatible as possible. Think of an enterprise
102distributions with long term support (more than five years since the initial
103release) or of an embedded platform that needs to use several years old
104toolchain supplied by the manufacturer.
105
106Therefore LTP test for more current features should be able to cope with older
107systems. It should at least compile fine and if it's not appropriate for the
108configuration it should return 'TCONF' (see test interface description below).
109
110There are several types of checks we use:
111
Cyril Hrubis187e3232014-02-13 14:58:07 +0100112The *configure script* is usually used to detect availability of a function
Cyril Hrubisafb61682014-01-13 19:08:02 +0100113declarations in system headers. It's used to disable tests at compile time.
114
115The *tst_kvercmp()* which is runtime kernel version detection and comparison
116and is used to disable tests at runtime.
117
118Checking the *errno* value is another type of runtime check. Most of the
119syscalls returns either 'EINVAL' or 'ENOSYS' when syscall was not implemented
120or was disabled upon kernel compilation.
121
122Sometimes it also makes sense to define a few macros instead of creating
123configure test. One example are Linux specific POSIX clock ids in
124'include/lapi/posix_clocks.h'.
125
1261.6 Dealing with messed up legacy code
127~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
128
129LTP contains a lot of old and messy code and we are cleaning it up as fast as
130we can but despite the efforts there is still a lot. If you start modifying
131old or a messed up testcase and your changes are more complicated than simple
Cyril Hrubis50493f62014-02-12 15:05:43 +0100132typo fixes you should do a cleanup first (in a separate patch). It's easier to
Cyril Hrubis187e3232014-02-13 14:58:07 +0100133review the changes if you separate the formatting fixes from the changes that
134affects the test behavior.
Cyril Hrubisafb61682014-01-13 19:08:02 +0100135
136The same goes for moving files. If you need a rename or move file do it in a
137separate patch.
138
1391.7 License
140~~~~~~~~~~~
141
142Code contributed to LTP should be licensed under GPLv2+ (GNU GPL version 2 or
143any later version).
144
1452. Writing a testcase
146---------------------
147
1482.1 LTP Structure
149~~~~~~~~~~~~~~~~~
150
151The structure of LTP is quite simple. Each test is a binary written either in
Jiri Jaburek44e1ed82014-06-23 09:49:08 -0700152portable shell (no bashism) or C. The test gets a configuration via
Cyril Hrubisafb61682014-01-13 19:08:02 +0100153environment variables and/or command line parameters, it prints additional
154information into the stdout and reports overall success/failure via the exit
155value.
156
157Tests are generally placed under the 'testcases/' directory. Everything that
Cyril Hrubis187e3232014-02-13 14:58:07 +0100158is a syscall or (slightly confusingly) libc syscall wrapper goes under
Cyril Hrubisafb61682014-01-13 19:08:02 +0100159'testcases/kernel/syscalls/'. Then there is 'testcases/open_posix_testsuite'
160which is a well maintained fork of the upstream project that has been dead
161since 2005 and also a number of directories with tests for more specific
162features.
163
1642.1.1 Runtest Files
165^^^^^^^^^^^^^^^^^^^
166
167The list of tests to be executed is stored in runtest files under the
168'runtest/' directory. The default set of runtest files to be executed is
169stored in 'scenario_groups/default'. When you add a test you should add
Jiri Jaburek44e1ed82014-06-23 09:49:08 -0700170corresponding entries into some runtest file(s) as well.
Cyril Hrubisafb61682014-01-13 19:08:02 +0100171
172For syscall tests (these placed under 'testcases/kernel/syscalls/') use
173'runtest/syscalls' file, for kernel related tests for memory management we
174have 'runtest/mm', etc.
175
Cyril Hrubis187e3232014-02-13 14:58:07 +0100176IMPORTANT: The runtest files should have one entry per a test. Creating a
177 wrapper that runs all your tests and adding it as a single test
178 into runtest file is strongly discouraged.
179
Cyril Hrubisafb61682014-01-13 19:08:02 +01001802.1.2 Datafiles
181^^^^^^^^^^^^^^^
182
Jan Stancekf423b1a2014-10-02 14:18:20 +0200183If your test needs datafiles to work, these should be put into a subdirectory
Cyril Hrubis1dc9d122014-10-16 11:50:35 +0200184named 'datafiles' and installed into the 'testcases/data/$TCID' directory (to
185do that you have to add 'INSTALL_DIR := testcases/data/TCID' into the
186'datafiles/Makefile').
Cyril Hrubisafb61682014-01-13 19:08:02 +0100187
Jan Stancekf423b1a2014-10-02 14:18:20 +0200188You can obtain path to datafiles via $LTP_DATAROOT provided by test.sh
Cyril Hrubis1dc9d122014-10-16 11:50:35 +0200189'$LTP_DATAROOT/...'
190or via C function 'tst_dataroot()' provided by libltp:
191
192[source,c]
193-------------------------------------------------------------------------------
194const char *dataroot = tst_dataroot();
195-------------------------------------------------------------------------------
Jan Stancekf423b1a2014-10-02 14:18:20 +0200196
197Datafiles can also be accessed as '$LTPROOT/testcases/data/$TCID/...',
Cyril Hrubis1dc9d122014-10-16 11:50:35 +0200198but '$LTP_DATAROOT' and 'tst_dataroot()' are preffered as these can be used
Jan Stancekf423b1a2014-10-02 14:18:20 +0200199when running testcases directly in git tree as well as from install
200location.
201
202The path is constructed according to these rules:
Cyril Hrubis1dc9d122014-10-16 11:50:35 +0200203
2041. if '$LTPROOT' is set, return '$LTPROOT/testcases/data/$TCID'
2052. else if 'tst_tmpdir()' was called return '$STARTWD/datafiles'
206 (where '$STARTWD' is initial working directory as recorded by 'tst_tmdir()')
Jan Stancekf423b1a2014-10-02 14:18:20 +02002073. else return '$CWD/datafiles'
208
209See 'testcases/commands/ade/ldd/ldd01' for example.
Cyril Hrubisafb61682014-01-13 19:08:02 +0100210
2112.1.3 Subexecutables
212^^^^^^^^^^^^^^^^^^^^
213
Jiri Jaburek44e1ed82014-06-23 09:49:08 -0700214If you test needs to execute a binary, place it in the same directory as the
Cyril Hrubis187e3232014-02-13 14:58:07 +0100215testcase and name the file starting with testname_ ('TCID_' see below).
Jiri Jaburek44e1ed82014-06-23 09:49:08 -0700216Once the test is executed by the framework, the path to the directory with all
217LTP binaries is added to the '$PATH' and you can execute it just by its name.
Cyril Hrubisafb61682014-01-13 19:08:02 +0100218
Jiri Jaburek44e1ed82014-06-23 09:49:08 -0700219TIP: If you need to execute such test from the LTP tree, you can add path to
Cyril Hrubis92eeadc2014-01-20 17:04:32 +0100220 current directory to '$PATH' manually with: 'PATH="$PATH:$PWD" ./foo01'.
Cyril Hrubisafb61682014-01-13 19:08:02 +0100221
Cyril Hrubisafb61682014-01-13 19:08:02 +01002222.2 Writing a test in C
223~~~~~~~~~~~~~~~~~~~~~~~
224
2252.2.1 Basic test structure
226^^^^^^^^^^^^^^^^^^^^^^^^^^
227
228Let's start with an example, following code is a simple test for a getenv().
229
230[source,c]
231-------------------------------------------------------------------------------
232/*
233 * This is test for basic functionality of getenv().
234 *
235 * - create an env variable and verify that getenv() can get get it
236 *
237 * - call getenv() with nonexisting variable name, check that it returns NULL
238 */
239
240#include "test.h"
241
242char *TCID = "getenv01";
Cyril Hrubis50493f62014-02-12 15:05:43 +0100243int TST_TOTAL = 2;
Cyril Hrubisafb61682014-01-13 19:08:02 +0100244
245#define TEST_ENV "LTP_TEST_ENV"
246#define TEST_NE_ENV "LTP_TEST_THIS_DOES_NOT_EXIST"
247#define TEST_ENV_VAL "val"
248
249static void setup(void)
250{
251 if (setenv(TEST_ENV, TEST_ENV_VAL, 1))
252 tst_brkm(TBROK | TERRNO, NULL, "setenv() failed");
253}
254
255static void test(void)
256{
257 char *ret;
258
Stanislav Kholmanskikhd40d54c2014-04-10 17:50:12 +0400259 ret = getenv(TEST_ENV);
Cyril Hrubisafb61682014-01-13 19:08:02 +0100260
261 if (ret) {
262 if (!strcmp(ret, TEST_ENV_VAL))
263 tst_resm(TPASS, "getenv(" TEST_ENV ") = '"
264 TEST_ENV_VAL "'");
265 else
266 tst_resm(TFAIL, "getenv(" TEST_ENV "} = '%s', "
267 "expected '" TEST_ENV_VAL "'", ret);
268 } else {
269 tst_resm(TFAIL, "getenv(" TEST_ENV ") = NULL");
270 }
271
272 ret = getenv(TEST_NE_ENV);
273
274 if (ret)
275 tst_resm(TFAIL, "getenv(" TEST_NE_ENV ") = '%s'", ret);
276 else
Stanislav Kholmanskikhd40d54c2014-04-10 17:50:12 +0400277 tst_resm(TPASS, "getenv(" TEST_NE_ENV ") = NULL");
Cyril Hrubisafb61682014-01-13 19:08:02 +0100278}
279
280int main(int argc, char *argv[])
281{
282 const char *msg;
283 int lc;
284
Stanislav Kholmanskikhd40d54c2014-04-10 17:50:12 +0400285 if ((msg = parse_opts(argc, argv, NULL, NULL)))
Cyril Hrubisafb61682014-01-13 19:08:02 +0100286 tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);
287
288 setup();
289
290 for (lc = 0; TEST_LOOPING(lc); lc++)
291 test();
292
293 tst_exit();
294}
295-------------------------------------------------------------------------------
296
297Each test must define 'TCID' and 'TST_TOTAL'.
298
299'TCID' defines test name (usually syscall/libcall name + number) and is used
300as a base for temporary directory name (if 'tst_tmpdir()' is used). In most of
301the cases the 'TCID' is the same as test filename (without the extension).
302
303'TST_TOTAL' defines total number of tests.
304
305NOTE: The test should report 'TST_TOTAL' PASSES/FAILS on each iteration.
306
307The overall test initialization is usually done in a 'setup()' function and
308the overall cleanup is done in a 'cleanup()' function. Here 'cleanup()' is
309omitted as the test don't have to clean anything up. Usually it's called right
310before the 'tst_exit()' to do the cleanup and passed to library functions that
311can exit the test execution, for example 'tst_brkm()', so that the test can do
312a cleanup before it exits.
313
314WARNING: Never pass a cleanup function to functions called from cleanup.
315 If you don't see why this is a problem you are not ready to write
316 a testcase yet.
317
Cyril Hrubis187e3232014-02-13 14:58:07 +0100318WARNING: Don't use 'tst_brkm()' in 'cleanup()' unless you really want to exit
319 the cleanup prematurely. See discussion below for further
320 information.
321
Cyril Hrubisafb61682014-01-13 19:08:02 +0100322The 'parse_opts()' parses the test command line arguments, it's important to
323use it even if the test has no (other than default) parameters.
324
325The last important thing is the 'TEST_LOOPING()' macro, each test has standard
326options so that it can be executed N times or for M seconds.
327
328NOTE: The 'test()' function must work correctly even if executed several times
329 from test main loop.
330
Cyril Hrubisd2d64cf2014-02-12 18:12:16 +0100331A word about the cleanup() callback
332+++++++++++++++++++++++++++++++++++
333
334There are a few rules that needs to be followed in order to write correct
335cleanup() callback.
336
3371. Don't call callback() from within the callback().
338(This includes passing callback pointer to library 'tst_' functions.)
339
Cyril Hrubis187e3232014-02-13 14:58:07 +01003402. Make sure to free resources in the reverse order they were
Cyril Hrubisd2d64cf2014-02-12 18:12:16 +0100341 initialized. (Some of the steps may not depend on others and everything
342 will work if there were swapped but let's keep it in order.)
343
Cyril Hrubis187e3232014-02-13 14:58:07 +01003443. Free only resources that were initialized.
Cyril Hrubisd2d64cf2014-02-12 18:12:16 +0100345
346The third rule needs a bit more detailed discussion. Consider, for example,
347test setup below which is example of a setup that prepares temporary
348directory, two file descriptors and allocates a buffer.
349
350[source,c]
351-------------------------------------------------------------------------------
352static int fd0, fd1;
353static void *buf;
354#define BUFSIZE (1024 * 1024)
355
356static void setup(void)
357{
358 tst_require_root();
359 tst_tmpdir();
360
361 fd0 = SAFE_OPEN(cleanup, "test_file1", O_CREAT | O_RDWR, 0666);
362 SAFE_UNLINK(cleanup, "test_file1");
363 fd1 = SAFE_OPEN(cleanup, "test_file2", O_CREAT | O_RDWR, 0666);
364 SAFE_UNLINK(cleanup, "test_file2");
365
366 buf = SAFE_MALLOC(cleanup, BUFSIZE);
367}
368-------------------------------------------------------------------------------
369
370In this case the 'cleanup()' function may be entered in five different states:
371
Cyril Hrubis187e3232014-02-13 14:58:07 +0100372* The first 'SAFE_OPEN()' has failed, temporary directory is created
Cyril Hrubisd2d64cf2014-02-12 18:12:16 +0100373 no files are open and +fd0 == -1+, +fd1 == 0+ and +buf == NULL+.
374
375* The first 'SAFE_UNLINK()' has failed, +fd0+ holds file descriptor and
376 +fd1 == 0+.
377
Cyril Hrubis187e3232014-02-13 14:58:07 +0100378* The second 'SAFE_OPEN()' has failed, +fd0+ holds file descriptor and
Cyril Hrubisd2d64cf2014-02-12 18:12:16 +0100379 +fd1 == -1+.
380
381* The second 'SAFE_UNLINK()' or 'SAFE_MALLOC()' has failed and both 'fd0' and
382 'fd1' holds file descriptors, +buf+ is still +NULL+.
383
384* The 'cleanup()' was called at the end of the test, all +fd0+, +fd1+ and
385 +buf+ are initialized.
386
387The 'cleanup()' functions should be able to cope with all scenarios. In this
388case following code will do:
389
390[source,c]
391-------------------------------------------------------------------------------
392static void cleanup(void)
393{
Cyril Hrubis187e3232014-02-13 14:58:07 +0100394 free(buf);
Cyril Hrubisd2d64cf2014-02-12 18:12:16 +0100395
396 if (fd1 > 0)
397 close(fd1);
398
399 if (fd0 > 0)
400 close(fd0);
401
402 tst_rmdir();
403}
404-------------------------------------------------------------------------------
Cyril Hrubisafb61682014-01-13 19:08:02 +0100405
4062.2.2 Basic test interface
407^^^^^^^^^^^^^^^^^^^^^^^^^^
408
409[source,c]
410-------------------------------------------------------------------------------
411void tst_resm(int ttype, char *arg_fmt, ...);
412-------------------------------------------------------------------------------
413
414Printf-like function to report test result, it's mostly used with ttype:
415
416|==============================
417| 'TPASS' | Test has passed.
418| 'TFAIL' | Test has failed.
419| 'TINFO' | General message.
420|==============================
421
Cyril Hrubis21977432014-05-29 18:47:03 +0200422The 'ttype' can be combined bitwise with 'TERRNO' or 'TTERRNO' to print
423'errno', 'TEST_ERRNO' respectively.
424
Cyril Hrubisafb61682014-01-13 19:08:02 +0100425[source,c]
426-------------------------------------------------------------------------------
427void tst_brkm(int ttype, void (*cleanup)(void), char *arg_fmt, ...);
428-------------------------------------------------------------------------------
429
430Printf-like function to report error and exit the test, it can be used with ttype:
431
432|============================================================
433| 'TBROK' | Something has failed in test preparation phase.
434| 'TCONF' | test is not appropriate for current configuration
435 (syscall not implemented, unsupported arch, ...)
436| 'TFAIL' | test has failed
437|============================================================
438
Cyril Hrubis21977432014-05-29 18:47:03 +0200439The 'ttype' can be combined bitwise with 'TERRNO' or 'TTERRNO' to print
440'errno', 'TEST_ERRNO' respectively.
Cyril Hrubisafb61682014-01-13 19:08:02 +0100441
442[source,c]
443-------------------------------------------------------------------------------
444void tst_require_root(void (*cleanup)(void));
445-------------------------------------------------------------------------------
446
447Abort the test if it's not executed with root privileges. If needed this should
448be one of the first checks in the test 'setup()'.
449
450WARNING: The cleanup parameter is deprecated and should always be 'NULL'.
451
452
453[source,c]
454-------------------------------------------------------------------------------
455void tst_exit(void);
456-------------------------------------------------------------------------------
457
458Exits the tests, note that this function has no parameters, the PASSES/FAILS
459reported by the 'tst_resm()' interfaces were stored and are used for the exit
460value.
461
Xiaoguang Wangef72ef82014-05-14 13:16:39 +0800462[source,c]
463-------------------------------------------------------------------------------
464const char *tst_strsig(int sig);
465-------------------------------------------------------------------------------
466
467Return the given signal number's corresponding string.
468
469
470[source,c]
471-------------------------------------------------------------------------------
472const char *tst_strerrno(int err);
473-------------------------------------------------------------------------------
474
475Return the given errno number's corresponding string.
476
Cyril Hrubisafb61682014-01-13 19:08:02 +0100477
4782.2.3 Test temporary directory
479^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
480
481If the test needs to create files (which is common case) it must create a test
482temporary directory in LTP temp directory and work with files only inside of
483this directory. Happily there are easy to use library functions exactly for
484this purpose.
485
486[source,c]
487-------------------------------------------------------------------------------
488void tst_tmpdir(void);
489-------------------------------------------------------------------------------
490
491Creates a directory with a unique name (based on the test 'TCID') under the
492LTP temporary directory (defaults to '/tmp/') and changes the test working
493directory to it. It's usually called from the test 'setup()'.
494
495[source,c]
496-------------------------------------------------------------------------------
497void tst_rmdir(void);
498-------------------------------------------------------------------------------
499
Cyril Hrubis187e3232014-02-13 14:58:07 +0100500Removes the directory recursively. It's usually called from test 'cleanup()'.
Cyril Hrubisafb61682014-01-13 19:08:02 +0100501
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700502It's important to close all file descriptors (that point to files in test
Cyril Hrubis50493f62014-02-12 15:05:43 +0100503temporary directory, even the unlinked ones) before the test calls
Cyril Hrubisafb61682014-01-13 19:08:02 +0100504'tst_rmdir()' otherwise the test may break on NFS mounted temp dir (look for
505"NFS silly rename").
506
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +0800507[[2.2.4]]
Cyril Hrubisafb61682014-01-13 19:08:02 +01005082.2.4 Safe macros
509^^^^^^^^^^^^^^^^^
510
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700511Safe macros aim to simplify error checking in test preparation. Instead of
Cyril Hrubisafb61682014-01-13 19:08:02 +0100512calling system API functions, checking for their return value and aborting the
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700513test if the operation has failed, you just use corresponding safe macros.
Cyril Hrubisafb61682014-01-13 19:08:02 +0100514
515Use them whenever it's possible.
516
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +0800517NOTE: Have a look at the the xref:2.2.7[doing real test in the child process]
518 if you want to use safe macros from within a child process.
Cyril Hrubisafb61682014-01-13 19:08:02 +0100519
520Instead of writing:
521
522[source,c]
523-------------------------------------------------------------------------------
524 fd = open("/dev/null", O_RDONLY);
525 if (fd < 0)
526 tst_brkm(TBROK | TERRNO, cleanup, "opening /dev/null failed");
527-------------------------------------------------------------------------------
528
529You write just:
530
531[source,c]
532-------------------------------------------------------------------------------
533 fd = SAFE_OPEN(cleanup, "/dev/null", O_RDONLY);
534-------------------------------------------------------------------------------
535
536They can also simplify reading and writing of sysfs files, you can, for
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700537example, do:
Cyril Hrubisafb61682014-01-13 19:08:02 +0100538
539[source,c]
540-------------------------------------------------------------------------------
541 SAFE_FILE_SCANF(cleanup, "/proc/sys/kernel/pid_max", "%lu", &pid_max);
542-------------------------------------------------------------------------------
543
544See 'include/safe_macros.h', 'include/safe_stdio.h' and
545'include/safe_file_ops.h' for a complete list.
546
Cyril Hrubis50493f62014-02-12 15:05:43 +0100547NOTE: It's wise NOT to use safe macros in test cleanup(). This is because
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700548 all safe macros call tst_brkm(), which exits the test immediately, making
549 the cleanup() exit prematurely. (Actually, this is hacked around in
Cyril Hrubis50493f62014-02-12 15:05:43 +0100550 the test library at the moment so that the cleanup() will finish, but
551 the hack will be removed in the future).
552
Cyril Hrubisddd3b852014-02-03 17:10:04 +01005532.2.5 Runtime kernel version detection
554^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Cyril Hrubisafb61682014-01-13 19:08:02 +0100555
556[source,c]
557-------------------------------------------------------------------------------
558int tst_kvercmp(int r1, int r2, int r3);
559
560struct tst_kern_exv {
561 char *dist_name;
562 char *extra_ver;
563};
564
565int tst_kvercmp2(int r1, int r2, int r3, struct tst_kern_exv *vers);
566-------------------------------------------------------------------------------
567
568These two functions are intended for runtime kernel version detection. They
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700569parse the output from 'uname()' and compare it to the passed values.
Cyril Hrubisafb61682014-01-13 19:08:02 +0100570
571The return value is similar to the 'strcmp()' function, i.e. zero means equal,
572negative value means that the kernel is older than than the expected value and
573positive means that it's newer.
574
575The second function 'tst_kvercmp2()' allows for specifying per-vendor table of
576kernel versions as vendors typically backport fixes to their kernels and the
577test may be relevant even if the kernel version does not suggests so. See
578'testcases/kernel/syscalls/inotify/inotify04.c' for example usage.
579
Cyril Hrubisddd3b852014-02-03 17:10:04 +01005802.2.6 Fork()-ing
581^^^^^^^^^^^^^^^^
582
Cyril Hrubis124c9872014-07-03 17:24:38 +0200583Be wary that if the test forks and there were messages printed by the tst_*
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700584interfaces, the data may still be in kernel buffers and these are NOT flushed
Cyril Hrubisddd3b852014-02-03 17:10:04 +0100585automatically.
586
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700587This happens when 'stdout' gets redirected to a file. In this case, the
588'stdout' is not line buffered, but block buffered, and buffered messages will be
589printed by the parent and each of the children.
Cyril Hrubisddd3b852014-02-03 17:10:04 +0100590
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700591To avoid that, you should either call 'tst_flush()' right before the 'fork()',
592or even better - use 'tst_fork()' instead.
Cyril Hrubisddd3b852014-02-03 17:10:04 +0100593
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +0800594[[2.2.7]]
5952.2.7 Doing real test in the child process
596^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
597
598If you have to do the test in a child process you have two possibilities:
599
600* You can use test interface ('tst_resm()', 'tst_brkm()', 'tst_exit()', ...)
601 but there are some rules to obey:
602
603** If you use 'tst_resm()' to record test the results in child process, you
604 *MUST* use either 'tst_exit()' or 'tst_brkm()' to exit the child process.
605
606** If you use 'tst_brkm()' with a non-NULL cleanup argument in the child
607 process, you're strongly recommended to create a separate cleanup function
608 for child process that will only clean up what has been allocated in child
609 process. Otherwise the 'cleanup()' will be called both from the parent and
610 child and the test will likely fail (for example in 'tst_rmdir()' because
611 both parent and child will attempt to remove the directory and one of them
612 will fail).
613
614** The same applies to xref:2.2.4[safe macros] because they call 'tst_brkm()'
615 when anything goes wrong.
616
617* Or you can stick to plain old 'exit()' with 'TPASS', 'TBROK', 'TFAIL' and
618 'TCONF' constants.
619
620Then you call 'tst_record_childstatus()' to records the result of the test
621(done in child process) which propagates the child result (child exit status)
622to the parent process correctly.
623
624[source,c]
625-------------------------------------------------------------------------------
626#include "test.h"
627
628void tst_record_childstatus(void (*cleanup)(void), pid_t child);
629-------------------------------------------------------------------------------
630
631This function does a 'waitpid()' on child process and record child process's
632return value into the overall test result.
633
6342.2.8 Fork() and Parent-child synchronization
Cyril Hrubisafb61682014-01-13 19:08:02 +0100635^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
636
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700637As LTP tests are written for Linux, most of the test involves fork()-ing and
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +0800638parent-child process synchronization. We have a checkpoint library code
Cyril Hrubisafb61682014-01-13 19:08:02 +0100639that works even for two different processes, all they need to is to run with
640the same working directory (they use FIFO for synchronization). The checkpoint
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700641interface provides two pairs of signal and wait functions. One pair to be used
Cyril Hrubisafb61682014-01-13 19:08:02 +0100642to signal child from parent and second to signal parent from child.
643
Jan Stanceka4bb6db2014-10-17 09:38:00 +0200644Checkpoint is represented by 'struct tst_checkpoint', which has to be
645initialized before first usage and FIFO has to be created. This is
646usually done in parent process in single step by calling
647'tst_checkpoint_create()'.
648
649Child processes created via fork() are ready to use tst_checkpoint_*
650synchronization functions, as they inherited already initialized
651'struct tst_checkpoint'.
652
653Child processes started via exec*, or any other process can use already
654created FIFO, provided they initialize 'struct tst_checkpoint' first by
655call to 'tst_checkpoint_init()'. This function does not create any FIFO,
656it relies on fact, that it was already created by some other process.
657Note, that if you use multiple FIFOs in this scenario, these should be
658initialized in same order as in process you are sychronizing against.
659
660IMPORTANT: Be aware, that following scenario is _NOT_ safe when using
661 only single checkpoint. You are advised to use two checkpoints
662 in this case.
663
664* tst_checkpoint_signal_child() followed by tst_checkpoint_parent_wait()
665
666 parent | child
667-------------------------------+-------------------------------
668 | tst_checkpoint_child_wait()
669 | blocking read, waits until
670 | parent opens write side
671tst_checkpoint_signal_child() |
672 NONBLOCK write |
673 | child is now able to read
674 | from FIFO
675tst_checkpoint_parent_wait() |
676 NONBLOCK read parent able to |
677 read from FIFO and can race |
678 with read in child |
679 | tst_checkpoint_signal_parent()
680-------------------------------+--------------------------------
681
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700682For the details of the interface, look into the 'include/tst_checkpoint.h' and
Cyril Hrubisafb61682014-01-13 19:08:02 +0100683'lib/tests/tst_checkpoint_*'.
684
685There is also an interface that allows parent to wait until child is blocked
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700686in kernel (for example waits in 'pause()'), see 'include/tst_process_state.h'
Cyril Hrubisafb61682014-01-13 19:08:02 +0100687for more.
688
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +08006892.2.9 Signal handlers
Cyril Hrubis12563f92014-02-03 17:55:41 +0100690^^^^^^^^^^^^^^^^^^^^^
691
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700692If you need to use signal handlers, keep the code short and simple. Don't
Cyril Hrubis124c9872014-07-03 17:24:38 +0200693forget that the signal handler is called asynchronously and can interrupt the
694code execution at any place.
Cyril Hrubis12563f92014-02-03 17:55:41 +0100695
Cyril Hrubis124c9872014-07-03 17:24:38 +0200696This means that problems arise when global state is changed both from the test
697code and signal handler, which will occasionally lead to:
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700698
Cyril Hrubis124c9872014-07-03 17:24:38 +0200699* Data corruption (data gets into inconsistent state), this may happen, for
700 example, for any operations on 'FILE' objects.
701
702* Deadlock, this happens, for example, if you call 'malloc(2)', 'free(2)',
703 etc. from both the test code and the signal handler at the same time because
704 'malloc' has global lock for it's internal data structures. (Be wary that
705 'malloc(2)' is used by the libc functions internally too.)
706
707* Any other unreproducible and unexpected behavior.
Cyril Hrubis12563f92014-02-03 17:55:41 +0100708
Cyril Hrubis187e3232014-02-13 14:58:07 +0100709Quite common mistake is to call 'exit(3)' from a signal handler. Note that this
Cyril Hrubis12563f92014-02-03 17:55:41 +0100710function is not signal-async-safe as it flushes buffers, etc. If you need to
711exit a test immediately from a signal handler use '_exit(2)' instead.
712
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700713TIP: See 'man 7 signal' for the list of signal-async-safe functions.
Cyril Hrubis12563f92014-02-03 17:55:41 +0100714
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700715If a signal handler sets a variable, its declaration must be 'volatile',
716otherwise compiler may misoptimize the code, because the variable may not be
Cyril Hrubis187e3232014-02-13 14:58:07 +0100717changed in the code flow analysis. There is 'sig_atomic_t' type defined in C99
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700718but this one DOES NOT imply volatile (it's just a typedef to int). So the
719correct type for a flag that is changed from a signal handler is either
720'volatile int' or 'volatile sig_atomic_t'.
Cyril Hrubis12563f92014-02-03 17:55:41 +0100721
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +08007222.2.10 Kernel Modules
723^^^^^^^^^^^^^^^^^^^^^
Cyril Hrubisafb61682014-01-13 19:08:02 +0100724
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700725There are certain cases where the test needs a kernel part and userspace part,
726happily, LTP can build a kernel module and then insert it to the kernel on test
Cyril Hrubisafb61682014-01-13 19:08:02 +0100727start for you. See 'testcases/kernel/device-drivers/block' for details.
728
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +08007292.2.11 Usefull macros
Cyril Hrubis50493f62014-02-12 15:05:43 +0100730^^^^^^^^^^^^^^^^^^^^^
731
732[source,c]
733-------------------------------------------------------------------------------
734ARRAY_SIZE(arr)
735-------------------------------------------------------------------------------
736
737Returns the size of statically defined array, i.e.
738'(sizeof(arr) / sizeof(*arr))'
739
740[source,c]
741-------------------------------------------------------------------------------
742LTP_ALIGN(x, a)
743-------------------------------------------------------------------------------
744
745Aligns the x to be next multiple of a. The a must be power of 2.
Cyril Hrubisafb61682014-01-13 19:08:02 +0100746
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +08007472.2.12 Filesystem type detection
Cyril Hrubis0f0e3482014-02-27 16:08:04 +0100748^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
749
750Some tests are known to fail on certain filesytems (you cannot swap on TMPFS,
751there are unimplemented fcntl() etc.).
752
Jiri Jaburekcc595b12014-06-23 10:30:03 -0700753If your test needs to be skipped on certain filesystems, use the interface
754below:
Cyril Hrubis0f0e3482014-02-27 16:08:04 +0100755
756[source,c]
757-------------------------------------------------------------------------------
758#include "tst_fs_type.h"
759
760 /*
761 * Unsupported only on NFS.
762 */
763 if (tst_fs_type(cleanup, ".") == TST_NFS_MAGIC) {
764 tst_brkm(TCONF, cleanup,
765 "Test not supported on NFS filesystem");
766 }
767
768 /*
769 * Unsupported on NFS, TMPFS and RAMFS
770 */
771 long type;
772
773 switch ((type = tst_fs_type(cleanup, "."))) {
774 case TST_NFS_MAGIC:
775 case TST_TMPFS_MAGIC:
776 case TST_RAMFS_MAGIC:
777 tst_brkm(TCONF, cleanup, "Test not supported on %s filesytem",
778 tst_fs_type_name(type));
779 break;
780 }
781-------------------------------------------------------------------------------
782
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +08007832.2.13 Thread-safety in the LTP library
Alexey Kodanev683d16e2014-03-27 17:28:18 +0400784^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
785
786It is safe to use library 'tst_' functions in multi-threaded tests.
787Synchronization mechanism is enabled only if the test is linked with pthread
788library, otherwise no-op stubs (defined in libc) are used.
789
790Also, LTP has a helper "TST_DECLARE_ONCE_FN" macro to declare a function which
791must be run only once (e.g. init or cleanup function), but might be called by
792multiple threads at the same time. See example below:
793
794[source,c]
795-------------------------------------------------------------------------------
796#include "test.h"
797
798...
799
800void do_cleanup(void)
801{
802 /* cleanup code */
803 ...
804}
805TST_DECLARE_ONCE_FN(cleanup, do_cleanup);
806
807...
808
809void test01(void)
810{
811 sfd = socket(AF_INET, SOCK_STREAM, 0);
812 if (sfd == -1)
813 tst_brkm(TBROK, cleanup, "Failed to create a socket");
814}
815-------------------------------------------------------------------------------
816
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +08008172.2.14 Acquiring a block device
Cyril Hrubis85e787e2014-06-18 17:09:21 +0200818^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
819
820Some tests needs a block device (inotify tests, syscall 'EROFS' failures,
821etc.). For your convenience LTP library includes a function to acquire and
822release a testing device.
823
824[source,c]
825-------------------------------------------------------------------------------
826#include "test.h"
827
828const char *tst_acquire_device(void (cleanup_fn)(void));
829-------------------------------------------------------------------------------
830
831This function returns a path to small block device suitable for formatting and
832mounting.
833
834WARNING: You can acquire only one device, calling it for second time without
835 releasing the device first will abort the test.
836
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700837In case that 'LTP_DEV' is passed to the test in environment, the function just
838checks that the file exists and that it's a block device.
Cyril Hrubis85e787e2014-06-18 17:09:21 +0200839
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700840Otherwise a temporary file is created and attached to a free loop device.
Cyril Hrubis85e787e2014-06-18 17:09:21 +0200841
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700842In case that that there are no unused loop devices, 'NULL' is returned. The
Cyril Hrubis85e787e2014-06-18 17:09:21 +0200843test should skip the particular part of the test that needs the device with
844'TCONF'.
845
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700846WARNING: Because 'tst_acquire_device()' may create temporary file, you must
Cyril Hrubis85e787e2014-06-18 17:09:21 +0200847 call 'tst_tmpdir()' before you call 'tst_acquire_device()'
848
849[source,c]
850-------------------------------------------------------------------------------
851#include "test.h"
852
853void tst_release_device(void (cleanup_fn)(void), const char *dev);
854-------------------------------------------------------------------------------
855
856Releases the device acquired by 'tst_acquire_device()'.
857
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +08008582.2.15 Formatting a device with a filesystem
Xiaoguang Wang35266852014-03-26 17:23:45 +0800859^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
860
861[source,c]
862-------------------------------------------------------------------------------
863#include "test.h"
864
Cyril Hrubise6c24c12014-06-19 12:46:45 +0200865const char *tst_dev_fs_type(void);
866-------------------------------------------------------------------------------
867
868Returns name of filesystem that should be used for tests. Unless is your test
869designed to test specific filesystem you should use this function to select
870filesystem for the 'tst_mkfs()'.
871
872NOTE: The default filesytem is hardcoded to 'ext2' in the sources and can be
873 overridden by setting 'LTP_DEV_FS_TYPE' environment variable.
874
875[source,c]
876-------------------------------------------------------------------------------
877#include "test.h"
878
Xiaoguang Wang35266852014-03-26 17:23:45 +0800879void tst_mkfs(void (cleanup_fn)(void), const char *dev,
880 const char *fs_type, const char *const fs_opts[]);
881-------------------------------------------------------------------------------
882
883This function takes a path to a device, filesystem type and an array of extra
884options passed to mkfs.
885
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700886The extra options 'fs_opts' should either be 'NULL' if there are none, or a
Xiaoguang Wang35266852014-03-26 17:23:45 +0800887'NULL' terminated array of strings such as '{"-b", "1024", NULL}'.
888
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +08008892.2.16 Verifying a filesystem's free space
Xiaoguang Wang4de5b2c2014-05-08 13:42:23 +0800890^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
891
892Some tests have size requirements for the filesystem's free space. If these
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700893requirements are not satisfied, the tests are not appropriate to run.
Xiaoguang Wang4de5b2c2014-05-08 13:42:23 +0800894Especially when you run runltp with "-z" option to specify a big block device,
895different tests have different requirements for the free space of this block
896device.
897
898[source,c]
899-------------------------------------------------------------------------------
900#include "test.h"
901
902int tst_fs_has_free(void (*cleanup)(void), const char *path,
903 unsigned int size, unsigned int mult);
904-------------------------------------------------------------------------------
905
906The 'tst_fs_has_free()' function returns 1 if there is enough space and 0 if
907there is not.
908
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700909The 'path' is the pathname of any directory/file within a filesystem you want to
910verify its free space of.
Xiaoguang Wang4de5b2c2014-05-08 13:42:23 +0800911
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700912The 'mult' is a multiplier, one of 'TST_BYTES', 'TST_KB', 'TST_MB' or 'TST_GB'.
Xiaoguang Wang4de5b2c2014-05-08 13:42:23 +0800913
914The required free space is calculated by 'size * mult', e.g.
915'tst_fs_has_free(cleanup, "/tmp/testfile", 64, TST_MB)' will return 1 if the
916filesystem, which '"/tmp/testfile"' is in, has 64MB free space at least, and 0
917if not.
918
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +08009192.2.17 Getting the maximum number of links to a regular file or directory
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700920^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Xiaoguang Wangcee6cbe2014-06-18 14:31:03 +0800921
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700922Some tests need to know the maximum count of links to a regular file or
Xiaoguang Wangcee6cbe2014-06-18 14:31:03 +0800923directory, such as 'rename(2)' or 'linkat(2)' to test 'EMLINK' error.
924
925[source,c]
926-------------------------------------------------------------------------------
927#include "test.h"
928
929int tst_fs_fill_hardlinks(void (*cleanup)(void), const char *dir);
930-------------------------------------------------------------------------------
931
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700932Try to get maximum count of hard links to a regular file inside the 'dir'.
Xiaoguang Wangcee6cbe2014-06-18 14:31:03 +0800933
934NOTE: This number depends on the filesystem 'dir' is on.
935
936This function uses 'link(2)' to create hard links to a single file until it
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700937gets 'EMLINK' or creates 65535 links. If the limit is hit, the maximum number of
Xiaoguang Wangcee6cbe2014-06-18 14:31:03 +0800938hardlinks is returned and the 'dir' is filled with hardlinks in format
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700939"testfile%i", where i belongs to [0, limit) interval. If no limit is hit or if
Xiaoguang Wangcee6cbe2014-06-18 14:31:03 +0800940'link(2)' failed with 'ENOSPC' or 'EDQUOT', zero is returned and previously
941created files are removed.
942
943[source,c]
944-------------------------------------------------------------------------------
945#include "test.h"
946
947int tst_fs_fill_subdirs(void (*cleanup)(void), const char *dir);
948-------------------------------------------------------------------------------
949
950Try to get maximum number of subdirectories in directory.
951
Sheng Yong4584f912015-02-02 08:47:13 +0000952NOTE: This number depends on the filesystem 'dir' is on. For current kernel,
953subdir limit is not availiable for all filesystems (availiable for ext2, ext3,
954minix, sysv and more). If the test runs on some other filesystems, like ramfs,
955tmpfs, it will not even try to reach the limit and return 0.
Xiaoguang Wangcee6cbe2014-06-18 14:31:03 +0800956
957This function uses 'mkdir(2)' to create directories in 'dir' until it gets
Jiri Jaburek1f5eb342014-06-24 02:45:12 -0700958'EMLINK' or creates 65535 directories. If the limit is hit, the maximum number
959of subdirectories is returned and the 'dir' is filled with subdirectories in
960format "testdir%i", where i belongs to [0, limit - 2) interval (because each
961newly created dir has two links already - the '.' and the link from parent
962dir). If no limit is hit or if 'mkdir(2)' failed with 'ENOSPC' or 'EDQUOT',
963zero is returned and previously created directories are removed.
Xiaoguang Wangcee6cbe2014-06-18 14:31:03 +0800964
Xiaoguang Wang3e15bd72014-07-28 19:51:40 +08009652.2.18 Getting an unused PID number
Stanislav Kholmanskikhd2eb7d42014-07-03 11:24:42 +0400966^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
967
968Some tests require a 'PID', which is not used by the OS (does not belong to
969any process within it). For example, kill(2) should set errno to 'ESRCH' if
970it's passed such 'PID'.
971
972[source,c]
973-------------------------------------------------------------------------------
974#include "test.h"
975
976pid_t tst_get_unused_pid(void (*cleanup)(void));
977-------------------------------------------------------------------------------
978
979Return a 'PID' value not used by the OS or any process within it.
980
Cyril Hrubis420add22015-01-29 16:00:10 +01009812.2.19 Umounting devices
982^^^^^^^^^^^^^^^^^^^^^^^^
983
984[source,c]
985-------------------------------------------------------------------------------
986#include "test.h"
987
988int tst_umount(const char *path);
989-------------------------------------------------------------------------------
990
991Since various desktop deamons (gvfsd-trash is known for that) may be stupid
992enough to probe all newly mounted filesystem which results in 'umount(2)'
993failing with 'EBUSY' LTP library includes 'tst_umount()' function that behaves
994exactly as 'umount(2)' but retries several times on a failure.
995
996IMPORTANT: All testcases should use 'tst_umount()' instead of 'umount(2)' to
997 umount filesystems.
998
Stanislav Kholmanskikh571db512015-02-03 19:00:40 +03009992.2.20 Running executables
1000^^^^^^^^^^^^^^^^^^^^^^^^^^
1001
1002[source,c]
1003-------------------------------------------------------------------------------
1004#include "test.h"
1005
1006int tst_run_cmd(void (cleanup_fn)(void),
1007 const char *const argv[],
1008 const char *stdout_path,
1009 const char *stderr_path,
1010 int pass_exit_val);
1011-------------------------------------------------------------------------------
1012
1013'tst_run_cmd' is a wrapper for 'vfork() + execvp()' which provides a way
1014to execute an external program.
1015
1016'argv[]' is a NULL-terminated array of strings starting with the program name
1017which is followed by optional arguments.
1018
1019A non-zero 'pass_exit_val' makes 'tst_run_cmd' return the program exit code to
1020the caller. A zero for 'pass_exit_val' makes 'tst_run_cmd' exit the tests
1021on failure and call 'cleanup_fn' (if not NULL) beforehand.
1022
1023'stdout_path' and 'stderr_path' determine where to redirect the program
1024stdout and stderr I/O streams.
1025
1026.Example
1027[source,c]
1028-------------------------------------------------------------------------------
1029#include "test.h"
1030
1031const char *const cmd[] = { "ls", "-l", NULL };
1032
1033...
1034 /* Store output of 'ls -l' into log.txt */
1035 tst_run_cmd(cleanup, cmd, "log.txt", NULL, 0);
1036...
1037-------------------------------------------------------------------------------
1038
Cyril Hrubis33463792014-03-12 17:13:30 +010010392.3 Writing a testcase in shell
1040~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1041
1042LTP supports testcases to be written in a portable shell too.
1043
1044There is a shell library modeled closely to the C interface (the source is
1045located at 'testcases/lib/test.sh') and is installed to the same directory as
1046the rest of the LTP test binaries.
1047
1048WARNING: All identifiers starting with TST_ or tst_ are reserved for the
1049 'test.sh' library.
1050
10512.3.1 Basic shell test structure
1052^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1053
1054[source,sh]
1055-------------------------------------------------------------------------------
1056#!/bin/sh
1057#
1058# This is a basic test for true shell buildin
1059#
1060
1061TCID=true01
1062TST_TOTAL=1
1063. test.sh
1064
1065true
1066ret=$?
1067
1068if [ $ret -eq 0 ]; then
1069 tst_resm TPASS "true returned 0"
1070else
1071 tst_resm TFAIL "true rturned $ret"
1072fi
1073
1074tst_exit
1075-------------------------------------------------------------------------------
1076
1077TIP: To execute this test the 'test.sh' library must be in '$PATH'. If you are
1078 executing the test from a git checkout you can run it as
1079 'PATH="$PATH:../../lib" ./foo01.sh'
1080
1081WARNING: Do not forget to add the 'tst_exit' at the end of the test,
1082 otherwise the test return value would be the return value of last
1083 executed command.
1084
10852.3.2 Basic test interface
1086^^^^^^^^^^^^^^^^^^^^^^^^^^
1087
1088Following functions similar to the LTP C intearface are available.
1089
1090* tst_resm()
1091* tst_brkm()
1092* tst_exit()
1093* tst_require_root()
1094* tst_tmpdir()
1095* tst_rmdir()
Xiaoguang Wang4de5b2c2014-05-08 13:42:23 +08001096* tst_fs_has_free()
Cyril Hrubis33463792014-03-12 17:13:30 +01001097
1098There is one more function called 'tst_check_cmds()' that gets unspecified
1099number of parameters and asserts that each parameter is a name of an
1100executable in '$PATH' and exits the test with 'TCONF' on first missing.
1101
Xiaoguang Wang4de5b2c2014-05-08 13:42:23 +08001102.tst_fs_has_free
1103[source,sh]
1104-------------------------------------------------------------------------------
1105#!/bin/sh
1106
1107...
1108
1109# whether current directory has 100MB free space at least.
1110if ! tst_fs_has_free . 100MB; then
1111 tst_brkm TCONF "Not enough free space"
1112fi
1113
1114...
1115-------------------------------------------------------------------------------
1116
1117The tst_fs_has_free shell interface returns 0 if the specified free space is
1118satisfied, 1 if not, and 2 on error.
1119
1120The second argument supports suffixes kB, MB and GB, the default unit is Byte.
1121
Cyril Hrubis33463792014-03-12 17:13:30 +010011222.3.3 Cleanup
1123^^^^^^^^^^^^^
1124
Jiri Jaburek1f5eb342014-06-24 02:45:12 -07001125Due to differences between C and shell, the cleanup callback is done using a
Cyril Hrubis33463792014-03-12 17:13:30 +01001126'TST_CLEANUP' shell variable that, if not empty, is evaluated before the test
1127exits (either after calling 'tst_exit()' or 'tst_brkm()'). See example below.
1128
1129[source,sh]
1130-------------------------------------------------------------------------------
1131#!/bin/sh
1132#
1133# Test cleanup example
1134#
1135
1136TCID=true01
1137TST_TOTAL=1
1138. test.sh
1139
1140cleanup()
1141{
1142 tst_rmdir
1143}
1144
1145tst_tmpdir
1146TST_CLEANUP=cleanup
1147
1148# Do the test here
1149
1150tst_exit
1151-------------------------------------------------------------------------------
1152
Cyril Hrubis79040742014-03-26 13:51:38 +010011532.3.4 Restarting daemons
1154^^^^^^^^^^^^^^^^^^^^^^^^
1155
1156Restarting system daemons is a complicated task for two reasons.
1157
1158* There are different init systems
1159 (SysV init, systemd, etc...)
1160
1161* Daemon names are not unified between distributions
1162 (apache vs httpd, cron vs crond, various syslog variations)
1163
1164To solve these problems LTP has 'testcases/lib/daemonlib.sh' library that
1165provides functions to start/stop/query daemons as well as variables that store
1166correct daemon name.
1167
1168.Supported operations
1169|==============================================================================
1170| start_daemon() | Starts daemon, name is passed as first parameter.
1171| stop_daemon() | Stops daemon, name is passed as first parameter.
1172| restart_daemon() | Restarts daemon, name is passed as first parameter.
1173| status_daemon() | Returns daemon status, TODO: what is return value?
1174|==============================================================================
1175
1176.Variables with detected names
1177|==============================================================================
1178| CROND_DAEMON | Cron daemon name (cron, crond).
1179| SYSLOG_DAEMON | Syslog daemon name (syslog, syslog-ng, rsyslog).
1180|==============================================================================
1181
1182.Cron daemon restart example
1183[source,sh]
1184-------------------------------------------------------------------------------
1185#!/bin/sh
1186#
1187# Cron daemon restart example
1188#
1189TCID=cron01
1190TST_COUNT=1
1191. test.sh
1192. daemonlib.sh
1193
1194...
1195
1196restart_daemon $CROND_DAEMON
1197
1198...
1199
1200tst_exit
1201-------------------------------------------------------------------------------
1202
Cyril Hrubiseb44f8e2014-03-13 14:42:16 +01001203
12043. Common problems
1205------------------
1206
Jiri Jaburek1f5eb342014-06-24 02:45:12 -07001207This chapter describes common problems/misuses and less obvious design patters
Cyril Hrubiseb44f8e2014-03-13 14:42:16 +01001208(quirks) in UNIX interfaces. Read it carefully :)
1209
12103.1 umask()
1211~~~~~~~~~~~
1212
Jiri Jaburek1f5eb342014-06-24 02:45:12 -07001213I've been hit by this one several times already... When you create files
Cyril Hrubiseb44f8e2014-03-13 14:42:16 +01001214with 'open()' or 'creat()' etc, the mode specified as the last parameter *is
1215not* the mode the file is created with. The mode depends on current 'umask()'
1216settings which may clear some of the bits. If your test depends on specific
Cyril Hrubis21977432014-05-29 18:47:03 +02001217file permissions you need either to change umask to 0 or 'chmod()' the file
1218afterwards or use SAFE_TOUCH() that does the 'chmod()' for you.
Cyril Hrubiseb44f8e2014-03-13 14:42:16 +01001219
Alexey Kodanevfb3da0a2014-05-13 15:34:32 +040012203.2 access()
1221~~~~~~~~~~~
1222
Jiri Jaburek1f5eb342014-06-24 02:45:12 -07001223If 'access(some_file, W_OK)' is executed by root, it will return success even
Alexey Kodanevfb3da0a2014-05-13 15:34:32 +04001224if the file doesn't have write permission bits set (the same holds for R_OK
Jiri Jaburek1f5eb342014-06-24 02:45:12 -07001225too). For sysfs files you can use 'open()' as a workaround to check file
Alexey Kodanevfb3da0a2014-05-13 15:34:32 +04001226read/write permissions. It might not work for other filesystems, for these you
1227have to use 'stat()', 'lstat()' or 'fstat()'.
Cyril Hrubiseb44f8e2014-03-13 14:42:16 +01001228
Cyril Hrubis420add22015-01-29 16:00:10 +010012293.3 umount() EBUSY
1230~~~~~~~~~~~~~~~~~~
1231
1232Various desktop deamons (gvfsd-trash is known for that) may be stupid enough
1233to probe all newly mounted filesystem which results in 'umount(2)' failing
1234with 'EBUSY'; use 'tst_umount()' described in 2.2.19 that retries in this case
1235instead of plain 'umount(2)'.
1236
1237
Cyril Hrubiseb44f8e2014-03-13 14:42:16 +010012384. Test Contribution Checklist
Cyril Hrubisafb61682014-01-13 19:08:02 +01001239------------------------------
1240
12411. Test compiles and runs fine (check with -i 10 too)
12422. Checkpatch does not report any errors
12433. The runtest entires are in place
12444. Test files are added into corresponding .gitignore files
12455. Patches apply over the latest git
Cyril Hrubiseb44f8e2014-03-13 14:42:16 +01001246
1247
12484.1 About .gitignore files
1249~~~~~~~~~~~~~~~~~~~~~~~~~~
1250
1251There are numerous '.gitignore' files in the LTP tree. Usually there is a
1252'.gitignore' file per a group of tests. The reason for this setup is simple.
Jiri Jaburek1f5eb342014-06-24 02:45:12 -07001253It's easier to maintain a '.gitignore' file per directory with tests, rather
1254than having single file in the project root directory. This way, we don't have
1255to update all the gitignore files when moving directories, and they get deleted
1256automatically when a directory with tests is removed.