Arman Uguray | f4c6181 | 2013-01-10 18:58:39 -0800 | [diff] [blame] | 1 | // Copyright (c) 2013 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "shill/file_reader.h" |
| 6 | |
| 7 | #include <string> |
| 8 | #include <vector> |
| 9 | |
| 10 | #include <base/file_util.h> |
| 11 | #include <base/scoped_temp_dir.h> |
| 12 | #include <base/string_util.h> |
| 13 | #include <gtest/gtest.h> |
| 14 | |
| 15 | using std::string; |
| 16 | using std::vector; |
| 17 | |
| 18 | namespace shill { |
| 19 | |
| 20 | class FileReaderTest : public ::testing::Test { |
| 21 | public: |
| 22 | void VerifyReadLines(const FilePath& path, const vector<string>& lines) { |
| 23 | string line; |
| 24 | EXPECT_FALSE(reader_.ReadLine(&line)); |
| 25 | EXPECT_TRUE(reader_.Open(path)); |
| 26 | for (size_t i = 0; i < lines.size(); ++i) { |
| 27 | EXPECT_TRUE(reader_.ReadLine(&line)); |
| 28 | EXPECT_EQ(lines[i], line); |
| 29 | } |
| 30 | EXPECT_FALSE(reader_.ReadLine(&line)); |
| 31 | reader_.Close(); |
| 32 | EXPECT_FALSE(reader_.ReadLine(&line)); |
| 33 | } |
| 34 | |
| 35 | protected: |
| 36 | FileReader reader_; |
| 37 | }; |
| 38 | |
| 39 | TEST_F(FileReaderTest, OpenNonExistentFile) { |
| 40 | EXPECT_FALSE(reader_.Open(FilePath("a_nonexistent_file"))); |
| 41 | } |
| 42 | |
| 43 | TEST_F(FileReaderTest, OpenEmptyFile) { |
| 44 | ScopedTempDir temp_dir; |
| 45 | ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); |
| 46 | FilePath path; |
| 47 | ASSERT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir.path(), &path)); |
| 48 | |
| 49 | EXPECT_TRUE(reader_.Open(path)); |
| 50 | string line; |
| 51 | EXPECT_FALSE(reader_.ReadLine(&line)); |
| 52 | reader_.Close(); |
| 53 | } |
| 54 | |
| 55 | TEST_F(FileReaderTest, ReadLine) { |
| 56 | vector<string> lines; |
| 57 | lines.push_back("this is"); |
| 58 | lines.push_back("a"); |
| 59 | lines.push_back(""); |
| 60 | lines.push_back("test"); |
| 61 | string content = JoinString(lines, '\n'); |
| 62 | |
| 63 | ScopedTempDir temp_dir; |
| 64 | ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); |
| 65 | FilePath path; |
| 66 | ASSERT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir.path(), &path)); |
| 67 | |
| 68 | // Test a file not ending with a new-line character |
| 69 | ASSERT_EQ(content.size(), |
| 70 | file_util::WriteFile(path, content.c_str(), content.size())); |
| 71 | VerifyReadLines(path, lines); |
| 72 | |
| 73 | // Test a file ending with a new-line character |
| 74 | content.push_back('\n'); |
| 75 | ASSERT_EQ(content.size(), |
| 76 | file_util::WriteFile(path, content.c_str(), content.size())); |
| 77 | VerifyReadLines(path, lines); |
| 78 | } |
| 79 | |
| 80 | } // namespace shill |