1 | //===-- Unittests for isatty ----------------------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #include "src/errno/libc_errno.h" |
10 | #include "src/fcntl/open.h" |
11 | #include "src/unistd/close.h" |
12 | #include "src/unistd/isatty.h" |
13 | #include "test/UnitTest/ErrnoSetterMatcher.h" |
14 | #include "test/UnitTest/Test.h" |
15 | |
16 | #include <sys/stat.h> |
17 | |
18 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails; |
19 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds; |
20 | |
21 | TEST(LlvmLibcIsATTYTest, StdInOutTests) { |
22 | // If stdin is connected to a terminal, assume that all of the standard i/o |
23 | // fds are. |
24 | LIBC_NAMESPACE::libc_errno = 0; |
25 | if (LIBC_NAMESPACE::isatty(fd: 0)) { |
26 | EXPECT_THAT(LIBC_NAMESPACE::isatty(0), Succeeds(1)); // stdin |
27 | EXPECT_THAT(LIBC_NAMESPACE::isatty(1), Succeeds(1)); // stdout |
28 | EXPECT_THAT(LIBC_NAMESPACE::isatty(2), Succeeds(1)); // stderr |
29 | } else { |
30 | EXPECT_THAT(LIBC_NAMESPACE::isatty(0), Fails(ENOTTY, 0)); // stdin |
31 | EXPECT_THAT(LIBC_NAMESPACE::isatty(1), Fails(ENOTTY, 0)); // stdout |
32 | EXPECT_THAT(LIBC_NAMESPACE::isatty(2), Fails(ENOTTY, 0)); // stderr |
33 | } |
34 | } |
35 | |
36 | TEST(LlvmLibcIsATTYTest, BadFdTest) { |
37 | LIBC_NAMESPACE::libc_errno = 0; |
38 | EXPECT_THAT(LIBC_NAMESPACE::isatty(-1), Fails(EBADF, 0)); // invalid fd |
39 | } |
40 | |
41 | TEST(LlvmLibcIsATTYTest, DevTTYTest) { |
42 | constexpr const char *FILENAME = "/dev/tty" ; |
43 | auto TTY_FILE = libc_make_test_file_path(FILENAME); |
44 | LIBC_NAMESPACE::libc_errno = 0; |
45 | int fd = LIBC_NAMESPACE::open(path: TTY_FILE, O_RDONLY); |
46 | if (fd > 0) { |
47 | ASSERT_ERRNO_SUCCESS(); |
48 | EXPECT_THAT(LIBC_NAMESPACE::isatty(fd), Succeeds(1)); |
49 | ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0)); |
50 | } |
51 | } |
52 | |
53 | TEST(LlvmLibcIsATTYTest, FileTest) { |
54 | constexpr const char *FILENAME = "isatty.test" ; |
55 | auto TEST_FILE = libc_make_test_file_path(FILENAME); |
56 | LIBC_NAMESPACE::libc_errno = 0; |
57 | int fd = LIBC_NAMESPACE::open(path: TEST_FILE, O_WRONLY | O_CREAT, S_IRWXU); |
58 | ASSERT_ERRNO_SUCCESS(); |
59 | ASSERT_GT(fd, 0); |
60 | EXPECT_THAT(LIBC_NAMESPACE::isatty(fd), Fails(ENOTTY, 0)); |
61 | ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0)); |
62 | } |
63 | |