1b58efe43e32d3cae8168385197012c79cde56a7
[folly.git] / folly / experimental / symbolizer / test / LineReaderTest.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
17 #include <folly/experimental/symbolizer/LineReader.h>
18
19 #include <glog/logging.h>
20 #include <gtest/gtest.h>
21
22 #include <folly/FileUtil.h>
23 #include <folly/experimental/TestUtil.h>
24
25 namespace folly { namespace symbolizer { namespace test {
26
27 using folly::test::TemporaryFile;
28
29 void writeAll(int fd, const char* str) {
30   ssize_t n = strlen(str);
31   CHECK_EQ(n, writeFull(fd, str, n));
32 }
33
34 void expect(LineReader& lr, const char* expected) {
35   StringPiece line;
36   size_t expectedLen = strlen(expected);
37   EXPECT_EQ(expectedLen != 0 ? LineReader::kReading : LineReader::kEof,
38             lr.readLine(line));
39   EXPECT_EQ(expectedLen, line.size());
40   EXPECT_EQ(std::string(expected, expectedLen), line.str());
41 }
42
43 TEST(LineReader, Simple) {
44   TemporaryFile file;
45   int fd = file.fd();
46   writeAll(fd,
47            "Meow\n"
48            "Hello world\n"
49            "This is a long line. It is longer than the other lines.\n"
50            "\n"
51            "Incomplete last line");
52
53   {
54     CHECK_ERR(lseek(fd, 0, SEEK_SET));
55     char buf[10];
56     LineReader lr(fd, buf, sizeof(buf));
57     expect(lr, "Meow\n");
58     expect(lr, "Hello worl");
59     expect(lr, "d\n");
60     expect(lr, "This is a ");
61     expect(lr, "long line.");
62     expect(lr, " It is lon");
63     expect(lr, "ger than t");
64     expect(lr, "he other l");
65     expect(lr, "ines.\n");
66     expect(lr, "\n");
67     expect(lr, "Incomplete");
68     expect(lr, " last line");
69     expect(lr, "");
70   }
71
72   {
73     CHECK_ERR(lseek(fd, 0, SEEK_SET));
74     char buf[80];
75     LineReader lr(fd, buf, sizeof(buf));
76     expect(lr, "Meow\n");
77     expect(lr, "Hello world\n");
78     expect(lr, "This is a long line. It is longer than the other lines.\n");
79     expect(lr, "\n");
80     expect(lr, "Incomplete last line");
81     expect(lr, "");
82   }
83 }
84
85 }}}  // namespaces
86