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 std::string delimiters = "\t ";
44 std::ifstream ifs(procSwapsPath);
45 std::string line;
46
47 // Discard the header (first line)
48 if (!std::getline(ifs, line)) {
49 FAIL() << "Failed to read /proc/swaps.";
50 }
51
52 if (!std::getline(ifs, line)) {
53 FAIL() << "No swaps found.";
54 }
55
56 std::vector<std::string> data = Split(line, delimiters);
57 // Remove empty strings
58 data.erase(std::remove_if(data.begin(), data.end(),
59 [](const std::string& x) { return x.empty(); }),
60 data.end());
61
62 ASSERT_EQ(SWAP_NUM, data.size()) << "Unexpected format in /proc/swaps.";
63 ASSERT_STREQ(swapFilename, data[SWAP_FILENAME].c_str())
64 << "No zram device found.";
65 ParseInt(data[SWAP_SIZE], &swapSize);
66 ASSERT_GE(swapSize, 0) << "No swap space on zram0.";
67 }
68 } // namespace android
69