blob: f87aacf2099491eacbdd032b942233ae82fa99a9 [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>
Paul Stewart5ad16062013-02-21 18:10:48 -080011#include <base/files/scoped_temp_dir.h>
Arman Ugurayf4c61812013-01-10 18:58:39 -080012#include <base/string_util.h>
13#include <gtest/gtest.h>
14
Albert Chaulk0e1cdea2013-02-27 15:32:55 -080015using base::FilePath;
Arman Ugurayf4c61812013-01-10 18:58:39 -080016using std::string;
17using std::vector;
18
19namespace shill {
20
21class FileReaderTest : public ::testing::Test {
22 public:
23 void VerifyReadLines(const FilePath& path, const vector<string>& lines) {
24 string line;
25 EXPECT_FALSE(reader_.ReadLine(&line));
26 EXPECT_TRUE(reader_.Open(path));
27 for (size_t i = 0; i < lines.size(); ++i) {
28 EXPECT_TRUE(reader_.ReadLine(&line));
29 EXPECT_EQ(lines[i], line);
30 }
31 EXPECT_FALSE(reader_.ReadLine(&line));
32 reader_.Close();
33 EXPECT_FALSE(reader_.ReadLine(&line));
34 }
35
36 protected:
37 FileReader reader_;
38};
39
40TEST_F(FileReaderTest, OpenNonExistentFile) {
41 EXPECT_FALSE(reader_.Open(FilePath("a_nonexistent_file")));
42}
43
44TEST_F(FileReaderTest, OpenEmptyFile) {
Paul Stewart5ad16062013-02-21 18:10:48 -080045 base::ScopedTempDir temp_dir;
Arman Ugurayf4c61812013-01-10 18:58:39 -080046 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
47 FilePath path;
48 ASSERT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir.path(), &path));
49
50 EXPECT_TRUE(reader_.Open(path));
51 string line;
52 EXPECT_FALSE(reader_.ReadLine(&line));
53 reader_.Close();
54}
55
56TEST_F(FileReaderTest, ReadLine) {
57 vector<string> lines;
58 lines.push_back("this is");
59 lines.push_back("a");
60 lines.push_back("");
61 lines.push_back("test");
62 string content = JoinString(lines, '\n');
63
Paul Stewart5ad16062013-02-21 18:10:48 -080064 base::ScopedTempDir temp_dir;
Arman Ugurayf4c61812013-01-10 18:58:39 -080065 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
66 FilePath path;
67 ASSERT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir.path(), &path));
68
69 // Test a file not ending with a new-line character
70 ASSERT_EQ(content.size(),
71 file_util::WriteFile(path, content.c_str(), content.size()));
72 VerifyReadLines(path, lines);
73
74 // Test a file ending with a new-line character
75 content.push_back('\n');
76 ASSERT_EQ(content.size(),
77 file_util::WriteFile(path, content.c_str(), content.size()));
78 VerifyReadLines(path, lines);
79}
80
81} // namespace shill