mirror of
https://github.com/XRPLF/rippled.git
synced 2026-08-21 22:30:57 +00:00
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: mvadari <8029314+mvadari@users.noreply.github.com> Co-authored-by: Mayukha Vadari <mvadari@ripple.com> Co-authored-by: Mayukha Vadari <mvadari@gmail.com> Co-authored-by: Ayaz Salikhov <mathbunnyru@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: mathbunnyru <12270691+mathbunnyru@users.noreply.github.com>
95 lines
2.2 KiB
C++
95 lines
2.2 KiB
C++
#include <xrpl/basics/FileUtilities.h>
|
|
|
|
#include <xrpl/basics/ByteUtilities.h>
|
|
|
|
#include <gtest/gtest.h>
|
|
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <system_error>
|
|
|
|
namespace xrpl {
|
|
|
|
namespace {
|
|
|
|
class TempFile
|
|
{
|
|
public:
|
|
explicit TempFile(std::string const& file, std::string const& contents)
|
|
: file_(
|
|
uniqueRandomPath(std::filesystem::temp_directory_path(), "xrpl-file-utilities-") /
|
|
file)
|
|
{
|
|
std::filesystem::create_directory(file_.parent_path());
|
|
|
|
std::ofstream output(file_);
|
|
if (!output)
|
|
throw std::runtime_error("Unable to create temporary test file");
|
|
|
|
output << contents;
|
|
}
|
|
|
|
~TempFile()
|
|
{
|
|
// use non-throwing calls in the destructor
|
|
std::error_code ec;
|
|
auto const dir = file_.parent_path();
|
|
std::filesystem::remove_all(dir, ec);
|
|
if (ec)
|
|
{
|
|
std::cerr << "Unable to remove temporary directory '" << dir.string()
|
|
<< "': " << ec.message() << '\n';
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] std::filesystem::path const&
|
|
file() const
|
|
{
|
|
return file_;
|
|
}
|
|
|
|
private:
|
|
std::filesystem::path file_;
|
|
};
|
|
|
|
} // namespace
|
|
|
|
TEST(FileUtilitiesTest, get_file_contents)
|
|
{
|
|
constexpr char const* kExpectedContents = "This file is very short. That's all we need.";
|
|
|
|
TempFile const file("test_file", "This is temporary text that should get overwritten");
|
|
|
|
std::error_code ec;
|
|
auto const path = file.file();
|
|
|
|
writeFileContents(ec, path, kExpectedContents);
|
|
EXPECT_FALSE(ec);
|
|
|
|
{
|
|
// Test with no max
|
|
auto const good = getFileContents(ec, path);
|
|
EXPECT_FALSE(ec);
|
|
EXPECT_EQ(good, kExpectedContents);
|
|
}
|
|
|
|
{
|
|
// Test with large max
|
|
auto const good = getFileContents(ec, path, kilobytes(1));
|
|
EXPECT_FALSE(ec);
|
|
EXPECT_EQ(good, kExpectedContents);
|
|
}
|
|
|
|
{
|
|
// Test with small max
|
|
auto const bad = getFileContents(ec, path, 16);
|
|
EXPECT_TRUE(ec && ec.value() == static_cast<int>(std::errc::file_too_large));
|
|
EXPECT_TRUE(bad.empty());
|
|
}
|
|
}
|
|
|
|
} // namespace xrpl
|