blob: fe1fed47c9a8ee5127b3c70df16f78a967e84c04 [file] [log] [blame]
William A. Kennington III4f5711c2022-08-12 17:01:53 -07001#include <gtest/gtest.h>
2
William A. Kennington IIIe7743452022-08-12 17:39:44 -07003#include <filesystem>
4#include <memory>
William A. Kennington III4f5711c2022-08-12 17:01:53 -07005#include <stdplus/fd/fmt.hpp>
6#include <stdplus/fd/managed.hpp>
William A. Kennington IIIe7743452022-08-12 17:39:44 -07007#include <stdplus/gtest/tmp.hpp>
William A. Kennington III4f5711c2022-08-12 17:01:53 -07008#include <stdplus/util/cexec.hpp>
9#include <sys/mman.h>
10
11namespace stdplus
12{
13namespace fd
14{
15
16TEST(FormatBuffer, Basic)
17{
18 auto fd = ManagedFd(CHECK_ERRNO(memfd_create("test", 0), "memfd_create"));
19 {
20 FormatBuffer buf(fd, 4096);
21 buf.append("hi\n");
22 EXPECT_EQ(0, fd.lseek(0, Whence::Cur));
23 buf.flush();
24
25 EXPECT_EQ(3, fd.lseek(0, Whence::Cur));
26 buf.append("{}", std::string(2050, 'a'));
27 EXPECT_EQ(3, fd.lseek(0, Whence::Cur));
28 buf.append("{}", std::string(2050, 'a'));
29 EXPECT_EQ(4103, fd.lseek(0, Whence::Cur));
30
31 buf.append("hi\n");
32 EXPECT_EQ(4103, fd.lseek(0, Whence::Cur));
33 }
34 EXPECT_EQ(4106, fd.lseek(0, Whence::Cur));
35}
36
William A. Kennington IIIe7743452022-08-12 17:39:44 -070037class FormatToFileTest : public gtest::TestWithTmp
38{
39 protected:
40 std::string tmpname;
41 std::unique_ptr<FormatToFile> file;
42
43 FormatToFileTest() :
44 tmpname(fmt::format("{}/tmp.XXXXXX", CaseTmpDir())),
45 file(std::make_unique<FormatToFile>(tmpname))
46 {
47 tmpname = file->getTmpname();
48 EXPECT_TRUE(std::filesystem::exists(tmpname));
49 }
50
51 ~FormatToFileTest() noexcept(true)
52 {
53 file.reset();
54 EXPECT_FALSE(std::filesystem::exists(tmpname));
55 }
56};
57
58TEST_F(FormatToFileTest, NoCommit)
59{
60 file->append("hi\n");
61 EXPECT_EQ(0, std::filesystem::file_size(tmpname));
62}
63
64TEST_F(FormatToFileTest, Basic)
65{
66 file->append("hi\n");
67 EXPECT_EQ(0, std::filesystem::file_size(tmpname));
68 auto filename = fmt::format("{}/out", CaseTmpDir());
69 file->commit(filename);
70 EXPECT_FALSE(std::filesystem::exists(tmpname));
71 EXPECT_EQ(3, std::filesystem::file_size(filename));
72}
73
William A. Kennington III4f5711c2022-08-12 17:01:53 -070074} // namespace fd
75} // namespace stdplus