From 659a426b03aaacd14793292c9b0771311ba8c995 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sun, 12 May 2024 13:13:20 -0400 Subject: [PATCH] fix(file_handler): avoid writing extra newline character (#2335) --- src/file_handler.cpp | 11 +------ tests/unit/test_file_handler.cpp | 50 ++++++++++++++++++++++++++++---- 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/src/file_handler.cpp b/src/file_handler.cpp index d0783431808..1c7f98e9b3b 100644 --- a/src/file_handler.cpp +++ b/src/file_handler.cpp @@ -31,16 +31,7 @@ namespace file_handler { } std::ifstream in(path); - - std::string input; - std::string base64_cert; - - while (!in.eof()) { - std::getline(in, input); - base64_cert += input + '\n'; - } - - return base64_cert; + return std::string { (std::istreambuf_iterator(in)), std::istreambuf_iterator() }; } /** diff --git a/tests/unit/test_file_handler.cpp b/tests/unit/test_file_handler.cpp index 9167b53de77..b77ba6188cc 100644 --- a/tests/unit/test_file_handler.cpp +++ b/tests/unit/test_file_handler.cpp @@ -6,14 +6,54 @@ #include -TEST(FileHandlerTests, WriteFileTest) { - EXPECT_EQ(file_handler::write_file("write_file_test.txt", "test"), 0); +class FileHandlerTests: public virtual BaseTest, public ::testing::WithParamInterface> { +protected: + void + SetUp() override { + BaseTest::SetUp(); + } + + void + TearDown() override { + BaseTest::TearDown(); + } +}; +INSTANTIATE_TEST_SUITE_P( + TestFiles, + FileHandlerTests, + ::testing::Values( + std::make_tuple(0, ""), // empty file + std::make_tuple(1, "a"), // single character + std::make_tuple(2, "Mr. Blue Sky - Electric Light Orchestra"), // single line + std::make_tuple(3, R"( +Morning! Today's forecast calls for blue skies +The sun is shining in the sky +There ain't a cloud in sight +It's stopped raining +Everybody's in the play +And don't you know, it's a beautiful new day +Hey, hey, hey! +Running down the avenue +See how the sun shines brightly in the city +All the streets where once was pity +Mr. Blue Sky is living here today! +Hey, hey, hey! + )") // multi-line + )); + +TEST_P(FileHandlerTests, WriteFileTest) { + auto [fileNum, content] = GetParam(); + std::string fileName = "write_file_test_" + std::to_string(fileNum) + ".txt"; + EXPECT_EQ(file_handler::write_file(fileName.c_str(), content), 0); } -TEST(FileHandlerTests, ReadFileTest) { - // read file from WriteFileTest - EXPECT_EQ(file_handler::read_file("write_file_test.txt"), "test\n"); // sunshine adds a newline +TEST_P(FileHandlerTests, ReadFileTest) { + auto [fileNum, content] = GetParam(); + std::string fileName = "write_file_test_" + std::to_string(fileNum) + ".txt"; + EXPECT_EQ(file_handler::read_file(fileName.c_str()), content); +} +TEST(FileHandlerTests, ReadMissingFileTest) { // read missing file EXPECT_EQ(file_handler::read_file("non-existing-file.txt"), ""); }