blob: 3703a4935643e743f8540c1c3215dddf505337bb [file] [log] [blame]
Elliott Hughesdec12b22015-02-02 17:31:27 -08001/*
2 * Copyright (C) 2013 The Android Open Source Project
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 "utils/file.h"
18
19#include <errno.h>
Elliott Hughesf682b472015-02-06 12:19:48 -080020#include <fcntl.h>
21#include <unistd.h>
Elliott Hughesdec12b22015-02-02 17:31:27 -080022#include <gtest/gtest.h>
23
Elliott Hughesf682b472015-02-06 12:19:48 -080024class TemporaryFile {
25 public:
26 TemporaryFile() {
27 init("/data/local/tmp");
28 if (fd == -1) {
29 init("/tmp");
30 }
31 }
32
33 ~TemporaryFile() {
34 close(fd);
35 unlink(filename);
36 }
37
38 int fd;
39 char filename[1024];
40
41 private:
42 void init(const char* tmp_dir) {
43 snprintf(filename, sizeof(filename), "%s/TemporaryFile-XXXXXX", tmp_dir);
44 fd = mkstemp(filename);
45 }
46};
47
Elliott Hughesdec12b22015-02-02 17:31:27 -080048TEST(file, ReadFileToString_ENOENT) {
49 std::string s("hello");
50 errno = 0;
Elliott Hughesf682b472015-02-06 12:19:48 -080051 ASSERT_FALSE(android::ReadFileToString("/proc/does-not-exist", &s));
Elliott Hughesdec12b22015-02-02 17:31:27 -080052 EXPECT_EQ(ENOENT, errno);
53 EXPECT_EQ("", s); // s was cleared.
54}
55
56TEST(file, ReadFileToString_success) {
57 std::string s("hello");
Elliott Hughesf682b472015-02-06 12:19:48 -080058 ASSERT_TRUE(android::ReadFileToString("/proc/version", &s)) << errno;
Elliott Hughesdec12b22015-02-02 17:31:27 -080059 EXPECT_GT(s.length(), 6U);
60 EXPECT_EQ('\n', s[s.length() - 1]);
61 s[5] = 0;
62 EXPECT_STREQ("Linux", s.c_str());
63}
Elliott Hughesf682b472015-02-06 12:19:48 -080064
65TEST(file, WriteStringToFile) {
66 TemporaryFile tf;
67 ASSERT_TRUE(tf.fd != -1);
68 ASSERT_TRUE(android::WriteStringToFile("abc", tf.filename)) << errno;
69 std::string s;
70 ASSERT_TRUE(android::ReadFileToString(tf.filename, &s)) << errno;
71 EXPECT_EQ("abc", s);
72}
73
74TEST(file, WriteStringToFd) {
75 TemporaryFile tf;
76 ASSERT_TRUE(tf.fd != -1);
77 ASSERT_TRUE(android::WriteStringToFd("abc", tf.fd));
78
79 ASSERT_EQ(0, lseek(tf.fd, 0, SEEK_SET)) << errno;
80
81 std::string s;
82 ASSERT_TRUE(android::ReadFdToString(tf.fd, &s)) << errno;
83 EXPECT_EQ("abc", s);
84}