coreutils / tests /dd /tests_for_iclose.c
AryaWu's picture
Upload folder using huggingface_hub
78d2150 verified
#include "../../unity/unity.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
/* Unity hooks */
void setUp(void) {
/* no-op */
}
void tearDown(void) {
/* no-op */
}
/* Target function under test (static in dd.c and available via inclusion) */
/* int iclose(int fd); -- already visible since this file is included into dd.c */
static void assert_fd_is_closed(int fd) {
errno = 0;
int r = fcntl(fd, F_GETFD);
TEST_ASSERT_EQUAL_INT(-1, r);
TEST_ASSERT_EQUAL_INT(EBADF, errno);
}
static int make_temp_fd(char *out_path_buf, size_t buf_size) {
/* Create a unique temporary file using mkstemp, then unlink it so only the fd remains. */
/* Use a template in /tmp. */
const char *prefix = "/tmp/dd_iclose_test_XXXXXX";
TEST_ASSERT_TRUE_MESSAGE(buf_size > strlen(prefix), "Buffer too small for template");
strcpy(out_path_buf, prefix);
int fd = mkstemp(out_path_buf);
TEST_ASSERT_TRUE_MESSAGE(fd >= 0, "mkstemp failed");
/* Unlink so no filesystem artifact remains */
unlink(out_path_buf);
return fd;
}
void test_iclose_valid_fd_closes_successfully(void) {
char path[64];
int fd = make_temp_fd(path, sizeof(path));
errno = 0;
int rc = iclose(fd);
TEST_ASSERT_EQUAL_INT(0, rc);
/* The fd should now be closed. */
assert_fd_is_closed(fd);
}
void test_iclose_invalid_fd_minus_one(void) {
errno = 0;
int rc = iclose(-1);
TEST_ASSERT_EQUAL_INT(-1, rc);
TEST_ASSERT_EQUAL_INT(EBADF, errno);
}
void test_iclose_double_close_returns_error_second_time(void) {
char path[64];
int fd = make_temp_fd(path, sizeof(path));
/* First close via iclose should succeed. */
errno = 0;
int rc1 = iclose(fd);
TEST_ASSERT_EQUAL_INT(0, rc1);
assert_fd_is_closed(fd);
/* Second close on same fd should fail with EBADF. */
errno = 0;
int rc2 = iclose(fd);
TEST_ASSERT_EQUAL_INT(-1, rc2);
TEST_ASSERT_EQUAL_INT(EBADF, errno);
}
void test_iclose_on_pipe_end(void) {
int fds[2];
int r = pipe(fds);
TEST_ASSERT_EQUAL_INT_MESSAGE(0, r, "pipe() failed");
int rfd = fds[0];
int wfd = fds[1];
/* Close the read end using iclose; should succeed. */
errno = 0;
int rc = iclose(rfd);
TEST_ASSERT_EQUAL_INT(0, rc);
assert_fd_is_closed(rfd);
/* Clean up the write end using plain close to avoid interacting with iclose further. */
close(wfd);
}
int main(void) {
UNITY_BEGIN();
RUN_TEST(test_iclose_valid_fd_closes_successfully);
RUN_TEST(test_iclose_invalid_fd_minus_one);
RUN_TEST(test_iclose_double_close_returns_error_second_time);
RUN_TEST(test_iclose_on_pipe_end);
return UNITY_END();
}