4 * The canonical version of this file is maintained in the rra-c-util package,
5 * which can be found at <https://www.eyrie.org/~eagle/software/rra-c-util/>.
7 * Written by Russ Allbery <eagle@eyrie.org>
9 * The Board of Trustees of the Leland Stanford Junior University
11 * Copying and distribution of this file, with or without modification, are
12 * permitted in any medium without royalty provided the copyright notice and
13 * this notice are preserved. This file is offered as-is, without any
16 * SPDX-License-Identifier: FSFAP
20 #include <portable/system.h>
25 #include <tests/tap/basic.h>
27 int test_mkstemp(char *template);
33 char template[] = "tsXXXXXXX";
34 char tooshort[] = "XXXXX";
35 char bad1[] = "/foo/barXXXXX";
36 char bad2[] = "/foo/barXXXXXX.out";
43 /* First, test a few error messages. */
45 is_int(-1, test_mkstemp(tooshort), "too short of template");
46 is_int(EINVAL, errno, "...with correct errno");
47 is_string("XXXXX", tooshort, "...and template didn't change");
49 is_int(-1, test_mkstemp(bad1), "bad template");
50 is_int(EINVAL, errno, "...with correct errno");
51 is_string("/foo/barXXXXX", bad1, "...and template didn't change");
53 is_int(-1, test_mkstemp(bad2), "template doesn't end in XXXXXX");
54 is_int(EINVAL, errno, "...with correct errno");
55 is_string("/foo/barXXXXXX.out", bad2, "...and template didn't change");
58 /* Now try creating a real file. */
59 fd = test_mkstemp(template);
60 ok(fd >= 0, "mkstemp works with valid template");
61 ok(strcmp(template, "tsXXXXXXX") != 0, "...and template changed");
62 ok(strncmp(template, "tsX", 3) == 0, "...and didn't touch first X");
63 ok(access(template, F_OK) == 0, "...and the file exists");
65 /* Make sure that it's the same file as template refers to now. */
66 ok(stat(template, &st1) == 0, "...and stat of template works");
67 ok(fstat(fd, &st2) == 0, "...and stat of open file descriptor works");
68 ok(st1.st_ino == st2.st_ino, "...and they're the same file");
71 /* Make sure the open mode is correct. */
72 length = strlen(template);
73 is_int(length, write(fd, template, length), "write to open file works");
74 ok(lseek(fd, 0, SEEK_SET) == 0, "...and rewind works");
75 is_int(length, read(fd, buffer, length), "...and the data is there");
76 buffer[length] = '\0';
77 is_string(template, buffer, "...and matches what we wrote");