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