Zephyr 的这个示例展示了如何让 Twister 负责发现、构建和汇总测试,再让 pytest 向应用的 Shell 发送命令并检查返回内容。测试只有两项:help 是否返回预期的命令列表标记,以及 kernel version 是否返回 Zephyr 版本信息。
本文按 Zephyr 4.4.0 的 Pytest shell application testing 整理,并核对了官方仓库 v4.4.0 标签下的 README、应用源码、Kconfig 配置、测试配置和 Python 测试文件。固定版本网页本次未能通过读取工具打开,已用对应版本的官方源文件完成全文核验。下列日志来自原文,本文没有安装、构建、烧录或运行该示例。

运行条件与版本边界
示例需要具有 UART 控制台的目标平台,可以是硬件开发板、native_sim 或 QEMU。4.4.0 的测试配置还要求启用串口、没有启用 SMP,并且设备树中 zephyr,shell-uart 所指节点有效。配置列出的集成平台为 native_sim 与 qemu_cortex_m3,并排除 qemu_rx。这些条件都应保留,不应因为“支持 pytest”就推断所有平台都能运行。
配套的 pytest 集成说明 仍把这项集成标记为进行中的工作。默认无需另外安装一个浮动版本的 pytest-twister-harness:Twister 会把源码树内插件的路径加入 PYTHONPATH,再用 -p twister_harness.plugin 加载它。只有明确使用已安装插件时才涉及 --allow-installed-plugin;本文使用源码树随附插件。
对于 native_sim,默认目标使用 32 位 ILP32 ABI,指针和 long 均为 32 位。在 64 位主机上通常需要相应的 multilib 支持,或使用 32 位用户空间。native_sim/native/64 使用 LP64 ABI,指针和 long 为 64 位;它可以解决部分主机不能运行 32 位程序的问题,但改变了 ABI,不能被当作完全等价的测试目标。
应用为什么可以没有业务逻辑
目录 samples/subsys/testsuite/pytest/shell 包含应用与测试。src/main.c 的作用很小,因为 Shell 功能由 Kconfig 选项引入。以下为原文件代码,注释保留其原始拼写:
/*
* Copyright (c) 2023 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
int main(void)
{
/* Shell application source code is injected by applied Kconfg SHELL
* options, no more "extra" functionalities are required for exemplary
* pytest test.
*/
return 0;
}
prj.conf 的完整配置为:
CONFIG_PRINTK=y
CONFIG_SHELL=y
CONFIG_LOG=y
CONFIG_SHELL_BACKEND_SERIAL=y
CONFIG_KERNEL_SHELL=y
CONFIG_SHELL 启用 Shell,串口后端提供交互通道,CONFIG_KERNEL_SHELL 提供测试所用的内核命令。因此,不需要在 main() 里自行实现 help 或 kernel version。
两条测试分别验证什么
Twister 构建应用后,会调用 pytest 子进程运行 pytest/test_shell.py。两项测试都接收由 pytest-twister-harness 提供的 shell 夹具。下面保留该文件的完整逻辑及版权声明:
# Copyright (c) 2023 Nordic Semiconductor ASA
#
# SPDX-License-Identifier: Apache-2.0
import logging
from twister_harness import Shell
logger = logging.getLogger(__name__)
def test_shell_print_help(shell: Shell):
logger.info('send "help" command')
lines = shell.exec_command('help')
assert 'Available commands:' in lines, 'expected response not found'
logger.info('response is valid')
def test_shell_print_version(shell: Shell):
logger.info('send "kernel version" command')
lines = shell.exec_command('kernel version')
assert any(['Zephyr version' in line for line in lines]), 'expected response not found'
logger.info('response is valid')
第一条断言检查返回的行集合中是否包含完整的一行 Available commands:;它不是在验证每一个命令及其说明。第二条断言检查是否至少有一行包含 Zephyr version;它也不要求某个固定版本号。因此,这两项测试验证的是基本 Shell 交互和输出格式,没有覆盖所有 Shell 功能、设备安全性或版本一致性。
理解 testcase.yaml 的平台筛选与变体
4.4.0 的完整配置如下。保留整个文件有助于解释为什么仅指定测试目录可能选中不止本篇的两项断言:
common:
tags:
- test_framework
- pytest
- shell
platform_exclude: qemu_rx
filter: CONFIG_SERIAL and not CONFIG_SMP and dt_chosen_enabled("zephyr,shell-uart")
extra_configs:
- arch:posix:CONFIG_UART_NATIVE_PTY_0_ON_STDINOUT=y
- platform:iotdk/arc_iot:CONFIG_ARC_IOT_CUSTOM_CPU_IDLE=y
min_ram: 40
integration_platforms:
- native_sim
- qemu_cortex_m3
tests:
sample.pytest.shell:
harness: pytest
sample.pytest.shell.vt100_colors_off:
harness: pytest
extra_configs:
- CONFIG_SHELL_VT100_COLORS=n
sample.harness.shell:
harness: shell
harness_config:
shell_commands: &kernel_commands
- command: "kernel cycles"
expected: "cycles: .* hw cycles"
- command: "kernel version"
expected: "Zephyr version .*"
- command: "kernel sleep 100"
sample.harness.shell.vt100_colors_off:
harness: shell
extra_configs:
- CONFIG_SHELL_VT100_COLORS=n
harness_config:
shell_commands: *kernel_commands
sample.pytest.required_app_demo:
required_applications:
- name: sample.pytest.shell
- name: sample.harness.shell
harness: pytest
harness_config:
pytest_root:
- "pytest_shared_app/test_shared_app.py"
sample.pytest.shell 是本文主场景;带 vt100_colors_off 的 pytest 场景关闭终端颜色。sample.harness.shell 使用不同的 Shell harness,命令包括 kernel cycles、kernel version 和 kernel sleep 100。共享应用示例依赖两个已构建应用,并把测试入口改为 pytest_shared_app/test_shared_app.py。这些变体存在于同一 YAML 中,但其结果不能替代本文两条 Python 断言的结果。
构建与运行:限定本篇场景
原 README 给出的命令如下,应在已完成环境准备的 Zephyr 源码根目录运行:
./scripts/twister -vv --platform native_sim -T samples/subsys/testsuite/pytest/shell
本文整理后的命令:在原命令后增加 -s sample.pytest.shell,只选择本文讨论的场景。这是相对于原 README 的明确改动:
./scripts/twister -vv --platform native_sim -T samples/subsys/testsuite/pytest/shell -s sample.pytest.shell
-T 限制发现测试的目录,--platform 选择目标,-vv 提高日志详细程度,-s 选择场景。命令会构建并运行应用;它不是只读检查。本文没有把真实硬件烧录或擦除选项加入这一命令。
怎样阅读原文的示例日志
下面保留原 README 展示的输出内容。首尾省略号本来就存在于原文,表示这不是一次完整运行的日志。版本 3.5.99 是历史示例输出,不是 Zephyr 4.4.0 的期望版本,也不是本文运行得到的结果:
...
samples/subsys/testsuite/pytest/shell/pytest/test_shell.py::test_shell_print_help
INFO: send "help" command
DEBUG: #: uart:~$ help
DEBUG: #: Please press the <Tab> button to see all available commands.
DEBUG: #: You can also use the <Tab> button to prompt or auto-complete all commands or its subcommands.
DEBUG: #: You can try to call commands with <-h> or <--help> parameter for more information.
DEBUG: #: Shell supports following meta-keys:
DEBUG: #: Ctrl + (a key from: abcdefklnpuw)
DEBUG: #: Alt + (a key from: bf)
DEBUG: #: Please refer to shell documentation for more details.
DEBUG: #: Available commands:
DEBUG: #: clear :Clear screen.
DEBUG: #: device :Device commands
DEBUG: #: devmem :Read/write physical memory
DEBUG: #: Usage:
DEBUG: #: Read memory at address with optional width:
DEBUG: #: devmem address [width]
DEBUG: #: Write memory at address with mandatory width and value:
DEBUG: #: devmem address <width> <value>
DEBUG: #: help :Prints the help message.
DEBUG: #: history :Command history.
DEBUG: #: kernel :Kernel commands
DEBUG: #: rem :Ignore lines beginning with 'rem '
DEBUG: #: resize :Console gets terminal screen size or assumes default in case the
DEBUG: #: readout fails. It must be executed after each terminal width change
DEBUG: #: to ensure correct text display.
DEBUG: #: retval :Print return value of most recent command
DEBUG: #: shell :Useful, not Unix-like shell commands.
DEBUG: #: uart:~$
INFO: response is valid
PASSED
samples/subsys/testsuite/pytest/shell/pytest/test_shell.py::test_shell_print_version
INFO: send "kernel version" command
DEBUG: #: uart:~$ kernel version
DEBUG: #: Zephyr version 3.5.99
DEBUG: #: uart:~$
INFO: response is valid
PASSED
...
帮助信息解释了 Tab 补全、-h/--help、快捷键以及可用命令。日志里列出的 devmem 具备物理内存读写能力;它只是历史帮助文本的一部分,本篇测试没有调用它,也不应把该输出当成开放调试 Shell 给不受信任使用者的安全依据。
实际验收应检查本次所选场景的两条断言及 pytest 报告。Twister 把构建目录、设备等参数通过 YAML 配置传给 pytest;pytest 结束后,Twister 读取 results.xml 并据此设置结果。看到旧日志里的 PASSED 不等于本机运行成功,构建成功也不等于两条断言通过。
静态审查与归属
本次只做安全静态审核。源测试发送的是固定的 help 和 kernel version 字符串,没有硬编码秘密或外部输入拼接执行;不过 Shell 接口本身可能提供高权限调试命令,生产固件需另行审阅暴露范围。没有执行任何源代码、测试、烧录或网络配置,未发现问题不代表不存在漏洞。
原文维护方为 Zephyr Project,页面未列个人作者;所引 main.c 和 test_shell.py 保留 Copyright (c) 2023 Nordic Semiconductor ASA 及 SPDX-License-Identifier: Apache-2.0。代码适用 Apache License 2.0,文末附完整许可。中文译写、自绘图和限定场景的命令说明由未完纪整理。
核对来源:示例 README、Python 测试、测试配置。所有版本相关解释均限定在已核对的 v4.4.0 源文件。
Zephyr 示例代码 Apache License 2.0 全文
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.












暂无评论内容