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