1 //===-- Unittests for vfprintf --------------------------------------------===//
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 // These tests are copies of the non-v variants of the printf functions. This is
10 // because these functions are identical in every way except for how the varargs
13 #ifndef LIBC_COPT_STDIO_USE_SYSTEM_FILE
14 #include "src/stdio/fclose.h"
15 #include "src/stdio/ferror.h"
16 #include "src/stdio/fopen.h"
17 #include "src/stdio/fread.h"
18 #endif // LIBC_COPT_STDIO_USE_SYSTEM_FILE
20 #include "src/stdio/vfprintf.h"
22 #include "test/UnitTest/Test.h"
24 namespace printf_test
{
25 #ifndef LIBC_COPT_STDIO_USE_SYSTEM_FILE
26 using LIBC_NAMESPACE::fclose
;
27 using LIBC_NAMESPACE::ferror
;
28 using LIBC_NAMESPACE::fopen
;
29 using LIBC_NAMESPACE::fread
;
30 #else // defined(LIBC_COPT_STDIO_USE_SYSTEM_FILE)
35 #endif // LIBC_COPT_STDIO_USE_SYSTEM_FILE
36 } // namespace printf_test
38 int call_vfprintf(::FILE *__restrict stream
, const char *__restrict format
,
41 va_start(vlist
, format
);
42 int ret
= LIBC_NAMESPACE::vfprintf(stream
, format
, vlist
);
47 TEST(LlvmLibcVFPrintfTest
, WriteToFile
) {
48 const char *FILENAME
= "vfprintf_output.test";
49 auto FILE_PATH
= libc_make_test_file_path(FILENAME
);
51 ::FILE *file
= printf_test::fopen(FILE_PATH
, "w");
52 ASSERT_FALSE(file
== nullptr);
56 constexpr char simple
[] = "A simple string with no conversions.\n";
57 written
= call_vfprintf(file
, simple
);
58 EXPECT_EQ(written
, 37);
60 constexpr char numbers
[] = "1234567890\n";
61 written
= call_vfprintf(file
, "%s", numbers
);
62 EXPECT_EQ(written
, 11);
64 constexpr char format_more
[] = "%s and more\n";
65 constexpr char short_numbers
[] = "1234";
66 written
= call_vfprintf(file
, format_more
, short_numbers
);
67 EXPECT_EQ(written
, 14);
69 ASSERT_EQ(0, printf_test::fclose(file
));
71 file
= printf_test::fopen(FILE_PATH
, "r");
72 ASSERT_FALSE(file
== nullptr);
75 ASSERT_EQ(printf_test::fread(data
, 1, sizeof(simple
) - 1, file
),
77 data
[sizeof(simple
) - 1] = '\0';
78 ASSERT_STREQ(data
, simple
);
79 ASSERT_EQ(printf_test::fread(data
, 1, sizeof(numbers
) - 1, file
),
81 data
[sizeof(numbers
) - 1] = '\0';
82 ASSERT_STREQ(data
, numbers
);
83 ASSERT_EQ(printf_test::fread(
84 data
, 1, sizeof(format_more
) + sizeof(short_numbers
) - 4, file
),
85 sizeof(format_more
) + sizeof(short_numbers
) - 4);
86 data
[sizeof(format_more
) + sizeof(short_numbers
) - 4] = '\0';
87 ASSERT_STREQ(data
, "1234 and more\n");
89 ASSERT_EQ(printf_test::ferror(file
), 0);
91 written
= call_vfprintf(file
, "Writing to a read only file should fail.");
92 EXPECT_LT(written
, 0);
94 ASSERT_EQ(printf_test::fclose(file
), 0);