• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# -*- coding: utf-8 -*-
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
15from ast import parse
16import encodings
17import json
18import sys
19import os
20import time
21import argparse
22import re
23import subprocess
24import shlex
25import datetime
26import sqlite3
27import shutil
28import numpy
29import cv2
30import pytesseract
31from pytesseract import Output
32from PIL import Image
33
34
35def print_to_log(str):
36    time = datetime.datetime.now()
37    str = "[{}] {}".format(time, str)
38    print(str)
39    with open(os.path.join(args.save_path, 'test_{}.log'.format(args.device_num)),\
40    mode='a', encoding='utf-8') as log_file:
41        console = sys.stdout
42        sys.stdout = log_file
43        print(str)
44        sys.stdout = console
45    log_file.close()
46
47
48def enter_cmd(mycmd, waittime=0, printresult=1):
49    if mycmd == "":
50        return
51    global cmd_retry_cnt
52    cmd_retry_cnt = 1
53    enter_cmdRetry = 2
54    while enter_cmdRetry:
55        enter_cmdRetry -= 1
56        try:
57            p = subprocess.Popen(mycmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
58            result, unused_err = p.communicate(timeout=25)
59            try:
60                result=result.decode(encoding="utf-8")
61            except UnicodeDecodeError:
62                result=result.decode('gbk', errors='ignore')
63            break
64        except Exception as e:
65            result = 'retry failed again'
66            print_to_log(e)
67            cmd_retry_cnt += 1
68            p.kill()
69    if printresult == 1:
70        with open(os.path.join(args.save_path, 'test_{}.bat'.format(args.device_num)),\
71        mode='a', encoding='utf-8') as cmd_f:
72            cmd_f.write(mycmd + '\n')
73        cmd_f.close()
74        print_to_log(mycmd)
75        print_to_log(result)
76        sys.stdout.flush()
77    if waittime != 0:
78        time.sleep(waittime)
79        if printresult == 1:
80            with open(os.path.join(args.save_path, 'test_{}.bat'.format(args.device_num)),\
81            mode='a', encoding='utf-8') as cmd_f:
82                cmd_f.write("ping -n {} 127.0.0.1>null\n".format(waittime))
83            cmd_f.close()
84    return result
85
86
87def enter_shell_cmd(shellcmd, waittime=0, printresult=1):
88    if shellcmd == "":
89        return
90    cmd = "hdc_std -t {} shell \"{}\"".format(args.device_num, shellcmd)
91    return enter_cmd(cmd, waittime, printresult)
92
93
94def sys_exit():
95    enter_shell_cmd("cd /data/log/faultlog/temp && tar -cf after_test_cppcrash{}.tar cppcrash*".format(args.device_num))
96    file_from_dev("/data/log/faultlog/temp/after_test_cppcrash{}.tar".format(args.device_num), \
97    os.path.normpath(args.save_path))
98    enter_shell_cmd("cd /data/log/faultlog/faultlogger && tar -cf after_test_jscrash{}.tar jscrash*".format(args.device_num))
99    file_from_dev("/data/log/faultlog/faultlogger/after_test_jscrash{}.tar".format(args.device_num), \
100    os.path.normpath(args.save_path))
101    print_to_log("SmokeTest:: SmokeTest find some key problems!")
102    print_to_log("SmokeTest:: End of check, test failed!")
103    sys.exit(98)
104
105
106def file_to_dev(src, dst):
107    cmd = "hdc_std -t {} file send \"{}\" \"{}\"".format(args.device_num, src, dst)
108    return enter_cmd(cmd, 1, 1)
109
110
111def file_from_dev(src, dst):
112    cmd = "hdc_std -t {} file recv \"{}\" \"{}\"".format(args.device_num, src, dst)
113    return enter_cmd(cmd, 1, 1)
114
115
116def connect_check():
117    connection_status = enter_cmd("hdc_std list targets", 2)
118    connection_cnt = 0
119    while args.device_num not in connection_status and connection_cnt < 15:
120        connection_status = enter_cmd("hdc_std list targets", 2)
121        connection_cnt += 1
122    if connection_cnt == 15:
123        print_to_log("SmokeTest:: Device disconnection!!")
124        print_to_log("SmokeTest:: End of check, test failed!")
125        sys.exit(101)
126
127
128def sandbox_check(process):
129    print_to_log("SmokeTest:: start to check sandbox path")
130    medialibrarydata_pidnum = enter_shell_cmd("pgrep -f {}".format(process), 1)
131    medialibrarydata_pidnum = medialibrarydata_pidnum.strip()
132    sandboxf = enter_shell_cmd("echo \"ls /storage/media/local/\"|nsenter -t {} -m sh".format(medialibrarydata_pidnum), 1)
133    if "files" not in sandboxf:
134        print_to_log("SmokeTest:: error: can not find sandbox path : /storage/media/local/files")
135        return -1
136    else:
137        print_to_log("SmokeTest:: success: find sandbox path : /storage/media/local/files")
138        return 1
139
140
141def get_coordinate(path, target):
142    wifi_numbers = 8
143    height = 97
144    wifi_range = [236, 286, 45, 300]
145    coordinate = []
146    img = cv2.imread(path)
147    tessdata_dir_config = '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata"'
148    while wifi_numbers:
149        wifi_range[0] += height
150        wifi_range[1] += height
151        print_to_log(wifi_range)
152        data_img = img[wifi_range[0]:wifi_range[1], wifi_range[2]:wifi_range[3]]
153        data = pytesseract.image_to_data(data_img, output_type=Output.DICT, config=tessdata_dir_config, lang='eng')
154        for i in range(len(data['text'])):
155            if data['text'][i] == target:
156                dx = int((wifi_range[2] + wifi_range[3]) / 2)
157                dy = int((wifi_range[0] + wifi_range[1]) / 2)
158                coordinate.append(dx)
159                coordinate.append(dy)
160        wifi_numbers -= 1
161        if coordinate:
162            break
163    return coordinate
164
165
166def connect_wifi(prefix, pic):
167    try:
168        data = get_coordinate("{}\\{}_{}".format(args.save_path, prefix, pic), "testapold")
169        enter_shell_cmd("uinput -M -m {} {} -c 0".format(data[0], data[1]), WAIT_TIME_TWO)
170        enter_shell_cmd("uinput -M -m 360 200 -c 0")
171        enter_shell_cmd("uinput -M -m 680 810 -c 0", WAIT_TIME_ONE)
172        enter_shell_cmd("uinput -M -m 80 910 -c 0", WAIT_TIME_ONE)
173        enter_shell_cmd("uinput -M -m 150 910 -c 0", WAIT_TIME_ONE)
174        enter_shell_cmd("uinput -M -m 150 910 -c 0", WAIT_TIME_ONE)
175        enter_shell_cmd("uinput -M -m 110 810 -c 0", WAIT_TIME_ONE)
176        enter_shell_cmd("uinput -M -m 50 1150 -c 0", WAIT_TIME_TWO)
177        enter_shell_cmd("uinput -M -m 680 810 -c 0", WAIT_TIME_ONE)
178        enter_shell_cmd("uinput -M -m 50 1150 -c 0", WAIT_TIME_TWO)
179        enter_shell_cmd("uinput -M -m 250 810 -c 0", WAIT_TIME_ONE)
180        enter_shell_cmd("uinput -M -m 220 910 -c 0", WAIT_TIME_ONE)
181        enter_shell_cmd("uinput -M -m 50 1150 -c 0", WAIT_TIME_TWO)
182        enter_shell_cmd("uinput -M -m 40 810 -c 0", WAIT_TIME_ONE)
183        enter_shell_cmd("uinput -M -m 500 1020 -c 0", WAIT_TIME_ONE)
184        enter_shell_cmd("uinput -M -m 50 1150 -c 0", WAIT_TIME_ONE)
185        enter_shell_cmd("uinput -M -m 680 690 -c 0")
186        enter_shell_cmd("snapshot_display -f /data/screen_test/{}".format("testapold.jpeg"))
187        file_from_dev("/data/screen_test/{}".format("testapold.jpeg"), args.save_path)
188        enter_shell_cmd("uinput -M -m 550 680 -c 0", single_action[0])
189    except Exception as e:
190        print(e)
191        print_to_log("SmokeTest:: wifi list loading errror!")
192
193
194def calculate(image1, image2):
195    image1 = cv2.cvtColor(numpy.asarray(image1), cv2.COLOR_RGB2BGR)
196    image2 = cv2.cvtColor(numpy.asarray(image2), cv2.COLOR_RGB2BGR)
197    hist1 = cv2.calcHist([image1], [0], None, [256], [0.0, 255.0])
198    hist2 = cv2.calcHist([image2], [0], None, [256], [0.0, 255.0])
199    degree = 0
200    for i in range(len(hist1)):
201        if hist1[i] != hist2[i]:
202            degree = degree + (1 - abs(hist1[i] - hist2[i]) / max(hist1[i], hist2[i]))
203        else:
204            degree = degree + 1
205    degree = degree / len(hist1)
206    return degree
207
208
209def classify_hist_with_split(image1, image2, size=(256, 256)):
210    image1 = Image.open(image1)
211    image2 = Image.open(image2)
212    image1 = cv2.cvtColor(numpy.asarray(image1), cv2.COLOR_RGB2BGR)
213    image2 = cv2.cvtColor(numpy.asarray(image2), cv2.COLOR_RGB2BGR)
214    image1 = cv2.resize(image1, size)
215    image2 = cv2.resize(image2, size)
216    sub_image1 = cv2.split(image1)
217    sub_image2 = cv2.split(image2)
218    sub_data = 0
219    for im1, im2 in zip(sub_image1, sub_image2):
220        sub_data += calculate(im1, im2)
221    sub_data = sub_data / 3
222    return sub_data
223
224
225def crop_picture(prefix, pic, crop_range):
226    pic_path = "{}\\{}_{}".format(args.save_path, prefix, pic)
227    save_path = "{}\\{}_{}".format(args.save_path, prefix, pic)
228    im = cv2.imread(pic_path)
229    im = im[crop_range[0]:crop_range[1], crop_range[2]:crop_range[3]]
230    cv2.imwrite(save_path, im)
231
232
233def cmp_picture(prefix, pic, num=1):
234    if num == 1:
235        img1_path = "{}\\{}".format(args.anwser_path, pic)
236    else:
237        img1_path = "{}\\2_{}".format(args.anwser_path, pic)
238    img2_path = "{}\\{}_{}".format(args.save_path, prefix, pic)
239    cmp_init = 0
240    try:
241        cmp_result = classify_hist_with_split(img1_path, img2_path)
242        print("compare result:" + "%.6f%%" % (cmp_result * 100))
243        return cmp_result * 100
244    except Exception as reason:
245        print("no such file: {}_{}".format(prefix, pic))
246        return cmp_init
247
248
249def shot_and_cmp(image):
250    prefix = args.device_num
251    enter_shell_cmd("snapshot_display -f /data/screen_test/{}_{}".format(prefix, image))
252    file_from_dev("/data/screen_test/{}_{}".format(prefix, image), args.save_path)
253    similarity = cmp_picture(prefix, image)
254    print_to_log("SmokeTest:: launcher similarity is {}%".format(similarity))
255    return similarity
256
257
258def distributed_test():
259    if "1/2" in args.test_num or "2/2" in args.test_num:
260        report_path = os.path.normpath(os.path.join(args.save_path, "distributed_report.txt"))
261        if args.test_num == "2/2":
262            enter_shell_cmd("ifconfig eth0 192.168.0.1", WAIT_TIME_ONE)
263            ping_result = enter_shell_cmd("ping 192.168.0.2 -i 1 -c 2", 3)
264            file_is_exist = enter_shell_cmd("cd /data; find . -name distributed_report.txt")
265            ping_cnt = 0
266            wait_cnt = 0
267            while "2 packets transmitted, 2 received" not in ping_result and ping_cnt < 20:
268                ping_result = enter_shell_cmd("ping 192.168.0.2 -i 1 -c 2", WAIT_TIME_FOUR)
269                ping_cnt += 1
270            if ping_cnt == 30:
271                print_to_log("SmokeTest:: Ping failed, timeout of 80s")
272                sys_exit()
273            while "distributed_report.txt" not in file_is_exist and wait_cnt < 30:
274                print_to_log("SmokeTest:: waiting for the distributed test to end ")
275                file_is_exist = enter_shell_cmd("cd /data; find . -name distributed_report.txt", WAIT_TIME_FOUR)
276                wait_cnt += 1
277        elif args.test_num == "1/2":
278            enter_shell_cmd("ifconfig eth0 192.168.0.2", WAIT_TIME_ONE)
279            ping_result = enter_shell_cmd("ping 192.168.0.1 -i 1 -c 2", WAIT_TIME_FOUR)
280            ping_cnt = 0
281            while "2 packets transmitted, 2 received" not in ping_result and ping_cnt < 20:
282                ping_result = enter_shell_cmd("ping 192.168.0.1 -i 1 -c 2", WAIT_TIME_FOUR)
283                ping_cnt += 1
284            if ping_cnt == 30:
285                print_to_log("SmokeTest:: Ping failed, timeout of 80s")
286            print_to_log("SmokeTest:: ##### case 0 : distributed test start #####")
287            execute_path = os.path.normpath(os.path.join(args.tools_path, "resource"))
288            os.system("cd {} && python distributedtest.py --path {}".format(execute_path, args.save_path))
289            distributed_result = ""
290            try:
291                with open(report_path, mode='r', encoding='utf-8', errors='ignore') as f:
292                    f.seek(0)
293                    distributed_result = f.read()
294                f.close()
295            except Exception as reason:
296                print_to_log("SmokeTest:: distributed_report.txt is not exist!")
297            if "distributedcalc" in distributed_result:
298                print_to_log("SmokeTest:: testcase 0, distributed is ok!")
299            else:
300                print_to_log("SmokeTest:: error:testcase 0, distributed failed!")
301                sys_exit()
302        enter_shell_cmd("ifconfig eth0 down", WAIT_TIME_ONE)
303
304
305def open_wlan():
306    enter_shell_cmd("aa start -a com.ohos.settings.MainAbility -b com.ohos.settings", WAIT_TIME_FOUR)
307    enter_shell_cmd("uinput -M -m 300 300 -c 0", WAIT_TIME_TWO)
308    enter_shell_cmd("uinput -M -m 640 200 -c 0", WAIT_TIME_FOUR)
309    time.sleep(WAIT_TIME_TWO)
310    enter_shell_cmd("killall com.ohos.settings", WAIT_TIME_TWO)
311
312
313if __name__ == "__main__":
314    parser = argparse.ArgumentParser(description='manual to this script')
315    parser.add_argument('--config', type=str, default = '.\\app_capture_screen_test_config.json')
316    parser.add_argument('--test_num', type=str, default = '1/1')
317    parser.add_argument('--tools_path', type=str, default = 'D:\\DeviceTestTools\\screenshot\\')
318    parser.add_argument('--anwser_path', type=str, default = 'D:\\DeviceTestTools\\screenshot\\resource')
319    parser.add_argument('--save_path', type=str, default = 'D:\\DeviceTestTools\\screenshot')
320    parser.add_argument('--device_num', type=str, default = 'null')
321    parser.add_argument('--pr_url', type=str, default = 'developtools_integration_verification')
322    args = parser.parse_args()
323
324    if args.device_num == 'null':
325        result = enter_cmd("hdc_std list targets", 1, 0)
326        print(result)
327        args.device_num = result.split()[0]
328    with open(args.config) as f:
329        all_app = json.load(f)
330    cmp_status = 0
331    global_pos = all_app[0]
332
333    WAIT_TIME_ONE = 1
334    WAIT_TIME_TWO = 2
335    WAIT_TIME_FOUR = 4
336
337    reboot_cnt = 2
338    while reboot_cnt:
339        reboot_cnt -= 1
340        enter_shell_cmd("mkdir -p /data/screen_test/train_set")
341        rmlock_cnt = 3
342        while rmlock_cnt:
343            enter_shell_cmd("uinput -T -m 425 1000 425 400;power-shell wakeup;uinput -T -m 425 400 425 1000;\
344            power-shell setmode 602;uinput -T -m 425 1000 425 400;", WAIT_TIME_ONE)
345            rmlock_cnt -= 1
346        enter_shell_cmd("hilog -w stop", WAIT_TIME_ONE)
347        enter_shell_cmd("cd /data/log/hilog && tar -cf system_start_log_{}.tar *".format(args.device_num), WAIT_TIME_ONE)
348        file_from_dev("/data/log/hilog/system_start_log_{}.tar".format(args.device_num), args.save_path)
349        connect_check()
350        launcher_similarity = shot_and_cmp("launcher.jpeg")
351        if launcher_similarity >= 90:
352            print_to_log("SmokeTest:: launcher screenshot comparison is ok!")
353            break
354        elif reboot_cnt >= 1:
355            print_to_log("SmokeTest:: launcher screenshot comparison failed, reboot and try!!!")
356            enter_shell_cmd("rm -rf /data/*;reboot")
357            for i in range(5):
358                enter_cmd("hdc_std list targets", 10)
359        else:
360            print_to_log("SmokeTest:: launcher screenshot comparison failed")
361            sys_exit()
362
363    enter_shell_cmd("cat /proc/`pidof foundation`/smaps_rollup")
364
365    print_to_log("\nSmokeTest:: ########## First check key processes start ##############")
366    lose_process = []
367    process_pid = {}
368    with open(os.path.normpath(os.path.join(args.tools_path, "resource/process.txt")), "r+") as f:
369        text = f.read()
370        two_check_process_list = text.split('#####')[1].split()[0:-1]
371        other_process_list = text.split('#####')[2].split()
372        for pname in two_check_process_list:
373            pids = enter_cmd("hdc_std -t {} shell pidof {}".format(args.device_num, pname), 0, 1)
374            try:
375                pidlist = pids.split()
376                int(pidlist[0])
377                for pid in pidlist:
378                    int(pid)
379                process_pid[pname] = pidlist
380            except:
381                lose_process.append(pname)
382        all_p = enter_shell_cmd("ps -elf")
383        for pname in other_process_list:
384            findp = all_p.find(pname, 0, len(all_p))
385            if findp == -1:
386                lose_process.append(pname)
387
388    if lose_process:
389        print_to_log("SmokeTest:: error: %s, These processes are not exist!!!" % lose_process)
390        sys_exit()
391    else:
392        print_to_log("SmokeTest:: first processes check is ok")
393
394    power_state = enter_shell_cmd("hidumper -s 3308", WAIT_TIME_ONE)
395    if "State=2" not in power_state:
396        print_to_log("SmokeTest:: DISPLAY POWER MANAGER DUMP State=0")
397        sys_exit()
398
399    open_wlan()
400
401    special_warehouse = [
402        "arkui_ace_engine",
403        "developtools_integration_verification",
404        "graphic_graphic_2d",
405        "windowmanager"]
406
407    for warehouse in special_warehouse:
408        if warehouse in args.pr_url:
409            if args.test_num == "1/2":
410                args.test_num = "3/2"
411            elif args.test_num == "2/2":
412                args.test_num = "4/2"
413    print(args.pr_url)
414    try:
415        args.test_num.index('/')
416        idx_total = args.test_num.split('/')
417        if len(idx_total) != 2:
418            print_to_log("SmokeTest:: test_num is invaild !!!")
419            sys_exit()
420        elif idx_total[1] == '1':
421            idx_list = list(range(1, len(all_app)))
422        else:
423            idx_list = global_pos['DEVICE_{}'.format(idx_total[0])]
424    except ValueError as e:
425        print_to_log(e)
426        idx_list = list(map(eval, args.test_num.split()))
427    print_to_log("SmokeTest:: start to carry out the following testcases: ")
428    print_to_log("SmokeTest:: testcase number: {} ".format(idx_list))
429
430    fail_idx_list = []
431    fail_name_list = []
432    smoke_first_failed = ''
433    for idx in idx_list:
434        single_app = all_app[idx]
435        sys.stdout.flush()
436        call_app_cmd = single_app['entry']
437        capture_screen_cmd = "snapshot_display -f /data/screen_test/{}_{}"
438        print_to_log("\nSmokeTest:: ##### case {} : {} test start #####".format(idx, single_app['app_name']))
439        with open(os.path.join(args.save_path, 'test_{}.bat'.format(args.device_num)),\
440        mode='a', encoding='utf-8') as cmd_f:
441            cmd_f.write("\nSmokeTest::::::case {} --- {} test start \n".format(idx, single_app['app_name']))
442        cmd_f.close()
443        testcnt = 3
444        while testcnt:
445            testok = 0
446            if testcnt != 3:
447                print_to_log("SmokeTest:: this testcase try again >>>>>>:\n")
448                with open(os.path.join(args.save_path, 'test_{}.bat'.format(args.device_num)),\
449                mode='a', encoding='utf-8') as cmd_f:
450                    cmd_f.write("\nSmokeTest::::::Last failed, try again \n")
451                cmd_f.close()
452            if idx == 1:
453                testcnt = 1
454            if single_app['entry'] != "":
455                enter_shell_cmd(call_app_cmd, WAIT_TIME_FOUR)
456            print_to_log("SmokeTest:: execute command {}".format(single_app['all_actions']))
457            prefix = args.device_num
458            raw_pic_name = ''
459            pic_name = ''
460            for single_action in single_app['all_actions']:
461                if type(single_action[1]) == str and single_action[1] == 'shot_cmd':
462                    if len(single_action) == 3:
463                        pic_name = "{}{}".format(single_action[2], ".jpeg")
464                    else:
465                        pic_name = "{}{}".format(single_app['app_name'], ".jpeg")
466                    enter_shell_cmd("rm /data/screen_test/*{}".format(pic_name), WAIT_TIME_ONE)
467                    enter_shell_cmd(capture_screen_cmd.format(prefix, pic_name), WAIT_TIME_ONE)
468                    file_from_dev("/data/screen_test/{}_{}".format(prefix, pic_name), args.save_path)
469                    next_cmd = ""
470                elif type(single_action[1]) == str and single_action[1] == 'cmp_twice':
471                    next_cmd = ""
472                    sys.stdout.flush()
473                    pic = "{}{}".format(single_action[2], ".jpeg")
474                    similarity = single_action[3]
475                    crop_range = single_app[single_action[4]]
476                    crop_picture(prefix, pic, crop_range)
477                    first_similarity = cmp_picture(prefix, pic)
478                    second_similarity = cmp_picture(prefix, pic, WAIT_TIME_TWO)
479                    print_to_log("SmokeTest:: first picture similarity is {}%".format(first_similarity))
480                    print_to_log("SmokeTest:: second picture similarity is {}%".format(second_similarity))
481                    if first_similarity >= similarity or second_similarity >= similarity:
482                        if testok != -1:
483                            testok = 1
484                        print_to_log("SmokeTest:: {} screenshot check is ok".format(pic))
485                    else:
486                        testok = -1
487                        print_to_log("SmokeTest:: {} screenshot check is abnarmal".format(pic))
488                elif type(single_action[1]) == str and single_action[1] == 'cmp_cmd-level':
489                    next_cmd = ""
490                    sys.stdout.flush()
491                    if len(single_action) == 4:
492                        similarity = single_action[3]
493                    else:
494                        similarity = global_pos['cmp_cmd-level'][1]
495                        similarity = int(similarity)
496                    print_to_log("SmokeTest:: start to contrast screenshot")
497                    pic = "{}{}".format(single_action[2], ".jpeg")
498                    crop_range = [80, 1200, 0, 720]
499                    crop_picture(prefix, pic, crop_range)
500                    pic_similarity = cmp_picture(prefix, pic)
501                    print_to_log("SmokeTest:: picture similarity is {}%".format(pic_similarity))
502                    if len(single_action) >= 3:
503                        if pic_similarity >= similarity:
504                            if testok != -1:
505                                testok = 1
506                            print_to_log("SmokeTest:: {} screenshot check is ok".format(pic))
507                        else:
508                            testok = -1
509                            print_to_log("SmokeTest:: {} screenshot check is abnarmal".format(pic))
510                elif type(single_action[1]) == str and single_action[1] == 'install_hap':
511                    next_cmd = ""
512                    if len(single_action) == 3:
513                        enter_cmd("hdc_std -t {} install \"{}\"".format(args.device_num,\
514                        os.path.normpath(os.path.join(args.tools_path, single_action[2]))))
515                elif type(single_action[1]) == str and single_action[1] == 'get_file_from_dev':
516                    next_cmd = ""
517                    if len(single_action) == 3:
518                        enter_cmd("hdc_std -t {} file recv \"{}\" \"{}\"".format(args.device_num,\
519                        single_action[2], os.path.normpath(args.save_path)))
520                elif type(single_action[1]) == str and single_action[1] == 'send_file_to_dev':
521                    next_cmd = ""
522                    if len(single_action) == 4:
523                        enter_cmd("hdc_std -t {} file send \"{}\" \"{}\"".format(args.device_num,\
524                        os.path.normpath(os.path.join(args.tools_path, single_action[2])), single_action[3]))
525                elif type(single_action[1]) == str and single_action[1] == 'connect_wifi':
526                    next_cmd = ""
527                    pic = "{}{}".format(single_action[2], ".jpeg")
528                    connect_wifi(prefix, pic)
529                elif type(single_action[1]) == str and single_action[1] == 'sandbox_path_check':
530                    next_cmd = ""
531                    if sandbox_check("com.ohos.medialibrary.medialibrarydata") == 1 and testok == 1:
532                        testok = 1
533                    else:
534                        testok = -1
535                elif type(single_action[1]) == str and single_action[1] == 'process_crash_check':
536                    next_cmd = ""
537                    if len(single_action) == 3:
538                        p = enter_shell_cmd("cd /data/log/faultlog/temp && grep \"Process name\" -rnw ./",\
539                        single_action[0])
540                        result = "".join(p)
541                        findsome = result.find(single_action[2], 0, len(result))
542                        if findsome != -1:
543                            testok = -1
544                            print_to_log("SmokeTest:: \"{}\" error:find fatal crash \"{}\"!".format(single_action[1],\
545                            single_action[2]))
546                            sys_exit()
547                        else:
548                            testok = 1
549                            print_to_log("SmokeTest:: \"{}\" result is ok, not find fatal\
550                            crash \"{}\"!".format(single_action[1], single_action[2]))
551                        sys.stdout.flush()
552                elif type(single_action[1]) == str:
553                    if single_action[1] not in single_app.keys():
554                        target_ = global_pos[single_action[1]]
555                    else:
556                        target_ = single_app[single_action[1]]
557                    if type(target_[0]) == str:
558                        next_cmd = ""
559                        p = enter_shell_cmd(target_[0], single_action[0])
560                        result = "".join(p)
561                        if len(target_) > 1:
562                            findsome = result.find(target_[1], 0, len(result))
563                            if findsome != -1:
564                                testok = 1
565                                print_to_log("SmokeTest:: \"{}\" check result is ok, find \"{}\"!".format(target_[0],\
566                                target_[1]))
567                            else:
568                                testok = -1
569                                print_to_log("SmokeTest:: \"{}\" result is not ok, not find \"{}\"!".format(target_[0],\
570                                target_[1]))
571                            sys.stdout.flush()
572                    else:
573                        next_cmd = "uinput -M -m {} {} -c 0".format(target_[0], target_[1])
574                else:
575                    next_cmd = "uinput -M -m {} {} -c 0".format(single_action[1], single_action[2])
576                enter_shell_cmd(next_cmd, single_action[0])
577
578            if testok == 1:
579                print_to_log("SmokeTest:: testcase {}, {} is ok!".format(idx, single_app['app_name']))
580                testcnt = 0
581            elif testok == -1 and smoke_first_failed == '':
582                if testcnt == 1:
583                    fail_idx_list.append(idx)
584                    fail_name_list.append(single_app['app_name'])
585                    smoke_first_failed = single_app['app_name']
586                    print_to_log("SmokeTest:: error:testcase {}, {} is failed!".format(idx, single_app['app_name']))
587                testcnt -= 1
588            elif testok == -1 and smoke_first_failed != '':
589                fail_idx_list.append(idx)
590                fail_name_list.append(single_app['app_name'])
591                print_to_log("SmokeTest:: error:testcase {}, {} is failed!".format(idx, single_app['app_name']))
592                testcnt = 0
593            else:
594                testcnt = 0
595            connect_check()
596
597    enter_shell_cmd("cd /data/log/faultlog/temp && grep \"Process name\" -rnw ./", 1)
598    enter_shell_cmd("cd /data/log/faultlog/faultlogger && grep \"Process name\" -rnw ./", 1)
599
600    fail_str_list = [str(x) for x in fail_idx_list]
601    reboot_test_num = " ".join(fail_str_list)
602    if len(fail_idx_list) != 0:
603        print_to_log("SmokeTest:: failed testcase number: {} ".format(fail_str_list))
604        print_to_log("SmokeTest:: check \"reboot\" in reboot.txt".format(args.save_path))
605        with open(os.path.normpath(os.path.join(args.tools_path, "reboot.txt")), mode='a+') as f:
606            f.seek(0)
607            reboot_result = f.read()
608        f.close()
609        if len(reboot_result) < 1 and reboot_cnt >= 1:
610            print_to_log("SmokeTest:: \"reboot\" is not found in the reboot.txt")
611            print_to_log("SmokeTest:: the device will reboot and try the failed testcase")
612            print_to_log("SmokeTest:: mkdir {}\\reboot".format(args.save_path))
613            os.system("mkdir {}\\reboot".format(args.save_path))
614            print_to_log("SmokeTest:: write \"reboot\" into reboot.txt".format(args.save_path))
615            with open(os.path.normpath(os.path.join(args.tools_path, "reboot.txt")), mode='w') as f:
616                f.write("reboot")
617            f.close()
618            print_to_log("SmokeTest:: error: name {}, index {}, failed, rm /data/* and reboot".format(fail_name_list,\
619            fail_idx_list))
620            enter_shell_cmd("rm -rf /data/* && reboot")
621            reboot_result_list = enter_cmd("hdc_std list targets", 2)
622            number = 0
623            while args.device_num not in reboot_result_list and number < 15:
624                reboot_result_list = enter_cmd("hdc_std list targets", 2)
625                number += 1
626            enter_shell_cmd("rm /data/log/hilog/*;hilog -r;hilog -w start -l 400000000 -m none", 1)
627            py_cmd = os.system("python {}\\resource\\capturescreentest.py --config \
628            {}\\resource\\app_capture_screen_test_config.json --anwser_path {} \
629            --save_path {}\\reboot --tools_path {} --device_num {} --test_num \"{}\"".format(args.tools_path, \
630            args.tools_path, args.anwser_path, args.save_path, args.tools_path, args.device_num, reboot_test_num))
631            if py_cmd == 0:
632                sys.exit(0)
633            elif py_cmd == 98:
634                sys.exit(98)
635            else:
636                sys.exit(101)
637        else:
638            print_to_log("SmokeTest:: error: name {}, index {}, these testcase is failed".format(fail_name_list,\
639            fail_idx_list))
640            sys_exit()
641    else:
642        print_to_log("SmokeTest:: all testcase is ok")
643        print_to_log("SmokeTest:: End of check, test succeeded!")
644        sys.exit(0)
645