1 /*
2 * Copyright (C) 2020 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 requied 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
18 #include <android-base/parseint.h>
19 #include <android-base/strings.h>
20 #include <gtest/gtest.h>
21
22 #include <algorithm>
23 #include <fstream>
24
25 using android::base::ParseInt;
26 using android::base::Split;
27
28 namespace android {
29
30 enum swap_fields {
31 SWAP_FILENAME = 0,
32 SWAP_TYPE = 1,
33 SWAP_SIZE = 2,
34 SWAP_USED = 3,
35 SWAP_PRIORITY = 4,
36 SWAP_NUM = 5,
37 };
38
TEST(ZramTest,hasZramSwap)39 TEST(ZramTest, hasZramSwap) {
40 const char* procSwapsPath = "/proc/swaps";
41 const char* swapFilename = "/dev/block/zram0";
42 int64_t swapSize;
43 bool fileFound = false;
44 std::string delimiters = "\t ";
45 std::ifstream ifs(procSwapsPath);
46 std::string line;
47
48 // Discard the header (first line)
49 if (!std::getline(ifs, line)) {
50 FAIL() << "Failed to read /proc/swaps.";
51 }
52 // Read all lines in the file and checks each line if it contains the string
53 // "zram0"
54 while (std::getline(ifs, line)) {
55 if (line.find(swapFilename) != std::string::npos) {
56 // zram device found
57 fileFound = true;
58 break;
59 }
60 }
61 if (!fileFound) {
62 FAIL() << "No swaps found.";
63 }
64
65 std::vector<std::string> data = Split(line, delimiters);
66 // Remove empty strings
67 data.erase(std::remove_if(data.begin(), data.end(),
68 [](const std::string& x) { return x.empty(); }),
69 data.end());
70
71 ASSERT_EQ(SWAP_NUM, data.size()) << "Unexpected format in /proc/swaps.";
72 ASSERT_STREQ(swapFilename, data[SWAP_FILENAME].c_str())
73 << "No zram device found.";
74 ParseInt(data[SWAP_SIZE], &swapSize);
75 ASSERT_GE(swapSize, 0) << "No swap space on zram0.";
76 }
77 } // namespace android
78