机器人 / 系统课时
为话题与服务编写集成测试
为话题与服务编写集成测试
终端能看到温度消息,不等于订阅回调一定收到;服务已经创建,也不等于异步请求一定返回正确结果。本篇用 pytest 和 rclpy 建立真实的 ROS 2 通信端点,验证温度话题在 3 秒内到达、设备开关服务在 3 秒内响应,并检查返回值和状态变化。
学习目标
- 用 pytest fixture 初始化、驱动并清理 ROS 2 节点。
- 限时断言
Float32话题消息的到达与数值。 - 检查
SetBool的服务发现、异步响应和设备状态。
确定验收条件
适用环境为 Ubuntu 24.04、ROS 2 Jazzy、系统 Python 3 和 pytest,需有 rclpy、std_msgs、std_srvs 及 python3-pytest。示例无需实体传感器:测试文件内定义最小设备节点,通信仍经过真实 ROS 2 中间件,而非直接调用回调函数。
| 通道 | 接口与类型 | 成功条件 |
|---|---|---|
| 温度话题 | /sensor/temperature,std_msgs/msg/Float32 |
每 0.1 秒发布约定为摄氏度的 23.5;3 秒内收到,误差不超过 0.01 |
| 设备服务 | /device/enable,std_srvs/srv/SetBool |
请求 data=True;3 秒内发现服务,再在 3 秒内取得 success=True、message=enabled,且设备状态变为开启 |
pytest 主线程只负责等待和断言,后台 SingleThreadedExecutor 负责定时器、订阅回调与服务响应。消息到达与服务响应是两条独立的异步链路,不能用一次固定睡眠替代事件通知。

编写完整的 pytest 测试
在工作目录创建 test/,将下列内容保存为 test/test_comm_integration.py。DeviceNode 是可运行的最小被测节点:定时发布温度,收到 SetBool 请求时改变 enabled。两个测试使用独立 fixture,互不共享节点状态。
from threading import Event, Thread
import pytest
import rclpy
from rclpy.executors import SingleThreadedExecutor
from rclpy.node import Node
from std_msgs.msg import Float32
from std_srvs.srv import SetBool
class DeviceNode(Node):
def __init__(self):
super().__init__('device_under_test')
self.enabled = False
self.temp_pub = self.create_publisher(
Float32, '/sensor/temperature', 10)
self.create_timer(0.1, self.publish_temp)
self.create_service(SetBool, '/device/enable', self.on_enable)
def publish_temp(self):
# 持续发送,避免 DDS 尚未发现订阅端时只丢失首条消息
self.temp_pub.publish(Float32(data=23.5))
def on_enable(self, request, response):
self.enabled = request.data
response.success = True
response.message = 'enabled' if self.enabled else 'disabled'
return response
@pytest.fixture
def ros_pair():
rclpy.init()
device = DeviceNode()
probe = Node('integration_probe')
executor = SingleThreadedExecutor()
executor.add_node(device)
executor.add_node(probe)
# 回调在后台执行;pytest 主线程使用 Event 限时等待
worker = Thread(target=executor.spin, daemon=True)
worker.start()
try:
yield device, probe
finally:
executor.shutdown()
worker.join()
probe.destroy_node()
device.destroy_node()
rclpy.shutdown()
def test_temperature_arrives(ros_pair):
_, probe = ros_pair
arrived = Event()
samples = []
def on_temperature(msg):
samples.append(msg.data)
arrived.set()
probe.create_subscription(
Float32, '/sensor/temperature', on_temperature, 10)
assert arrived.wait(3.0), '3 秒内未收到温度消息'
assert samples[0] == pytest.approx(23.5, abs=0.01)
def test_switch_service(ros_pair):
device, probe = ros_pair
client = probe.create_client(SetBool, '/device/enable')
# 服务发现超时和请求响应超时分别判断
assert client.wait_for_service(timeout_sec=3.0), '服务发现超时'
request = SetBool.Request()
request.data = True
future = client.call_async(request)
completed = Event()
future.add_done_callback(lambda _: completed.set())
assert completed.wait(3.0), '服务响应超时'
result = future.result()
assert result.success is True
assert result.message == 'enabled'
assert device.enabled is True预期结果:test_temperature_arrives 接收到约 23.5 的数值,test_switch_service 收到成功响应并观察到状态变更;任一断言失败,pytest 会标出具体位置。
执行并识别测试结果
在保存文件的工作目录运行下列命令。ROS_DOMAIN_ID=42 用于隔离测试通信,若该域已被其他设备使用,请更换为未占用的有效值;两个测试节点会继承同一个域。
source /opt/ros/jazzy/setup.bash
export ROS_DOMAIN_ID=42
python3 -m pytest -q test/test_comm_integration.py预期输出(耗时随主机变化,<TIME> 为动态值):
.. [100%]
2 passed in <TIME>s这验证的是同一进程内两个独立节点的 ROS 2 话题与服务通信,并未验证 Launch 启动、多进程退出或硬件驱动。迁移到真实项目时,将 DeviceNode 替换为项目中的节点类,保留探针、时限与断言,并把话题名称、消息类型及预期值改成实际接口。
按失败阶段定位问题
| 失败现象 | 先检查什么 | 修复方式 |
|---|---|---|
ModuleNotFoundError: rclpy |
Python 解释器和 ROS 环境 | 在同一终端加载 /opt/ros/jazzy/setup.bash,确认使用系统 Python |
| 3 秒内收不到温度 | 发布者是否持续发送、话题名是否一致、QoS 是否兼容 | 保留 0.1 秒周期;发布与订阅均使用深度 10 的默认可靠 QoS |
wait_for_service 超时 |
服务端是否创建、节点是否加入执行器、通信域是否一致 | 对齐 /device/enable、ROS_DOMAIN_ID 并启动 executor.spin() |
| Future 响应超时 | 服务回调是否阻塞、执行器是否仍在运行 | 保持回调非阻塞,不要在同一个执行器线程里同步等待服务结果 |
不要把 time.sleep(3) 当作接收成功的证据,也不要仅断言 future.done()。通过测试必须同时满足时限、消息内容、响应字段和业务状态;测试结束后先停止执行器,再销毁节点并关闭 rclpy,避免下一次测试沿用残留资源。