From 714c9361eacecf0004524fdb782bd512ff040595 Mon Sep 17 00:00:00 2001 From: sfan5 Date: Sat, 20 Jan 2024 17:16:08 +0100 Subject: [PATCH] Add unit tests for fs::CopyFileContents --- src/unittest/test_filesys.cpp | 38 +++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/src/unittest/test_filesys.cpp b/src/unittest/test_filesys.cpp index dde541a7c..302371361 100644 --- a/src/unittest/test_filesys.cpp +++ b/src/unittest/test_filesys.cpp @@ -40,6 +40,7 @@ public: void testRemoveLastPathComponentWithTrailingDelimiter(); void testRemoveRelativePathComponent(); void testSafeWriteToFile(); + void testCopyFileContents(); }; static TestFileSys g_test_instance; @@ -52,6 +53,7 @@ void TestFileSys::runTests(IGameDef *gamedef) TEST(testRemoveLastPathComponentWithTrailingDelimiter); TEST(testRemoveRelativePathComponent); TEST(testSafeWriteToFile); + TEST(testCopyFileContents); } //////////////////////////////////////////////////////////////////////////////// @@ -59,7 +61,7 @@ void TestFileSys::runTests(IGameDef *gamedef) // adjusts a POSIX path to system-specific conventions // -> changes '/' to DIR_DELIM // -> absolute paths start with "C:\\" on windows -std::string p(std::string path) +static std::string p(std::string path) { for (size_t i = 0; i < path.size(); ++i) { if (path[i] == '/') { @@ -275,5 +277,37 @@ void TestFileSys::testSafeWriteToFile() UASSERT(fs::PathExists(dest_path)); std::string contents_actual; UASSERT(fs::ReadFile(dest_path, contents_actual)); - UASSERT(contents_actual == test_data); + UASSERTEQ(auto, contents_actual, test_data); +} + +void TestFileSys::testCopyFileContents() +{ + const auto dir_path = getTestTempDirectory(); + const auto file1 = dir_path + DIR_DELIM "src", file2 = dir_path + DIR_DELIM "dst"; + const std::string test_data("hello\0world", 11); + + // error case + UASSERT(!fs::CopyFileContents(file1, "somewhere")); + + { + std::ofstream ofs(file1); + ofs << test_data; + } + + // normal case + UASSERT(fs::CopyFileContents(file1, file2)); + std::string contents_actual; + UASSERT(fs::ReadFile(file2, contents_actual)); + UASSERTEQ(auto, contents_actual, test_data); + + // should overwrite and truncate + { + std::ofstream ofs(file2); + for (int i = 0; i < 10; i++) + ofs << "OH MY GAH"; + } + UASSERT(fs::CopyFileContents(file1, file2)); + contents_actual.clear(); + UASSERT(fs::ReadFile(file2, contents_actual)); + UASSERTEQ(auto, contents_actual, test_data); }