github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/syscalls/linux/proc_pid_oomscore.cc (about)

     1  // Copyright 2020 The gVisor Authors.
     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 <errno.h>
    16  
    17  #include <exception>
    18  #include <iostream>
    19  #include <string>
    20  
    21  #include "test/util/fs_util.h"
    22  #include "test/util/test_util.h"
    23  
    24  namespace gvisor {
    25  namespace testing {
    26  
    27  namespace {
    28  
    29  PosixErrorOr<int> ReadProcNumber(std::string path) {
    30    ASSIGN_OR_RETURN_ERRNO(std::string contents, GetContents(path));
    31    EXPECT_EQ(contents[contents.length() - 1], '\n');
    32  
    33    int num;
    34    if (!absl::SimpleAtoi(contents, &num)) {
    35      return PosixError(EINVAL, "invalid value: " + contents);
    36    }
    37  
    38    return num;
    39  }
    40  
    41  TEST(ProcPidOomscoreTest, BasicRead) {
    42    auto const oom_score =
    43        ASSERT_NO_ERRNO_AND_VALUE(ReadProcNumber("/proc/self/oom_score"));
    44    EXPECT_LE(oom_score, 1000);
    45    EXPECT_GE(oom_score, -1000);
    46  }
    47  
    48  TEST(ProcPidOomscoreAdjTest, BasicRead) {
    49    auto const oom_score =
    50        ASSERT_NO_ERRNO_AND_VALUE(ReadProcNumber("/proc/self/oom_score_adj"));
    51  
    52    // oom_score_adj defaults to 0.
    53    EXPECT_EQ(oom_score, 0);
    54  }
    55  
    56  TEST(ProcPidOomscoreAdjTest, BasicWrite) {
    57    constexpr int test_value = 7;
    58    FileDescriptor fd =
    59        ASSERT_NO_ERRNO_AND_VALUE(Open("/proc/self/oom_score_adj", O_WRONLY));
    60    ASSERT_THAT(
    61        RetryEINTR(write)(fd.get(), std::to_string(test_value).c_str(), 1),
    62        SyscallSucceeds());
    63  
    64    auto const oom_score =
    65        ASSERT_NO_ERRNO_AND_VALUE(ReadProcNumber("/proc/self/oom_score_adj"));
    66    EXPECT_EQ(oom_score, test_value);
    67  }
    68  
    69  }  // namespace
    70  
    71  }  // namespace testing
    72  }  // namespace gvisor