summaryrefslogtreecommitdiff
path: root/test/file_test.cc
diff options
context:
space:
mode:
Diffstat (limited to 'test/file_test.cc')
-rw-r--r--test/file_test.cc64
1 files changed, 64 insertions, 0 deletions
diff --git a/test/file_test.cc b/test/file_test.cc
new file mode 100644
index 0000000..b2f4f05
--- /dev/null
+++ b/test/file_test.cc
@@ -0,0 +1,64 @@
+#include "common.hh"
+
+#include "file_test.hh"
+#include "io.hh"
+#include "str_buffer.hh"
+
+FileTest::FileTest() = default;
+
+FileTest::~FileTest() {
+ if (!path_.empty()) {
+ std::error_code err;
+ std::filesystem::remove(path_, err);
+ }
+}
+
+std::string const& FileTest::extension() {
+ static std::string empty;
+ return empty;
+}
+
+void FileTest::SetUp() {
+ fd_ = create_temp_file(extension(), &path_);
+ ASSERT_FALSE(path_.empty());
+}
+
+void FileTest::write(std::string_view content) {
+ ASSERT_TRUE(fd_);
+ auto buffer = make_strbuffer(content);
+ while (!buffer->empty()) {
+ ASSERT_TRUE(io::drain(buffer.get(), fd_.get()));
+ }
+ close();
+}
+
+void FileTest::close() {
+ if (fd_) {
+ ASSERT_TRUE(io::close(fd_.release()));
+ }
+}
+
+unique_fd FileTest::create_temp_file(std::string const& extension,
+ std::filesystem::path* path) {
+ std::error_code err;
+ auto tmpdir = std::filesystem::temp_directory_path(err);
+ if (tmpdir.empty())
+ return unique_fd();
+ unique_fd ret;
+ for (uint8_t i = 0; i < 0xff; ++i) {
+ char name[50];
+ snprintf(name, sizeof(name), "test-%u%s", i, extension.c_str());
+ auto test = tmpdir / name;
+ ret = io::open(test, io::open_flags::wronly | io::open_flags::create |
+ io::open_flags::excl,
+ std::filesystem::perms::owner_read |
+ std::filesystem::perms::owner_write);
+ if (ret) {
+ *path = test;
+ break;
+ }
+ if (errno != EEXIST)
+ break;
+ }
+ return ret;
+}