当串口输出乱码时,如何自动调整波特率重试?

解读

国内 Python 测试面试里,这道题表面问“串口乱码→调波特率”,实则考察候选人能否把“异常检测→参数化重试→测试报告”闭环做成可维护的 Pytest 方案。
核心痛点有三:

  1. 乱码判定:串口返回的是字节流,必须给出可量化的“乱码”定义,不能拍脑袋。
  2. 重试策略:波特率列表往往有 6~8 个常用值,不能写 8 层 if/else,而要利用 Pytest 原生机制。
  3. 测试资产:重试过程要留痕(log、allure、junit xml),否则 CI 失败时无法复盘。

知识点

  1. Pytest fixture 的 scope、params、yield 与 addfinalizer 组合,实现“串口打开→多波特率轮询→关闭”一次完成。
  2. pytest-assume 或 pytest-check 软断言,保证所有波特率都跑完再汇总失败,而不是第一次失败就退出。
  3. 字节流合法性判定:
    • 正则掩码(预期帧头、帧尾、校验和)
    • 可打印字符比例 < 阈值(如 75 %)
    • 双缓冲区采样,降低误判
  4. 重试与参数化分离:fixture 负责“硬件+波特率”资源,测试函数只关心业务帧内容,做到硬件与业务解耦。
  5. allure.dynamic 动态更新用例标题,把最终成功的波特率写进报告,方便运维同学一眼定位。
  6. 并发安全:串口是独占设备,pytest-xdist 并行执行时,通过 filelock 或 worker_id 保证同一时刻只有一个 worker 占用串口。
  7. 国内常见 CI(GitLab-CI、Jenkins、禅道 DevOps)对 junit xml 的解析规则,要求 failure message 里不能出现非 utf-8 字符,因此乱码字节要先做 hex 转义再断言。

答案

给出一套可直接落地的 Pytest 方案,目录结构符合国内大中厂规范:

tests/
├── conftest.py
├── test_uart.py
└── utils/
    └── uart_helper.py

uart_helper.py

import serial, re, string, logging
from contextlib import contextmanager

LOGGER = logging.getLogger(__name__)

VALID_FRAME = re.compile(rb'\xAA.\{6,22\}\x55')   # 示例帧格式
PRINTABLE_RATIO = 0.75

def is_garbled(data: bytes) -> bool:
    """返回 True 表示乱码"""
    if not data:
        return True
    # 1. 帧格式检查
    if VALID_FRAME.search(data):
        return False
    # 2. 可打印字符比例
    printable = sum(1 for b in data if chr(b) in string.printable)
    return (printable / len(data)) < PRINTABLE_RATIO

@contextmanager
def open_port(port: str, baud: int, timeout: 1):
    ser = serial.Serial(port, baud, timeout=timeout)
    try:
        yield ser
    finally:
        ser.close()

conftest.py

import pytest, allure, logging
from utils.uart_helper import open_port, is_garbled, LOGGER

# 国内常用波特率
BAUDRATES = [9600, 19200, 38400, 57600, 115200, 230400, 460800]

@pytest.fixture(scope="session")
def uart_port(pytestconfig):
    return pytestconfig.getoption("--uart-port")

@pytest.fixture(scope="function", params=BAUDRATES)
def uart(request, uart_port):
    baud = request.param
    with open_port(uart_port, baud, timeout=1) as ser:
        LOGGER.info("尝试波特率 %s", baud)
        yield ser, baud

@pytest.fixture(scope="function", autouse=True)
def _auto_baud(uart):
    ser, baud = uart
    ser.reset_input_buffer()
    # 发任意指令,等待 200 ms
    ser.write(b'\x01\x02')
    data = ser.read(100)
    if not is_garbled(data):
        allure.dynamic.title(f"串口通信正常,波特率={baud}")
        return
    # 乱码则 skip 当前参数,pytest 会自动用下一个波特率重跑
    pytest.skip(f"baud {baud} 乱码,自动重试下一波特率")

test_uart.py

import pytest, allure
from utils.uart_helper import is_garbled

@allure.feature("串口协议测试")
def test_query_version(uart):
    ser, baud = uart
    ser.write(b'\xAA\x01\x00\x55')          # 查询版本号指令
    resp = ser.read(30)
    assert not is_garbled(resp), "帧格式异常"
    assert resp[-1] == 0x55, "帧尾错误"
    allure.attach(resp.hex(), name="版本帧", attachment_type=allure.attachment_type.TEXT)

运行命令
pytest tests/ --uart-port=/dev/ttyUSB0 --alluredir=report -n1
效果:

  • 如果 9600 乱码,自动 skip 并继续 19200,直到找到合法波特率;
  • 所有失败 skip 记录都会写进 junit xml 与 allure 报告,CI 可直接解析;
  • 测试函数零样板代码,完全符合 Pytest 哲学。

拓展思考

  1. 如果设备上电后波特率自适应窗口只有 500 ms,可把波特率列表倒序(先高速后低速),并在 fixture 里加 50 ms 轮询,减少整体耗时。
  2. 对于多串口场景(如 4G 模组 + GNSS),可以用 pytest 的 parametrize 嵌套,实现“端口 × 波特率”矩阵,但需加文件锁防止端口冲突。
  3. 国内不少 SOC 出厂固件在 115200 下会输出一次性启动日志,随后自动降为 9600。此时可把“乱码判定”升级为状态机:第一次合法帧出现后,锁定当前波特率并写入 session 级缓存,后续用例直接复用,避免重复探测。
  4. 若项目需满足 GJB-5000A 或 ISO 26262,要求“测试可追溯”,可把每次波特率切换的串口原始 log 以 hex 形式存入 Artifactory 或 Git LFS,作为审计证据。
  5. 在 Jenkins 流水线里,可把最终锁定波特率回写到构建产物(如 build_info.json),供下游老化测试 Job 直接读取,实现全流程闭环。