1 | //===-- Unittests for lseek -----------------------------------------------===// |
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/fcntl/open.h" |
10 | #include "src/unistd/close.h" |
11 | #include "src/unistd/lseek.h" |
12 | #include "src/unistd/read.h" |
13 | #include "test/UnitTest/ErrnoCheckingTest.h" |
14 | #include "test/UnitTest/ErrnoSetterMatcher.h" |
15 | #include "test/UnitTest/Test.h" |
16 | |
17 | #include <unistd.h> |
18 | |
19 | using LlvmLibcUniStd = LIBC_NAMESPACE::testing::ErrnoCheckingTest; |
20 | |
21 | TEST_F(LlvmLibcUniStd, LseekTest) { |
22 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds; |
23 | constexpr const char *FILENAME = "testdata/lseek.test" ; |
24 | auto TEST_FILE = libc_make_test_file_path(FILENAME); |
25 | int fd = LIBC_NAMESPACE::open(TEST_FILE, O_RDONLY); |
26 | ASSERT_ERRNO_SUCCESS(); |
27 | ASSERT_GT(fd, 0); |
28 | constexpr const char LSEEK_TEST[] = "lseek test" ; |
29 | constexpr ssize_t LSEEK_TEST_SIZE = sizeof(LSEEK_TEST) - 1; |
30 | |
31 | char read_buf[20]; |
32 | ASSERT_THAT(LIBC_NAMESPACE::read(fd, read_buf, LSEEK_TEST_SIZE), |
33 | Succeeds(LSEEK_TEST_SIZE)); |
34 | read_buf[LSEEK_TEST_SIZE] = '\0'; |
35 | EXPECT_STREQ(read_buf, LSEEK_TEST); |
36 | |
37 | // Seek to the beginning of the file and re-read. |
38 | ASSERT_THAT(LIBC_NAMESPACE::lseek(fd, 0, SEEK_SET), Succeeds(off_t(0))); |
39 | ASSERT_THAT(LIBC_NAMESPACE::read(fd, read_buf, LSEEK_TEST_SIZE), |
40 | Succeeds(LSEEK_TEST_SIZE)); |
41 | read_buf[LSEEK_TEST_SIZE] = '\0'; |
42 | EXPECT_STREQ(read_buf, LSEEK_TEST); |
43 | |
44 | // Seek to the beginning of the file from the end and re-read. |
45 | ASSERT_THAT(LIBC_NAMESPACE::lseek(fd, -LSEEK_TEST_SIZE, SEEK_END), |
46 | Succeeds(off_t(0))); |
47 | ASSERT_THAT(LIBC_NAMESPACE::read(fd, read_buf, LSEEK_TEST_SIZE), |
48 | Succeeds(LSEEK_TEST_SIZE)); |
49 | read_buf[LSEEK_TEST_SIZE] = '\0'; |
50 | EXPECT_STREQ(read_buf, LSEEK_TEST); |
51 | |
52 | ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0)); |
53 | } |
54 | |
55 | TEST_F(LlvmLibcUniStd, LseekFailsTest) { |
56 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails; |
57 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds; |
58 | constexpr const char *FILENAME = "testdata/lseek.test" ; |
59 | auto TEST_FILE = libc_make_test_file_path(FILENAME); |
60 | int fd = LIBC_NAMESPACE::open(TEST_FILE, O_RDONLY); |
61 | ASSERT_ERRNO_SUCCESS(); |
62 | ASSERT_GT(fd, 0); |
63 | EXPECT_THAT(LIBC_NAMESPACE::lseek(fd, -1, SEEK_CUR), Fails<off_t>(EINVAL)); |
64 | ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0)); |
65 | } |
66 | |