xref: /aosp_15_r20/external/llvm-libc/test/src/stdio/fgetc_test.cpp (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- Unittests for fgetc -----------------------------------------------===//
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/stdio/clearerr.h"
10 #include "src/stdio/fclose.h"
11 #include "src/stdio/feof.h"
12 #include "src/stdio/ferror.h"
13 #include "src/stdio/fgetc.h"
14 #include "src/stdio/fopen.h"
15 #include "src/stdio/fwrite.h"
16 #include "src/stdio/getc.h"
17 #include "test/UnitTest/Test.h"
18 
19 #include "hdr/stdio_macros.h"
20 #include "src/errno/libc_errno.h"
21 
22 class LlvmLibcGetcTest : public LIBC_NAMESPACE::testing::Test {
23 public:
24   using GetcFunc = int(FILE *);
test_with_func(GetcFunc * func,const char * filename)25   void test_with_func(GetcFunc *func, const char *filename) {
26     ::FILE *file = LIBC_NAMESPACE::fopen(filename, "w");
27     ASSERT_FALSE(file == nullptr);
28     constexpr char CONTENT[] = "123456789";
29     constexpr size_t WRITE_SIZE = sizeof(CONTENT) - 1;
30     ASSERT_EQ(WRITE_SIZE, LIBC_NAMESPACE::fwrite(CONTENT, 1, WRITE_SIZE, file));
31     // This is a write-only file so reads should fail.
32     ASSERT_EQ(func(file), EOF);
33     // This is an error and not a real EOF.
34     ASSERT_EQ(LIBC_NAMESPACE::feof(file), 0);
35     ASSERT_NE(LIBC_NAMESPACE::ferror(file), 0);
36     LIBC_NAMESPACE::libc_errno = 0;
37 
38     ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));
39 
40     file = LIBC_NAMESPACE::fopen(filename, "r");
41     ASSERT_FALSE(file == nullptr);
42 
43     for (size_t i = 0; i < WRITE_SIZE; ++i) {
44       int c = func(file);
45       ASSERT_EQ(c, int('1' + i));
46     }
47     // Reading more should return EOF but not set error.
48     ASSERT_EQ(func(file), EOF);
49     ASSERT_NE(LIBC_NAMESPACE::feof(file), 0);
50     ASSERT_EQ(LIBC_NAMESPACE::ferror(file), 0);
51 
52     ASSERT_EQ(0, LIBC_NAMESPACE::fclose(file));
53   }
54 };
55 
TEST_F(LlvmLibcGetcTest,WriteAndReadCharactersWithFgetc)56 TEST_F(LlvmLibcGetcTest, WriteAndReadCharactersWithFgetc) {
57   test_with_func(&LIBC_NAMESPACE::fgetc, "testdata/fgetc.test");
58 }
59 
TEST_F(LlvmLibcGetcTest,WriteAndReadCharactersWithGetc)60 TEST_F(LlvmLibcGetcTest, WriteAndReadCharactersWithGetc) {
61   test_with_func(&LIBC_NAMESPACE::getc, "testdata/getc.test");
62 }
63