xrpld
Loading...
Searching...
No Matches
tests/libxrpl/basics/FileUtilities.cpp
1#include <xrpl/basics/FileUtilities.h>
2
3#include <xrpl/basics/ByteUtilities.h>
4
5#include <gtest/gtest.h>
6
7#include <filesystem>
8#include <fstream>
9#include <iostream>
10#include <stdexcept>
11#include <string>
12#include <system_error>
13
14namespace xrpl {
15
16namespace {
17
18class TempFile
19{
20public:
21 explicit TempFile(std::string const& file, std::string const& contents)
22 : file_(
23 uniqueRandomPath(std::filesystem::temp_directory_path(), "xrpl-file-utilities-") /
24 file)
25 {
26 std::filesystem::create_directory(file_.parent_path());
27
28 std::ofstream output(file_);
29 if (!output)
30 throw std::runtime_error("Unable to create temporary test file");
31
32 output << contents;
33 }
34
35 ~TempFile()
36 {
37 // use non-throwing calls in the destructor
38 std::error_code ec;
39 auto const dir = file_.parent_path();
41 if (ec)
42 {
43 std::cerr << "Unable to remove temporary directory '" << dir.string()
44 << "': " << ec.message() << '\n';
45 }
46 }
47
48 [[nodiscard]] std::filesystem::path const&
49 file() const
50 {
51 return file_;
52 }
53
54private:
55 std::filesystem::path file_;
56};
57
58} // namespace
59
60TEST(FileUtilitiesTest, get_file_contents)
61{
62 constexpr char const* kExpectedContents = "This file is very short. That's all we need.";
63
64 TempFile const file("test_file", "This is temporary text that should get overwritten");
65
67 auto const path = file.file();
68
69 writeFileContents(ec, path, kExpectedContents);
70 EXPECT_FALSE(ec);
71
72 {
73 // Test with no max
74 auto const good = getFileContents(ec, path);
75 EXPECT_FALSE(ec);
76 EXPECT_EQ(good, kExpectedContents);
77 }
78
79 {
80 // Test with large max
81 auto const good = getFileContents(ec, path, kilobytes(1));
82 EXPECT_FALSE(ec);
83 EXPECT_EQ(good, kExpectedContents);
84 }
85
86 {
87 // Test with small max
88 auto const bad = getFileContents(ec, path, 16);
89 EXPECT_TRUE(ec && ec.value() == static_cast<int>(std::errc::file_too_large));
90 EXPECT_TRUE(bad.empty());
91 }
92}
93
94} // namespace xrpl
T create_directory(T... args)
T message(T... args)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
TEST(FileUtilitiesTest, get_file_contents)
std::filesystem::path uniqueRandomPath(std::filesystem::path const &base, std::string const &prefix="", std::size_t maxAttempts=100)
Generate a unique, non-existing path under base whose filename starts with prefix and ends with a ran...
std::string getFileContents(std::error_code &ec, std::filesystem::path const &sourcePath, std::optional< std::size_t > maxSize=std::nullopt)
constexpr auto kilobytes(T value) noexcept
void writeFileContents(std::error_code &ec, std::filesystem::path const &destPath, std::string const &contents)
T remove_all(T... args)
T value(T... args)