• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright (C) 2024 Huawei Device Co., Ltd.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15# 运行环境: python 3.10+, pytest, pytest-repeat, pytest-testreport
16# 准备文件:package.zip
17# pip install pytest pytest-testreport pytest-repeat
18# python hdc_normal_test.py
19
20
21import argparse
22import time
23import os
24import multiprocessing
25
26import pytest
27
28from dev_hdc_test import GP
29from dev_hdc_test import check_library_installation, check_hdc_version, check_cmd_time
30from dev_hdc_test import check_hdc_cmd, check_hdc_targets, get_local_path, get_remote_path, run_command_with_timeout
31from dev_hdc_test import check_app_install, check_app_uninstall, prepare_source, pytest_run, update_source, check_rate
32from dev_hdc_test import make_multiprocess_file, rmdir, get_shell_result
33from dev_hdc_test import check_app_install_multi, check_app_uninstall_multi
34from dev_hdc_test import check_rom, check_shell, check_shell_any_device, check_cmd_block
35
36
37def test_hdc_server_foreground():
38    port = os.getenv('OHOS_HDC_SERVER_PORT')
39    if port is None:
40        port = 8710
41    assert check_hdc_cmd("kill", "Kill server finish")
42    assert check_cmd_block(f"{GP.hdc_exe} -m", f"port: {port}", timeout=5)
43    assert check_hdc_cmd("start")
44    time.sleep(3) # sleep 3s to wait for the device to connect channel
45
46
47def test_list_targets():
48    assert check_hdc_targets()
49    assert check_hdc_cmd("shell rm -rf data/local/tmp/it_*")
50    assert check_hdc_cmd("shell mkdir data/local/tmp/it_send_dir")
51
52
53def test_usb_disconnect():
54    assert check_hdc_targets()
55    cmd = 'shell "kill -9 `pidof hdcd`"'
56    check_hdc_cmd(f"{cmd}", "[Fail][E001003] USB communication abnormal, please check the USB communication link.")
57    time.sleep(2)
58    assert check_hdc_targets()
59
60
61def test_list_targets_multi_usb_device():
62    devices_str = check_shell_any_device(f"{GP.hdc_exe} list targets", None, True)
63    time.sleep(3) # sleep 3s to wait for the device to connect channel
64    devices_array = devices_str[1].split('\n')
65    if devices_array:
66        for device in devices_array:
67            if len(device) > 8:
68                assert check_shell_any_device(f"{GP.hdc_exe} -t {device} shell id", "u:r:")[0]
69
70
71@pytest.mark.repeat(5)
72def test_empty_file():
73    assert check_hdc_cmd(f"file send {get_local_path('empty')} {get_remote_path('it_empty')}")
74    assert check_hdc_cmd(f"file recv {get_remote_path('it_empty')} {get_local_path('empty_recv')}")
75
76
77@pytest.mark.repeat(5)
78def test_empty_dir():
79    assert check_shell(f"file send {get_local_path('empty_dir')} {get_remote_path('it_empty_dir')}",
80        "the source folder is empty")
81    assert check_hdc_cmd("shell mkdir data/local/tmp/it_empty_dir_recv")
82    assert check_shell(f"file recv {get_remote_path('it_empty_dir_recv')} {get_local_path('empty_dir_recv')}",
83        "the source folder is empty")
84
85
86@pytest.mark.repeat(5)
87def test_long_path():
88    assert check_hdc_cmd(f"file send {get_local_path('deep_test_dir')} {get_remote_path('it_send_dir')}",
89                         is_single_dir=False)
90    assert check_hdc_cmd(f"file recv {get_remote_path('it_send_dir/deep_test_dir')} {get_local_path('recv_test_dir')}",
91                         is_single_dir=False)
92
93
94@pytest.mark.repeat(5)
95def test_small_file():
96    assert check_hdc_cmd(f"file send {get_local_path('small')} {get_remote_path('it_small')}")
97    assert check_hdc_cmd(f"file recv {get_remote_path('it_small')} {get_local_path('small_recv')}")
98
99
100@pytest.mark.repeat(1)
101def test_node_file():
102    assert check_hdc_cmd(f"file recv {get_remote_path('../../../sys/power/state')} {get_local_path('state')}")
103    assert check_hdc_cmd(f"file recv {get_remote_path('../../../sys/firmware/fdt')} {get_local_path('fdt')}")
104    assert check_hdc_cmd(f"file recv {get_remote_path('../../../proc/cpuinfo')} {get_local_path('cpuinfo')}")
105
106
107@pytest.mark.repeat(1)
108def test_medium_file():
109    assert check_hdc_cmd(f"file send {get_local_path('medium')} {get_remote_path('it_medium')}")
110    assert check_hdc_cmd(f"file recv {get_remote_path('it_medium')} {get_local_path('medium_recv')}")
111
112
113@pytest.mark.repeat(1)
114def test_large_file():
115    assert check_hdc_cmd(f"file send {get_local_path('large')} {get_remote_path('it_large')}")
116    assert check_hdc_cmd(f"file recv {get_remote_path('it_large')} {get_local_path('large_recv')}")
117
118
119@pytest.mark.repeat(1)
120def test_running_file():
121    assert check_hdc_cmd(f"file recv system/bin/hdcd {get_local_path('running_recv')}")
122
123
124@pytest.mark.repeat(1)
125def test_rate():
126    assert check_rate(f"file send {get_local_path('large')} {get_remote_path('it_large')}", 18000)
127    assert check_rate(f"file recv {get_remote_path('it_large')} {get_local_path('large_recv')}", 18000)
128
129
130@pytest.mark.repeat(1)
131def test_file_error():
132    assert check_hdc_cmd("target mount")
133    assert check_shell(
134        f"file send {get_local_path('small')} system/bin/hdcd",
135        "busy"
136    )
137    assert check_shell(
138        f"file recv",
139        "[Fail]There is no local and remote path"
140    )
141    assert check_shell(
142        f"file send",
143        "[Fail]There is no local and remote path"
144    )
145    assert check_hdc_cmd(f"shell rm -rf {get_remote_path('../../../large')}")
146    assert check_hdc_cmd(f"shell param set persist.hdc.control.file false")
147    assert check_shell(
148        f"file send {get_local_path('small')} {get_remote_path('it_small_false')}",
149        "debugging is not allowed"
150    )
151    assert check_hdc_cmd(f"shell param set persist.hdc.control.file true")
152    assert check_hdc_cmd(f"file send {get_local_path('small')} {get_remote_path('it_small_true')}")
153
154
155@pytest.mark.repeat(5)
156def test_recv_dir():
157    if os.path.exists(get_local_path('it_problem_dir')):
158        rmdir(get_local_path('it_problem_dir'))
159    assert check_hdc_cmd(f"shell rm -rf {get_remote_path('it_problem_dir')}")
160    assert check_hdc_cmd(f"shell rm -rf {get_remote_path('problem_dir')}")
161    assert make_multiprocess_file(get_local_path('problem_dir'), get_remote_path(''), 'send', 1, "dir")
162    assert check_hdc_cmd(f"shell mv {get_remote_path('problem_dir')} {get_remote_path('it_problem_dir')}")
163    assert make_multiprocess_file(get_local_path(''), get_remote_path('it_problem_dir'), 'recv', 1, "dir")
164
165
166@pytest.mark.repeat(5)
167def test_hap_install():
168    assert check_hdc_cmd(f"install -r {get_local_path('entry-default-signed-debug.hap')}",
169                            bundle="com.hmos.diagnosis")
170
171
172@pytest.mark.repeat(5)
173def test_install_hap():
174    package_hap = "entry-default-signed-debug.hap"
175    app_name_default = "com.hmos.diagnosis"
176
177    # default
178    assert check_app_install(package_hap, app_name_default)
179    assert check_app_uninstall(app_name_default)
180
181    # -r
182    assert check_app_install(package_hap, app_name_default, "-r")
183    assert check_app_uninstall(app_name_default)
184
185    # -k
186    assert check_app_install(package_hap, app_name_default, "-r")
187    assert check_app_uninstall(app_name_default, "-k")
188
189    # -s
190    assert check_app_install(package_hap, app_name_default, "-s")
191
192
193@pytest.mark.repeat(5)
194def test_install_hsp():
195    package_hsp = "libA_v10001.hsp"
196    hsp_name_default = "com.example.liba"
197
198    assert check_app_install(package_hsp, hsp_name_default, "-s")
199    assert check_app_uninstall(hsp_name_default, "-s")
200    assert check_app_install(package_hsp, hsp_name_default)
201
202
203@pytest.mark.repeat(5)
204def test_install_multi_hap():
205    # default multi hap
206    tables = {
207        "entry-default-signed-debug.hap" : "com.hmos.diagnosis",
208        "ActsAudioRecorderJsTest.hap" : "ohos.acts.multimedia.audio.audiorecorder"
209    }
210    assert check_app_install_multi(tables)
211    assert check_app_uninstall_multi(tables)
212    assert check_app_install_multi(tables, "-s")
213
214    # default multi hap -r -k
215    tables = {
216        "entry-default-signed-debug.hap" : "com.hmos.diagnosis",
217        "ActsAudioRecorderJsTest.hap" : "ohos.acts.multimedia.audio.audiorecorder"
218    }
219    assert check_app_install_multi(tables, "-r")
220    assert check_app_uninstall_multi(tables, "-k")
221
222
223@pytest.mark.repeat(5)
224def test_install_multi_hsp():
225    # default multi hsp -s
226    tables = {
227        "libA_v10001.hsp" : "com.example.liba",
228        "libB_v10001.hsp" : "com.example.libb",
229    }
230    assert check_app_install_multi(tables, "-s")
231    assert check_app_uninstall_multi(tables, "-s")
232    assert check_app_install_multi(tables)
233
234
235@pytest.mark.repeat(5)
236def test_install_hsp_and_hap():
237    #default multi hsp and hsp
238    tables = {
239        "libA_v10001.hsp" : "com.example.liba",
240        "entry-default-signed-debug.hap" : "com.hmos.diagnosis",
241    }
242    assert check_app_install_multi(tables)
243    assert check_app_install_multi(tables, "-s")
244
245
246@pytest.mark.repeat(5)
247def test_install_dir():
248    package_haps_dir = "app_dir"
249    app_name_default = "com.hmos.diagnosis"
250    assert check_app_install(package_haps_dir, app_name_default)
251    assert check_app_uninstall(app_name_default)
252
253
254def test_server_kill():
255    assert check_hdc_cmd("kill", "Kill server finish")
256    assert check_hdc_cmd("start server")
257    time.sleep(3) # sleep 3s to wait for the device to connect channel
258    assert check_hdc_cmd("checkserver", "Ver")
259
260
261def test_target_cmd():
262    assert check_hdc_targets()
263    check_hdc_cmd("target boot")
264    start_time = time.time()
265    run_command_with_timeout(f"{GP.hdc_head} wait", 30) # reboot takes up to 30 seconds
266    time.sleep(3) # sleep 3s to wait for the device to boot
267    run_command_with_timeout(f"{GP.hdc_head} wait", 30) # reboot takes up to 30 seconds
268    end_time = time.time()
269    print(f"command exec time {end_time - start_time}")
270    time.sleep(3) # sleep 3s to wait for the device to connect channel
271    assert (end_time - start_time) > 8 # Reboot takes at least 8 seconds
272
273
274@pytest.mark.repeat(1)
275def test_file_switch_off():
276    assert check_hdc_cmd("shell param set persist.hdc.control.file false")
277    assert check_shell(f"shell param get persist.hdc.control.file", "false")
278    assert check_shell(f"file send {get_local_path('small')} {get_remote_path('it_small')}",
279                       "debugging is not allowed")
280    assert check_shell(f"file recv {get_remote_path('it_small')} {get_local_path('small_recv')}",
281                       "debugging is not allowed")
282
283
284@pytest.mark.repeat(1)
285def test_file_switch_on():
286    assert check_hdc_cmd("shell param set persist.hdc.control.file true")
287    assert check_shell(f"shell param get persist.hdc.control.file", "true")
288    assert check_hdc_cmd(f"file send {get_local_path('small')} {get_remote_path('it_small')}")
289    assert check_hdc_cmd(f"file recv {get_remote_path('it_small')} {get_local_path('small_recv')}")
290
291
292def test_target_mount():
293    assert (check_hdc_cmd("target mount", "Mount finish" or "[Fail]Operate need running as root"))
294    remount_vendor = get_shell_result(f'shell "mount |grep /vendor |head -1"')
295    print(remount_vendor)
296    assert "rw" in remount_vendor
297    remount_system = get_shell_result(f'shell "cat proc/mounts | grep /system |head -1"')
298    print(remount_system)
299    assert "rw" in remount_system
300
301
302def test_tmode_port():
303    assert (check_hdc_cmd("tmode port", "Set device run mode successful"))
304    time.sleep(3) # sleep 3s to wait for the device to connect channel
305    run_command_with_timeout(f"{GP.hdc_head} wait", 3) # wait 3s for the device to connect channel
306    time.sleep(3) # sleep 3s to wait for the device to connect channel
307    run_command_with_timeout(f"{GP.hdc_head} wait", 3) # wait 3s for the device to connect channel
308    assert (check_hdc_cmd("tmode port 12345"))
309    time.sleep(3) # sleep 3s to wait for the device to connect channel
310    run_command_with_timeout(f"{GP.hdc_head} wait", 3) # wait 3s for the device to connect channel
311    time.sleep(3) # sleep 3s to wait for the device to connect channel
312    run_command_with_timeout(f"{GP.hdc_head} wait", 3) # wait 3s for the device to connect channel
313    netstat_port = get_shell_result(f'shell "netstat -anp | grep 12345"')
314    print(netstat_port)
315    assert "LISTEN" in netstat_port
316    assert "hdcd" in netstat_port
317
318
319def test_tconn():
320    daemon_port = 58710
321    address = "127.0.0.1"
322    assert (check_hdc_cmd(f"tmode port {daemon_port}"))
323    time.sleep(3) # sleep 3s to wait for the device to connect channel
324    run_command_with_timeout(f"{GP.hdc_head} wait", 3) # wait 3s for the device to connect channel
325    time.sleep(3) # sleep 3s to wait for the device to connect channel
326    run_command_with_timeout(f"{GP.hdc_head} wait", 3) # wait 3s for the device to connect channel
327    assert check_hdc_cmd(f"shell param get persist.hdc.port", f"{daemon_port}")
328    assert check_hdc_cmd(f"fport tcp:{daemon_port} tcp:{daemon_port}", "Forwardport result:OK")
329    assert check_hdc_cmd(f"fport ls ", f"tcp:{daemon_port} tcp:{daemon_port}")
330    assert check_shell(f"tconn {address}:{daemon_port}", "Connect OK", head=GP.hdc_exe)
331    time.sleep(3)
332    assert check_shell("list targets", f"{address}:{daemon_port}", head=GP.hdc_exe)
333    tcp_head = f"{GP.hdc_exe} -t {address}:{daemon_port}"
334    assert check_hdc_cmd(f"file send {get_local_path('medium')} {get_remote_path('it_tcp_medium')}",
335        head=tcp_head)
336    assert check_hdc_cmd(f"file recv {get_remote_path('it_tcp_medium')} {get_local_path('medium_tcp_recv')}",
337        head=tcp_head)
338    assert check_shell(f"tconn {address}:{daemon_port} -remove", head=GP.hdc_exe)
339    assert not check_shell("list targets", f"{address}:{daemon_port}", head=GP.hdc_exe)
340    assert check_hdc_cmd(f"fport rm tcp:{daemon_port} tcp:{daemon_port}", "Remove forward ruler success")
341    assert not check_hdc_cmd(f"fport ls ", f"tcp:{daemon_port} tcp:{daemon_port}")
342
343
344def test_target_key():
345    device_key = get_shell_result(f"list targets").split("\r\n")[0]
346    hdcd_pid = get_shell_result(f"-t {device_key} shell pgrep -x hdcd").split("\r\n")[0]
347    assert hdcd_pid.isdigit()
348
349
350def test_version_cmd():
351    version = "Ver: 2.0.0a"
352    assert check_hdc_version("-v", version)
353    assert check_hdc_version("version", version)
354    assert check_hdc_version("checkserver", version)
355
356
357def test_fport_cmd_output():
358    local_port = 18070
359    remote_port = 11080
360    fport_arg = f"tcp:{local_port} tcp:{remote_port}"
361    assert check_hdc_cmd(f"fport {fport_arg}", "Forwardport result:OK")
362    assert check_shell_any_device(f"netstat -ano", "LISTENING", False)[0]
363    assert check_shell_any_device(f"netstat -ano", f"{local_port}", False)[0]
364    assert check_hdc_cmd(f"fport ls", fport_arg)
365    assert check_hdc_cmd(f"fport rm {fport_arg}", "success")
366
367
368def test_rport_cmd_output():
369    local_port = 17090
370    remote_port = 11080
371    rport_arg = f"tcp:{local_port} tcp:{remote_port}"
372    assert check_hdc_cmd(f"rport {rport_arg}", "Forwardport result:OK")
373    netstat_line = get_shell_result(f'shell "netstat -anp | grep {local_port}"')
374    assert "LISTEN" in netstat_line
375    assert "hdcd" in netstat_line
376    fport_list = get_shell_result(f"fport ls")
377    assert "Reverse" in fport_list
378    assert rport_arg in fport_list
379    assert check_hdc_cmd(f"fport rm {rport_arg}", "success")
380
381
382def test_fport_cmd():
383    fport_list = []
384    rport_list = []
385    start_port = 10000
386    end_port = 10020
387    for i in range(start_port, end_port):
388        fport = f"tcp:{i+100} tcp:{i+200}"
389        rport = f"tcp:{i+300} tcp:{i+400}"
390        localabs = f"tcp:{i+500} localabstract:{f'helloworld.com.app.{i+600}'}"
391        fport_list.append(fport)
392        rport_list.append(rport)
393        fport_list.append(localabs)
394
395    for fport in fport_list:
396        assert check_hdc_cmd(f"fport {fport}", "Forwardport result:OK")
397        assert check_hdc_cmd(f"fport {fport}", "TCP Port listen failed at")
398        assert check_hdc_cmd("fport ls", fport)
399
400    for fport in fport_list:
401        assert check_hdc_cmd(f"fport rm {fport}", "success")
402        assert not check_hdc_cmd("fport ls", fport)
403
404    for rport in rport_list:
405        assert check_hdc_cmd(f"rport {rport}", "Forwardport result:OK")
406        assert check_hdc_cmd(f"rport {rport}", "TCP Port listen failed at")
407        assert check_hdc_cmd("rport ls", rport) or check_hdc_cmd("fport ls", rport)
408
409    for rport in rport_list:
410        assert check_hdc_cmd(f"fport rm {rport}", "success")
411        assert not check_hdc_cmd("rport ls", fport) and not check_hdc_cmd("fport ls", fport)
412
413    task_str1 = "tcp:33333 tcp:33333"
414    assert check_hdc_cmd(f"fport {task_str1}", "Forwardport result:OK")
415    assert check_hdc_cmd(f"fport rm {task_str1}", "success")
416    assert check_hdc_cmd(f"fport {task_str1}", "Forwardport result:OK")
417    assert check_hdc_cmd(f"fport rm {task_str1}", "success")
418
419    task_str2 = "tcp:44444 tcp:44444"
420    assert check_hdc_cmd(f"rport {task_str2}", "Forwardport result:OK")
421    assert check_hdc_cmd(f"fport rm {task_str2}", "success")
422    assert check_hdc_cmd(f"rport {task_str2}", "Forwardport result:OK")
423    assert check_hdc_cmd(f"fport rm {task_str2}", "success")
424
425
426#子进程执行函数
427def new_process_run(cmd):
428    # 重定向 stdout 和 stderr 到 /dev/null
429    with open(os.devnull, 'w') as devnull:
430        old_stdout = os.dup2(devnull.fileno(), 1)  # 重定向 stdout
431        old_stderr = os.dup2(devnull.fileno(), 2)  # 重定向 stderr
432        try:
433            # 这里是子进程的代码,不会有任何输出到控制台
434            check_shell(f'{cmd}')
435        finally:
436            # 恢复原始的 stdout 和 stderr
437            os.dup2(old_stdout, 1)
438            os.dup2(old_stderr, 2)
439
440
441def test_hilog_exit_after_hdc_kill():
442    # 新开进程执行hdc shell hilog,防止阻塞主进程
443    p = multiprocessing.Process(target=new_process_run, args=("shell hilog",))
444    p.start()
445    time.sleep(1)
446    hilog_pid = get_shell_result(f'shell pidof hilog')
447    hilog_pid = hilog_pid.replace("\r\n", "")
448    assert hilog_pid.isdigit()
449    assert check_hdc_cmd(f'kill', "Kill server finish")
450    assert check_hdc_cmd("start")
451    time.sleep(3) # sleep 3s to wait for the device to connect channel
452    run_command_with_timeout(f"{GP.hdc_head} wait", 3) # wait 3s for the device to connect channel
453    hilog_pid2 = get_shell_result(f'shell pidof hilog')
454    assert hilog_pid2 == ''
455    p.join()
456
457
458def test_shell_cmd_timecost():
459    assert check_cmd_time(
460        cmd="shell \"ps -ef | grep hdcd\"",
461        pattern="hdcd",
462        duration=None,
463        times=10)
464
465
466def test_shell_huge_cat():
467    assert check_hdc_cmd(f"file send {get_local_path('word_100M.txt')} {get_remote_path('it_word_100M.txt')}")
468    assert check_cmd_time(
469        cmd=f"shell cat {get_remote_path('it_word_100M.txt')}",
470        pattern=None,
471        duration=10000, # 10 seconds
472        times=10)
473
474
475def test_file_option_bundle_normal():
476    version = "Ver: 3.1.0e"
477    if not check_hdc_version("version", version) or not check_hdc_version("shell hdcd -v", version):
478        print("version does not match, ignore this case")
479    else:
480        data_storage_el2_path = "data/storage/el2/base"
481        check_shell(f"shell rm -rf mnt/debug/100/debug_hap/{GP.debug_app}/{data_storage_el2_path}/it*")
482        check_shell(f"shell mkdir -p mnt/debug/100/debug_hap/{GP.debug_app}/{data_storage_el2_path}")
483
484        # file send & recv test
485        test_resource_list = ['empty', 'medium', 'small', 'problem_dir']
486        for test_item in test_resource_list:
487            if test_item == 'problem_dir' and os.path.exists(get_local_path(f'recv_bundle_{test_item}')):
488                rmdir(get_local_path(f'recv_bundle_{test_item}'))
489
490            assert check_hdc_cmd(f"file send -b {GP.debug_app} "
491                                 f"{get_local_path(f'{test_item}')} {data_storage_el2_path}/it_{test_item}")
492            assert check_hdc_cmd(f"file recv -b {GP.debug_app} {data_storage_el2_path}/it_{test_item} "
493                                 f"{get_local_path(f'recv_bundle_{test_item}')} ")
494
495
496def test_file_option_bundle_error():
497    version = "Ver: 3.1.0e"
498    if not check_hdc_version("version", version) or not check_hdc_version("shell hdcd -v", version):
499        print("version does not match, ignore this case")
500    else:
501        data_storage_el2_path = "data/storage/el2/base"
502        is_user = check_shell("shell id", "uid=2000(shell)")
503        assert check_shell(f"file send -b {GP.debug_app} "
504                           f"{get_local_path('empty_dir')} {get_remote_path('it_empty_dir')}",
505                           "the source folder is empty")
506
507        assert check_shell(f"file send -b {GP.debug_app} ", "There is no local and remote path")
508        assert check_shell(f"file recv -b {GP.debug_app} ", "There is no local and remote path")
509
510        # 报错优先级
511        assert check_shell(f"file send -b ./{GP.debug_app} ", "There is no local and remote path")
512        assert check_shell(f"file recv -b ./{GP.debug_app} ", "There is no local and remote path")
513
514        # 报错优先级
515        assert check_shell(f"file recv -b ", "[E005003]")
516        assert check_shell(f"file send -b ", "[E005003]")
517
518        assert check_shell(f"file send -b ./{GP.debug_app} "
519                    f"{get_local_path('small')} {get_remote_path('it_small')}", "[E005101]")
520        assert check_shell(f"file recv -b ./{GP.debug_app} "
521                    f"{get_local_path('small')} {get_remote_path('it_small')}", "[E005101]")
522
523        # bundle不存在或不符合要求
524        assert check_shell(f"file send -b ./{GP.debug_app} "
525                           f"{get_local_path('small')} {get_remote_path('it_small')}", "[E005101]")
526        assert check_shell(f"file send -b com.AAAA "
527                           f"{get_local_path('small')} {get_remote_path('it_small')}", "[E005101]")
528        assert check_shell(f"file send -b 1 "
529                           f"{get_local_path('small')} {get_remote_path('it_small')}", "[E005101]")
530        assert check_shell(f"file send -b "
531                           f"{get_local_path('small')} {get_remote_path('it_small')}", "There is no remote path")
532        assert check_shell(f"file recv -b ./{GP.debug_app} "
533                           f"{get_remote_path('it_small')} {get_local_path('small_recv')}", "[E005101]")
534        # 逃逸
535        assert check_shell(f"file send -b {GP.debug_app} "
536                           f"{get_local_path('small')} ../../../it_small", "[E005102]")
537        assert check_shell(f"file recv -b {GP.debug_app} ../../../it_small"
538                           f"{get_local_path('small_recv')} ", "[E005102]")
539        assert check_shell(f"file send -b {GP.debug_app} "
540                           f"{get_local_path('small')} {data_storage_el2_path}/../../../../../ ",
541                           "permission denied" if is_user else "[E005102]")
542        assert check_shell(f"file send -b {GP.debug_app} "
543                           f"{get_local_path('small')} {data_storage_el2_path}/aa/bb/cc/ ",
544                           "[E005102]")
545
546
547def test_shell_option_bundle_normal():
548    version = "Ver: 3.1.0e"
549    if not check_hdc_version("version", version) or not check_hdc_version("shell hdcd -v", version):
550        print("version does not match, ignore this case")
551    else:
552        data_storage_el2_path = "data/storage/el2/base"
553        check_shell(f"shell mkdir -p mnt/debug/100/debug_hap/{GP.debug_app}/{data_storage_el2_path}")
554        assert check_shell(f"shell -b {GP.debug_app} pwd", f"mnt/debug/100/debug_hap/{GP.debug_app}")
555        assert check_shell(f"shell -b {GP.debug_app} cd {data_storage_el2_path}; pwd",
556                           f"mnt/debug/100/debug_hap/{GP.debug_app}/{data_storage_el2_path}")
557        check_shell(f"shell -b {GP.debug_app} touch {data_storage_el2_path}/test01")
558        assert not check_shell(f"shell -b {GP.debug_app} touch {data_storage_el2_path}/test01", "denied")
559        assert not check_shell(f"shell -b {GP.debug_app} touch -a {data_storage_el2_path}/test01", "denied")
560        assert check_shell(f"shell -b {GP.debug_app} ls {data_storage_el2_path}/", "test01")
561        assert check_shell(f"shell           -b            {GP.debug_app} echo            123             ",
562                    "123")
563        check_shell(f"shell -b {GP.debug_app} \"echo 123 > {data_storage_el2_path}/test02\"")
564        assert check_shell(f"shell -b {GP.debug_app} cat {data_storage_el2_path}/test02", "123")
565        check_shell(f"shell -b {GP.debug_app} mkdir {data_storage_el2_path}/test03")
566        assert check_shell(f"shell -b {GP.debug_app} stat {data_storage_el2_path}/test03", "Access")
567        check_shell(f"shell -b {GP.debug_app} rm -rf {data_storage_el2_path}/test01 "
568                    f"{data_storage_el2_path}/test02 {data_storage_el2_path}/test03")
569        assert check_shell(f"shell -b {GP.debug_app} ls {data_storage_el2_path}/test01",
570                           "test01: No such file or directory")
571        assert check_shell(f"shell -b {GP.debug_app} ls {data_storage_el2_path}/test02",
572                           "test02: No such file or directory")
573        assert check_shell(f"shell -b {GP.debug_app} ls {data_storage_el2_path}/test03",
574                           "test03: No such file or directory")
575
576
577def test_shell_option_bundle_error():
578    version = "Ver: 3.1.0e"
579    if not check_hdc_version("version", version) or not check_hdc_version("shell hdcd -v", version):
580        print("version does not match, ignore this case")
581    else:
582        # 不存在的bundle名称
583        assert check_shell("shell -b com.XXXX.not.exist.app pwd", "[Fail][E003001]")
584        # 相对路径逃逸1
585        assert check_shell(f"shell -b ../../../../ pwd", "[Fail][E003001")
586        # 相对路径逃逸2
587        assert check_shell(f"shell -b ././././pwd", "[Fail][E003001]")
588        # 相对路径逃逸3
589        assert check_shell(f"shell -b / pwd", "[Fail][E003001]")
590        # 交互式shell不支持
591        assert check_shell(f"shell -b {GP.debug_app}", "[Fail][E003002]")
592        # bundle参数(129)超过128
593        str_len_129 = "a" * 129
594        assert check_shell(f"shell -b {str_len_129} pwd", "[Fail][E003001]")
595        # bundle参数(6)低于7
596        str_len_6 = "a" * 6
597        assert check_shell(f"shell -b {str_len_6} pwd", "[Fail][E003001]")
598        # bundle参数存在非法参数
599        str_invalid = "#########"
600        assert check_shell(f"shell -b {str_invalid} pwd", "[Fail][E003001]")
601        # 其他参数用例1
602        assert check_shell("shell -param 1234567890 pwd", "[Fail][E003003]")
603        # 其他参数用例2
604        assert check_shell("shell -basd {GP.debug_app} pwd", "[Fail][E003003]")
605        # 缺少参数字母
606        assert check_shell(f"shell - {GP.debug_app} ls", "[Fail][E003003]")
607        # 缺少bundle参数1
608        assert check_shell("shell -b ls", "[Fail][E003001]")
609        # 缺少bundle参数2
610        assert check_shell("shell -b", "[Fail][E003005]")
611        # 存在未知参数在前面
612        assert check_shell(f"shell -t -b {GP.debug_app} ls", "[Fail][E003003]")
613        # 参数在后面
614        assert check_shell(f"shell ls -b {GP.debug_app}", "No such file or directory")
615        # 双倍参数
616        assert check_shell(f"shell -b -b {GP.debug_app} ls", "[Fail][E003001]")
617        # 双倍-杠
618        assert check_shell(f"shell --b {GP.debug_app}", "[Fail][E003003]")
619
620
621def test_option_bundle_error_usage_support():
622    version = "Ver: 3.1.0e"
623    if not check_hdc_version("version", version) or not check_hdc_version("shell hdcd -v", version):
624        print("version does not match, ignore this case")
625    else:
626        assert check_shell("shell -b", "Usage: hdc shell [-b bundlename] [COMMAND...]")
627        assert check_shell(f"file recv -b ", "Usage: hdc file recv [-b bundlename] remote local")
628        assert check_shell(f"file send -b ", "Usage: hdc file send [-b bundlename] local remote")
629
630
631def test_hdcd_rom():
632    baseline = 2200 # 2200KB
633    assert check_rom(baseline)
634
635
636def test_smode_r():
637    assert check_hdc_cmd(f'smode -r')
638    time.sleep(3) # sleep 3s to wait for the device to connect channel
639    run_command_with_timeout(f"{GP.hdc_head} wait", 3) # wait 3s for the device to connect channel
640    time.sleep(3) # sleep 3s to wait for the device to connect channel
641    run_command_with_timeout(f"{GP.hdc_head} wait", 3) # wait 3s for the device to connect channel
642    assert check_shell(f"shell id", "context=u:r:sh:s0")
643
644
645def test_smode():
646    assert check_hdc_cmd(f'smode')
647    time.sleep(3) # sleep 3s to wait for the device to connect channel
648    run_command_with_timeout(f"{GP.hdc_head} wait", 3) # wait 3s for the device to connect channel
649    time.sleep(3) # sleep 3s to wait for the device to connect channel
650    run_command_with_timeout(f"{GP.hdc_head} wait", 3) # wait 3s for the device to connect channel
651    assert check_shell(f"shell id", "context=u:r:su:s0")
652    assert not check_hdc_cmd("ls data/log/faultlog/faultlogger | grep hdcd", "hdcd")
653
654
655def setup_class():
656    print("setting up env ...")
657    check_hdc_cmd("shell rm -rf data/local/tmp/it_*")
658    GP.load()
659
660
661def teardown_class():
662    pass
663
664
665def run_main():
666    if check_library_installation("pytest"):
667        exit(1)
668
669    if check_library_installation("pytest-testreport"):
670        exit(1)
671
672    if check_library_installation("pytest-repeat"):
673        exit(1)
674
675    GP.init()
676
677    prepare_source()
678    update_source()
679
680    choice_default = ""
681    parser = argparse.ArgumentParser()
682    parser.add_argument('--count', type=int, default=1,
683                        help='test times')
684    parser.add_argument('--verbose', '-v', default=__file__,
685                        help='filename')
686    parser.add_argument('--desc', '-d', default='Test for function.',
687                        help='Add description on report')
688    args = parser.parse_args()
689
690    pytest_run(args)
691
692
693if __name__ == "__main__":
694    run_main()
695