1/*
2 * Copyright (c) 2021-2023 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 <string>
16#include <vector>
17
18#include <fcntl.h>
19#include <fstream>
20#include <gtest/gtest.h>
21#include <regex>
22#include "sys_event.h"
23#include <sys/stat.h>
24#include <sys/types.h>
25#include <sys/inotify.h>
26#include <sys/ioctl.h>
27#include <unistd.h>
28
29#include "bundle_mgr_client.h"
30#include "event.h"
31#include "faultlog_util.h"
32#include "faultlog_database.h"
33#include "faultlogger.h"
34#include "faultevent_listener.h"
35#include "faultlog_formatter.h"
36#include "faultlog_info_ohos.h"
37#include "faultlog_query_result_ohos.h"
38#include "faultlogger_adapter.h"
39#include "faultlogger_service_ohos.h"
40#include "file_util.h"
41#include "hisysevent_manager.h"
42#include "hiview_global.h"
43#include "hiview_platform.h"
44#include "ipc_skeleton.h"
45#include "json/json.h"
46#include "log_analyzer.h"
47#include "sys_event.h"
48#include "sys_event_dao.h"
49#include "zip_helper.h"
50
51using namespace testing::ext;
52using namespace OHOS::HiviewDFX;
53namespace OHOS {
54namespace HiviewDFX {
55static std::shared_ptr<FaultEventListener> faultEventListener = nullptr;
56static std::unordered_map<std::string, std::string> g_stacks;
57static std::map<int, std::string> fileNames_ = {};
58
59static HiviewContext& InitHiviewContext()
60{
61    OHOS::HiviewDFX::HiviewPlatform &platform = HiviewPlatform::GetInstance();
62    bool result = platform.InitEnvironment("/data/test/test_faultlogger_data/hiview_platform_config");
63    printf("InitHiviewContext result:%d\n", result);
64    return platform;
65}
66
67static HiviewContext& GetHiviewContext()
68{
69    static HiviewContext& hiviewContext = InitHiviewContext();
70    return hiviewContext;
71}
72
73static void StartHisyseventListen(std::string domain, std::string eventName)
74{
75    faultEventListener = std::make_shared<FaultEventListener>();
76    ListenerRule tagRule(domain, eventName, RuleType::WHOLE_WORD);
77    std::vector<ListenerRule> sysRules = {tagRule};
78    HiSysEventManager::AddListener(faultEventListener, sysRules);
79}
80
81static std::shared_ptr<Faultlogger> InitFaultloggerInstance()
82{
83    auto plugin = std::make_shared<Faultlogger>();
84    plugin->SetName("Faultlogger");
85    plugin->SetHandle(nullptr);
86    plugin->SetHiviewContext(&GetHiviewContext());
87    plugin->OnLoad();
88    return plugin;
89}
90
91static std::shared_ptr<Faultlogger> GetFaultloggerInstance()
92{
93    static std::shared_ptr<Faultlogger> faultloggerInstance = InitFaultloggerInstance();
94    return faultloggerInstance;
95}
96
97namespace {
98auto g_fdDeleter = [] (int32_t *ptr) {
99    if (*ptr > 0) {
100        close(*ptr);
101    }
102    delete ptr;
103};
104}
105
106class FaultloggerUnittest : public testing::Test {
107public:
108    void SetUp()
109    {
110        sleep(1);
111        GetHiviewContext();
112    };
113    void TearDown() {};
114
115    static void CheckSumarryParseResult(std::string& info, int& matchCount)
116    {
117        Json::Reader reader;
118        Json::Value appEvent;
119        if (!(reader.parse(info, appEvent))) {
120            matchCount--;
121        }
122        auto exception = appEvent["exception"];
123        GTEST_LOG_(INFO) << "========name:" << exception["name"];
124        if (exception["name"] == "" || exception["name"] == "none") {
125            matchCount--;
126        }
127        GTEST_LOG_(INFO) << "========message:" << exception["message"];
128        if (exception["message"] == "" || exception["message"] == "none") {
129            matchCount--;
130        }
131        GTEST_LOG_(INFO) << "========stack:" << exception["stack"];
132        if (exception["stack"] == "" || exception["stack"] == "none") {
133            matchCount--;
134        }
135    }
136
137    static int CheckKeyWordsInFile(const std::string& filePath, std::string *keywords, int length, bool isJsError)
138    {
139        std::ifstream file;
140        file.open(filePath.c_str(), std::ios::in);
141        std::ostringstream infoStream;
142        infoStream << file.rdbuf();
143        std::string info = infoStream.str();
144        if (info.length() == 0) {
145            std::cout << "file is empty, file:" << filePath << std::endl;
146            return 0;
147        }
148        int matchCount = 0;
149        for (int index = 0; index < length; index++) {
150            if (info.find(keywords[index]) != std::string::npos) {
151                matchCount++;
152            } else {
153                std::cout << "can not find keyword:" << keywords[index] << std::endl;
154            }
155        }
156        if (isJsError) {
157            CheckSumarryParseResult(info, matchCount);
158        }
159        file.close();
160        return matchCount;
161    }
162
163    static void ConstructJsErrorAppEvent(std::string summmay, std::shared_ptr<Faultlogger> plugin)
164    {
165        SysEventCreator sysEventCreator("AAFWK", "JSERROR", SysEventCreator::FAULT);
166        sysEventCreator.SetKeyValue("SUMMARY", summmay);
167        sysEventCreator.SetKeyValue("name_", "JS_ERROR");
168        sysEventCreator.SetKeyValue("happenTime_", 1670248360359); // 1670248360359 : Simulate happenTime_ value
169        sysEventCreator.SetKeyValue("REASON", "TypeError");
170        sysEventCreator.SetKeyValue("tz_", "+0800");
171        sysEventCreator.SetKeyValue("pid_", 2413); // 2413 : Simulate pid_ value
172        sysEventCreator.SetKeyValue("tid_", 2413); // 2413 : Simulate tid_ value
173        sysEventCreator.SetKeyValue("what_", 3); // 3 : Simulate what_ value
174        sysEventCreator.SetKeyValue("PACKAGE_NAME", "com.ohos.systemui");
175        sysEventCreator.SetKeyValue("VERSION", "1.0.0");
176        sysEventCreator.SetKeyValue("TYPE", 3); // 3 : Simulate TYPE value
177        sysEventCreator.SetKeyValue("VERSION", "1.0.0");
178
179        auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
180        std::shared_ptr<Event> event = std::dynamic_pointer_cast<Event>(sysEvent);
181        bool result = plugin->OnEvent(event);
182        ASSERT_EQ(result, true);
183    }
184
185    static void ConstructJsErrorAppEventWithNoValue(std::string summmay, std::shared_ptr<Faultlogger> plugin)
186    {
187        SysEventCreator sysEventCreator("AAFWK", "JSERROR", SysEventCreator::FAULT);
188        sysEventCreator.SetKeyValue("SUMMARY", summmay);
189        sysEventCreator.SetKeyValue("name_", "JS_ERROR");
190        sysEventCreator.SetKeyValue("happenTime_", 1670248360359); // 1670248360359 : Simulate happenTime_ value
191        sysEventCreator.SetKeyValue("TYPE", 3); // 3 : Simulate TYPE value
192        sysEventCreator.SetKeyValue("VERSION", "1.0.0");
193
194        auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
195        std::shared_ptr<Event> event = std::dynamic_pointer_cast<Event>(sysEvent);
196        bool result = plugin->OnEvent(event);
197        ASSERT_EQ(result, true);
198    }
199
200    static void CheckKeyWordsInJsErrorAppEventFile(std::string name)
201    {
202        std::string keywords[] = {
203            "\"bundle_name\":", "\"bundle_version\":", "\"crash_type\":", "\"exception\":",
204            "\"foreground\":", "\"hilog\":", "\"pid\":", "\"time\":", "\"uid\":", "\"uuid\":",
205            "\"name\":", "\"message\":", "\"stack\":"
206        };
207        int length = sizeof(keywords) / sizeof(keywords[0]);
208        std::cout << "length:" << length << std::endl;
209        std::string oldFileName = "/data/test_jsError_info";
210        int count = CheckKeyWordsInFile(oldFileName, keywords, length, true);
211        std::cout << "count:" << count << std::endl;
212        ASSERT_EQ(count, length) << "ReportJsErrorToAppEventTest001-" + name + " check keywords failed";
213        if (FileUtil::FileExists(oldFileName)) {
214            std::string newFileName = oldFileName + "_" + name;
215            rename(oldFileName.c_str(), newFileName.c_str());
216        }
217        auto ret = remove("/data/test_jsError_info");
218        if (ret == 0) {
219            GTEST_LOG_(INFO) << "remove /data/test_jsError_info failed";
220        }
221    }
222
223    static void CheckDeleteStackErrorMessage(std::string name)
224    {
225        std::string keywords[] = {"\"Cannot get SourceMap info, dump raw stack:"};
226        int length = sizeof(keywords) / sizeof(keywords[0]);
227        std::cout << "========length:" << length << std::endl;
228        std::string oldFileName = "/data/test_jsError_info";
229        int count = CheckKeyWordsInFile(oldFileName, keywords, length, true);
230        std::cout << "========count:" << count << std::endl;
231        ASSERT_NE(count, length) << "check delete stack error message failed";
232    }
233};
234
235/**
236 * @tc.name: dumpFileListTest001
237 * @tc.desc: dump with cmds, check the result
238 * @tc.type: FUNC
239 */
240HWTEST_F(FaultloggerUnittest, dumpFileListTest001, testing::ext::TestSize.Level3)
241{
242    /**
243     * @tc.steps: step1. add multiple cmds to faultlogger
244     * @tc.expected: check the content size of the dump function
245     */
246    auto plugin = GetFaultloggerInstance();
247    int fd = TEMP_FAILURE_RETRY(open("/data/test/testFile", O_CREAT | O_WRONLY | O_TRUNC, 770));
248    bool isSuccess = fd >= 0;
249    if (!isSuccess) {
250        ASSERT_FALSE(isSuccess);
251        printf("Fail to create test result file.\n");
252        return;
253    }
254    std::vector<std::string> cmds;
255    plugin->Dump(fd, cmds);
256    cmds.push_back("Faultlogger");
257    plugin->Dump(fd, cmds);
258    cmds.push_back("-l");
259    plugin->Dump(fd, cmds);
260    cmds.push_back("-f");
261    plugin->Dump(fd, cmds);
262    cmds.push_back("cppcrash-ModuleName-10-20201209103823");
263    plugin->Dump(fd, cmds);
264    cmds.push_back("-d");
265    plugin->Dump(fd, cmds);
266    cmds.push_back("-t");
267    plugin->Dump(fd, cmds);
268    cmds.push_back("20201209103823");
269    plugin->Dump(fd, cmds);
270    cmds.push_back("-m");
271    plugin->Dump(fd, cmds);
272    cmds.push_back("FAULTLOGGER");
273    close(fd);
274    fd = -1;
275
276    std::string result;
277    if (FileUtil::LoadStringFromFile("/data/test/testFile", result)) {
278        ASSERT_GT(result.length(), 0uL);
279    } else {
280        FAIL();
281    }
282}
283
284/**
285 * @tc.name: DumpTest002
286 * @tc.desc: dump with cmds, check the result
287 * @tc.type: FUNC
288 */
289HWTEST_F(FaultloggerUnittest, DumpTest002, testing::ext::TestSize.Level3)
290{
291    /**
292     * @tc.steps: step1. add multiple cmds to faultlogger
293     * @tc.expected: check the content size of the dump function
294     */
295    auto plugin = GetFaultloggerInstance();
296    int fd = TEMP_FAILURE_RETRY(open("/data/test/testFile", O_CREAT | O_WRONLY | O_TRUNC, 770));
297    bool isSuccess = fd >= 0;
298    if (!isSuccess) {
299        ASSERT_FALSE(isSuccess);
300        printf("Fail to create test result file.\n");
301        return;
302    }
303    std::vector<std::vector<std::string>> cmds = {
304        {"-f", "1cppcrash-10-20201209103823"},
305        {"-f", "1cppcrash-ModuleName-10-20201209103823"},
306        {"-f", "cppcrash--10-20201209103823"},
307        {"-f", "cppcrash-ModuleName-a10-20201209103823"}
308    };
309
310    for (auto& cmd : cmds) {
311        plugin->Dump(fd, cmd);
312    }
313
314    close(fd);
315    fd = -1;
316
317    std::string result;
318    if (FileUtil::LoadStringFromFile("/data/test/testFile", result)) {
319        ASSERT_GT(result.length(), 0uL);
320    } else {
321        FAIL();
322    }
323}
324
325/**
326 * @tc.name: DumpTest003
327 * @tc.desc: dump with cmds, check the result
328 * @tc.type: FUNC
329 */
330HWTEST_F(FaultloggerUnittest, DumpTest003, testing::ext::TestSize.Level3)
331{
332    /**
333     * @tc.steps: step1. add multiple cmds to faultlogger
334     * @tc.expected: check the content size of the dump function
335     */
336    auto plugin = GetFaultloggerInstance();
337    int fd = TEMP_FAILURE_RETRY(open("/data/test/testFile", O_CREAT | O_WRONLY | O_TRUNC, 770));
338    bool isSuccess = fd >= 0;
339    if (!isSuccess) {
340        ASSERT_FALSE(isSuccess);
341        printf("Fail to create test result file.\n");
342        return;
343    }
344    std::vector<std::vector<std::string>> cmds = {
345        {"-t", "cppcrash--10-20201209103823"},
346        {"-m", ""},
347        {"-l", ""},
348        {"-xx"}
349    };
350
351    for (auto& cmd : cmds) {
352        plugin->Dump(fd, cmd);
353    }
354
355    close(fd);
356    fd = -1;
357
358    std::string result;
359    if (FileUtil::LoadStringFromFile("/data/test/testFile", result)) {
360        ASSERT_GT(result.length(), 0uL);
361    } else {
362        FAIL();
363    }
364}
365
366static void GenCppCrashLogTestCommon(int32_t uid, bool ifFileExist)
367{
368    int pipeFd[2] = {-1, -1};
369    ASSERT_EQ(pipe(pipeFd), 0) << "create pipe failed";
370    auto plugin = GetFaultloggerInstance();
371    FaultLogInfo info;
372    info.time = 1607161163; // 1607161163 : analog value of time
373    info.id = uid;
374    info.pid = 7496; // 7496 : analog value of pid
375    info.faultLogType = 2; // 2 : CPP_CRASH
376    info.module = "com.example.myapplication";
377    info.sectionMap["APPVERSION"] = "1.0";
378    info.sectionMap["FAULT_MESSAGE"] = "Nullpointer";
379    info.sectionMap["TRACEID"] = "0x1646145645646";
380    info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
381    info.sectionMap["REASON"] = "TestReason";
382    info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
383    info.pipeFd.reset(new int32_t(pipeFd[0]), g_fdDeleter);
384    std::string jsonInfo = R"~({"crash_type":"NativeCrash", "exception":{"frames":
385        [{"buildId":"", "file":"/system/lib/ld-musl-arm.so.1", "offset":28, "pc":"000ac0a4", "symbol":"test_abc"},
386        {"buildId":"12345abcde", "file":"/system/lib/chipset-pub-sdk/libeventhandler.z.so", "offset":278,
387        "pc":"0000bef3", "symbol":"OHOS::AppExecFwk::EpollIoWaiter::WaitFor(std::__h::unique_lock<std::__h::mutex>&,
388        long long)"}], "message":"", "signal":{"code":0, "signo":6}, "thread_name":"e.myapplication", "tid":1605},
389        "pid":1605, "threads":[{"frames":[{"buildId":"", "file":"/system/lib/ld-musl-arm.so.1", "offset":72, "pc":
390        "000c80b4", "symbol":"ioctl"}, {"buildId":"2349d05884359058d3009e1fe27b15fa", "file":
391        "/system/lib/platformsdk/libipc_core.z.so", "offset":26, "pc":"0002cad7",
392        "symbol":"OHOS::BinderConnector::WriteBinder(unsigned long, void*)"}], "thread_name":"OS_IPC_0_1607",
393        "tid":1607}, {"frames":[{"buildId":"", "file":"/system/lib/ld-musl-arm.so.1", "offset":0, "pc":"000fdf4c",
394        "symbol":""}, {"buildId":"", "file":"/system/lib/ld-musl-arm.so.1", "offset":628, "pc":"000ff7f4",
395        "symbol":"__pthread_cond_timedwait_time64"}], "thread_name":"OS_SignalHandle", "tid":1608}],
396        "time":1701863741296, "uid":20010043, "uuid":""})~";
397    TEMP_FAILURE_RETRY(write(pipeFd[1], jsonInfo.c_str(), jsonInfo.size()));
398    close(pipeFd[1]);
399    plugin->AddFaultLog(info);
400    std::string timeStr = GetFormatedTime(info.time);
401    std::string appName = GetApplicationNameById(info.id);
402    if (appName.size() == 0) {
403        appName = info.module;
404    }
405    std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-" + appName + "-" +
406        std::to_string(info.id) + "-" + timeStr;
407    ASSERT_EQ(FileUtil::FileExists(fileName), true);
408    ASSERT_GT(FileUtil::GetFileSize(fileName), 0ul);
409    auto parsedInfo = plugin->GetFaultLogInfo(fileName);
410    ASSERT_EQ(parsedInfo->module, appName);
411    // check appevent json info
412    ASSERT_EQ(FileUtil::FileExists("/data/test_cppcrash_info_7496"), ifFileExist);
413}
414
415/**
416 * @tc.name: genCppCrashLogTest001
417 * @tc.desc: create cpp crash event and send it to faultlogger
418 *           check info which send to appevent
419 * @tc.type: FUNC
420 */
421HWTEST_F(FaultloggerUnittest, GenCppCrashLogTest001, testing::ext::TestSize.Level3)
422{
423    GenCppCrashLogTestCommon(10001, true); // 10001 : analog value of user uid
424    string keywords[] = { "\"time\":", "\"pid\":", "\"exception\":", "\"threads\":", "\"thread_name\":", "\"tid\":" };
425    int length = sizeof(keywords) / sizeof(keywords[0]);
426    ASSERT_EQ(CheckKeyWordsInFile("/data/test_cppcrash_info_7496", keywords, length, false), length);
427    auto ret = remove("/data/test_cppcrash_info_7496");
428    if (ret == 0) {
429        GTEST_LOG_(INFO) << "remove /data/test_jsError_info failed";
430    }
431}
432
433/**
434 * @tc.name: genCppCrashLogTest002
435 * @tc.desc: create cpp crash event and send it to faultlogger
436 *           check info which send to appevent
437 * @tc.type: FUNC
438 */
439HWTEST_F(FaultloggerUnittest, GenCppCrashLogTest002, testing::ext::TestSize.Level3)
440{
441    GenCppCrashLogTestCommon(0, false); // 0 : analog value of system uid
442}
443
444/**
445 * @tc.name: AddFaultLogTest001
446 * @tc.desc: create cpp crash event and send it to faultlogger
447 *           check info which send to appevent
448 * @tc.type: FUNC
449 */
450HWTEST_F(FaultloggerUnittest, AddFaultLogTest001, testing::ext::TestSize.Level3)
451{
452    auto plugin = GetFaultloggerInstance();
453    FaultLogInfo info;
454    plugin->hasInit_ = false;
455    plugin->AddFaultLog(info);
456
457    plugin->hasInit_ = true;
458    info.faultLogType = -1;
459    plugin->AddFaultLog(info);
460
461    info.faultLogType = 8; // 8 : 8 is bigger than FaultLogType::ADDR_SANITIZER
462    plugin->AddFaultLog(info);
463
464    info.faultLogType = FaultLogType::CPP_CRASH;
465    info.id = 1;
466    info.module = "com.example.myapplication";
467    info.time = 1607161163;
468    info.pid = 7496;
469    plugin->AddFaultLog(info);
470    std::string timeStr = GetFormatedTime(info.time);
471    std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-com.example.myapplication-0-" + timeStr;
472    ASSERT_EQ(FileUtil::FileExists(fileName), true);
473}
474
475/**
476 * @tc.name: AddPublicInfoTest001
477 * @tc.desc: create cpp crash event and send it to faultlogger
478 *           check info which send to appevent
479 * @tc.type: FUNC
480 */
481HWTEST_F(FaultloggerUnittest, AddPublicInfoTest001, testing::ext::TestSize.Level3)
482{
483    auto plugin = GetFaultloggerInstance();
484    FaultLogInfo info;
485    info.time = 1607161163;
486    info.id = 0;
487    info.pid = 7496;
488    info.faultLogType = 1;
489    info.module = "com.example.myapplication";
490    info.sectionMap["APPVERSION"] = "1.0";
491    info.sectionMap["FAULT_MESSAGE"] = "Nullpointer";
492    info.sectionMap["TRACEID"] = "0x1646145645646";
493    info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
494    info.sectionMap["REASON"] = "TestReason";
495    info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
496    plugin->AddPublicInfo(info);
497    std::string timeStr = GetFormatedTime(info.time);
498    std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-com.example.myapplication-0-" + timeStr;
499    ASSERT_EQ(FileUtil::FileExists(fileName), true);
500}
501
502/**
503 * @tc.name: GetFreezeJsonCollectorTest001
504 * @tc.desc: test GetFreezeJsonCollector
505 * @tc.type: FUNC
506 */
507HWTEST_F(FaultloggerUnittest, GetFreezeJsonCollectorTest001, testing::ext::TestSize.Level3)
508{
509    auto plugin = GetFaultloggerInstance();
510    FaultLogInfo info;
511    info.time = 20170805172159;
512    info.id = 10006;
513    info.pid = 1;
514    info.faultLogType = 1;
515    info.module = "com.example.myapplication";
516    info.sectionMap["APPVERSION"] = "1.0";
517    info.sectionMap["FAULT_MESSAGE"] = "Nullpointer";
518    info.sectionMap["TRACEID"] = "0x1646145645646";
519    info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
520    info.sectionMap["REASON"] = "TestReason";
521    info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
522    FreezeJsonUtil::FreezeJsonCollector collector = plugin->GetFreezeJsonCollector(info);
523    ASSERT_EQ(collector.exception, "{}");
524}
525
526/**
527 * @tc.name: genCppCrashtoAnalysisFaultlog
528 * @tc.desc: create cpp crash event and check AnalysisFaultlog
529 * @tc.type: FUNC
530 */
531HWTEST_F(FaultloggerUnittest, genCppCrashtoAnalysisFaultlog001, testing::ext::TestSize.Level3)
532{
533    /**
534     * @tc.steps: step1. create a cpp crash event and pass it to faultlogger
535     * @tc.expected: AnalysisFaultlog return expected result
536     */
537    FaultLogInfo info;
538    info.time = 1607161163;
539    info.id = 0;
540    info.pid = 7497;
541    info.faultLogType = 2;
542    info.module = "com.example.testapplication";
543    info.reason = "TestReason";
544    std::map<std::string, std::string> eventInfos;
545    ASSERT_EQ(AnalysisFaultlog(info, eventInfos), false);
546    ASSERT_EQ(!eventInfos["fingerPrint"].empty(), true);
547}
548
549/**
550 * @tc.name: genJsCrashtoAnalysisFaultlog001
551 * @tc.desc: create Js crash FaultLogInfo and check AnalysisFaultlog
552 * @tc.type: FUNC
553 */
554HWTEST_F(FaultloggerUnittest, genJsCrashtoAnalysisFaultlog001, testing::ext::TestSize.Level3)
555{
556    /**
557     * @tc.steps: step1. create Js crash FaultLogInfo
558     * @tc.expected: AnalysisFaultlog return expected result
559     */
560    FaultLogInfo info;
561    info.time = 1607161163;
562    info.id = 0;
563    info.pid = 7497;
564    info.faultLogType = 3;
565    info.module = "com.example.testapplication";
566    info.reason = "TestReason";
567    std::map<std::string, std::string> eventInfos;
568    ASSERT_EQ(AnalysisFaultlog(info, eventInfos), false);
569    ASSERT_EQ(!eventInfos["fingerPrint"].empty(), true);
570}
571
572/**
573 * @tc.name: genjserrorLogTest002
574 * @tc.desc: create JS ERROR event and send it to faultlogger
575 * @tc.type: FUNC
576 */
577HWTEST_F(FaultloggerUnittest, genjserrorLogTest002, testing::ext::TestSize.Level3)
578{
579    /**
580     * @tc.steps: step1. create a jss_error event and pass it to faultlogger
581     * @tc.expected: the calling is success and the file has been created
582     */
583    SysEventCreator sysEventCreator("AAFWK", "JSERROR", SysEventCreator::FAULT);
584    sysEventCreator.SetKeyValue("SUMMARY", "Error message:is not callable\nStacktrace:");
585    sysEventCreator.SetKeyValue("name_", "JS_ERROR");
586    sysEventCreator.SetKeyValue("happenTime_", 1670248360359);
587    sysEventCreator.SetKeyValue("REASON", "TypeError");
588    sysEventCreator.SetKeyValue("tz_", "+0800");
589    sysEventCreator.SetKeyValue("pid_", 2413);
590    sysEventCreator.SetKeyValue("tid_", 2413);
591    sysEventCreator.SetKeyValue("what_", 3);
592    sysEventCreator.SetKeyValue("PACKAGE_NAME", "com.ohos.systemui");
593    sysEventCreator.SetKeyValue("VERSION", "1.0.0");
594    sysEventCreator.SetKeyValue("TYPE", 3);
595    sysEventCreator.SetKeyValue("VERSION", "1.0.0");
596
597    auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
598    auto testPlugin = GetFaultloggerInstance();
599    std::shared_ptr<Event> event = std::dynamic_pointer_cast<Event>(sysEvent);
600    bool result = testPlugin->OnEvent(event);
601    ASSERT_EQ(result, true);
602    auto ret = remove("/data/test_jsError_info");
603    if (ret == 0) {
604        GTEST_LOG_(INFO) << "remove /data/test_jsError_info failed";
605    }
606}
607
608/**
609 * @tc.name: IsInterestedPipelineEvent
610 * @tc.desc: Test calling IsInterestedPipelineEvent Func
611 * @tc.type: FUNC
612 */
613HWTEST_F(FaultloggerUnittest, IsInterestedPipelineEvent, testing::ext::TestSize.Level3)
614{
615    auto testPlugin = GetFaultloggerInstance();
616    std::shared_ptr<Event> event = std::make_shared<Event>("test");
617    event->SetEventName("PROCESS_EXIT");
618    EXPECT_TRUE(testPlugin->IsInterestedPipelineEvent(event));
619    event->SetEventName("JS_ERROR");
620    EXPECT_TRUE(testPlugin->IsInterestedPipelineEvent(event));
621    event->SetEventName("RUST_PANIC");
622    EXPECT_TRUE(testPlugin->IsInterestedPipelineEvent(event));
623    event->SetEventName("ADDR_SANITIZER");
624    EXPECT_TRUE(testPlugin->IsInterestedPipelineEvent(event));
625    event->SetEventName("OTHERS");
626    EXPECT_FALSE(testPlugin->IsInterestedPipelineEvent(event));
627};
628
629/**
630 * @tc.name: CanProcessEvent
631 * @tc.desc: Test calling CanProcessEvent Func
632 * @tc.type: FUNC
633 */
634HWTEST_F(FaultloggerUnittest, CanProcessEvent, testing::ext::TestSize.Level3)
635{
636    auto testPlugin = GetFaultloggerInstance();
637    std::shared_ptr<Event> event = std::make_shared<Event>("test");
638    ASSERT_TRUE(testPlugin->CanProcessEvent(event));
639};
640
641/**
642 * @tc.name: ReadyToLoad
643 * @tc.desc: Test calling ReadyToLoad Func
644 * @tc.type: FUNC
645 */
646HWTEST_F(FaultloggerUnittest, ReadyToLoad, testing::ext::TestSize.Level3)
647{
648    auto testPlugin = GetFaultloggerInstance();
649    ASSERT_TRUE(testPlugin->ReadyToLoad());
650};
651
652/**
653 * @tc.name: GetListenerName
654 * @tc.desc: Test calling GetListenerName Func
655 * @tc.type: FUNC
656 */
657HWTEST_F(FaultloggerUnittest, GetListenerName, testing::ext::TestSize.Level3)
658{
659    auto testPlugin = GetFaultloggerInstance();
660    ASSERT_EQ(testPlugin->GetListenerName(), "FaultLogger");
661};
662
663/**
664 * @tc.name: SaveFaultLogInfoTest001
665 * @tc.desc: Test calling SaveFaultLogInfo Func
666 * @tc.type: FUNC
667 */
668HWTEST_F(FaultloggerUnittest, SaveFaultLogInfoTest001, testing::ext::TestSize.Level3)
669{
670    StartHisyseventListen("RELIABILITY", "CPP_CRASH");
671    time_t now = std::time(nullptr);
672    std::vector<std::string> keyWords = { std::to_string(now) };
673    faultEventListener->SetKeyWords(keyWords);
674    FaultLogDatabase *faultLogDb = new FaultLogDatabase(GetHiviewContext().GetSharedWorkLoop());
675    FaultLogInfo info;
676    info.time = now;
677    info.pid = getpid();
678    info.id = 0;
679    info.faultLogType = 2;
680    info.module = "FaultloggerUnittest";
681    info.reason = "unittest for SaveFaultLogInfo";
682    info.summary = "summary for SaveFaultLogInfo";
683    info.sectionMap["APPVERSION"] = "1.0";
684    info.sectionMap["FAULT_MESSAGE"] = "abort";
685    info.sectionMap["TRACEID"] = "0x1646145645646";
686    info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
687    info.sectionMap["REASON"] = "TestReason";
688    info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
689    faultLogDb->SaveFaultLogInfo(info);
690    ASSERT_TRUE(faultEventListener->CheckKeyWords());
691}
692
693/**
694 * @tc.name: GetFaultInfoListTest001
695 * @tc.desc: Test calling GetFaultInfoList Func
696 * @tc.type: FUNC
697 */
698HWTEST_F(FaultloggerUnittest, GetFaultInfoListTest001, testing::ext::TestSize.Level3)
699{
700    std::string jsonStr = R"~({"domain_":"RELIABILITY", "name_":"CPP_CRASH", "type_":1, "time_":1501973701070, "tz_":
701    "+0800", "pid_":1854, "tid_":1854, "uid_":0, "FAULT_TYPE":"2", "PID":1854, "UID":0, "MODULE":"FaultloggerUnittest",
702    "REASON":"unittest for SaveFaultLogInfo", "SUMMARY":"summary for SaveFaultLogInfo", "LOG_PATH":"", "VERSION":"",
703    "HAPPEN_TIME":"1501973701", "PNAME":"/", "FIRST_FRAME":"/", "SECOND_FRAME":"/", "LAST_FRAME":"/", "FINGERPRINT":
704    "04c0d6f03c73da531f00eb112479a8a2f19f59fafba6a474dcbe455a13288f4d", "level_":"CRITICAL", "tag_":"STABILITY", "id_":
705    "17165544771317691984", "info_":""})~";
706    auto sysEvent = std::make_shared<SysEvent>("SysEventSource", nullptr, jsonStr);
707    sysEvent->SetLevel("MINOR");
708    sysEvent->SetEventSeq(447); // 447: test seq
709    EventStore::SysEventDao::Insert(sysEvent);
710    FaultLogDatabase *faultLogDb = new FaultLogDatabase(GetHiviewContext().GetSharedWorkLoop());
711    std::list<FaultLogInfo> infoList = faultLogDb->GetFaultInfoList("FaultloggerUnittest", 0, 2, 10);
712    ASSERT_GT(infoList.size(), 0);
713}
714
715/**
716 * @tc.name: FaultLogManager::CreateTempFaultLogFile
717 * @tc.desc: Test calling CreateTempFaultLogFile Func
718 * @tc.type: FUNC
719 */
720HWTEST_F(FaultloggerUnittest, FaultlogManager001, testing::ext::TestSize.Level3)
721{
722    std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
723    faultLogManager->Init();
724    int fd = faultLogManager->CreateTempFaultLogFile(1607161345, 0, 2, "FaultloggerUnittest");
725    ASSERT_GT(fd, 0);
726    std::string content = "testContent";
727    TEMP_FAILURE_RETRY(write(fd, content.data(), content.length()));
728    close(fd);
729}
730
731/**
732 * @tc.name: FaultLogManager::GetFaultLogFileList
733 * @tc.desc: Test calling GetFaultLogFileList Func
734 * @tc.type: FUNC
735 */
736HWTEST_F(FaultloggerUnittest, GetFaultLogFileList001, testing::ext::TestSize.Level3)
737{
738    std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
739    faultLogManager->Init();
740    std::list<std::string> fileList = faultLogManager->GetFaultLogFileList("FaultloggerUnittest", 1607161344, 0, 2, 1);
741    ASSERT_EQ(fileList.size(), 1);
742}
743
744/**
745 * @tc.name: FaultLogManager::GetFaultLogContent
746 * @tc.desc: Test calling GetFaultLogContent Func
747 * @tc.type: FUNC
748 */
749HWTEST_F(FaultloggerUnittest, GetFaultLogContent001, testing::ext::TestSize.Level3)
750{
751    std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
752    faultLogManager->Init();
753    FaultLogInfo info {
754        .time = 1607161345,
755        .id = 0,
756        .faultLogType = 2,
757        .module = "FaultloggerUnittest"
758    };
759    std::string fileName = GetFaultLogName(info);
760    std::string content;
761    ASSERT_TRUE(faultLogManager->GetFaultLogContent(fileName, content));
762    ASSERT_EQ(content, "testContent");
763}
764
765/**
766 * @tc.name: FaultLogManager::SaveFaultInfoToRawDb
767 * @tc.desc: Test calling SaveFaultInfoToRawDb Func
768 * @tc.type: FUNC
769 */
770HWTEST_F(FaultloggerUnittest, FaultLogManagerTest001, testing::ext::TestSize.Level3)
771{
772    StartHisyseventListen("RELIABILITY", "CPP_CRASH");
773    time_t now = std::time(nullptr);
774    std::vector<std::string> keyWords = { std::to_string(now) };
775    faultEventListener->SetKeyWords(keyWords);
776    FaultLogInfo info;
777    info.time = now;
778    info.pid = getpid();
779    info.id = 0;
780    info.faultLogType = 2;
781    info.module = "FaultloggerUnittest1111";
782    info.reason = "unittest for SaveFaultLogInfo";
783    info.summary = "summary for SaveFaultLogInfo";
784    info.sectionMap["APPVERSION"] = "1.0";
785    info.sectionMap["FAULT_MESSAGE"] = "abort";
786    info.sectionMap["TRACEID"] = "0x1646145645646";
787    info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
788    info.sectionMap["REASON"] = "TestReason";
789    info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
790    std::unique_ptr<FaultLogManager> faultLogManager =
791        std::make_unique<FaultLogManager>(GetHiviewContext().GetSharedWorkLoop());
792    faultLogManager->Init();
793    faultLogManager->SaveFaultInfoToRawDb(info);
794    ASSERT_TRUE(faultEventListener->CheckKeyWords());
795}
796
797std::string getTargetFileName(int32_t faultLogType, int64_t time)
798{
799    fileNames_.clear();
800    fileNames_ = {
801        {1, "Unknown"},
802        {2, "cppcrash"}, // 2 : faultLogType to cppcrash
803        {3, "jscrash"}, // 3 : faultLogType to jscrash
804        {4, "appfreeze"}, // 4 : faultLogType to appfreeze
805        {5, "sysfreeze"}, // 5 : faultLogType to sysfreeze
806        {6, "syswarning"}, // 6 : faultLogType to syswarning
807        {7, "rustpanic"}, // 7 : faultLogType to rustpanic
808        {8, "sanitizer"}, // 8 : faultLogType to sanitizer
809    };
810    std::string fileName = fileNames_[faultLogType];
811    return fileName + "-FaultloggerUnittest1111-0-" + GetFormatedTime(time);
812}
813
814/**
815 * @tc.name: FaultLogManager::SaveFaultLogToFile
816 * @tc.desc: Test calling SaveFaultLogToFile Func
817 * @tc.type: FUNC
818 */
819HWTEST_F(FaultloggerUnittest, FaultLogManagerTest003, testing::ext::TestSize.Level3)
820{
821    FaultLogInfo info;
822    std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
823    faultLogManager->Init();
824    for (int i = 1; i <= fileNames_.size(); i++) {
825        info.time = std::time(nullptr);
826        info.pid = getpid();
827        info.id = 0;
828        info.faultLogType = i;
829        info.module = "FaultloggerUnittest1111";
830        info.reason = "unittest for SaveFaultLogInfo";
831        info.summary = "summary for SaveFaultLogInfo";
832        info.sectionMap["APPVERSION"] = "1.0";
833        info.sectionMap["FAULT_MESSAGE"] = "abort";
834        info.sectionMap["TRACEID"] = "0x1646145645646";
835        info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
836        info.sectionMap["REASON"] = "TestReason";
837        info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
838
839        std::string fileName = faultLogManager->SaveFaultLogToFile(info);
840        if (fileName.find("FaultloggerUnittest1111") == std::string::npos) {
841            FAIL();
842        }
843        std::string targetFileName = getTargetFileName(i, info.time);
844        ASSERT_EQ(fileName, targetFileName);
845    }
846}
847
848/**
849 * @tc.name: faultLogManager GetFaultInfoListTest001
850 * @tc.desc: Test calling faultLogManager.GetFaultInfoList Func
851 * @tc.type: FUNC
852 */
853HWTEST_F(FaultloggerUnittest, FaultLogManagerTest002, testing::ext::TestSize.Level3)
854{
855    std::string jsonStr = R"~({"domain_":"RELIABILITY", "name_":"CPP_CRASH", "type_":1, "time_":1501973701070,
856        "tz_":"+0800", "pid_":1854, "tid_":1854, "uid_":0, "FAULT_TYPE":"2", "PID":1854, "UID":0,
857        "MODULE":"FaultloggerUnittest", "REASON":"unittest for SaveFaultLogInfo",
858        "SUMMARY":"summary for SaveFaultLogInfo", "LOG_PATH":"", "VERSION":"", "HAPPEN_TIME":"1501973701",
859        "PNAME":"/", "FIRST_FRAME":"/", "SECOND_FRAME":"/", "LAST_FRAME":"/",
860        "FINGERPRINT":"04c0d6f03c73da531f00eb112479a8a2f19f59fafba6a474dcbe455a13288f4d",
861        "level_":"CRITICAL", "tag_":"STABILITY", "id_":"17165544771317691984", "info_":""})~";
862    auto sysEvent = std::make_shared<SysEvent>("SysEventSource", nullptr, jsonStr);
863    sysEvent->SetLevel("MINOR");
864    sysEvent->SetEventSeq(448); // 448: test seq
865    EventStore::SysEventDao::Insert(sysEvent);
866
867    std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
868    auto isProcessedFault1 = faultLogManager->IsProcessedFault(1854, 0, 2);
869    ASSERT_EQ(isProcessedFault1, false);
870
871    faultLogManager->Init();
872
873    auto list = faultLogManager->GetFaultInfoList("FaultloggerUnittest", 0, 2, 10);
874    ASSERT_GT(list.size(), 0);
875
876    auto isProcessedFault2 = faultLogManager->IsProcessedFault(1854, 0, 2);
877    ASSERT_EQ(isProcessedFault2, true);
878
879    auto isProcessedFault3 = faultLogManager->IsProcessedFault(1855, 0, 2);
880    ASSERT_EQ(isProcessedFault3, false);
881
882    auto isProcessedFault4 = faultLogManager->IsProcessedFault(1855, 5, 2);
883    ASSERT_EQ(isProcessedFault4, false);
884}
885
886/**
887 * @tc.name: FaultLogUtilTest001
888 * @tc.desc: check ExtractInfoFromFileName Func
889 * @tc.type: FUNC
890 */
891HWTEST_F(FaultloggerUnittest, FaultLogUtilTest001, testing::ext::TestSize.Level3)
892{
893    std::string filename = "appfreeze-com.ohos.systemui-10006-20170805172159";
894    auto info = ExtractInfoFromFileName(filename);
895    ASSERT_EQ(info.pid, 0);
896    ASSERT_EQ(info.faultLogType, FaultLogType::APP_FREEZE); // 4 : APP_FREEZE
897    ASSERT_EQ(info.module, "com.ohos.systemui");
898    ASSERT_EQ(info.id, 10006); // 10006 : test uid
899}
900
901/**
902 * @tc.name: FaultLogUtilTest002
903 * @tc.desc: check ExtractInfoFromTempFile Func
904 * @tc.type: FUNC
905 */
906HWTEST_F(FaultloggerUnittest, FaultLogUtilTest002, testing::ext::TestSize.Level3)
907{
908    std::string filename = "appfreeze-10006-20170805172159";
909    auto info = ExtractInfoFromTempFile(filename);
910    ASSERT_EQ(info.faultLogType, FaultLogType::APP_FREEZE); // 4 : APP_FREEZE
911    ASSERT_EQ(info.pid, 10006); // 10006 : test uid
912
913    std::string filename3 = "jscrash-10006-20170805172159";
914    auto info3 = ExtractInfoFromTempFile(filename3);
915    ASSERT_EQ(info3.faultLogType, FaultLogType::JS_CRASH); // 3 : JS_CRASH
916    ASSERT_EQ(info3.pid, 10006); // 10006 : test uid
917
918    std::string filename4 = "cppcrash-10006-20170805172159";
919    auto info4 = ExtractInfoFromTempFile(filename4);
920    ASSERT_EQ(info4.faultLogType, FaultLogType::CPP_CRASH); // 2 : CPP_CRASH
921    ASSERT_EQ(info4.pid, 10006); // 10006 : test uid
922
923    std::string filename5 = "all-10006-20170805172159";
924    auto info5 = ExtractInfoFromTempFile(filename5);
925    ASSERT_EQ(info5.faultLogType, FaultLogType::ALL); // 0 : ALL
926    ASSERT_EQ(info5.pid, 10006); // 10006 : test uid
927
928    std::string filename6 = "other-10006-20170805172159";
929    auto info6 = ExtractInfoFromTempFile(filename6);
930    ASSERT_EQ(info6.faultLogType, -1); // -1 : other
931    ASSERT_EQ(info6.pid, 10006); // 10006 : test uid
932}
933
934/**
935 * @tc.name: FaultloggerAdapter.StartService
936 * @tc.desc: Test calling FaultloggerAdapter.StartService Func
937 * @tc.type: FUNC
938 */
939HWTEST_F(FaultloggerUnittest, FaultloggerAdapterTest001, testing::ext::TestSize.Level3)
940{
941    FaultloggerAdapter::StartService(nullptr);
942    ASSERT_EQ(FaultloggerServiceOhos::GetOrSetFaultlogger(nullptr), nullptr);
943
944    Faultlogger faultlogger;
945    FaultloggerAdapter::StartService(&faultlogger);
946    ASSERT_EQ(FaultloggerServiceOhos::GetOrSetFaultlogger(nullptr), &faultlogger);
947}
948
949/**
950 * @tc.name: FaultloggerServiceOhos.StartService
951 * @tc.desc: Test calling FaultloggerServiceOhos.StartService Func
952 * @tc.type: FUNC
953 */
954HWTEST_F(FaultloggerUnittest, FaultloggerServiceOhosTest001, testing::ext::TestSize.Level3)
955{
956    auto service = GetFaultloggerInstance();
957    FaultloggerServiceOhos serviceOhos;
958    FaultloggerServiceOhos::StartService(service.get());
959    ASSERT_EQ(FaultloggerServiceOhos::GetOrSetFaultlogger(nullptr), service.get());
960    FaultLogInfoOhos info;
961    info.time = std::time(nullptr);
962    info.pid = getpid();
963    info.uid = 0;
964    info.faultLogType = 2;
965    info.module = "FaultloggerUnittest333";
966    info.reason = "unittest for SaveFaultLogInfo";
967    serviceOhos.AddFaultLog(info);
968    auto list = serviceOhos.QuerySelfFaultLog(2, 10);
969    ASSERT_NE(list, nullptr);
970    info.time = std::time(nullptr);
971    info.pid = getpid();
972    info.uid = 10;
973    info.faultLogType = 2;
974    info.module = "FaultloggerUnittest333";
975    info.reason = "unittest for SaveFaultLogInfo";
976    serviceOhos.AddFaultLog(info);
977    list = serviceOhos.QuerySelfFaultLog(2, 10);
978    ASSERT_EQ(list, nullptr);
979    info.time = std::time(nullptr);
980    info.pid = getpid();
981    info.uid = 0;
982    info.faultLogType = 2;
983    info.module = "FaultloggerUnittest333";
984    info.reason = "unittest for SaveFaultLogInfo";
985    serviceOhos.AddFaultLog(info);
986    list = serviceOhos.QuerySelfFaultLog(8, 10);
987    ASSERT_EQ(list, nullptr);
988
989    serviceOhos.Destroy();
990}
991
992/**
993 * @tc.name: FaultloggerServiceOhos.Dump
994 * @tc.desc: Test calling FaultloggerServiceOhos.Dump Func
995 * @tc.type: FUNC
996 */
997HWTEST_F(FaultloggerUnittest, FaultloggerServiceOhosTest002, testing::ext::TestSize.Level3)
998{
999    auto service = GetFaultloggerInstance();
1000    FaultloggerServiceOhos serviceOhos;
1001    FaultloggerServiceOhos::StartService(service.get());
1002    ASSERT_EQ(FaultloggerServiceOhos::GetOrSetFaultlogger(nullptr), service.get());
1003    auto fd = TEMP_FAILURE_RETRY(open("/data/test/testFile2", O_CREAT | O_WRONLY | O_TRUNC, 770));
1004    bool isSuccess = fd >= 0;
1005    if (!isSuccess) {
1006        ASSERT_FALSE(isSuccess);
1007        printf("Fail to create test result file.\n");
1008        return;
1009    }
1010    std::vector<std::u16string>args;
1011    args.push_back(u"Faultlogger");
1012    args.push_back(u"-l");
1013    serviceOhos.Dump(fd, args);
1014    args.push_back(u"&@#");
1015    ASSERT_EQ(serviceOhos.Dump(fd, args), -1);
1016    close(fd);
1017    fd = -1;
1018    std::string result;
1019    if (FileUtil::LoadStringFromFile("/data/test/testFile2", result)) {
1020        ASSERT_GT(result.length(), 0uL);
1021    } else {
1022        FAIL();
1023    }
1024    serviceOhos.Destroy();
1025}
1026
1027/**
1028 * @tc.name: FaultLogQueryResultOhosTest001
1029 * @tc.desc: test HasNext and GetNext
1030 * @tc.type: FUNC
1031 */
1032HWTEST_F(FaultloggerUnittest, FaultLogQueryResultOhosTest001, testing::ext::TestSize.Level3)
1033{
1034    auto service = GetFaultloggerInstance();
1035    FaultloggerServiceOhos serviceOhos;
1036    FaultloggerServiceOhos::StartService(service.get());
1037    bool isSuccess = FaultloggerServiceOhos::GetOrSetFaultlogger(nullptr) == service.get();
1038    if (!isSuccess) {
1039        ASSERT_FALSE(isSuccess);
1040        printf("FaultloggerServiceOhos start service error.\n");
1041        return;
1042    }
1043    auto remoteObject = serviceOhos.QuerySelfFaultLog(FaultLogType::CPP_CRASH, 10); // 10 : maxNum
1044    auto result = iface_cast<FaultLogQueryResultOhos>(remoteObject);
1045    ASSERT_NE(result, nullptr);
1046    if (result != nullptr) {
1047        while (result->HasNext()) {
1048            result->GetNext();
1049        }
1050    }
1051    auto getNextRes = result->GetNext();
1052    ASSERT_NE(result, nullptr);
1053
1054    result->result_ = nullptr;
1055    bool hasNext = result->HasNext();
1056    ASSERT_FALSE(hasNext);
1057    getNextRes = result->GetNext();
1058    ASSERT_NE(result, nullptr);
1059}
1060
1061class TestFaultLogQueryResultStub : public FaultLogQueryResultStub {
1062public:
1063    TestFaultLogQueryResultStub() {}
1064    virtual ~TestFaultLogQueryResultStub() {}
1065
1066    bool HasNext()
1067    {
1068        return false;
1069    }
1070
1071    sptr<FaultLogInfoOhos> GetNext()
1072    {
1073        return nullptr;
1074    }
1075
1076public:
1077    enum Code {
1078        DEFAULT = -1,
1079        HASNEXT = 0,
1080        GETNEXT,
1081    };
1082};
1083
1084/**
1085 * @tc.name: FaultLogQueryResultStubTest001
1086 * @tc.desc: test OnRemoteRequest
1087 * @tc.type: FUNC
1088 */
1089HWTEST_F(FaultloggerUnittest, FaultLogQueryResultStubTest001, testing::ext::TestSize.Level3)
1090{
1091    TestFaultLogQueryResultStub faultLogQueryResultStub;
1092    MessageParcel data;
1093    MessageParcel reply;
1094    MessageOption option;
1095    int ret = faultLogQueryResultStub.OnRemoteRequest(TestFaultLogQueryResultStub::Code::HASNEXT, data, reply, option);
1096    ASSERT_EQ(ret, -1);
1097    data.WriteInterfaceToken(FaultLogQueryResultStub::GetDescriptor());
1098    ret = faultLogQueryResultStub.OnRemoteRequest(TestFaultLogQueryResultStub::Code::HASNEXT, data, reply, option);
1099    ASSERT_EQ(ret, 0);
1100    data.WriteInterfaceToken(FaultLogQueryResultStub::GetDescriptor());
1101    ret = faultLogQueryResultStub.OnRemoteRequest(TestFaultLogQueryResultStub::Code::GETNEXT, data, reply, option);
1102    ASSERT_EQ(ret, -1);
1103    data.WriteInterfaceToken(FaultLogQueryResultStub::GetDescriptor());
1104    ret = faultLogQueryResultStub.OnRemoteRequest(TestFaultLogQueryResultStub::Code::DEFAULT, data, reply, option);
1105    ASSERT_EQ(ret, 305); // 305 : method not exist
1106}
1107
1108class TestFaultLoggerServiceStub : public FaultLoggerServiceStub {
1109public:
1110    TestFaultLoggerServiceStub() {}
1111    virtual ~TestFaultLoggerServiceStub() {}
1112
1113    void AddFaultLog(const FaultLogInfoOhos& info)
1114    {
1115    }
1116
1117    sptr<IRemoteObject> QuerySelfFaultLog(int32_t faultType, int32_t maxNum)
1118    {
1119        return nullptr;
1120    }
1121
1122    void Destroy()
1123    {
1124    }
1125
1126public:
1127    enum Code {
1128        DEFAULT = -1,
1129        ADD_FAULTLOG = 0,
1130        QUERY_SELF_FAULTLOG,
1131        DESTROY,
1132    };
1133};
1134
1135/**
1136 * @tc.name: FaultLoggerServiceStubTest001
1137 * @tc.desc: test OnRemoteRequest
1138 * @tc.type: FUNC
1139 */
1140HWTEST_F(FaultloggerUnittest, FaultLoggerServiceStubTest001, testing::ext::TestSize.Level3)
1141{
1142    TestFaultLoggerServiceStub faultLoggerServiceStub;
1143    MessageParcel data;
1144    MessageParcel reply;
1145    MessageOption option;
1146    int ret = faultLoggerServiceStub.OnRemoteRequest(TestFaultLoggerServiceStub::Code::ADD_FAULTLOG,
1147        data, reply, option);
1148    ASSERT_EQ(ret, -1);
1149    data.WriteInterfaceToken(FaultLoggerServiceStub::GetDescriptor());
1150    ret = faultLoggerServiceStub.OnRemoteRequest(TestFaultLoggerServiceStub::Code::ADD_FAULTLOG,
1151        data, reply, option);
1152    ASSERT_EQ(ret, 3); // 3 : ERR_FLATTEN_OBJECT
1153    data.WriteInterfaceToken(FaultLoggerServiceStub::GetDescriptor());
1154    ret = faultLoggerServiceStub.OnRemoteRequest(TestFaultLoggerServiceStub::Code::QUERY_SELF_FAULTLOG,
1155        data, reply, option);
1156    ASSERT_EQ(ret, -1);
1157    data.WriteInterfaceToken(FaultLoggerServiceStub::GetDescriptor());
1158    ret = faultLoggerServiceStub.OnRemoteRequest(TestFaultLoggerServiceStub::Code::DESTROY,
1159        data, reply, option);
1160    ASSERT_EQ(ret, 0);
1161    data.WriteInterfaceToken(FaultLoggerServiceStub::GetDescriptor());
1162    ret = faultLoggerServiceStub.OnRemoteRequest(TestFaultLoggerServiceStub::Code::DEFAULT,
1163        data, reply, option);
1164    ASSERT_EQ(ret, 305); // 305 : method not exist
1165}
1166
1167/**
1168 * @tc.name: FaultloggerTest001
1169 * @tc.desc: Test calling Faultlogger.StartBootScan Func
1170 * @tc.type: FUNC
1171 */
1172HWTEST_F(FaultloggerUnittest, FaultloggerTest001, testing::ext::TestSize.Level3)
1173{
1174    StartHisyseventListen("RELIABILITY", "CPP_CRASH");
1175    time_t now = time(nullptr);
1176    std::vector<std::string> keyWords = { std::to_string(now) };
1177    faultEventListener->SetKeyWords(keyWords);
1178    std::string timeStr = GetFormatedTime(now);
1179    std::string content = "Pid:101\nUid:0\nProcess name:BootScanUnittest\nReason:unittest for StartBootScan\n"
1180        "Fault thread info:\nTid:101, Name:BootScanUnittest\n#00 xxxxxxx\n#01 xxxxxxx\n";
1181    ASSERT_TRUE(FileUtil::SaveStringToFile("/data/log/faultlog/temp/cppcrash-101-" + std::to_string(now), content));
1182    auto plugin = GetFaultloggerInstance();
1183    plugin->StartBootScan();
1184    //check faultlog file content
1185    std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-BootScanUnittest-0-" + timeStr;
1186    ASSERT_TRUE(FileUtil::FileExists(fileName));
1187    ASSERT_GT(FileUtil::GetFileSize(fileName), 0ul);
1188    ASSERT_EQ(plugin->GetFaultLogInfo(fileName)->module, "BootScanUnittest");
1189
1190    // check event database
1191    ASSERT_TRUE(faultEventListener->CheckKeyWords());
1192}
1193
1194/**
1195 * @tc.name: FaultloggerTest002
1196 * @tc.desc: Test calling Faultlogger.StartBootScan Func
1197 * @tc.type: FUNC
1198 */
1199HWTEST_F(FaultloggerUnittest, FaultloggerTest002, testing::ext::TestSize.Level3)
1200{
1201    StartHisyseventListen("RELIABILITY", "CPP_CRASH_NO_LOG");
1202    std::vector<std::string> keyWords = { "BootScanUnittest" };
1203    faultEventListener->SetKeyWords(keyWords);
1204    time_t now = time(nullptr);
1205    std::string timeStr = GetFormatedTime(now);
1206    std::string content = "Pid:102\nUid:0\nProcess name:BootScanUnittest\nReason:unittest for StartBootScan\n"
1207        "Fault thread info:\nTid:102, Name:BootScanUnittest\n";
1208    std::string fileName = "/data/log/faultlog/temp/cppcrash-102-" + std::to_string(now);
1209    ASSERT_TRUE(FileUtil::SaveStringToFile(fileName, content));
1210    auto plugin = GetFaultloggerInstance();
1211    plugin->StartBootScan();
1212    ASSERT_FALSE(FileUtil::FileExists(fileName));
1213
1214    // check event database
1215    ASSERT_TRUE(faultEventListener->CheckKeyWords());
1216}
1217
1218/**
1219 * @tc.name: FaultloggerTest003
1220 * @tc.desc: Test calling Faultlogger.StartBootScan Func, for full log
1221 * @tc.type: FUNC
1222 */
1223HWTEST_F(FaultloggerUnittest, FaultloggerTest003, testing::ext::TestSize.Level3)
1224{
1225    StartHisyseventListen("RELIABILITY", "CPP_CRASH");
1226    time_t now = time(nullptr);
1227    std::vector<std::string> keyWords = { std::to_string(now) };
1228    faultEventListener->SetKeyWords(keyWords);
1229    std::string timeStr = GetFormatedTime(now);
1230    std::string regs = "r0:00000019 r1:0097cd3c\nr4:f787fd2c\nfp:f787fd18 ip:7fffffff pc:0097c982\n";
1231    std::string otherThreadInfo =
1232        "Tid:1336, Name:BootScanUnittes\n#00 xxxxxx\nTid:1337, Name:BootScanUnittes\n#00 xx\n";
1233    std::string content = std::string("Pid:111\nUid:0\nProcess name:BootScanUnittest\n") +
1234        "Reason:unittest for StartBootScan\n" +
1235        "Fault thread info:\nTid:111, Name:BootScanUnittest\n#00 xxxxxxx\n#01 xxxxxxx\n" +
1236        "Registers:\n" + regs +
1237        "Other thread info:\n" + otherThreadInfo +
1238        "Memory near registers:\nr1(/data/xxxxx):\n    0097cd34 47886849\n    0097cd38 96059d05\n\n" +
1239        "Maps:\n96e000-978000 r--p 00000000 /data/xxxxx\n978000-9a6000 r-xp 00009000 /data/xxxx\n";
1240    ASSERT_TRUE(FileUtil::SaveStringToFile("/data/log/faultlog/temp/cppcrash-111-" + std::to_string(now), content));
1241    auto plugin = GetFaultloggerInstance();
1242    plugin->StartBootScan();
1243
1244    //check faultlog file content
1245    std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-BootScanUnittest-0-" + timeStr;
1246    ASSERT_TRUE(FileUtil::FileExists(fileName));
1247    ASSERT_GT(FileUtil::GetFileSize(fileName), 0ul);
1248    auto info = plugin->GetFaultLogInfo(fileName);
1249    ASSERT_EQ(info->module, "BootScanUnittest");
1250
1251    // check regs and otherThreadInfo is ok
1252    std::string logInfo;
1253    FileUtil::LoadStringFromFile(fileName, logInfo);
1254    ASSERT_TRUE(logInfo.find(regs) != std::string::npos);
1255    ASSERT_TRUE(logInfo.find(otherThreadInfo) != std::string::npos);
1256
1257    // check event database
1258    ASSERT_TRUE(faultEventListener->CheckKeyWords());
1259}
1260
1261/**
1262 * @tc.name: FaultloggerTest004
1263 * @tc.desc: Test calling Faultlogger.StartBootScan Func, for full cpp crash log limit
1264 * @tc.type: FUNC
1265 */
1266HWTEST_F(FaultloggerUnittest, FaultloggerTest004, testing::ext::TestSize.Level3)
1267{
1268    StartHisyseventListen("RELIABILITY", "CPP_CRASH");
1269    time_t now = time(nullptr);
1270    std::vector<std::string> keyWords = { std::to_string(now) };
1271    faultEventListener->SetKeyWords(keyWords);
1272    std::string timeStr = GetFormatedTime(now);
1273    std::string fillMapsContent = "96e000-978000 r--p 00000000 /data/xxxxx\n978000-9a6000 r-xp 00009000 /data/xxxx\n";
1274    std::string regs = "r0:00000019 r1:0097cd3c\nr4:f787fd2c\nfp:f787fd18 ip:7fffffff pc:0097c982\n";
1275    std::string otherThreadInfo =
1276        "Tid:1336, Name:BootScanUnittes\n#00 xxxxxx\nTid:1337, Name:BootScanUnittes\n#00 xx\n";
1277    std::string content = std::string("Pid:111\nUid:0\nProcess name:BootScanUnittest\n") +
1278        "Reason:unittest for StartBootScan\n" +
1279        "Fault thread info:\nTid:111, Name:BootScanUnittest\n#00 xxxxxxx\n#01 xxxxxxx\n" +
1280        "Registers:\n" + regs +
1281        "Other thread info:\n" + otherThreadInfo +
1282        "Memory near registers:\nr1(/data/xxxxx):\n    0097cd34 47886849\n    0097cd38 96059d05\n\n" +
1283        "Maps:\n96e000-978000 r--p 00000000 /data/xxxxx\n978000-9a6000 r-xp 00009000 /data/xxxx\n";
1284    // let content more than 512k, trigger loglimit
1285    for (int i = 0; i < 10000; i++) {
1286        content += fillMapsContent;
1287    }
1288
1289    ASSERT_TRUE(FileUtil::SaveStringToFile("/data/log/faultlog/temp/cppcrash-114-" + std::to_string(now), content));
1290    auto plugin = GetFaultloggerInstance();
1291    plugin->StartBootScan();
1292    // check faultlog file content
1293    std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-BootScanUnittest-0-" + timeStr;
1294    GTEST_LOG_(INFO) << "========fileName:" << fileName;
1295    ASSERT_TRUE(FileUtil::FileExists(fileName));
1296    ASSERT_GT(FileUtil::GetFileSize(fileName), 0ul);
1297    if (FaultLogger::IsFaultLogLimit()) {
1298        ASSERT_LT(FileUtil::GetFileSize(fileName), 514 * 1024ul);
1299    } else {
1300        ASSERT_GT(FileUtil::GetFileSize(fileName), 512 * 1024ul);
1301    }
1302    // check event database
1303    ASSERT_TRUE(faultEventListener->CheckKeyWords());
1304}
1305
1306/**
1307 * @tc.name: ReportJsErrorToAppEventTest001
1308 * @tc.desc: create JS ERROR event and send it to hiappevent
1309 * @tc.type: FUNC
1310 */
1311HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest001, testing::ext::TestSize.Level3)
1312{
1313    auto plugin = GetFaultloggerInstance();
1314    // has Error name、Error message、Error code、SourceCode、Stacktrace
1315    std::string summaryHasAll = R"~(Error name:summaryHasAll TypeError
1316Error message:Obj is not a Valid object
1317Error code:get BLO
1318SourceCode:CKSSvalue() {new Error("TestError");}
1319Stacktrace:
1320    at anonymous(entry/src/main/ets/pages/index.ets:76:10)
1321    at anonymous2(entry/src/main/ets/pages/index.ets:76:10)
1322    at anonymous3(entry/src/main/ets/pages/index.ets:76:10)
1323)~";
1324    GTEST_LOG_(INFO) << "========summaryHasAll========";
1325    ConstructJsErrorAppEvent(summaryHasAll, plugin);
1326    CheckKeyWordsInJsErrorAppEventFile("summaryHasAll");
1327}
1328
1329/**
1330 * @tc.name: ReportJsErrorToAppEventTest002
1331 * @tc.desc: create JS ERROR event and send it to hiappevent
1332 * @tc.type: FUNC
1333 */
1334HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest002, testing::ext::TestSize.Level3)
1335{
1336    auto plugin = GetFaultloggerInstance();
1337    // has Error name、Error message、Error code、SourceCode、Stacktrace
1338    std::string summaryNotFindSourcemap = R"~(Error name:summaryNotFindSourcemap Error
1339Error message:BussinessError 2501000: Operation failed.
1340Error code:2501000
1341Stacktrace:
1342Cannot get SourceMap info, dump raw stack:
1343  at anonymous(entry/src/main/ets/pages/index.ets:76:10)
1344  at anonymous2(entry/src/main/ets/pages/index.ets:76:10)
1345  at anonymous3(entry/src/main/ets/pages/index.ets:76:10)
1346)~";
1347    GTEST_LOG_(INFO) << "========summaryNotFindSourcemap========";
1348    ConstructJsErrorAppEvent(summaryNotFindSourcemap, plugin);
1349    CheckDeleteStackErrorMessage("summaryNotFindSourcemap");
1350    CheckKeyWordsInJsErrorAppEventFile("summaryNotFindSourcemap");
1351}
1352
1353/**
1354 * @tc.name: ReportJsErrorToAppEventTest003
1355 * @tc.desc: create JS ERROR event and send it to hiappevent
1356 * @tc.type: FUNC
1357 */
1358HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest003, testing::ext::TestSize.Level3)
1359{
1360    auto plugin = GetFaultloggerInstance();
1361    // has Error name、Error message、SourceCode、Stacktrace
1362    std::string summaryHasNoErrorCode = R"~(Error name:summaryHasNoErrorCode TypeError
1363Error message:Obj is not a Valid object
1364SourceCode:CKSSvalue() {new Error("TestError");}
1365Stacktrace:
1366    at anonymous(entry/src/main/ets/pages/index.ets:76:10)
1367    at anonymous2(entry/src/main/ets/pages/index.ets:76:10)
1368    at anonymous3(entry/src/main/ets/pages/index.ets:76:10)
1369)~";
1370    GTEST_LOG_(INFO) << "========summaryHasNoErrorCode========";
1371    ConstructJsErrorAppEvent(summaryHasNoErrorCode, plugin);
1372    CheckKeyWordsInJsErrorAppEventFile("summaryHasNoErrorCode");
1373}
1374
1375/**
1376 * @tc.name: ReportJsErrorToAppEventTest004
1377 * @tc.desc: create JS ERROR event and send it to hiappevent
1378 * @tc.type: FUNC
1379 */
1380HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest004, testing::ext::TestSize.Level3)
1381{
1382    auto plugin = GetFaultloggerInstance();
1383    // has Error name、Error message、Error code、Stacktrace
1384    std::string summaryHasNoSourceCode = R"~(Error name:summaryHasNoSourceCode TypeError
1385Error message:Obj is not a Valid object
1386Error code:get BLO
1387Stacktrace:
1388    at anonymous(entry/src/main/ets/pages/index.ets:76:10)
1389    at anonymous2(entry/src/main/ets/pages/index.ets:76:10)
1390    at anonymous3(entry/src/main/ets/pages/index.ets:76:10)
1391)~";
1392    GTEST_LOG_(INFO) << "========summaryHasNoSourceCode========";
1393    ConstructJsErrorAppEvent(summaryHasNoSourceCode, plugin);
1394    CheckKeyWordsInJsErrorAppEventFile("summaryHasNoSourceCode");
1395}
1396
1397/**
1398 * @tc.name: ReportJsErrorToAppEventTest005
1399 * @tc.desc: create JS ERROR event and send it to hiappevent
1400 * @tc.type: FUNC
1401 */
1402HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest005, testing::ext::TestSize.Level3)
1403{
1404    auto plugin = GetFaultloggerInstance();
1405    // has Error name、Error message、Stacktrace
1406    std::string summaryHasNoErrorCodeAndSourceCode = R"~(Error name:summaryHasNoErrorCodeAndSourceCode TypeError
1407Error message:Obj is not a Valid object
1408Stacktrace:
1409    at anonymous(entry/src/main/ets/pages/index.ets:76:10)
1410    at anonymous2(entry/src/main/ets/pages/index.ets:76:10)
1411    at anonymous3(entry/src/main/ets/pages/index.ets:76:10)
1412)~";
1413    GTEST_LOG_(INFO) << "========summaryHasNoErrorCodeAndSourceCode========";
1414    ConstructJsErrorAppEvent(summaryHasNoErrorCodeAndSourceCode, plugin);
1415    CheckKeyWordsInJsErrorAppEventFile("summaryHasNoErrorCodeAndSourceCode");
1416}
1417
1418/**
1419 * @tc.name: ReportJsErrorToAppEventTest006
1420 * @tc.desc: create JS ERROR event and send it to hiappevent
1421 * @tc.type: FUNC
1422 */
1423HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest006, testing::ext::TestSize.Level3)
1424{
1425    auto plugin = GetFaultloggerInstance();
1426    // has Error name、Error message、Error code、SourceCode
1427    std::string summaryHasNoStacktrace = R"~(Error name:summaryHasNoStacktrace TypeError
1428Error message:Obj is not a Valid object
1429Error code:get BLO
1430SourceCode:CKSSvalue() {new Error("TestError");}
1431Stacktrace:
1432)~";
1433    GTEST_LOG_(INFO) << "========summaryHasNoStacktrace========";
1434    ConstructJsErrorAppEvent(summaryHasNoStacktrace, plugin);
1435    CheckKeyWordsInJsErrorAppEventFile("summaryHasNoStacktrace");
1436}
1437
1438/**
1439 * @tc.name: ReportJsErrorToAppEventTest007
1440 * @tc.desc: create JS ERROR event and send it to hiappevent
1441 * @tc.type: FUNC
1442 */
1443HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest007, testing::ext::TestSize.Level3)
1444{
1445    auto plugin = GetFaultloggerInstance();
1446    // has Error name、Error message
1447    std::string summaryHasErrorNameAndErrorMessage = R"~(Error name:summaryHasErrorNameAndErrorMessage TypeError
1448Error message:Obj is not a Valid object
1449Stacktrace:
1450)~";
1451    GTEST_LOG_(INFO) << "========summaryHasErrorNameAndErrorMessage========";
1452    ConstructJsErrorAppEvent(summaryHasErrorNameAndErrorMessage, plugin);
1453    CheckKeyWordsInJsErrorAppEventFile("summaryHasErrorNameAndErrorMessage");
1454}
1455
1456/**
1457 * @tc.name: ReportJsErrorToAppEventTest008
1458 * @tc.desc: create JS ERROR event and send it to hiappevent
1459 * @tc.type: FUNC
1460 */
1461HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest008, testing::ext::TestSize.Level3)
1462{
1463    auto plugin = GetFaultloggerInstance();
1464    // has Error name、Error message
1465    std::string noKeyValue = R"~(Error name:summaryHasErrorNameAndErrorMessage TypeError
1466Error message:Obj is not a Valid object
1467Stacktrace:
1468)~";
1469    GTEST_LOG_(INFO) << "========noKeyValue========";
1470    ConstructJsErrorAppEventWithNoValue(noKeyValue, plugin);
1471    CheckKeyWordsInJsErrorAppEventFile("noKeyValue");
1472}
1473
1474/**
1475 * @tc.name: ReportJsErrorToAppEventTest009
1476 * @tc.desc: create JS ERROR event and send it to hiappevent
1477 * @tc.type: FUNC
1478 */
1479HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest009, testing::ext::TestSize.Level3)
1480{
1481    auto plugin = GetFaultloggerInstance();
1482    GTEST_LOG_(INFO) << "========noKeyValue========";
1483    ConstructJsErrorAppEventWithNoValue("", plugin);
1484    std::string oldFileName = "/data/test_jsError_info";
1485    ASSERT_TRUE(FileUtil::FileExists(oldFileName));
1486    auto ret = remove("/data/test_jsError_info");
1487    if (ret == 0) {
1488        GTEST_LOG_(INFO) << "remove /data/test_jsError_info failed";
1489    }
1490}
1491
1492bool SendSysEvent(SysEventCreator sysEventCreator)
1493{
1494    auto plugin = GetFaultloggerInstance();
1495    auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
1496    std::shared_ptr<Event> event = std::dynamic_pointer_cast<Event>(sysEvent);
1497    return plugin->OnEvent(event);
1498}
1499
1500/**
1501 * @tc.name: OnEventTest001
1502 * @tc.desc: create JS ERROR event and send it to hiappevent
1503 * @tc.type: FUNC
1504 */
1505HWTEST_F(FaultloggerUnittest, OnEventTest001, testing::ext::TestSize.Level3)
1506{
1507    {
1508        SysEventCreator sysEventCreator("AAFWK", "JSERROR", SysEventCreator::FAULT);
1509        sysEventCreator.SetKeyValue("name_", "JS_ERRORS");
1510        auto result = SendSysEvent(sysEventCreator);
1511        ASSERT_EQ(result, true);
1512    }
1513    {
1514        SysEventCreator sysEventCreator("AAFWK", "CPPCRASH", SysEventCreator::FAULT);
1515        sysEventCreator.SetKeyValue("name_", "RUST_PANIC");
1516        auto result = SendSysEvent(sysEventCreator);
1517        ASSERT_EQ(result, true);
1518    }
1519}
1520
1521/**
1522 * @tc.name: FaultloggerUnittest001
1523 * @tc.desc: test GetFaultLogInfo, QuerySelfFaultLog and GetMemoryStrByPid
1524 * @tc.type: FUNC
1525 */
1526HWTEST_F(FaultloggerUnittest, FaultloggerUnittest001, testing::ext::TestSize.Level3)
1527{
1528    auto plugin = GetFaultloggerInstance();
1529    plugin->hasInit_ = false;
1530    plugin->GetFaultLogInfo("test");
1531    std::unique_ptr<FaultLogQueryResultInner> obj = plugin->QuerySelfFaultLog(1, 1, 1, 1);
1532    ASSERT_EQ(obj, nullptr);
1533
1534    std::string str = plugin->GetMemoryStrByPid(-1);
1535    ASSERT_EQ(str, "");
1536    str = plugin->GetMemoryStrByPid(1);
1537    ASSERT_NE(str, "");
1538}
1539
1540/**
1541 * @tc.name: FaultlogDatabaseUnittest001
1542 * @tc.desc: test RunSanitizerd
1543 * @tc.type: FUNC
1544 */
1545HWTEST_F(FaultloggerUnittest, FaultlogDatabaseUnittest001, testing::ext::TestSize.Level3)
1546{
1547    FaultLogDatabase *faultLogDb = new FaultLogDatabase(GetHiviewContext().GetSharedWorkLoop());
1548    std::list<FaultLogInfo> queryResult = faultLogDb->GetFaultInfoList("com.example.myapplication", 0, -1, 10);
1549    ASSERT_EQ(queryResult.size(), 0);
1550    queryResult = faultLogDb->GetFaultInfoList("com.example.myapplication", 0, 8, 10);
1551    ASSERT_EQ(queryResult.size(), 0);
1552    queryResult = faultLogDb->GetFaultInfoList("com.example.myapplication", 1, 2, 10);
1553    ASSERT_EQ(queryResult.size(), 0);
1554    queryResult = faultLogDb->GetFaultInfoList("com.example.myapplication", 1, 0, 10);
1555    ASSERT_EQ(queryResult.size(), 0);
1556
1557    FaultLogInfo info;
1558    info.faultLogType = FaultLogType::SYS_FREEZE;
1559    faultLogDb->eventLoop_ = nullptr;
1560    faultLogDb->SaveFaultLogInfo(info);
1561
1562    bool res = faultLogDb->IsFaultExist(1, 1, -1);
1563    ASSERT_FALSE(res);
1564    res = faultLogDb->IsFaultExist(1, 1, 8);
1565    ASSERT_FALSE(res);
1566}
1567
1568/**
1569 * @tc.name: FaultlogUtilUnittest001
1570 * @tc.desc: test RunSanitizerd
1571 * @tc.type: FUNC
1572 */
1573HWTEST_F(FaultloggerUnittest, FaultlogUtilUnittest001, testing::ext::TestSize.Level3)
1574{
1575    std::string result = GetFaultNameByType(FaultLogType::ADDR_SANITIZER, false);
1576    ASSERT_EQ(result, "ADDR_SANITIZER");
1577
1578    FaultLogInfo info;
1579    info.module = "test/test";
1580    info.faultLogType = FaultLogType::ADDR_SANITIZER;
1581    info.reason = "TSAN";
1582    std::string str = GetFaultLogName(info);
1583    ASSERT_EQ(str, "tsan-test-0-19700101080000");
1584    info.reason = "UBSAN";
1585    str = GetFaultLogName(info);
1586    ASSERT_EQ(str, "ubsan-test-0-19700101080000");
1587    info.reason = "GWP-ASAN";
1588    str = GetFaultLogName(info);
1589    ASSERT_EQ(str, "gwpasan-test-0-19700101080000");
1590    info.reason = "GWP-ASANS";
1591    str = GetFaultLogName(info);
1592    ASSERT_EQ(str, "sanitizer-test-0-19700101080000");
1593
1594    str = RegulateModuleNameIfNeed("");
1595    ASSERT_EQ(str, "");
1596}
1597
1598/**
1599 * @tc.name: FaultloggerServiceOhosUnittest001
1600 * @tc.desc: test RunSanitizerd
1601 * @tc.type: FUNC
1602 */
1603HWTEST_F(FaultloggerUnittest, FaultloggerServiceOhosUnittest001, testing::ext::TestSize.Level3)
1604{
1605    FaultloggerServiceOhos faultloggerServiceOhos;
1606    std::vector<std::u16string> args;
1607    args.push_back(u"*m");
1608    int32_t result = faultloggerServiceOhos.Dump(1, args);
1609    ASSERT_EQ(result, -1);
1610
1611    FaultLogInfoOhos info;
1612    faultloggerServiceOhos.AddFaultLog(info);
1613    sptr<IRemoteObject> res = faultloggerServiceOhos.QuerySelfFaultLog(1, 10);
1614    ASSERT_EQ(res, nullptr);
1615    faultloggerServiceOhos.Destroy();
1616}
1617} // namespace HiviewDFX
1618} // namespace OHOS
1619