1 // Copyright 2020 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "android/base/misc/FileUtils.h"
16 
17 #include "android/base/files/ScopedFd.h"
18 #include "android/utils/eintr_wrapper.h"
19 #include "android/utils/file_io.h"
20 #include "android/utils/tempfile.h"
21 
22 #include <fcntl.h>
23 #include <gtest/gtest.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <limits>
27 #include <string>
28 
29 using android::base::ScopedFd;
30 
31 namespace android {
32 
TEST(FileUtils,stringToFile)33 TEST(FileUtils, stringToFile) {
34     const char test_pattern[] = "test pattern";
35     TempFile* tf = tempfile_create();
36 
37     ScopedFd fd(HANDLE_EINTR(open(tempfile_path(tf), O_RDWR, 0600)));
38     EXPECT_NE(-1, fd.get());
39 
40     EXPECT_FALSE(writeStringToFile(-1, test_pattern));
41     EXPECT_TRUE(writeStringToFile(fd.get(), test_pattern));
42 
43     std::string dummy_buffer("dummy");
44     EXPECT_FALSE(readFileIntoString(-1, &dummy_buffer));
45     EXPECT_STREQ("dummy", dummy_buffer.c_str());
46 
47     std::string read_buffer;
48     EXPECT_TRUE(readFileIntoString(fd.get(), &read_buffer));
49     EXPECT_STREQ(test_pattern, read_buffer.c_str());
50 
51     fd.close();
52 
53     auto readFailedRes = readFileIntoString("!@#%R#$%W$*@#$*");
54     EXPECT_FALSE(readFailedRes);
55 
56     auto readSucceededRes = readFileIntoString(tempfile_path(tf));
57     EXPECT_TRUE(readSucceededRes);
58     EXPECT_STREQ(test_pattern, readSucceededRes->c_str());
59 
60     tempfile_close(tf);
61 }
62 
63 // Tests readFileIntoString
TEST(FileUtils,fileToString)64 TEST(FileUtils, fileToString) {
65     const int bytesToTest = 100;
66 
67     std::vector<uint8_t> testPattern;
68 
69     for (int i = 0; i < bytesToTest; i++) {
70         testPattern.push_back(i % 3 == 0 ? 0x0 : 0x1a);
71     }
72 
73     TempFile* tf = tempfile_create();
74 
75     ScopedFd fd(HANDLE_EINTR(open(tempfile_path(tf), O_RDWR, 0600)));
76     EXPECT_NE(-1, fd.get());
77 
78     HANDLE_EINTR(write(fd.get(), testPattern.data(), bytesToTest));
79 
80     fd.close();
81 
82     const auto testOutput = readFileIntoString(tempfile_path(tf));
83 
84     EXPECT_TRUE(testOutput);
85     EXPECT_EQ(bytesToTest, testOutput->size());
86 
87     for (int i = 0; i < bytesToTest; i++) {
88         EXPECT_EQ((char)testPattern[i], (char)testOutput->at(i));
89     }
90 }
91 
92 }  // namespace android
93