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/ErrnoSetterMatcher.h" 14 #include "utils/UnitTest/Test.h" 15 #include "utils/testutils/FDReader.h" 16 17 #include <errno.h> 18 #include <unistd.h> 19 20 TEST(LlvmLibcUniStd, LseekTest) { 21 using __llvm_libc::testing::ErrnoSetterMatcher::Succeeds; 22 constexpr const char *TEST_FILE = "testdata/lseek.test"; 23 int fd = __llvm_libc::open(TEST_FILE, O_RDONLY); 24 ASSERT_EQ(errno, 0); 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(__llvm_libc::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(__llvm_libc::lseek(fd, 0, SEEK_SET), Succeeds(0)); 37 ASSERT_THAT(__llvm_libc::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(__llvm_libc::lseek(fd, -LSEEK_TEST_SIZE, SEEK_END), Succeeds(0)); 44 ASSERT_THAT(__llvm_libc::read(fd, read_buf, LSEEK_TEST_SIZE), 45 Succeeds(LSEEK_TEST_SIZE)); 46 read_buf[LSEEK_TEST_SIZE] = '\0'; 47 EXPECT_STREQ(read_buf, LSEEK_TEST); 48 49 ASSERT_THAT(__llvm_libc::close(fd), Succeeds(0)); 50 } 51 52 TEST(LlvmLibcUniStd, LseekFailsTest) { 53 using __llvm_libc::testing::ErrnoSetterMatcher::Fails; 54 using __llvm_libc::testing::ErrnoSetterMatcher::Succeeds; 55 constexpr const char *TEST_FILE = "testdata/lseek.test"; 56 int fd = __llvm_libc::open(TEST_FILE, O_RDONLY); 57 ASSERT_EQ(errno, 0); 58 ASSERT_GT(fd, 0); 59 EXPECT_THAT(__llvm_libc::lseek(fd, -1, SEEK_CUR), Fails(EINVAL)); 60 ASSERT_THAT(__llvm_libc::close(fd), Succeeds(0)); 61 } 62