1 /**
2 * Copyright (c) 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
16 #include <dirent.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <test.h>
20
21 #define NAME_BUFFER_SIZE 512
22
check_log(const char * file,const char * pattern)23 void check_log(const char *file, const char *pattern)
24 {
25 char buffer[NAME_BUFFER_SIZE];
26 FILE *fp = fopen(file, "r");
27 if (!fp) {
28 return;
29 }
30 if (fseek(fp, 0, SEEK_END) == -1) {
31 fclose(fp);
32 return;
33 }
34 int size = ftell(fp);
35 if (size <= 0) {
36 fclose(fp);
37 t_error("FAIL %s size is <=0!\n", file);
38 }
39 if (fseek(fp, 0, SEEK_SET) == -1) {
40 fclose(fp);
41 return;
42 }
43 int rsize = fread(buffer, 1, size, fp);
44 if (rsize == 0) {
45 fclose(fp);
46 return;
47 }
48
49 if (strstr(buffer, pattern) != NULL) {
50 printf("It's ok to found %s in %s.\n", pattern, file);
51 } else {
52 // libctest use "FAIL" to determine whether test case failed.
53 t_error("FAIL can't find %s in %s!\n", pattern, file);
54 }
55 int r = fclose(fp);
56 if (r) {
57 t_error("FAIL fclose failed!\n");
58 }
59 return;
60 }
61
find_and_check_file(const char * log_dir,const char * file_tag,const char * pattern)62 void find_and_check_file(const char *log_dir, const char *file_tag, const char *pattern)
63 {
64 struct dirent *ptr;
65 int found = 0;
66 if (!log_dir) {
67 return;
68 }
69 DIR *dir = opendir(log_dir);
70 if (!dir) {
71 return;
72 }
73 while ((ptr = readdir(dir)) != NULL) {
74 if (strstr(ptr->d_name, file_tag) != NULL) {
75 found = 1;
76 char target_file[NAME_BUFFER_SIZE];
77 snprintf(target_file, NAME_BUFFER_SIZE, "%s%s", log_dir, ptr->d_name);
78 check_log(target_file, pattern);
79 }
80 }
81 if (!found) {
82 t_error("FAIL can't find matched file, log_dir:%s file_tag:%s.\n", log_dir, file_tag);
83 }
84 closedir(dir);
85 }
86
clear_log(const char * log_dir,const char * file_tag)87 void clear_log(const char *log_dir, const char *file_tag)
88 {
89 struct dirent *ptr;
90 if (!log_dir) {
91 return;
92 }
93 DIR *dir = opendir(log_dir);
94 if (!dir) {
95 return;
96 }
97 while ((ptr = readdir(dir)) != NULL) {
98 if (strstr(ptr->d_name, file_tag) != NULL) {
99 char target_file[NAME_BUFFER_SIZE];
100 snprintf(target_file, NAME_BUFFER_SIZE, "%s%s", log_dir, ptr->d_name);
101 remove(target_file);
102 }
103 }
104 closedir(dir);
105 }