如何在 PC 端运行 pytest 并远程调用 ESP32 固件?

解读

面试官真正想考察的是:

  1. 你是否理解 pytest 的“测试即代码”理念,能把硬件抽象成可被 pytest 调用的资源;
  2. 能否把 ESP32 的远程交互(串口、Wi-Fi、BLE、JTAG、OTA 等)封装成 Python 对象,并注册为 fixture,实现测试用例与硬件解耦;
  3. 是否熟悉国内开发环境(Windows 占比高、公司内网隔离、代理、CI 常见 GitLab-Runner/Jenkins),能给出落地步骤;
  4. 是否具备“测试左移”思维:让固件在本地 commit 阶段就被 pytest 回归,而不是等人工烧录。

一句话:把 ESP32 当成“远程依赖”,用 pytest 的 fixture + 插件机制把它注入到测试函数里,跑在 PC 端即可。

知识点

  1. pytest fixture:scope、params、yield teardown、autouse、name 别名。
  2. 串口通信:pyserial 的 Serial 类,跨平台端口枚举(list_ports.comports)。
  3. 网络协议:
    • MicroPython WebREPL、raw-REPL 协议帧格式(0x05 开头 + 64 B 对齐);
    • ESP-IDF 的 esp-protocols/mqtt、https_ota、json 日志传输。
  4. 插件化:pytest 的 hookwrapper(pytest_cmdline_main、pytest_collection_modifyitems)与第三方插件 pytest-xdist、pytest-html、pytest-timeout。
  5. 国内 CI 落地:
    • GitLab-Runner 注册 shell/docker 执行器,.gitlab-ci.yml 中 tags 匹配“esp32_lab”;
    • Jenkins + BlueOcean 在 Windows 节点上装 USB 驱动,用 lockable-resources 插件保证多板卡互斥。
  6. 日志与断言:
    • 环形缓冲区实时抓取串口日志,用 re.match 做“expect”断言;
    • 采用 Allure 的 @allure.step 记录每条 AT 指令与回复,方便回溯。
  7. 安全合规:公司内网禁用公网 pip,需搭建 devpi 私服;固件 bin 文件走 Nexus 制品库版本化。

答案

给出一个可直接落地的“三步走”方案,全部代码在 PC 端运行,无需在 ESP32 上安装 pytest。

第一步:环境准备

  1. PC 安装 Python 3.8+、venv 创建虚拟环境,requirements.txt 固定版本:
    pytest==7.4
    pyserial==3.5
    pexpect==4.8
    requests==2.31
  2. 把公司私服地址写入 pip.conf,避免外网依赖。
  3. 硬件连接:
    • 开发板通过 USB-TTL 接到 PC,设备管理器确认 COMx;
    • 若用网络,ESP32 启动后连接实验室统一 Wi-Fi,DHCP 分配 192.168.x.x,MAC 地址贴标签做资产编号。

第二步:封装 fixture
在项目根目录建 conftest.py,实现“自动发现板卡 + 自动复位 + 自动下载固件”:

import serial, time, subprocess, pytest, os
from contextlib import ExitStack

def get_available_board():
    """国产 Win10 环境枚举串口,过滤 CP210x/CH340 驱动"""
    import serial.tools.list_ports as lp
    for p in lp.comports():
        if "CP210" in p.description or "CH340" in p.description:
            return p.device
    pytest.skip("未检测到 ESP32 开发板,跳过硬件测试")

@pytest.fixture(scope="session")
def esp32():
    port = get_available_board()
    bin_path = os.getenv("ESP32_BIN", "build/app.bin")
    # 使用 esptool 烧录,国内镜像 -c 选择 dio 模式
    cmd = f"esptool.py -p {port} -b 921600 write_flash 0x0 {bin_path}"
    subprocess.run(cmd.split(), check=True)
    ser = serial.Serial(port, 115200, timeout=3)
    ser.reset_input_buffer()
    yield ser
    ser.close()

第三步:编写测试用例
tests/test_led.py:

import re, time, pytest

def test_led_blink(esp32):
    esp32.write(b"import blink; blink.start()\r\n")
    time.sleep(2)
    lines = []
    for _ in range(20):  # 最多读 20 行
        l = esp32.readline()
        if not l:
            break
        lines.append(l.decode(errors="ignore"))
    assert any("LED ON" in l for l in lines), "未检测到 LED 打印"

运行命令:
pytest -s --html=report.html --self-contained-html
即可在 PC 端完成远程调用 ESP32 固件的自动化测试。

若需并行多板卡:

  1. 在 conftest.py 把 fixture 的 params 写成串口列表,配合 pytest-xdist 的 --dist=loadgroup;
  2. 用文件锁实现 esptool 互斥烧录,避免同时下载导致失败。

拓展思考

  1. 无串口场景:ESP32 跑的是 ESP-IDF + mqtt 固件,PC 端 pytest 通过 paho-mqtt 订阅 /dev/{chip_id}/log,用 json 字段断言,实现“纯网络”测试。
  2. OTA 日构建:GitLab nightly 把 bin 包推到 Nexus,pytest 用 requests 下载后调用 esp_https_ota 接口,实现“不插线”升级验证。
  3. 硬件看门狗:fixture 里启动后台线程,若 30 s 内无日志心跳,自动拉低 EN 引脚复位,防止固件死机导致 CI 挂死。
  4. 测试数据驱动:pytest 的 @pytest.mark.parametrize 与 fixture 组合,可把“温度传感器-预期值”表格化成 CSV,一条用例循环 50 组数据,实现环境应力测试。
  5. 安全审计:在 CI 阶段加入 pytest-audit 插件,自动抓取固件 map 文件,统计 SRAM 使用量,防止内存溢出流入生产。