William A. Kennington III | aa4fcfc | 2022-08-23 16:35:10 -0700 | [diff] [blame] | 1 | #include <stdplus/fd/atomic.hpp> |
| 2 | #include <stdplus/fd/ops.hpp> |
| 3 | #include <stdplus/gtest/tmp.hpp> |
Patrick Williams | d1984dd | 2023-05-10 16:12:44 -0500 | [diff] [blame] | 4 | |
| 5 | #include <filesystem> |
| 6 | #include <memory> |
William A. Kennington III | aa4fcfc | 2022-08-23 16:35:10 -0700 | [diff] [blame] | 7 | #include <string_view> |
| 8 | |
| 9 | namespace stdplus |
| 10 | { |
| 11 | namespace fd |
| 12 | { |
| 13 | |
| 14 | using std::literals::string_view_literals::operator""sv; |
| 15 | |
| 16 | class AtomicWriterTest : public gtest::TestWithTmp |
| 17 | { |
| 18 | protected: |
| 19 | std::string filename; |
| 20 | std::unique_ptr<AtomicWriter> file; |
| 21 | |
Patrick Williams | d1984dd | 2023-05-10 16:12:44 -0500 | [diff] [blame] | 22 | AtomicWriterTest() : filename(fmt::format("{}/out", CaseTmpDir())) {} |
William A. Kennington III | aa4fcfc | 2022-08-23 16:35:10 -0700 | [diff] [blame] | 23 | |
| 24 | ~AtomicWriterTest() noexcept |
| 25 | { |
| 26 | if (file) |
| 27 | { |
| 28 | auto tmpname = file->getTmpname(); |
| 29 | file.reset(); |
| 30 | if (!tmpname.empty()) |
| 31 | { |
| 32 | EXPECT_FALSE(std::filesystem::exists(tmpname)); |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | }; |
| 37 | |
| 38 | TEST_F(AtomicWriterTest, NoCommit) |
| 39 | { |
| 40 | ASSERT_NO_THROW(file = std::make_unique<AtomicWriter>(filename, 0644)); |
| 41 | writeExact(*file, "hi\n"sv); |
| 42 | EXPECT_FALSE(std::filesystem::exists(filename)); |
| 43 | EXPECT_TRUE(std::filesystem::exists(file->getTmpname())); |
| 44 | } |
| 45 | |
| 46 | TEST_F(AtomicWriterTest, BadCommit) |
| 47 | { |
| 48 | auto tmp = fmt::format("{}/tmp.XXXXXX", CaseTmpDir()); |
Patrick Williams | d1984dd | 2023-05-10 16:12:44 -0500 | [diff] [blame] | 49 | ASSERT_NO_THROW( |
| 50 | file = std::make_unique<AtomicWriter>("/dev/null", 0644, tmp)); |
William A. Kennington III | aa4fcfc | 2022-08-23 16:35:10 -0700 | [diff] [blame] | 51 | writeExact(*file, "hi\n"sv); |
| 52 | EXPECT_TRUE(std::filesystem::exists(file->getTmpname())); |
| 53 | EXPECT_THROW(file->commit(), std::filesystem::filesystem_error); |
| 54 | EXPECT_EQ(file->getTmpname(), ""sv); |
| 55 | } |
| 56 | |
| 57 | TEST_F(AtomicWriterTest, Basic) |
| 58 | { |
| 59 | ASSERT_NO_THROW(file = std::make_unique<AtomicWriter>(filename, 0644)); |
| 60 | writeExact(*file, "hi\n"sv); |
| 61 | EXPECT_TRUE(std::filesystem::exists(file->getTmpname())); |
| 62 | EXPECT_NO_THROW(file->commit()); |
| 63 | EXPECT_EQ(file->getTmpname(), ""sv); |
| 64 | std::error_code ec; |
| 65 | EXPECT_EQ(3, std::filesystem::file_size(filename, ec)); |
| 66 | EXPECT_EQ(std::errc{}, ec); |
| 67 | } |
| 68 | |
| 69 | } // namespace fd |
| 70 | } // namespace stdplus |