blob: 85d51ed2b816835e24622bf84816070c86710219 [file] [log] [blame]
Arman Ugurayf4c61812013-01-10 18:58:39 -08001// 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
15using std::string;
16using std::vector;
17
18namespace shill {
19
20class 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
39TEST_F(FileReaderTest, OpenNonExistentFile) {
40 EXPECT_FALSE(reader_.Open(FilePath("a_nonexistent_file")));
41}
42
43TEST_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
55TEST_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