William A. Kennington III | 4f5711c | 2022-08-12 17:01:53 -0700 | [diff] [blame] | 1 | #include <gtest/gtest.h> |
| 2 | |
William A. Kennington III | e774345 | 2022-08-12 17:39:44 -0700 | [diff] [blame^] | 3 | #include <filesystem> |
| 4 | #include <memory> |
William A. Kennington III | 4f5711c | 2022-08-12 17:01:53 -0700 | [diff] [blame] | 5 | #include <stdplus/fd/fmt.hpp> |
| 6 | #include <stdplus/fd/managed.hpp> |
William A. Kennington III | e774345 | 2022-08-12 17:39:44 -0700 | [diff] [blame^] | 7 | #include <stdplus/gtest/tmp.hpp> |
William A. Kennington III | 4f5711c | 2022-08-12 17:01:53 -0700 | [diff] [blame] | 8 | #include <stdplus/util/cexec.hpp> |
| 9 | #include <sys/mman.h> |
| 10 | |
| 11 | namespace stdplus |
| 12 | { |
| 13 | namespace fd |
| 14 | { |
| 15 | |
| 16 | TEST(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 III | e774345 | 2022-08-12 17:39:44 -0700 | [diff] [blame^] | 37 | class 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 | |
| 58 | TEST_F(FormatToFileTest, NoCommit) |
| 59 | { |
| 60 | file->append("hi\n"); |
| 61 | EXPECT_EQ(0, std::filesystem::file_size(tmpname)); |
| 62 | } |
| 63 | |
| 64 | TEST_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 III | 4f5711c | 2022-08-12 17:01:53 -0700 | [diff] [blame] | 74 | } // namespace fd |
| 75 | } // namespace stdplus |