|
| 1 | +/* |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | + |
| 8 | +#include <gtest/gtest.h> |
| 9 | +#include <stdio.h> |
| 10 | +#include <filesystem> |
| 11 | +#include <string> |
| 12 | +#include "folly/logging/xlog.h" |
| 13 | + |
| 14 | +#include "fbpcf/io/api/LocalFileWriter.h" |
| 15 | +#include "fbpcf/io/api/test/utils/IOTestHelper.h" |
| 16 | + |
| 17 | +namespace fbpcf::io { |
| 18 | + |
| 19 | +inline void cleanup(std::string fileToDelete) { |
| 20 | + remove(fileToDelete.c_str()); |
| 21 | +} |
| 22 | + |
| 23 | +TEST(LocalFileWriterTest, testWritingToFile) { |
| 24 | + std::string baseDir = IOTestHelper::getBaseDirFromPath(__FILE__); |
| 25 | + std::string fileToWriteTo = baseDir + "data/local_file_writer_test_file.txt"; |
| 26 | + auto writer = std::make_unique<fbpcf::io::LocalFileWriter>(fileToWriteTo); |
| 27 | + |
| 28 | + /* |
| 29 | + CASE 1 |
| 30 | + Write simple string to file |
| 31 | + */ |
| 32 | + std::string toWrite = |
| 33 | + "this file contains the expected text in local_file_writer_test_file.text"; |
| 34 | + auto buf = |
| 35 | + std::vector<char>(toWrite.c_str(), toWrite.c_str() + toWrite.size()); |
| 36 | + auto nBytes = writer->write(buf); |
| 37 | + EXPECT_EQ(nBytes, toWrite.size()); |
| 38 | + |
| 39 | + /* |
| 40 | + CASE 2 |
| 41 | + Write arbitrary bytes to file |
| 42 | + */ |
| 43 | + std::vector<char> arbitraryBytes{'\n', '\n', 'L', 'o', 'c', 'a', 'l', 'F', |
| 44 | + 'i', 'l', 'e', 'W', 'r', 'i', 't', 'e', |
| 45 | + 'r', 'T', 'e', 's', 't', ' '}; |
| 46 | + nBytes = writer->write(arbitraryBytes); |
| 47 | + EXPECT_EQ(nBytes, arbitraryBytes.size()); |
| 48 | + |
| 49 | + /* |
| 50 | + CASE 3 |
| 51 | + Write larger buffer |
| 52 | + */ |
| 53 | + std::string remainingLine = |
| 54 | + "writes to the above file\nWe assert that it's contents match this file\n"; |
| 55 | + auto buf2 = std::vector<char>( |
| 56 | + remainingLine.c_str(), remainingLine.c_str() + remainingLine.size()); |
| 57 | + nBytes = writer->write(buf2); |
| 58 | + EXPECT_EQ(nBytes, remainingLine.size()); |
| 59 | + |
| 60 | + EXPECT_EQ(writer->close(), 0); |
| 61 | + |
| 62 | + /* |
| 63 | + Verify that file contents match the expected |
| 64 | + */ |
| 65 | + IOTestHelper::expectFileContentsMatch( |
| 66 | + fileToWriteTo, baseDir + "data/expected_local_file_writer_test_file.txt"); |
| 67 | + |
| 68 | + cleanup(fileToWriteTo); |
| 69 | +} |
| 70 | + |
| 71 | +} // namespace fbpcf::io |
0 commit comments