I am developing a lib for a Linux project that stores files using boost::serialization. Because the files might be very large (1-50 GiB) and the program might fail writing them at some point (we are talking about thousands of them) I want to use a simple backup system to recover the files if they are not valid.
I have to test this using QtTests (the Qt unit test suite), but I could add additional libs if neccessary. The question is now how to test the backup system. In theory the test needs to let the ofstream ofs
add invalid data after a given amount of data.
Here is the source code of the function in question. I am already testing the saving process itself, only the backup system could only be tested by hand.
The code (glued together and shortened to one method):
void DataStore::storeNodeData(TrajectoryDataSet data) {
string path = getDataFileName(data);
string oldPath = getDataFileName(data).append(".old");
if (access(path.c_str(), F_OK) == 0 &&
access(oldPath.c_str(), F_OK) != 0) {
if (rename(path.c_str(), oldPath.c_str()) != 0) {
throw FileSystemException("Unable to rename file to '.old'.");
}
}
bool broken = false;
ofstream ofs(path);
boost::archive::text_oarchive oa(ofs);
oa << data;
if (!ofs.good())
broken = true;
ofs.close();
//File verification
TrajectoryDataSet fData;
ifstream ifs(path);
boost::archive::text_iarchive ia(ifs);
ia >> fData;
ifs.close();
if (fData != data)
broken = true;
if (broken) {
rename(oldPath.c_str(), path.c_str());
throw FileSystemException("Unable write valid file.");
} else if (access(oldPath.c_str(), F_OK) != -1 &&
unlink(oldPath.c_str()) != 0)
throw FileSystemException("Unable to delete backup file.");
}
broken = true;
and if possible by an return value of-1
(!= 0
) forrename
andunlink
. In general the error handling of the method.