1 /*
2  * Copyright (C) 2018 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 "libdm/loop_control.h"
18 
19 #include <fcntl.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 
26 #include <android-base/file.h>
27 #include <android-base/unique_fd.h>
28 #include <gtest/gtest.h>
29 #include "test_util.h"
30 
31 using namespace std;
32 using namespace android::dm;
33 using unique_fd = android::base::unique_fd;
34 
TempFile()35 static unique_fd TempFile() {
36     // A loop device needs to be at least one sector to actually work, so fill
37     // up the file with a message.
38     unique_fd fd(CreateTempFile("temp", 0));
39     if (fd < 0) {
40         return {};
41     }
42     char buffer[] = "Hello";
43     for (size_t i = 0; i < 1000; i++) {
44         if (!android::base::WriteFully(fd, buffer, sizeof(buffer))) {
45             perror("write");
46             return {};
47         }
48     }
49     return fd;
50 }
51 
TEST(libdm,LoopControl)52 TEST(libdm, LoopControl) {
53     unique_fd fd = TempFile();
54     ASSERT_GE(fd, 0);
55 
56     LoopDevice loop(fd, 10s);
57     ASSERT_TRUE(loop.valid());
58 
59     char buffer[6];
60     unique_fd loop_fd(open(loop.device().c_str(), O_RDWR));
61     ASSERT_GE(loop_fd, 0);
62     ASSERT_TRUE(android::base::ReadFully(loop_fd, buffer, sizeof(buffer)));
63     ASSERT_EQ(memcmp(buffer, "Hello", 6), 0);
64 }
65