1 /* 2 * Copyright (c) 2021 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 <cerrno> 17 #include <cstring> 18 #include <fcntl.h> 19 #include <sys/statvfs.h> 20 21 #include "init_file.h" 22 #include "init_service_file.h" 23 #include "param_stub.h" 24 #include "securec.h" 25 26 using namespace testing::ext; 27 using namespace std; 28 29 namespace init_ut { 30 class ServiceFileUnitTest : public testing::Test { 31 public: SetUpTestCase(void)32 static void SetUpTestCase(void) {}; TearDownTestCase(void)33 static void TearDownTestCase(void) {}; SetUp()34 void SetUp() {}; TearDown()35 void TearDown() {}; 36 }; 37 38 HWTEST_F(ServiceFileUnitTest, TestServiceFile, TestSize.Level1) 39 { 40 const char *fileName = "/data/filetest"; 41 ServiceFile *fileOpt = (ServiceFile *)calloc(1, sizeof(ServiceFile) + strlen(fileName) + 1); 42 ASSERT_NE(fileOpt, nullptr); 43 fileOpt->next = nullptr; 44 fileOpt->flags = O_RDWR; 45 fileOpt->uid = 1000; 46 fileOpt->gid = 1000; 47 fileOpt->fd = -1; 48 fileOpt->perm = 0770; 49 if (strncpy_s(fileOpt->fileName, strlen(fileName) + 1, fileName, strlen(fileName)) != 0) { 50 free(fileOpt); 51 fileOpt = nullptr; 52 FAIL(); 53 } 54 CreateServiceFile(fileOpt); 55 int ret = GetControlFile("/data/filetest"); 56 EXPECT_NE(ret, -1); 57 if (strncpy_s(fileOpt->fileName, strlen(fileName) + 1, "fileName", strlen("fileName")) != 0) { 58 free(fileOpt); 59 fileOpt = nullptr; 60 FAIL(); 61 } 62 fileOpt->fd = 100; // 100 is fd 63 CreateServiceFile(fileOpt); 64 CloseServiceFile(fileOpt); 65 if (strncpy_s(fileOpt->fileName, strlen(fileName) + 1, "/dev/filetest", strlen("/dev/filetest")) != 0) { 66 free(fileOpt); 67 fileOpt = nullptr; 68 FAIL(); 69 } 70 char *wrongName = (char *)malloc(PATH_MAX); 71 ASSERT_NE(wrongName, nullptr); 72 EXPECT_EQ(memset_s(wrongName, PATH_MAX, 1, PATH_MAX), 0); 73 ret = GetControlFile(wrongName); 74 EXPECT_NE(ret, 0); 75 GetControlFile("notExist"); 76 GetControlFile(nullptr); 77 EXPECT_EQ(setenv("OHOS_FILE_ENV_PREFIX_testPath", "5", 0), 0); 78 GetControlFile("testPath"); 79 EXPECT_EQ(setenv("OHOS_FILE_ENV_PREFIX_testPath1", "aaaaaaaa", 0), 0); 80 GetControlFile("testPath1"); 81 82 fileOpt->fd = -1; 83 CreateServiceFile(fileOpt); 84 CloseServiceFile(fileOpt); 85 free(fileOpt); 86 free(wrongName); 87 fileOpt = nullptr; 88 wrongName = nullptr; 89 } 90 } 91