Files
cpp17-threaded-app-non-thre…/tests/helpers/scoped_file_test.cpp
T

84 lines
1.3 KiB
C++
Raw Normal View History

#include <cassert>
#include <filesystem>
#include <fstream>
#include <stdexcept>
#include <sys/stat.h>
#include "scoped_file.hpp"
namespace {
void testFileRemovedAfterScope() {
const std::string fileName = "scoped_file_test.log";
{
ScopedFile file(fileName);
file.throwIfExists();
std::ofstream output(file.getFileName());
assert(output.is_open());
output << "test";
output.close();
assert(std::filesystem::exists(fileName));
} // call ~ScopedFile()
assert(!std::filesystem::exists(fileName));
}
void testThrowIfExists() {
const std::string fileName = "existing_file.log";
{
ScopedFile file(fileName);
if (std::filesystem::exists(fileName)) {
throw std::runtime_error("Test file already exists: " + fileName);
}
std::ofstream output(file.getFileName());
assert(output.is_open());
output.close();
bool thrown = false;
try {
file.throwIfExists();
} catch (const std::runtime_error &) {
thrown = true;
}
assert(thrown);
}
assert(!std::filesystem::exists(fileName));
}
void testGetFileName() {
ScopedFile file("test.log");
file.throwIfExists();
assert(file.getFileName() == "test.log");
}
void runTests() {
testFileRemovedAfterScope();
testThrowIfExists();
testGetFileName();
}
} // namespace
int main() {
runTests();
return 0;
}