Skip to content

Instantly share code, notes, and snippets.

@t-book
Last active March 31, 2025 06:18
Show Gist options
  • Save t-book/5b7fdad8198c182c95a8e054b4e58a9b to your computer and use it in GitHub Desktop.
Save t-book/5b7fdad8198c182c95a8e054b4e58a9b to your computer and use it in GitHub Desktop.
SECTION("ReadFileContent")
{
// Create a temporary file with known content
QTemporaryFile tempFile;
REQUIRE(tempFile.open());
const QString testContent = "This is test content for file reading";
tempFile.write(testContent.toUtf8());
tempFile.flush();
// Test reading the file content
QByteArray content = FileUtils::readFileContent(tempFile.fileName());
REQUIRE(content == testContent.toUtf8());
// Test reading non-existent file returns empty content
QByteArray emptyContent = FileUtils::readFileContent("/non/existent/path.txt");
REQUIRE(emptyContent.isEmpty());
}
SECTION("WriteFileContent")
{
// Generate a temporary file path
QString tempDir = QDir::tempPath();
QString filePath = tempDir + "/qfield_test_write_file.txt";
// Remove the file if it already exists
QFile existingFile(filePath);
if (existingFile.exists())
existingFile.remove();
// Test writing to a file
const QString testContent = "This is test content for file writing";
bool writeSuccess = FileUtils::writeFileContent(filePath, testContent.toUtf8());
REQUIRE(writeSuccess);
// Verify the file was written correctly
QFile writtenFile(filePath);
REQUIRE(writtenFile.exists());
REQUIRE(writtenFile.open(QIODevice::ReadOnly));
QByteArray readContent = writtenFile.readAll();
writtenFile.close();
REQUIRE(readContent == testContent.toUtf8());
// Clean up
writtenFile.remove();
}
SECTION("GetFileInfo")
{
// Create a temporary file with known content
QTemporaryFile tempFile;
REQUIRE(tempFile.open());
const QString testContent = "File info test content";
tempFile.write(testContent.toUtf8());
tempFile.flush();
// Calculate the MD5 hash directly for comparison
QCryptographicHash hash(QCryptographicHash::Md5);
hash.addData(testContent.toUtf8());
QString expectedMd5 = hash.result().toHex();
// Test getting file information
QVariantMap fileInfo = FileUtils::getFileInfo(tempFile.fileName());
REQUIRE(fileInfo["exists"].toBool() == true);
REQUIRE(fileInfo["content"].toByteArray() == testContent.toUtf8());
REQUIRE(fileInfo["md5"].toString() == expectedMd5);
REQUIRE(fileInfo["fileName"].toString() == QFileInfo(tempFile.fileName()).fileName());
REQUIRE(fileInfo["fileSize"].toLongLong() == testContent.length());
// Test getting file information for non-existent file
QVariantMap nonExistentFileInfo = FileUtils::getFileInfo("/non/existent/path.txt");
REQUIRE(nonExistentFileInfo["exists"].toBool() == false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment