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