|
| 1 | +import unittest |
| 2 | +import rclpy |
| 3 | +from rclpy.node import Node |
| 4 | +from rclpy.qos import QoSProfile, ReliabilityPolicy, DurabilityPolicy, HistoryPolicy |
| 5 | +from xbot_msgs.msg import JointState |
| 6 | + |
| 7 | + |
| 8 | +TOPIC = '/xbotcore/joint_states' |
| 9 | +TIMEOUT_SEC = 5.0 |
| 10 | + |
| 11 | +# Match the most permissive QoS to be compatible with any publisher |
| 12 | +QOS = QoSProfile( |
| 13 | + reliability=ReliabilityPolicy.BEST_EFFORT, |
| 14 | + durability=DurabilityPolicy.VOLATILE, |
| 15 | + history=HistoryPolicy.KEEP_LAST, |
| 16 | + depth=10, |
| 17 | +) |
| 18 | + |
| 19 | + |
| 20 | +class JointStateListener(Node): |
| 21 | + def __init__(self): |
| 22 | + super().__init__('test_joint_state_listener') |
| 23 | + self.latest_msg = None |
| 24 | + self.sub = self.create_subscription( |
| 25 | + JointState, |
| 26 | + TOPIC, |
| 27 | + self._cb, |
| 28 | + QOS, |
| 29 | + ) |
| 30 | + |
| 31 | + def _cb(self, msg): |
| 32 | + self.latest_msg = msg |
| 33 | + |
| 34 | + |
| 35 | +class TestJointStateTopic(unittest.TestCase): |
| 36 | + |
| 37 | + @classmethod |
| 38 | + def setUpClass(cls): |
| 39 | + rclpy.init() |
| 40 | + cls.node = JointStateListener() |
| 41 | + |
| 42 | + @classmethod |
| 43 | + def tearDownClass(cls): |
| 44 | + cls.node.destroy_node() |
| 45 | + rclpy.shutdown() |
| 46 | + |
| 47 | + def test_receives_joint_state(self): |
| 48 | + """Fail if no message is received on /xbotcore/joint_states within TIMEOUT_SEC.""" |
| 49 | + import time |
| 50 | + deadline = time.time() + TIMEOUT_SEC |
| 51 | + while time.time() < deadline and self.node.latest_msg is None: |
| 52 | + rclpy.spin_once(self.node, timeout_sec=0.1) |
| 53 | + |
| 54 | + self.assertIsNotNone( |
| 55 | + self.node.latest_msg, |
| 56 | + f'No message received on {TOPIC} within {TIMEOUT_SEC} seconds.', |
| 57 | + ) |
| 58 | + |
| 59 | + msg = self.node.latest_msg |
| 60 | + self.get_logger_info(f'Received joint state with {len(msg.name)} joints: {msg.name}') |
| 61 | + |
| 62 | + def get_logger_info(self, text): |
| 63 | + self.node.get_logger().info(text) |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + unittest.main() |
0 commit comments