github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/syscalls/linux/file_base.h (about) 1 // Copyright 2018 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 #ifndef GVISOR_TEST_SYSCALLS_FILE_BASE_H_ 16 #define GVISOR_TEST_SYSCALLS_FILE_BASE_H_ 17 18 #include <arpa/inet.h> 19 #include <errno.h> 20 #include <fcntl.h> 21 #include <netinet/in.h> 22 #include <stddef.h> 23 #include <stdio.h> 24 #include <string.h> 25 #include <sys/socket.h> 26 #include <sys/stat.h> 27 #include <sys/types.h> 28 #include <sys/uio.h> 29 #include <unistd.h> 30 31 #include <cstring> 32 #include <string> 33 34 #include "gmock/gmock.h" 35 #include "gtest/gtest.h" 36 #include "absl/strings/string_view.h" 37 #include "test/util/file_descriptor.h" 38 #include "test/util/posix_error.h" 39 #include "test/util/temp_path.h" 40 #include "test/util/test_util.h" 41 42 namespace gvisor { 43 namespace testing { 44 45 class FileTest : public ::testing::Test { 46 public: 47 void SetUp() override { 48 test_pipe_[0] = -1; 49 test_pipe_[1] = -1; 50 51 test_file_name_ = NewTempAbsPath(); 52 test_file_fd_ = ASSERT_NO_ERRNO_AND_VALUE( 53 Open(test_file_name_, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)); 54 55 ASSERT_THAT(pipe(test_pipe_), SyscallSucceeds()); 56 ASSERT_THAT(fcntl(test_pipe_[0], F_SETFL, O_NONBLOCK), SyscallSucceeds()); 57 } 58 59 // CloseFile will allow the test to manually close the file descriptor. 60 void CloseFile() { test_file_fd_.reset(); } 61 62 // UnlinkFile will allow the test to manually unlink the file. 63 void UnlinkFile() { 64 if (!test_file_name_.empty()) { 65 EXPECT_THAT(unlink(test_file_name_.c_str()), SyscallSucceeds()); 66 test_file_name_.clear(); 67 } 68 } 69 70 // ClosePipes will allow the test to manually close the pipes. 71 void ClosePipes() { 72 if (test_pipe_[0] > 0) { 73 EXPECT_THAT(close(test_pipe_[0]), SyscallSucceeds()); 74 } 75 76 if (test_pipe_[1] > 0) { 77 EXPECT_THAT(close(test_pipe_[1]), SyscallSucceeds()); 78 } 79 80 test_pipe_[0] = -1; 81 test_pipe_[1] = -1; 82 } 83 84 void TearDown() override { 85 CloseFile(); 86 UnlinkFile(); 87 ClosePipes(); 88 } 89 90 protected: 91 std::string test_file_name_; 92 FileDescriptor test_file_fd_; 93 94 int test_pipe_[2]; 95 }; 96 97 } // namespace testing 98 } // namespace gvisor 99 100 #endif // GVISOR_TEST_SYSCALLS_FILE_BASE_H_