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

source code of libc/test/src/stdio/fgetc_unlocked_test.cpp