172c6f98deecd27f00543ba0414658334ecadda7
[folly.git] / folly / gen / test / FileTest.cpp
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <gtest/gtest.h>
17 #include <string>
18 #include <vector>
19
20 #include <folly/File.h>
21 #include <folly/Range.h>
22 #include <folly/experimental/TestUtil.h>
23 #include <folly/gen/Base.h>
24 #include <folly/gen/File.h>
25
26 using namespace folly::gen;
27 using namespace folly;
28 using std::string;
29 using std::vector;
30
31 TEST(FileGen, ByLine) {
32   auto collect = eachTo<std::string>() | as<vector>();
33   test::TemporaryFile file("ByLine");
34   static const std::string lines(
35       "Hello world\n"
36       "This is the second line\n"
37       "\n"
38       "\n"
39       "a few empty lines above\n"
40       "incomplete last line");
41   EXPECT_EQ(lines.size(), write(file.fd(), lines.data(), lines.size()));
42
43   auto expected = from({lines}) | resplit('\n') | collect;
44   auto found = byLine(file.path().c_str()) | collect;
45
46   EXPECT_TRUE(expected == found);
47 }
48
49 class FileGenBufferedTest : public ::testing::TestWithParam<int> { };
50
51 TEST_P(FileGenBufferedTest, FileWriter) {
52   size_t bufferSize = GetParam();
53   test::TemporaryFile file("FileWriter");
54
55   static const std::string lines(
56       "Hello world\n"
57       "This is the second line\n"
58       "\n"
59       "\n"
60       "a few empty lines above\n");
61
62   auto src = from({lines, lines, lines, lines, lines, lines, lines, lines});
63   auto collect = eachTo<std::string>() | as<vector>();
64   auto expected = src | resplit('\n') | collect;
65
66   src | eachAs<StringPiece>() | toFile(File(file.fd()), bufferSize);
67   auto found = byLine(file.path().c_str()) | collect;
68
69   EXPECT_TRUE(expected == found);
70 }
71
72 INSTANTIATE_TEST_CASE_P(
73     DifferentBufferSizes,
74     FileGenBufferedTest,
75     ::testing::Values(0, 1, 2, 4, 8, 64, 4096));
76 int main(int argc, char *argv[]) {
77   testing::InitGoogleTest(&argc, argv);
78   google::ParseCommandLineFlags(&argc, &argv, true);
79   return RUN_ALL_TESTS();
80 }