Skip to content

Commit

Permalink
Add unit tests for fs::CopyFileContents
Browse files Browse the repository at this point in the history
  • Loading branch information
sfan5 committed Feb 4, 2024
1 parent 9338101 commit 714c936
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions src/unittest/test_filesys.cpp
Expand Up @@ -40,6 +40,7 @@ class TestFileSys : public TestBase
void testRemoveLastPathComponentWithTrailingDelimiter();
void testRemoveRelativePathComponent();
void testSafeWriteToFile();
void testCopyFileContents();
};

static TestFileSys g_test_instance;
Expand All @@ -52,14 +53,15 @@ void TestFileSys::runTests(IGameDef *gamedef)
TEST(testRemoveLastPathComponentWithTrailingDelimiter);
TEST(testRemoveRelativePathComponent);
TEST(testSafeWriteToFile);
TEST(testCopyFileContents);
}

////////////////////////////////////////////////////////////////////////////////

// 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] == '/') {
Expand Down Expand Up @@ -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);
}

0 comments on commit 714c936

Please sign in to comment.