1 /* 2 * mkstemp test suite. 3 * 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/>. 6 * 7 * Written by Russ Allbery <eagle@eyrie.org> 8 * Copyright 2009, 2011 9 * The Board of Trustees of the Leland Stanford Junior University 10 * 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 14 * warranty. 15 * 16 * SPDX-License-Identifier: FSFAP 17 */ 18 19 #include <config.h> 20 #include <portable/system.h> 21 22 #include <errno.h> 23 #include <sys/stat.h> 24 25 #include <tests/tap/basic.h> 26 27 int test_mkstemp(char *template); 28 29 int 30 main(void) 31 { 32 int fd; 33 char template[] = "tsXXXXXXX"; 34 char tooshort[] = "XXXXX"; 35 char bad1[] = "/foo/barXXXXX"; 36 char bad2[] = "/foo/barXXXXXX.out"; 37 char buffer[256]; 38 struct stat st1, st2; 39 ssize_t length; 40 41 plan(20); 42 43 /* First, test a few error messages. */ 44 errno = 0; 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"); 48 errno = 0; 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"); 52 errno = 0; 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"); 56 errno = 0; 57 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"); 64 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"); 69 unlink(template); 70 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"); 78 close(fd); 79 80 return 0; 81 } 82