github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/syscalls/linux/creat.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 <sys/stat.h>
    17  #include <sys/types.h>
    18  
    19  #include <string>
    20  
    21  #include "gtest/gtest.h"
    22  #include "test/util/fs_util.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  constexpr int kMode = 0666;
    32  
    33  TEST(CreatTest, CreatCreatesNewFile) {
    34    std::string const path = NewTempAbsPath();
    35    struct stat buf;
    36    int fd;
    37    ASSERT_THAT(stat(path.c_str(), &buf), SyscallFailsWithErrno(ENOENT));
    38    ASSERT_THAT(fd = creat(path.c_str(), kMode), SyscallSucceeds());
    39    EXPECT_THAT(close(fd), SyscallSucceeds());
    40    EXPECT_THAT(stat(path.c_str(), &buf), SyscallSucceeds());
    41  }
    42  
    43  TEST(CreatTest, CreatTruncatesExistingFile) {
    44    auto temp_path = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
    45    int fd;
    46    ASSERT_NO_ERRNO(SetContents(temp_path.path(), "non-empty"));
    47    ASSERT_THAT(fd = creat(temp_path.path().c_str(), kMode), SyscallSucceeds());
    48    EXPECT_THAT(close(fd), SyscallSucceeds());
    49    std::string new_contents;
    50    ASSERT_NO_ERRNO(GetContents(temp_path.path(), &new_contents));
    51    EXPECT_EQ("", new_contents);
    52  }
    53  
    54  TEST(CreatTest, CreatWithNameTooLong) {
    55    // Start with a unique name, and pad it to NAME_MAX + 1;
    56    std::string name = NewTempRelPath();
    57    int padding = (NAME_MAX + 1) - name.size();
    58    name.append(padding, 'x');
    59    const std::string& path = JoinPath(GetAbsoluteTestTmpdir(), name);
    60  
    61    // Creation should return ENAMETOOLONG.
    62    ASSERT_THAT(creat(path.c_str(), kMode), SyscallFailsWithErrno(ENAMETOOLONG));
    63  }
    64  
    65  }  // namespace
    66  
    67  }  // namespace testing
    68  }  // namespace gvisor