github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/syscalls/linux/fsync.cc (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  #include <fcntl.h>
    16  #include <stdio.h>
    17  #include <unistd.h>
    18  
    19  #include <string>
    20  
    21  #include "gtest/gtest.h"
    22  #include "test/util/file_descriptor.h"
    23  #include "test/util/temp_path.h"
    24  #include "test/util/test_util.h"
    25  
    26  namespace gvisor {
    27  namespace testing {
    28  
    29  namespace {
    30  
    31  TEST(FsyncTest, TempFileSucceeds) {
    32    auto file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
    33    auto fd = ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR, 0666));
    34    const std::string data = "some data to sync";
    35    EXPECT_THAT(write(fd.get(), data.c_str(), data.size()),
    36                SyscallSucceedsWithValue(data.size()));
    37    EXPECT_THAT(fsync(fd.get()), SyscallSucceeds());
    38  }
    39  
    40  TEST(FsyncTest, TempDirSucceeds) {
    41    auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());
    42    auto fd = ASSERT_NO_ERRNO_AND_VALUE(Open(dir.path(), O_RDONLY | O_DIRECTORY));
    43    EXPECT_THAT(fsync(fd.get()), SyscallSucceeds());
    44  }
    45  
    46  TEST(FsyncTest, CannotFsyncOnUnopenedFd) {
    47    auto file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
    48    int fd;
    49    ASSERT_THAT(fd = open(file.path().c_str(), O_RDONLY), SyscallSucceeds());
    50    ASSERT_THAT(close(fd), SyscallSucceeds());
    51  
    52    // fd is now invalid.
    53    EXPECT_THAT(fsync(fd), SyscallFailsWithErrno(EBADF));
    54  }
    55  }  // namespace
    56  
    57  }  // namespace testing
    58  }  // namespace gvisor