You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Bleak异步单元测试中仅连接一次BLE设备执行多测试

解决方案

可以通过重写setUpClass和tearDownClass类方法,结合asyncio.run()实现异步的类级初始化与清理,从而做到仅连接一次BLE设备、跑完所有测试再断开。

核心思路

  • 用类级变量存储BLE设备客户端实例,供所有测试方法共享
  • 在同步的类方法setUpClass/tearDownClass中,通过asyncio.run()包装异步的连接/断开逻辑
  • 测试方法直接调用类共享的客户端实例执行操作

代码示例

import unittest
import asyncio
from bleak import BleakClient

# 替换为你的BLE设备地址
DEVICE_ADDRESS = "XX:XX:XX:XX:XX:XX"

class TestBLEDevice(unittest.IsolatedAsyncioTestCase):
    # 类级共享的BLE客户端
    _ble_client = None

    @classmethod
    def setUpClass(cls):
        async def connect():
            cls._ble_client = BleakClient(DEVICE_ADDRESS)
            await cls._ble_client.connect()
        
        # 用asyncio.run执行异步连接逻辑
        asyncio.run(connect())

    @classmethod
    def tearDownClass(cls):
        async def disconnect():
            if cls._ble_client and cls._ble_client.is_connected:
                await cls._ble_client.disconnect()
        
        # 用asyncio.run执行异步断开逻辑
        asyncio.run(disconnect())

    async def test_read_sensor_data(self):
        # 直接使用类共享的客户端
        sensor_char_uuid = "0000FFB2-0000-1000-8000-00805F9B34FB"
        data = await self._ble_client.read_gatt_char(sensor_char_uuid)
        self.assertGreater(len(data), 0)

    async def test_write_config(self):
        config_char_uuid = "0000FFB1-0000-1000-8000-00805F9B34FB"
        await self._ble_client.write_gatt_char(config_char_uuid, b"\x01")
        # 验证写入结果
        result = await self._ble_client.read_gatt_char(config_char_uuid)
        self.assertEqual(result, b"\x01")

注意事项

  • 若连接失败,setUpClass会直接抛出异常,终止所有测试执行,避免后续测试使用未连接的设备
  • 部分场景下,BLE客户端在多事件循环中共享需验证兼容性(bleak 0.22.2版本的BleakClient支持跨事件循环复用)
  • 若测试中设备意外断开,可在测试方法内增加连接状态检查或重试逻辑

内容的提问来源于stack exchange,提问作者Evan Clausse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 18:14:52