| #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> |
|
|
| |
| void setUp(void) { |
| |
| } |
| void tearDown(void) { |
| |
| } |
|
|
| |
| |
|
|
| 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) { |
| |
| |
| 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(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); |
|
|
| |
| 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)); |
|
|
| |
| errno = 0; |
| int rc1 = iclose(fd); |
| TEST_ASSERT_EQUAL_INT(0, rc1); |
| assert_fd_is_closed(fd); |
|
|
| |
| 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]; |
|
|
| |
| errno = 0; |
| int rc = iclose(rfd); |
| TEST_ASSERT_EQUAL_INT(0, rc); |
| assert_fd_is_closed(rfd); |
|
|
| |
| 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(); |
| } |