blob: b49112c36e5d7cff7e088f28dea3ef82148af9be [file] [log] [blame]
William A. Kennington IIIaa4fcfc2022-08-23 16:35:10 -07001#include <stdplus/fd/atomic.hpp>
2#include <stdplus/fd/ops.hpp>
3#include <stdplus/gtest/tmp.hpp>
Patrick Williamsd1984dd2023-05-10 16:12:44 -05004
5#include <filesystem>
6#include <memory>
William A. Kennington IIIaa4fcfc2022-08-23 16:35:10 -07007#include <string_view>
8
9namespace stdplus
10{
11namespace fd
12{
13
14using std::literals::string_view_literals::operator""sv;
15
16class AtomicWriterTest : public gtest::TestWithTmp
17{
18 protected:
19 std::string filename;
20 std::unique_ptr<AtomicWriter> file;
21
Patrick Williamsd1984dd2023-05-10 16:12:44 -050022 AtomicWriterTest() : filename(fmt::format("{}/out", CaseTmpDir())) {}
William A. Kennington IIIaa4fcfc2022-08-23 16:35:10 -070023
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
38TEST_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
46TEST_F(AtomicWriterTest, BadCommit)
47{
48 auto tmp = fmt::format("{}/tmp.XXXXXX", CaseTmpDir());
Patrick Williamsd1984dd2023-05-10 16:12:44 -050049 ASSERT_NO_THROW(
50 file = std::make_unique<AtomicWriter>("/dev/null", 0644, tmp));
William A. Kennington IIIaa4fcfc2022-08-23 16:35:10 -070051 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
57TEST_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