[OptTable] Fix typo VALUE => VALUES (NFCI) (#121523)
[llvm-project.git] / libc / test / src / stdio / fprintf_test.cpp
blob82a3e039d9baadf2392fe0e23d4a8abc36b99927
1 //===-- Unittests for fprintf ---------------------------------------------===//
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 //===----------------------------------------------------------------------===//
9 #ifndef LIBC_COPT_STDIO_USE_SYSTEM_FILE
10 #include "src/stdio/fclose.h"
11 #include "src/stdio/ferror.h"
12 #include "src/stdio/fopen.h"
13 #include "src/stdio/fread.h"
14 #endif // LIBC_COPT_STDIO_USE_SYSTEM_FILE
16 #include "src/stdio/fprintf.h"
18 #include "test/UnitTest/Test.h"
20 namespace printf_test {
21 #ifndef LIBC_COPT_STDIO_USE_SYSTEM_FILE
22 using LIBC_NAMESPACE::fclose;
23 using LIBC_NAMESPACE::ferror;
24 using LIBC_NAMESPACE::fopen;
25 using LIBC_NAMESPACE::fread;
26 #else // defined(LIBC_COPT_STDIO_USE_SYSTEM_FILE)
27 using ::fclose;
28 using ::ferror;
29 using ::fopen;
30 using ::fread;
31 #endif // LIBC_COPT_STDIO_USE_SYSTEM_FILE
32 } // namespace printf_test
34 TEST(LlvmLibcFPrintfTest, WriteToFile) {
35 const char *FILENAME = "fprintf_output.test";
36 auto FILE_PATH = libc_make_test_file_path(FILENAME);
38 ::FILE *file = printf_test::fopen(FILE_PATH, "w");
39 ASSERT_FALSE(file == nullptr);
41 int written;
43 constexpr char simple[] = "A simple string with no conversions.\n";
44 written = LIBC_NAMESPACE::fprintf(file, simple);
45 EXPECT_EQ(written, 37);
47 constexpr char numbers[] = "1234567890\n";
48 written = LIBC_NAMESPACE::fprintf(file, "%s", numbers);
49 EXPECT_EQ(written, 11);
51 constexpr char format_more[] = "%s and more\n";
52 constexpr char short_numbers[] = "1234";
53 written = LIBC_NAMESPACE::fprintf(file, format_more, short_numbers);
54 EXPECT_EQ(written, 14);
56 ASSERT_EQ(0, printf_test::fclose(file));
58 file = printf_test::fopen(FILE_PATH, "r");
59 ASSERT_FALSE(file == nullptr);
61 char data[50];
62 ASSERT_EQ(printf_test::fread(data, 1, sizeof(simple) - 1, file),
63 sizeof(simple) - 1);
64 data[sizeof(simple) - 1] = '\0';
65 ASSERT_STREQ(data, simple);
66 ASSERT_EQ(printf_test::fread(data, 1, sizeof(numbers) - 1, file),
67 sizeof(numbers) - 1);
68 data[sizeof(numbers) - 1] = '\0';
69 ASSERT_STREQ(data, numbers);
70 ASSERT_EQ(printf_test::fread(
71 data, 1, sizeof(format_more) + sizeof(short_numbers) - 4, file),
72 sizeof(format_more) + sizeof(short_numbers) - 4);
73 data[sizeof(format_more) + sizeof(short_numbers) - 4] = '\0';
74 ASSERT_STREQ(data, "1234 and more\n");
76 ASSERT_EQ(printf_test::ferror(file), 0);
78 written =
79 LIBC_NAMESPACE::fprintf(file, "Writing to a read only file should fail.");
80 EXPECT_LT(written, 0);
82 ASSERT_EQ(printf_test::fclose(file), 0);