From 6a3b40524c63f54116e5d77fa16771816ec2b263 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Fri, 4 Jul 2025 09:50:55 -0700 Subject: [PATCH] Use actual example code and move safe_fopen to os-test --- test/format-test.cc | 18 +++++++----------- test/os-test.cc | 13 ++++++++++++- test/util.h | 11 ----------- 3 files changed, 19 insertions(+), 23 deletions(-) diff --git a/test/format-test.cc b/test/format-test.cc index 322b2794..6697dc17 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -1809,19 +1809,15 @@ TEST(format_test, format_examples) { fmt::format_to(std::back_inserter(out), "The answer is {}.", 42); EXPECT_EQ("The answer is 42.", to_string(out)); - const char* filename = "nonexistent"; - FILE* ftest = safe_fopen(filename, "r"); - if (ftest) fclose(ftest); - int error_code = errno; - EXPECT_TRUE(ftest == nullptr); - EXPECT_SYSTEM_ERROR( + EXPECT_THROW( { - FILE* f = safe_fopen(filename, "r"); - if (!f) - throw fmt::system_error(errno, "Cannot open file '{}'", filename); - fclose(f); + const char* filename = "madeup"; + FILE* file = fopen(filename, "r"); + if (!file) + throw fmt::system_error(errno, "cannot open file '{}'", filename); + fclose(file); }, - error_code, "Cannot open file 'nonexistent'"); + std::system_error); EXPECT_EQ("First, thou shalt count to three", fmt::format("First, thou shalt count to {0}", "three")); diff --git a/test/os-test.cc b/test/os-test.cc index db861e55..f3f39d24 100644 --- a/test/os-test.cc +++ b/test/os-test.cc @@ -19,10 +19,21 @@ using fmt::buffered_file; using testing::HasSubstr; using wstring_view = fmt::basic_string_view; -static std::string uniq_file_name(unsigned line_number) { +static auto uniq_file_name(unsigned line_number) -> std::string { return "test-file" + std::to_string(line_number); } +auto safe_fopen(const char* filename, const char* mode) -> FILE* { +#if defined(_WIN32) && !defined(__MINGW32__) + // Fix MSVC warning about "unsafe" fopen. + FILE* f = nullptr; + errno = fopen_s(&f, filename, mode); + return f; +#else + return std::fopen(filename, mode); +#endif +} + #ifdef _WIN32 # include diff --git a/test/util.h b/test/util.h index 803cdeea..1f2916a9 100644 --- a/test/util.h +++ b/test/util.h @@ -31,17 +31,6 @@ extern const char* const file_content; // Opens a buffered file for reading. auto open_buffered_file(FILE** fp = nullptr) -> fmt::buffered_file; -inline auto safe_fopen(const char* filename, const char* mode) -> FILE* { -#if defined(_WIN32) && !defined(__MINGW32__) - // Fix MSVC warning about "unsafe" fopen. - FILE* f = nullptr; - errno = fopen_s(&f, filename, mode); - return f; -#else - return std::fopen(filename, mode); -#endif -} - template class basic_test_string { private: std::basic_string value_;