blob: b56bd83d3a76394e2ac8e3de296f0ff0feea0193 [file] [log] [blame]
Mike Frysinger38ae98d2012-04-11 12:03:44 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Ben Chanbeefd0d2011-07-25 09:31:34 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "cros-disks/file-reader.h"
6
7#include <string>
8#include <vector>
9
10#include <base/file_util.h>
Ben Chan97f99ff2013-02-14 14:59:33 -080011#include <base/files/scoped_temp_dir.h>
Ben Chanbeefd0d2011-07-25 09:31:34 -070012#include <base/string_util.h>
13#include <gtest/gtest.h>
14
15using std::string;
16using std::vector;
17
18namespace cros_disks {
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) {
Ben Chan97f99ff2013-02-14 14:59:33 -080044 base::ScopedTempDir temp_dir;
Ben Chanbeefd0d2011-07-25 09:31:34 -070045 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
Ben Chan97f99ff2013-02-14 14:59:33 -080063 base::ScopedTempDir temp_dir;
Ben Chanbeefd0d2011-07-25 09:31:34 -070064 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 cros_disks