1 //===-- Unittests for lseek -----------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
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(TEST_FILE
, O_RDONLY
);
24 ASSERT_ERRNO_SUCCESS();
26 constexpr const char LSEEK_TEST
[] = "lseek test";
27 constexpr int LSEEK_TEST_SIZE
= sizeof(LSEEK_TEST
) - 1;
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
);
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
);
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
),
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
);
50 ASSERT_THAT(LIBC_NAMESPACE::close(fd
), Succeeds(0));
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(TEST_FILE
, O_RDONLY
);
59 ASSERT_ERRNO_SUCCESS();
61 EXPECT_THAT(LIBC_NAMESPACE::lseek(fd
, -1, SEEK_CUR
), Fails(EINVAL
));
62 ASSERT_THAT(LIBC_NAMESPACE::close(fd
), Succeeds(0));