1 /* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 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 16 #include <gtest/gtest.h> 17 #include <fcntl.h> 18 #include "smart_fd.h" 19 20 using namespace testing::ext; 21 22 namespace OHOS { 23 namespace HiviewDFX { 24 /** 25 * @tc.name: SmartFdTest001 26 * @tc.desc: test invalid. 27 * @tc.type: FUNC 28 */ 29 HWTEST(SmartFdTest, SmartFdTest001, TestSize.Level0) 30 { 31 SmartFd fd; 32 ASSERT_FALSE(fd); 33 ASSERT_LT(fd.GetFd(), 0); 34 35 SmartFd fd1{-1}; 36 ASSERT_FALSE(fd1); 37 ASSERT_LT(fd1.GetFd(), 0); 38 } 39 40 /** 41 * @tc.name: SmartFdTest002 42 * @tc.desc: test valid. 43 * @tc.type: FUNC 44 */ 45 HWTEST(SmartFdTest, SmartFdTest002, TestSize.Level0) 46 { 47 SmartFd fd(open("/dev/null", O_WRONLY)); 48 ASSERT_TRUE(fd); 49 ASSERT_GT(fd.GetFd(), 0); 50 51 fd.Reset(); 52 ASSERT_FALSE(fd); 53 ASSERT_LT(fd.GetFd(), 0); 54 55 SmartFd fd1(open("/dev/null", O_WRONLY), false); 56 ASSERT_TRUE(fd1); 57 ASSERT_GT(fd1.GetFd(), 0); 58 } 59 60 /** 61 * @tc.name: SmartFdTest003 62 * @tc.desc: test move construct. 63 * @tc.type: FUNC 64 */ 65 HWTEST(SmartFdTest, SmartFdTest003, TestSize.Level0) 66 { 67 SmartFd fd(open("/dev/null", O_WRONLY)); 68 ASSERT_TRUE(fd); 69 70 SmartFd fd1(std::move(fd)); 71 ASSERT_TRUE(fd1); 72 ASSERT_FALSE(fd); 73 } 74 75 /** 76 * @tc.name: SmartFdTest004 77 * @tc.desc: test move assign. 78 * @tc.type: FUNC 79 */ 80 HWTEST(SmartFdTest, SmartFdTest004, TestSize.Level0) 81 { 82 SmartFd fd(open("/dev/null", O_WRONLY)); 83 ASSERT_TRUE(fd); 84 85 SmartFd fd1; 86 ASSERT_FALSE(fd1); 87 88 fd1 = std::move(fd); 89 ASSERT_TRUE(fd1); 90 ASSERT_FALSE(fd); 91 92 SmartFd fd2(open("/dev/null", O_WRONLY), false); 93 ASSERT_TRUE(fd2); 94 95 fd1 = std::move(fd2); 96 ASSERT_TRUE(fd1); 97 ASSERT_FALSE(fd2); 98 } 99 100 /** 101 * @tc.name: SmartFdTest005 102 * @tc.desc: test close. 103 * @tc.type: FUNC 104 */ 105 HWTEST(SmartFdTest, SmartFdTest005, TestSize.Level2) 106 { 107 SmartFd fd(open("/dev/null", O_WRONLY)); 108 ASSERT_TRUE(fd); 109 int handle = fd.GetFd(); 110 { 111 SmartFd {std::move(fd)}; 112 ASSERT_FALSE(fd); 113 } 114 // double close 115 ASSERT_LT(close(handle), 0); 116 117 SmartFd fd1(open("/dev/null", O_WRONLY)); 118 { 119 SmartFd tmp; 120 tmp = std::move(fd1); 121 ASSERT_TRUE(tmp); 122 handle = tmp.GetFd(); 123 } 124 // double close 125 ASSERT_LT(close(handle), 0); 126 } 127 128 } // namespace HiviewDFX 129 } // namespace OHOS