如何为 I2C 传感器写 fixture 并模拟温湿度数据?
解读
国内嵌入式 Python 项目(树莓派、边缘网关、工业 DTU)普遍用 pytest 做硬件抽象层(HAL)测试。面试官问“写 I2C fixture 并模拟温湿度”,核心想验证三点:
- 能否把硬件依赖隔离到 fixture,让测试在 PC/CI 上无板卡也能跑;
- 是否熟悉 pytest 的 fixture 依赖注入、参数化与 cleanup;
- 对 I2C 协议、字节序、CRC 校验、异常注入是否严谨,能否覆盖温湿度换算公式。
一句话:让代码“像真的一样”读寄存器,但“完全假”地返回数据,且支持并发、重入、CI 零配置。
知识点
- pytest fixture 作用域:session/module/class/function,I2C 总线通常用 module 级,避免重复开关;
- Monkeypatch 与 unittest.mock 差异:后者支持 spec_set、call_args_list,更适合寄存器级断言;
- SMBus 协议:起始位 + 7 位地址 + R/W 位,温湿度芯片(如 SHT3x、AHT20)返回 6 字节数据,高 16 位温度,低 16 位湿度,CRC-8 MAXIM;
- 参数化 fixture:结合 indirect=True,把“温度、湿度、是否 NACK”作为测试输入;
- 异常注入:OSError errno 121(Remote I/O error)模拟总线占用,TimeoutError 模拟传感器未就绪;
- 并发安全:使用 threading.Lock 防止跨测试用例竞态;
- CI 零依赖:GitHub Actions / Gitee Go 中安装 i2c-stub 内核模块即可,无需真实硬件;
- 覆盖率:pytest-cov 要求 HAL 层分支覆盖 90% 以上,国内甲方常写入交付 checklist。
答案
项目结构 i2c_sensor/ ├── hal/ │ └── aht20.py ├── tests/ │ ├── conftest.py │ └── test_aht20.py └── requirements-test.txt
requirements-test.txt pytest>=7.4 pytest-cov pytest-xdist
hal/aht20.py
import smbus2
import time
import struct
class AHT20:
def __init__(self, bus_no: int = 1, addr: int = 0x38):
self._bus = smbus2.SMBus(bus_no)
self._addr = addr
def measure(self) -> tuple[float, float]:
self._bus.write_i2c_block_data(self._addr, 0xAC, [0x33, 0x00])
time.sleep(0.08)
data = self._bus.read_i2c_block_data(self._addr, 0x00, 6)
if data[0] & 0x80:
raise RuntimeError("Sensor not calibrated")
raw_h = ((data[1] << 16) | (data[2] << 8) | data[3]) >> 4
raw_t = ((data[3] & 0x0F) << 16) | (data[4] << 8) | data[5]
hum = raw_h * 100.0 / 0x100000
temp = raw_t * 200.0 / 0x100000 - 50.0
return round(temp, 2), round(hum, 2)
tests/conftest.py
import pytest
import smbus2
from unittest.mock import Mock
from contextlib import contextmanager
import threading
lock = threading.Lock()
@pytest.fixture(scope="module")
def mock_bus():
with lock:
bus_mock = Mock(spec=smbus2.SMBus)
yield bus_mock
@pytest.fixture
def aht20_mock(mock_bus, monkeypatch):
from hal.aht20 import AHT20
monkeypatch.setattr("hal.aht20.smbus2.SMBus", lambda bus: mock_bus)
return AHT20()
def _crc8(data: bytes) -> int:
crc = 0xFF
for b in data:
crc ^= b
for _ in range(8):
if crc & 0x80:
crc = (crc << 1) ^ 0x31
else:
crc <<= 1
crc &= 0xFF
return crc
def _encode(temp: float, hum: float) -> list[int]:
raw_t = int((temp + 50) * 0x100000 / 200) & 0xFFFFF
raw_h = int(hum * 0x100000 / 100) & 0xFFFFF
b3 = (raw_h >> 16) & 0xFF
b4 = (raw_h >> 8) & 0xFF
b5 = raw_h & 0xF0 | (raw_t >> 16) & 0x0F
b6 = (raw_t >> 8) & 0xFF
b7 = raw_t & 0xFF
crc = _crc8(bytes([b3, b4, b5, b6]))
return [0x1C, b3, b4, b5, b6, b7, crc]
@pytest.fixture
def mock_data(request):
temp, hum, nack = getattr(request, "param", (25.3, 60.1, False))
if nack:
def raiser(*a, **k):
raise OSError(121, "Remote I/O error")
return raiser
return _encode(temp, hum)
@pytest.fixture
def inject_read(mock_bus, mock_data):
if callable(mock_data):
mock_bus.read_i2c_block_data.side_effect = mock_data
else:
mock_bus.read_i2c_block_data.return_value = mock_data
return mock_bus
tests/test_aht20.py
import pytest
from hal.aht20 import AHT20
@pytest.mark.parametrize("mock_data", [(25.3, 60.1, False)], indirect=True)
def test_normal_measure(aht20_mock, inject_read):
t, h = aht20_mock.measure()
assert t == 25.3
assert h == 60.1
@pytest.mark.parametrize("mock_data", [(35.8, 90.5, False)], indirect=True)
def test_high_humidity(aht20_mock, inject_read):
t, h = aht20_mock.measure()
assert h == 90.5
@pytest.mark.parametrize("mock_data", [(None, None, True)], indirect=True)
def test_bus_nack(aht20_mock, inject_read):
with pytest.raises(OSError):
aht20_mock.measure()
运行 pytest -q --cov=hal --cov-report=term-missing 预期输出 test_aht20.py ... [100%] hal/aht20.py 15->0 100%
拓展思考
- 多传感器级联:在 conftest.py 再定义
mock_mux_channelfixture,切换 TCA9548A 通道,确保地址冲突测试; - 温湿度校准:把“标准值 25.3 ℃ / 60.1 %RH”写入独立 JSON,配合 pytest-benchmark 做回归,防止算法漂移;
- 并发压力:使用 pytest-xdist -n auto,结合 lock 验证总线仲裁,满足国内车规项目“双核同时读传感器”需求;
- 硬件在环(HIL):在 GitLab CI 里加一条
hardwarejob,标签 runner 带树莓派,只有该 job 访问真实/dev/i2c-1,其余 job 仍跑 mock,实现“同一套代码,双轨验证”; - 安全合规:国内电力行业要求代码审计,mock 数据必须可溯源,因此在 fixture 里加
hashlib.sha256(repr(mock_data).encode()).hexdigest()写入日志,审计时可复现。