1 /* 2 * Copyright (c) 2024 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 #include "hilog_collector.h" 16 #include <iostream> 17 #include <unistd.h> 18 #include <gtest/gtest.h> 19 #include "hiview_logger.h" 20 21 using namespace testing::ext; 22 using namespace OHOS::HiviewDFX; 23 using namespace OHOS::HiviewDFX::UCollectUtil; 24 using namespace OHOS::HiviewDFX::UCollect; 25 26 namespace { 27 DEFINE_LOG_TAG("HilogCollectorTest"); 28 const std::string TEST_STR = "HilogCollectorTest"; 29 constexpr uint32_t HILOG_LINE_NUM = 100; 30 constexpr uint32_t SLEEP_TIME = 300 * 1000; // 300ms 31 constexpr uint32_t LOG_SLEEP_TIME = 1000; // 1ms 32 } 33 34 class HilogCollectorTest : public testing::Test { 35 public: SetUp()36 void SetUp() {}; TearDown()37 void TearDown() {}; SetUpTestCase()38 static void SetUpTestCase() {}; TearDownTestCase()39 static void TearDownTestCase() {}; 40 }; 41 42 /** 43 * @tc.name: HilogCollectorTest001 44 * @tc.desc: write hilog, collect hilog success 45 * @tc.type: FUNC 46 */ 47 HWTEST_F(HilogCollectorTest, HilogCollectorTest001, TestSize.Level1) 48 { 49 int childPid = fork(); 50 if (childPid < 0) { 51 HIVIEW_LOGE("fork fail"); 52 return; 53 } 54 55 if (childPid == 0) { 56 // clear hilog buffer at first 57 execl("/system/bin/hilog", "hilog", "-r", nullptr); 58 _exit(EXIT_SUCCESS); 59 } else { 60 usleep(SLEEP_TIME); 61 for (uint32_t idx = 0; idx < HILOG_LINE_NUM; idx++) { 62 HIVIEW_LOGE("%{public}s", TEST_STR.c_str()); 63 usleep(LOG_SLEEP_TIME); 64 } 65 66 // get current process log 67 usleep(SLEEP_TIME); 68 std::shared_ptr<HilogCollector> collector = HilogCollector::Create(); 69 pid_t pid = getpid(); 70 CollectResult<std::string> result = collector->CollectLastLog(pid, HILOG_LINE_NUM); 71 ASSERT_TRUE(result.retCode == UcError::SUCCESS); 72 ASSERT_TRUE(result.data.find(TEST_STR) != std::string::npos); 73 int lineNum = std::count(result.data.begin(), result.data.end(), '\n'); 74 std::cout << "line num :" << lineNum << std::endl; 75 ASSERT_TRUE(lineNum >= HILOG_LINE_NUM); 76 77 // get child process log 78 result = collector->CollectLastLog(childPid, HILOG_LINE_NUM); 79 ASSERT_TRUE(result.retCode == UcError::SUCCESS); 80 ASSERT_TRUE(result.data == ""); 81 } 82 } 83