Dataset Viewer
Auto-converted to Parquet Duplicate
language
stringclasses
4 values
source_code
stringlengths
2
986k
test_code
stringlengths
125
758k
repo_name
stringclasses
97 values
instruction
stringlengths
156
643
python
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List, Optional, Set, TYPE_CHECKING import weakref from rcl_interfaces.msg import SetParametersResult from rclpy.clock import ROSClock from rclpy.clock_type import ClockType from rclpy.parameter import Parameter from rclpy.qos import QoSProfile from rclpy.qos import ReliabilityPolicy from rclpy.time import Time import rosgraph_msgs.msg if TYPE_CHECKING: from rclpy.node import Node from rclpy.subscription import Subscription CLOCK_TOPIC = '/clock' USE_SIM_TIME_NAME = 'use_sim_time' class TimeSource: def __init__(self, *, node: Optional['Node'] = None): self._clock_sub: Optional['Subscription[rosgraph_msgs.msg.Clock]'] = None self._node_weak_ref: Optional[weakref.ReferenceType['Node']] = None self._associated_clocks: Set[ROSClock] = set() # Zero time is a special value that means time is uninitialzied self._last_time_set = Time(clock_type=ClockType.ROS_TIME) self._ros_time_is_active = False if node is not None: self.attach_node(node) @property def ros_time_is_active(self) -> bool: return self._ros_time_is_active @ros_time_is_active.setter def ros_time_is_active(self, enabled: bool) -> None: if self._ros_time_is_active == enabled: return self._ros_time_is_active = enabled for clock in self._associated_clocks: clock._set_ros_time_is_active(enabled) if enabled: self._subscribe_to_clock_topic() else: if self._clock_sub is not None: node = self._get_node() if node is not None: node.destroy_subscription(self._clock_sub) self._clock_sub = None def _subscribe_to_clock_topic(self) -> None: if self._clock_sub is None: node = self._get_node() if node is not None: self._clock_sub = node.create_subscription( rosgraph_msgs.msg.Clock, CLOCK_TOPIC, self.clock_callback, QoSProfile(depth=1, reliability=ReliabilityPolicy.BEST_EFFORT) ) def attach_node(self, node: 'Node') -> None: from rclpy.node import Node if not isinstance(node, Node): raise TypeError('Node must be of type rclpy.node.Node') # Remove an existing node. if self._node_weak_ref is not None: self.detach_node() self._node_weak_ref = weakref.ref(node) if not node.has_parameter(USE_SIM_TIME_NAME): node.declare_parameter(USE_SIM_TIME_NAME, False) use_sim_time_param = node.get_parameter(USE_SIM_TIME_NAME) if use_sim_time_param.type_ != Parameter.Type.NOT_SET: if use_sim_time_param.type_ == Parameter.Type.BOOL: self.ros_time_is_active = use_sim_time_param.value else: node.get_logger().error( "Invalid type for parameter '{}' {!r} should be bool" .format(USE_SIM_TIME_NAME, use_sim_time_param.type_)) else: node.get_logger().debug( "'{}' parameter not set, using wall time by default" .format(USE_SIM_TIME_NAME)) node.add_on_set_parameters_callback(self._on_parameter_event) def detach_node(self) -> None: # Remove the subscription to the clock topic. if self._clock_sub is not None: node = self._get_node() if node is None: raise RuntimeError('Unable to destroy previously created clock subscription') node.destroy_subscription(self._clock_sub) self._clock_sub = None self._node_weak_ref = None def attach_clock(self, clock: ROSClock) -> None: if not isinstance(clock, ROSClock): raise ValueError('Only clocks with type ROS_TIME can be attached.') clock.set_ros_time_override(self._last_time_set) clock._set_ros_time_is_active(self.ros_time_is_active) self._associated_clocks.add(clock) def clock_callback(self, msg: rosgraph_msgs.msg.Clock) -> None: # Cache the last message in case a new clock is attached. time_from_msg = Time.from_msg(msg.clock) self._last_time_set = time_from_msg for clock in self._associated_clocks: clock.set_ros_time_override(time_from_msg) def _on_parameter_event(self, parameter_list: List[Parameter[bool]]) -> SetParametersResult: successful = True reason = '' for parameter in parameter_list: if parameter.name == USE_SIM_TIME_NAME: if parameter.type_ == Parameter.Type.BOOL: self.ros_time_is_active = parameter.value else: successful = False reason = '{} parameter set to something besides a bool'.format( USE_SIM_TIME_NAME) node = self._get_node() if node: node.get_logger().error(reason) break return SetParametersResult(successful=successful, reason=reason) def _get_node(self) -> Optional['Node']: if self._node_weak_ref is not None: return self._node_weak_ref() return None
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import unittest from unittest.mock import Mock import rclpy from rclpy.clock import Clock from rclpy.clock import ClockChange from rclpy.clock import JumpThreshold from rclpy.clock import ROSClock from rclpy.clock_type import ClockType from rclpy.duration import Duration from rclpy.parameter import Parameter from rclpy.time import Time from rclpy.time_source import CLOCK_TOPIC from rclpy.time_source import TimeSource import rosgraph_msgs.msg class TestTimeSource(unittest.TestCase): def setUp(self) -> None: self.context = rclpy.context.Context() rclpy.init(context=self.context) self.node = rclpy.create_node( 'TestTimeSource', namespace='/rclpy', context=self.context, allow_undeclared_parameters=True) def tearDown(self) -> None: self.node.destroy_node() rclpy.shutdown(context=self.context) def publish_clock_messages(self) -> None: clock_pub = self.node.create_publisher(rosgraph_msgs.msg.Clock, CLOCK_TOPIC, 1) cycle_count = 0 time_msg = rosgraph_msgs.msg.Clock() while rclpy.ok(context=self.context) and cycle_count < 5: time_msg.clock.sec = cycle_count clock_pub.publish(time_msg) cycle_count += 1 executor = rclpy.executors.SingleThreadedExecutor(context=self.context) rclpy.spin_once(self.node, timeout_sec=1, executor=executor) # TODO(dhood): use rate once available time.sleep(1) def publish_reversed_clock_messages(self) -> None: clock_pub = self.node.create_publisher(rosgraph_msgs.msg.Clock, CLOCK_TOPIC, 1) cycle_count = 0 time_msg = rosgraph_msgs.msg.Clock() while rclpy.ok(context=self.context) and cycle_count < 5: time_msg.clock.sec = 6 - cycle_count clock_pub.publish(time_msg) cycle_count += 1 executor = rclpy.executors.SingleThreadedExecutor(context=self.context) rclpy.spin_once(self.node, timeout_sec=1, executor=executor) time.sleep(1) def set_use_sim_time_parameter(self, value: bool) -> bool: self.node.set_parameters( [Parameter('use_sim_time', Parameter.Type.BOOL, value)]) executor = rclpy.executors.SingleThreadedExecutor(context=self.context) cycle_count = 0 while rclpy.ok(context=self.context) and cycle_count < 5: use_sim_time_param: Parameter[bool] = self.node.get_parameter('use_sim_time') cycle_count += 1 if use_sim_time_param.type_ == Parameter.Type.BOOL: break rclpy.spin_once(self.node, timeout_sec=1, executor=executor) time.sleep(1) return use_sim_time_param.value == value def test_time_source_attach_clock(self) -> None: time_source = TimeSource(node=self.node) # ROSClock is a specialization of Clock with ROS time methods. time_source.attach_clock(ROSClock()) # Other clock types are not supported. with self.assertRaises(ValueError): time_source.attach_clock( Clock(clock_type=ClockType.SYSTEM_TIME)) # type: ignore[arg-type] with self.assertRaises(ValueError): time_source.attach_clock( Clock(clock_type=ClockType.STEADY_TIME)) # type: ignore[arg-type] def test_time_source_not_using_sim_time(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) # When not using sim time, ROS time should look like system time now = clock.now() system_now = Clock(clock_type=ClockType.SYSTEM_TIME).now() assert (system_now.nanoseconds - now.nanoseconds) < 1e9 # Presence of clock publisher should not affect the clock self.publish_clock_messages() self.assertFalse(clock.ros_time_is_active) now = clock.now() system_now = Clock(clock_type=ClockType.SYSTEM_TIME).now() assert (system_now.nanoseconds - now.nanoseconds) < 1e9 # Whether or not an attached clock is using ROS time should be determined by the time # source managing it. self.assertFalse(time_source.ros_time_is_active) clock2 = ROSClock() clock2._set_ros_time_is_active(True) time_source.attach_clock(clock2) self.assertFalse(clock2.ros_time_is_active) assert time_source._clock_sub is None def test_time_source_using_sim_time(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) # Setting ROS time active on a time source should also cause attached clocks' use of ROS # time to be set to active. self.assertFalse(time_source.ros_time_is_active) self.assertFalse(clock.ros_time_is_active) assert self.set_use_sim_time_parameter(True) self.assertTrue(time_source.ros_time_is_active) self.assertTrue(clock.ros_time_is_active) # A subscriber should have been created assert time_source._clock_sub is not None # Before any messages have been received on the /clock topic, now() should return 0 assert clock.now() == Time(seconds=0, clock_type=ClockType.ROS_TIME) # When using sim time, ROS time should look like the messages received on /clock self.publish_clock_messages() assert clock.now() > Time(seconds=0, clock_type=ClockType.ROS_TIME) assert clock.now() <= Time(seconds=5, clock_type=ClockType.ROS_TIME) # Check that attached clocks get the cached message clock2 = Clock(clock_type=ClockType.ROS_TIME) time_source.attach_clock(clock2) assert clock2.now() > Time(seconds=0, clock_type=ClockType.ROS_TIME) assert clock2.now() <= Time(seconds=5, clock_type=ClockType.ROS_TIME) # Check detaching the node time_source.detach_node() node2 = rclpy.create_node('TestTimeSource2', namespace='/rclpy', context=self.context) time_source.attach_node(node2) node2.destroy_node() assert time_source._get_node() == node2 assert time_source._clock_sub is None def test_forwards_jump(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) assert self.set_use_sim_time_parameter(True) pre_cb = Mock() post_cb = Mock() threshold = JumpThreshold( min_forward=Duration(seconds=0.5), min_backward=None, on_clock_change=False) handler = clock.create_jump_callback( threshold, pre_callback=pre_cb, post_callback=post_cb) self.publish_clock_messages() pre_cb.assert_called() post_cb.assert_called() assert post_cb.call_args[0][0].clock_change == ClockChange.ROS_TIME_NO_CHANGE handler.unregister() def test_backwards_jump(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) assert self.set_use_sim_time_parameter(True) pre_cb = Mock() post_cb = Mock() threshold = JumpThreshold( min_forward=None, min_backward=Duration(seconds=-0.5), on_clock_change=False) handler = clock.create_jump_callback( threshold, pre_callback=pre_cb, post_callback=post_cb) self.publish_reversed_clock_messages() pre_cb.assert_called() post_cb.assert_called() assert post_cb.call_args[0][0].clock_change == ClockChange.ROS_TIME_NO_CHANGE handler.unregister() def test_clock_change(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) assert self.set_use_sim_time_parameter(True) pre_cb = Mock() post_cb = Mock() threshold = JumpThreshold(min_forward=None, min_backward=None, on_clock_change=True) handler = clock.create_jump_callback( threshold, pre_callback=pre_cb, post_callback=post_cb) assert self.set_use_sim_time_parameter(False) pre_cb.assert_called() post_cb.assert_called() assert post_cb.call_args[0][0].clock_change == ClockChange.ROS_TIME_DEACTIVATED pre_cb.reset_mock() post_cb.reset_mock() assert self.set_use_sim_time_parameter(True) pre_cb.assert_called() post_cb.assert_called() assert post_cb.call_args[0][0].clock_change == ClockChange.ROS_TIME_ACTIVATED handler.unregister() def test_no_pre_callback(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) assert self.set_use_sim_time_parameter(True) post_cb = Mock() threshold = JumpThreshold(min_forward=None, min_backward=None, on_clock_change=True) handler = clock.create_jump_callback( threshold, pre_callback=None, post_callback=post_cb) assert self.set_use_sim_time_parameter(False) post_cb.assert_called_once() assert post_cb.call_args[0][0].clock_change == ClockChange.ROS_TIME_DEACTIVATED handler.unregister() def test_no_post_callback(self) -> None: time_source = TimeSource(node=self.node) clock = ROSClock() time_source.attach_clock(clock) assert self.set_use_sim_time_parameter(True) pre_cb = Mock() threshold = JumpThreshold(min_forward=None, min_backward=None, on_clock_change=True) handler = clock.create_jump_callback( threshold, pre_callback=pre_cb, post_callback=None) assert self.set_use_sim_time_parameter(False) pre_cb.assert_called_once() handler.unregister() if __name__ == '__main__': unittest.main()
rclpy
You are an expert Python testing engineer. Task: Write a unit test for 'TimeSource' using 'unittest' and 'unittest.mock'. Context: - Class Name: TimeSource - Dependencies to Mock: TYPE_CHECKING, weakref, SetParametersResult, ROSClock, ClockType Requirements: Use @patch for mocks, follow AAA pattern.
python
# Copyright 2024-2025 Brad Martin # Copyright 2024 Merlin Labs, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import faulthandler import typing import rclpy.executors from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy # Try to look like we inherit from the rclpy Executor for type checking purposes without # getting any of the code from the base class. def EventsExecutor(*, context: typing.Optional[rclpy.Context] = None) -> rclpy.executors.Executor: if context is None: context = rclpy.get_default_context() # For debugging purposes, if anything goes wrong in C++ make sure we also get a # Python backtrace dumped with the crash. faulthandler.enable() ex = typing.cast(rclpy.executors.Executor, _rclpy.EventsExecutor(context)) # rclpy.Executor does this too. Note, the context itself is smart enough to check # for bound methods, and check whether the instances they're bound to still exist at # callback time, so we don't have to worry about tearing down this stale callback at # destruction time. # TODO(bmartin427) This should really be done inside of the EventsExecutor # implementation itself, but I'm unable to figure out a pybind11 incantation that # allows me to pass this bound method call from C++. context.on_shutdown(ex.wake) return ex
# Copyright 2024-2025 Brad Martin # Copyright 2024 Merlin Labs, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import typing import unittest import action_msgs.msg import rclpy.action from rclpy.action.client import ClientGoalHandle from rclpy.action.server import ServerGoalHandle import rclpy.clock_type import rclpy.duration import rclpy.event_handler import rclpy.executors import rclpy.experimental import rclpy.node import rclpy.parameter import rclpy.qos import rclpy.time import rclpy.timer import rosgraph_msgs.msg import test_msgs.action import test_msgs.msg import test_msgs.srv from typing_extensions import TypeAlias FibonacciServerGoalHandle: TypeAlias = ServerGoalHandle[test_msgs.action.Fibonacci.Goal, test_msgs.action.Fibonacci.Result, test_msgs.action.Fibonacci.Feedback] FibonacciClientGoalHandle: TypeAlias = ClientGoalHandle[test_msgs.action.Fibonacci.Goal, test_msgs.action.Fibonacci.Result, test_msgs.action.Fibonacci.Feedback] def _get_pub_sub_qos(transient_local: bool) -> rclpy.qos.QoSProfile: if not transient_local: return rclpy.qos.QoSProfile(history=rclpy.qos.HistoryPolicy.KEEP_ALL) # For test purposes we deliberately want a TRANSIENT_LOCAL QoS with KEEP_ALL # history. return rclpy.qos.QoSProfile( history=rclpy.qos.HistoryPolicy.KEEP_ALL, durability=rclpy.qos.DurabilityPolicy.TRANSIENT_LOCAL, ) class SubTestNode(rclpy.node.Node): """Node to test subscriptions and subscription-related events.""" def __init__(self, *, transient_local: bool = False, use_async_handler: bool = False) -> None: super().__init__('test_sub_node') self._new_pub_future: typing.Optional[ rclpy.Future[rclpy.event_handler.QoSSubscriptionMatchedInfo] ] = None self._received_future: typing.Optional[rclpy.Future[test_msgs.msg.BasicTypes]] = None self._sub = self.create_subscription( test_msgs.msg.BasicTypes, # This node seems to get stale discovery data and then complain about QoS # changes if we reuse the same topic name. 'test_topic' + ('_transient_local' if transient_local else ''), self._async_handle_sub if use_async_handler else self._handle_sub, _get_pub_sub_qos(transient_local), event_callbacks=rclpy.event_handler.SubscriptionEventCallbacks( matched=self._handle_matched_sub ), ) def drop_subscription(self) -> None: self.destroy_subscription(self._sub) def expect_pub_info( self, ) -> rclpy.Future[rclpy.event_handler.QoSSubscriptionMatchedInfo]: self._new_pub_future = rclpy.Future() return self._new_pub_future def expect_message(self) -> rclpy.Future[test_msgs.msg.BasicTypes]: self._received_future = rclpy.Future() return self._received_future def _handle_sub(self, msg: test_msgs.msg.BasicTypes) -> None: if self._received_future is not None: future = self._received_future self._received_future = None future.set_result(msg) async def _async_handle_sub(self, msg: test_msgs.msg.BasicTypes) -> None: # Don't bother to actually delay at all for this test return self._handle_sub(msg) def _handle_matched_sub(self, info: rclpy.event_handler.QoSSubscriptionMatchedInfo) -> None: """Handle a new publisher being matched to our subscription.""" if self._new_pub_future is not None: self._new_pub_future.set_result(info) self._new_pub_future = None class PubTestNode(rclpy.node.Node): """Node to test publications and publication-related events.""" def __init__(self, *, transient_local: bool = False) -> None: super().__init__('test_pub_node') self._new_sub_future: typing.Optional[ rclpy.Future[rclpy.event_handler.QoSPublisherMatchedInfo] ] = None self._pub = self.create_publisher( test_msgs.msg.BasicTypes, 'test_topic' + ('_transient_local' if transient_local else ''), _get_pub_sub_qos(transient_local), event_callbacks=rclpy.event_handler.PublisherEventCallbacks( matched=self._handle_matched_pub ), ) def expect_sub_info( self, ) -> rclpy.Future[rclpy.event_handler.QoSPublisherMatchedInfo]: self._new_sub_future = rclpy.Future() return self._new_sub_future def publish(self, value: float) -> None: self._pub.publish(test_msgs.msg.BasicTypes(float32_value=value)) def _handle_matched_pub(self, info: rclpy.event_handler.QoSPublisherMatchedInfo) -> None: """Handle a new subscriber being matched to our publication.""" if self._new_sub_future is not None: self._new_sub_future.set_result(info) self._new_sub_future = None class ServiceServerTestNode(rclpy.node.Node): """Node to test service server-side operation.""" def __init__( self, *, use_async_handler: bool = False, parameter_overrides: typing.Optional[list[rclpy.parameter.Parameter[bool]]] = None, ) -> None: super().__init__('test_service_server_node', parameter_overrides=parameter_overrides) self._got_request_future: typing.Optional[ rclpy.Future[test_msgs.srv.BasicTypes.Request] ] = None self._pending_response: typing.Optional[test_msgs.srv.BasicTypes.Response] = None self.create_service( test_msgs.srv.BasicTypes, 'test_service', self._async_handle_service if use_async_handler else self._handle_service, ) def expect_request( self, success: bool, error_msg: str ) -> rclpy.Future[test_msgs.srv.BasicTypes.Request]: """ Expect an incoming request. The arguments are used to compose the response. """ self._got_request_future = rclpy.Future() self._pending_response = test_msgs.srv.BasicTypes.Response( bool_value=success, string_value=error_msg ) return self._got_request_future def _handle_service( self, req: test_msgs.srv.BasicTypes.Request, res: test_msgs.srv.BasicTypes.Response, ) -> test_msgs.srv.BasicTypes.Response: self._handle_request(req) return self._get_response(res) def _handle_request(self, req: test_msgs.srv.BasicTypes.Request) -> None: if self._got_request_future is not None: self._got_request_future.set_result(req) self._got_request_future = None def _get_response( self, res: test_msgs.srv.BasicTypes.Response ) -> test_msgs.srv.BasicTypes.Response: if self._pending_response is not None: res = self._pending_response self._pending_response = None return res async def _async_handle_service( self, req: test_msgs.srv.BasicTypes.Request, res: test_msgs.srv.BasicTypes.Response ) -> test_msgs.srv.BasicTypes.Response: self._handle_request(req) # Create and await a timer before replying, to represent other work. timer_future = rclpy.Future[None]() timer = self.create_timer( 1.0, lambda: timer_future.set_result(None), # NOTE: As of this writing, the callback_group is entirely ignored by EventsExecutor; # however, it would be needed for SingleThreadedExecutor to pass this same test, so # we'll include it anyway. callback_group=rclpy.callback_groups.ReentrantCallbackGroup(), ) await timer_future self.destroy_timer(timer) return self._get_response(res) class ServiceClientTestNode(rclpy.node.Node): """Node to test service client-side operation.""" def __init__(self) -> None: super().__init__('test_service_client_node') self._client: rclpy.client.Client[ test_msgs.srv.BasicTypes.Request, test_msgs.srv.BasicTypes.Response ] = self.create_client(test_msgs.srv.BasicTypes, 'test_service') def issue_request(self, value: float) -> rclpy.Future[test_msgs.srv.BasicTypes.Response]: req = test_msgs.srv.BasicTypes.Request(float32_value=value) return self._client.call_async(req) class TimerTestNode(rclpy.node.Node): """Node to test timer operation.""" def __init__( self, index: int = 0, parameter_overrides: typing.Optional[list[rclpy.parameter.Parameter[bool]]] = None, ) -> None: super().__init__(f'test_timer{index}', parameter_overrides=parameter_overrides) self._timer_events = 0 self._tick_future: typing.Optional[rclpy.Future[rclpy.timer.TimerInfo]] = None self._timer = self.create_timer(0.1, self._handle_timer) @property def timer_events(self) -> int: return self._timer_events def expect_tick(self) -> rclpy.Future[rclpy.timer.TimerInfo]: """Get future on TimerInfo for an anticipated timer tick.""" self._tick_future = rclpy.Future() return self._tick_future def _handle_timer(self, info: rclpy.timer.TimerInfo) -> None: self._timer_events += 1 if self._tick_future is not None: self._tick_future.set_result(info) self._tick_future = None class ClockPublisherNode(rclpy.node.Node): """Node to publish rostime clock updates.""" def __init__(self) -> None: super().__init__('clock_node') self._now = rclpy.time.Time(clock_type=rclpy.clock_type.ClockType.ROS_TIME) self._pub = self.create_publisher( rosgraph_msgs.msg.Clock, '/clock', rclpy.qos.QoSProfile(depth=1, reliability=rclpy.qos.ReliabilityPolicy.BEST_EFFORT), ) def advance_time(self, millisec: int) -> None: self._now += rclpy.duration.Duration(nanoseconds=millisec * 1000000) self._pub.publish(rosgraph_msgs.msg.Clock(clock=self._now.to_msg())) @property def now(self) -> rclpy.time.Time: return self._now class ActionServerTestNode(rclpy.node.Node): """Node to test action server-side operation.""" def __init__(self) -> None: super().__init__( 'test_action_server_node', parameter_overrides=[rclpy.parameter.Parameter('use_sim_time', value=True)], ) self._got_goal_future: typing.Optional[rclpy.Future[test_msgs.action.Fibonacci.Goal]] = ( None ) self._srv = rclpy.action.ActionServer( self, test_msgs.action.Fibonacci, 'test_action', self._handle_execute, handle_accepted_callback=self._handle_accepted, result_timeout=10, ) self._goal_handle: typing.Optional[FibonacciServerGoalHandle] = None self._sequence: list[int] = [] def expect_goal(self) -> rclpy.Future[test_msgs.action.Fibonacci.Goal]: self._goal_handle = None self._got_goal_future = rclpy.Future() return self._got_goal_future def _handle_accepted(self, goal_handle: FibonacciServerGoalHandle) -> None: self._goal_handle = goal_handle self._sequence = [0, 1] if self._got_goal_future is not None: self._got_goal_future.set_result(goal_handle.request) self._got_goal_future = None # Wait to finish until instructed by test def advance_feedback(self) -> typing.Optional[list[int]]: """ Add an entry to the result in progress and sends a feedback message. Returns the current sequence in progress if incomplete, or None if the sequence is complete and it's time to complete the operation instead. """ assert self._goal_handle is not None n = self._goal_handle.request.order + 1 if len(self._sequence) < n: self._sequence.append(self._sequence[-2] + self._sequence[-1]) if len(self._sequence) >= n: return None # FYI normally feedbacks would be sent from the execute handler, but we've tied # it to its own public method for testing fb = test_msgs.action.Fibonacci.Feedback() fb.sequence = self._sequence self._goal_handle.publish_feedback(fb) return self._sequence def execute(self) -> FibonacciServerGoalHandle: """ Completes the action in progress. Returns the handle to the goal executed. """ handle = self._goal_handle self._goal_handle = None assert handle is not None handle.execute() return handle def _handle_execute( self, goal_handle: FibonacciServerGoalHandle ) -> test_msgs.action.Fibonacci.Result: goal_handle.succeed() result = test_msgs.action.Fibonacci.Result() result.sequence = self._sequence return result class ActionClientTestNode(rclpy.node.Node): """Node to test action client-side operation.""" def __init__(self) -> None: super().__init__('test_action_client_node') self._client = rclpy.action.ActionClient[ test_msgs.action.Fibonacci.Goal, test_msgs.action.Fibonacci.Result, test_msgs.action.Fibonacci.Feedback, ](self, test_msgs.action.Fibonacci, 'test_action') self._feedback_future: typing.Optional[ rclpy.Future[test_msgs.action.Fibonacci.Feedback] ] = None self._result_future: typing.Optional[rclpy.Future[test_msgs.action.Fibonacci.Result]] = ( None ) def send_goal(self, order: int) -> rclpy.Future[FibonacciClientGoalHandle]: """ Send a new goal. The future will contain the goal handle when the goal submission response has been received. """ self._client.wait_for_server() goal_ack_future = self._client.send_goal_async( test_msgs.action.Fibonacci.Goal(order=order), feedback_callback=self._handle_feedback, ) goal_ack_future.add_done_callback(self._handle_goal_ack) return goal_ack_future def _handle_goal_ack(self, future: rclpy.Future[FibonacciClientGoalHandle]) -> None: handle = future.result() assert handle is not None result_future = handle.get_result_async() result_future.add_done_callback(self._handle_result_response) def expect_feedback(self) -> rclpy.Future[test_msgs.action.Fibonacci.Feedback]: self._feedback_future = rclpy.Future() return self._feedback_future def _handle_feedback( self, # If this is a private 'Impl' detail, why is rclpy handing this out?? fb_msg: test_msgs.action.Fibonacci.Impl.FeedbackMessage, ) -> None: if self._feedback_future is not None: self._feedback_future.set_result(fb_msg.feedback) self._feedback_future = None def expect_result( self, ) -> rclpy.Future[test_msgs.action.Fibonacci.Result]: self._result_future = rclpy.Future() return self._result_future def _handle_result_response( self, future: rclpy.Future[test_msgs.action.Fibonacci_GetResult_Response] ) -> None: response: typing.Optional[test_msgs.action.Fibonacci_GetResult_Response] = future.result() assert response is not None assert self._result_future is not None result: test_msgs.action.Fibonacci.Result = response.result self._result_future.set_result(result) self._result_future = None # These two python types are both actually rmw_matched_status_t rmw_matched_status_t = typing.Union[ rclpy.event_handler.QoSSubscriptionMatchedInfo, rclpy.event_handler.QoSPublisherMatchedInfo ] class TestEventsExecutor(unittest.TestCase): def setUp(self, *args: typing.Any, **kwargs: typing.Any) -> None: super().__init__(*args, **kwargs) # Prevent nodes under test from discovering other random stuff to talk to os.environ['ROS_AUTOMATIC_DISCOVERY_RANGE'] = 'OFF' rclpy.init() self.executor = rclpy.experimental.EventsExecutor() def tearDown(self) -> None: # Clean up all nodes still in the executor before shutdown for node in self.executor.get_nodes(): self.executor.remove_node(node) node.destroy_node() self.executor.shutdown() rclpy.shutdown() def _expect_future_done(self, future: rclpy.Future[typing.Any]) -> None: # Use a moderately long timeout with the expectation that we shouldn't often # need the whole duration. self.executor.spin_until_future_complete(future, 1.0) self.assertTrue(future.done()) def _expect_future_not_done(self, future: rclpy.Future[typing.Any]) -> None: # Use a short timeout to give the future some time to complete if we are going # to fail, but not very long because we'll be waiting the full duration every # time during successful tests. It's ok if the timeout is a bit short and the # failure isn't 100% deterministic. self.executor.spin_until_future_complete(future, 0.2) self.assertFalse(future.done()) def _spin_for(self, sec: float) -> None: """Spins the executor for the given number of realtime seconds.""" # Note that this roundabout approach of waiting on a future that will never # finish with a timeout seems to be the only way with the rclpy.Executor API to # spin for a fixed time. self.executor.spin_until_future_complete(rclpy.Future(), sec) def _check_match_event_future( self, future: rclpy.Future[rmw_matched_status_t], total_count: int, current_count: int, ) -> None: # NOTE: fastdds appears to be buggy and reports a change in total_count with # total_count_change staying zero. cyclonedds works as expected. Rather than # have this test be sensitive to which RMW is selected, let's just avoid testing # the change fields altogether. self._expect_future_done(future) info: typing.Optional[rmw_matched_status_t] = future.result() assert info is not None self.assertEqual(info.total_count, total_count) self.assertEqual(info.current_count, current_count) def _check_message_future( self, future: rclpy.Future[test_msgs.msg.BasicTypes], value: float ) -> None: self._expect_future_done(future) msg: typing.Optional[test_msgs.msg.BasicTypes] = future.result() assert msg is not None self.assertAlmostEqual(msg.float32_value, value, places=5) def _check_service_request_future( self, future: rclpy.Future[test_msgs.srv.BasicTypes.Request], value: float ) -> None: self._expect_future_done(future) req: typing.Optional[test_msgs.srv.BasicTypes.Request] = future.result() assert req is not None self.assertAlmostEqual(req.float32_value, value, places=5) def _check_service_response_future( self, future: rclpy.Future[test_msgs.srv.BasicTypes.Response], success: bool, error_msg: str, ) -> None: self._expect_future_done(future) res: typing.Optional[test_msgs.srv.BasicTypes.Response] = future.result() assert res is not None self.assertEqual(res.bool_value, success) self.assertEqual(res.string_value, error_msg) def test_pub_sub(self) -> None: sub_node = SubTestNode() new_pub_future = sub_node.expect_pub_info() received_future = sub_node.expect_message() self.executor.add_node(sub_node) # With subscriber node alone, should be no publisher or messages self._expect_future_not_done(new_pub_future) self.assertFalse(received_future.done()) # Already waited a bit pub_node = PubTestNode() new_sub_future = pub_node.expect_sub_info() self.executor.add_node(pub_node) # Publisher and subscriber should find each other but no messages should be # exchanged yet self._check_match_event_future(new_pub_future, 1, 1) new_pub_future = sub_node.expect_pub_info() self._check_match_event_future(new_sub_future, 1, 1) new_sub_future = pub_node.expect_sub_info() self._expect_future_not_done(received_future) # Send messages and make sure they're received. for i in range(300): pub_node.publish(0.1 * i) self._check_message_future(received_future, 0.1 * i) received_future = sub_node.expect_message() # Destroy the subscription, make sure the publisher is notified sub_node.drop_subscription() self._check_match_event_future(new_sub_future, 1, 0) new_sub_future = pub_node.expect_sub_info() # Publish another message to ensure all subscriber callbacks got cleaned up pub_node.publish(4.7) self._expect_future_not_done(new_pub_future) self.assertFalse(received_future.done()) # Already waited a bit # Delete the subscribing node entirely. There should be no additional match activity and # still no subscriber callbacks. self.executor.remove_node(sub_node) sub_node.destroy_node() self._expect_future_not_done(new_sub_future) self.assertFalse(new_pub_future.done()) # Already waited a bit self.assertFalse(received_future.done()) # Already waited a bit def test_async_sub(self) -> None: sub_node = SubTestNode(use_async_handler=True) received_future = sub_node.expect_message() self.executor.add_node(sub_node) self._expect_future_not_done(received_future) pub_node = PubTestNode() self.executor.add_node(pub_node) pub_node.publish(0.0) self._check_message_future(received_future, 0.0) def test_pub_sub_multi_message(self) -> None: # Creates a transient local publisher and queues multiple messages on it. Then # creates a subscriber and makes sure all sent messages get delivered when it # comes up. pub_node = PubTestNode(transient_local=True) self.executor.add_node(pub_node) for i in range(5): pub_node.publish(0.1 * i) sub_node = SubTestNode(transient_local=True) received_future = sub_node.expect_message() received_messages: list[test_msgs.msg.BasicTypes] = [] def handle_message(future: rclpy.Future[test_msgs.msg.BasicTypes]) -> None: nonlocal received_future msg = future.result() assert msg is not None received_messages.append(msg) received_future = sub_node.expect_message() received_future.add_done_callback(handle_message) received_future.add_done_callback(handle_message) self._expect_future_not_done(received_future) self.executor.add_node(sub_node) while len(received_messages) < 5: self._expect_future_done(received_future) self.assertEqual(len(received_messages), 5) for i in range(5): self.assertAlmostEqual(received_messages[i].float32_value, 0.1 * i, places=5) self._expect_future_not_done(received_future) pub_node.publish(0.5) self._check_message_future(received_future, 0.5) def test_service(self) -> None: server_node = ServiceServerTestNode() got_request_future = server_node.expect_request(True, 'test response 0') self.executor.add_node(server_node) self._expect_future_not_done(got_request_future) client_node = ServiceClientTestNode() self.executor.add_node(client_node) self._expect_future_not_done(got_request_future) for i in range(300): got_response_future = client_node.issue_request(7.1) self._check_service_request_future(got_request_future, 7.1) got_request_future = server_node.expect_request(True, f'test response {i + 1}') self._check_service_response_future(got_response_future, True, f'test response {i}') # Destroy server node and retry issuing a request self.executor.remove_node(server_node) server_node.destroy_node() self._expect_future_not_done(got_request_future) got_response_future = client_node.issue_request(5.0) self._expect_future_not_done(got_request_future) self.assertFalse(got_response_future.done()) # Already waited a bit def test_async_service(self) -> None: server_node = ServiceServerTestNode( use_async_handler=True, parameter_overrides=[rclpy.parameter.Parameter('use_sim_time', value=True)], ) got_request_future = server_node.expect_request(True, 'test response') client_node = ServiceClientTestNode() clock_node = ClockPublisherNode() for node in [server_node, client_node, clock_node]: self.executor.add_node(node) self._expect_future_not_done(got_request_future) got_response_future = client_node.issue_request(7.1) self._check_service_request_future(got_request_future, 7.1) self._expect_future_not_done(got_response_future) clock_node.advance_time(1000) self._check_service_response_future(got_response_future, True, 'test response') def test_timers(self) -> None: realtime_node = TimerTestNode(index=0) rostime_node = TimerTestNode( index=1, parameter_overrides=[rclpy.parameter.Parameter('use_sim_time', value=True)] ) clock_node = ClockPublisherNode() for node in [realtime_node, rostime_node, clock_node]: self.executor.add_node(node) # Wait a bit, and make sure the realtime timer ticks, and the rostime one does # not. Since this is based on wall time, be very flexible on tolerances here. realtime_tick_future = realtime_node.expect_tick() self._spin_for(1.0) realtime_ticks = realtime_node.timer_events self.assertGreater(realtime_ticks, 1) self.assertLess(realtime_ticks, 50) self.assertEqual(rostime_node.timer_events, 0) info = realtime_tick_future.result() assert info is not None self.assertGreaterEqual(info.actual_call_time, info.expected_call_time) # Manually tick the rostime timer by less than a full interval. rostime_tick_future = rostime_node.expect_tick() for _ in range(99): clock_node.advance_time(1) self._expect_future_not_done(rostime_tick_future) clock_node.advance_time(1) self._expect_future_done(rostime_tick_future) info = rostime_tick_future.result() assert info is not None self.assertEqual(info.actual_call_time, info.expected_call_time) self.assertEqual(info.actual_call_time, clock_node.now) # Now tick by a bunch of full intervals. for _ in range(300): rostime_tick_future = rostime_node.expect_tick() clock_node.advance_time(100) self._expect_future_done(rostime_tick_future) # Ensure the realtime timer ticked much less than the rostime one. self.assertLess(realtime_node.timer_events, rostime_node.timer_events) # Create two timers with the same interval, both set to cancel the other from the callback. # Only one of the callbacks should be delivered, though we can't necessarily predict which # one. def handler() -> None: nonlocal count, timer1, timer2 # type: ignore[misc] count += 1 timer1.cancel() timer2.cancel() count = 0 timer1 = rostime_node.create_timer(0.01, handler) timer2 = rostime_node.create_timer(0.01, handler) self._spin_for(0.0) self.assertEqual(count, 0) clock_node.advance_time(10) self._spin_for(0.0) self.assertEqual(count, 1) clock_node.advance_time(10) self._spin_for(0.0) self.assertEqual(count, 1) def test_action(self) -> None: clock_node = ClockPublisherNode() self.executor.add_node(clock_node) server_node = ActionServerTestNode() got_goal_future = server_node.expect_goal() self.executor.add_node(server_node) clock_node.advance_time(0) self._expect_future_not_done(got_goal_future) client_node = ActionClientTestNode() self.executor.add_node(client_node) self._expect_future_not_done(got_goal_future) for i in range(300): order = (i % 40) + 1 # Don't want sequence to get too big goal_acknowledged_future = client_node.send_goal(order) self._expect_future_done(got_goal_future) self._expect_future_done(goal_acknowledged_future) req: typing.Optional[test_msgs.action.Fibonacci.Goal] = got_goal_future.result() assert req is not None self.assertEqual(req.order, order) result_future = client_node.expect_result() while True: got_feedback_future = client_node.expect_feedback() seq = server_node.advance_feedback() if seq is None: break self._expect_future_done(got_feedback_future) feedback = got_feedback_future.result() assert feedback is not None self.assertEqual(len(feedback.sequence), len(seq)) last_handle = server_node.execute() self._expect_future_done(result_future) self.assertFalse(got_feedback_future.done()) res: typing.Optional[test_msgs.action.Fibonacci.Result] = result_future.result() assert res is not None self.assertEqual(len(res.sequence), order + 1) got_goal_future = server_node.expect_goal() # Test completed goal expiration by time self.assertEqual(last_handle.status, action_msgs.msg.GoalStatus.STATUS_SUCCEEDED) clock_node.advance_time(9999) self._spin_for(0.2) self.assertEqual(last_handle.status, action_msgs.msg.GoalStatus.STATUS_SUCCEEDED) clock_node.advance_time(2) self._spin_for(0.2) self.assertEqual(last_handle.status, action_msgs.msg.GoalStatus.STATUS_UNKNOWN) # Destroy server node and retry issuing a goal self.executor.remove_node(server_node) server_node.destroy_node() self._expect_future_not_done(got_goal_future) goal_acknowledged_future = client_node.send_goal(5) self._expect_future_not_done(got_goal_future) self.assertFalse(goal_acknowledged_future.done()) # Already waited a bit if __name__ == '__main__': unittest.main()
rclpy
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: faulthandler, typing, rclpy.executors, _rclpy Requirements: Use @patch for mocks, follow AAA pattern.
python
# Copyright 2016 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from enum import Enum import inspect from types import TracebackType from typing import Callable from typing import Generic from typing import Literal from typing import Optional from typing import overload from typing import Type from typing import TypedDict from typing import TypeVar from typing import Union from rclpy.callback_groups import CallbackGroup from rclpy.event_handler import SubscriptionEventCallbacks from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.qos import QoSProfile from rclpy.subscription_content_filter_options import ContentFilterOptions from rclpy.type_support import MsgT from typing_extensions import TypeAlias class PublisherGID(TypedDict): implementation_identifier: str data: bytes class MessageInfo(TypedDict): source_timestamp: int received_timestamp: int publication_sequence_number: Optional[int] reception_sequence_number: Optional[int] publisher_gid: Optional[PublisherGID] # Re-export exception defined in _rclpy C extension. RCLError = _rclpy.RCLError # Left to support Legacy TypeVars. MsgType = TypeVar('MsgType') # Can be redone with TypeVar(default=MsgT) when either typing-extensions4.11.0+ or python3.13+ T = TypeVar('T') GenericSubscriptionCallback: TypeAlias = Union[Callable[[T], None], Callable[[T, MessageInfo], None]] SubscriptionCallbackUnion: TypeAlias = Union[GenericSubscriptionCallback[MsgT], GenericSubscriptionCallback[bytes]] class Subscription(Generic[MsgT]): class CallbackType(Enum): MessageOnly = 0 WithMessageInfo = 1 @overload def __init__( self, subscription_impl: '_rclpy.Subscription[MsgT]', msg_type: Type[MsgT], topic: str, callback: GenericSubscriptionCallback[bytes], callback_group: CallbackGroup, qos_profile: QoSProfile, raw: Literal[True], event_callbacks: SubscriptionEventCallbacks, ) -> None: ... @overload def __init__( self, subscription_impl: '_rclpy.Subscription[MsgT]', msg_type: Type[MsgT], topic: str, callback: GenericSubscriptionCallback[MsgT], callback_group: CallbackGroup, qos_profile: QoSProfile, raw: Literal[False], event_callbacks: SubscriptionEventCallbacks, ) -> None: ... @overload def __init__( self, subscription_impl: '_rclpy.Subscription[MsgT]', msg_type: Type[MsgT], topic: str, callback: SubscriptionCallbackUnion[MsgT], callback_group: CallbackGroup, qos_profile: QoSProfile, raw: bool, event_callbacks: SubscriptionEventCallbacks, ) -> None: ... def __init__( self, subscription_impl: '_rclpy.Subscription[MsgT]', msg_type: Type[MsgT], topic: str, callback: SubscriptionCallbackUnion[MsgT], callback_group: CallbackGroup, qos_profile: QoSProfile, raw: bool, event_callbacks: SubscriptionEventCallbacks, ) -> None: """ Create a container for a ROS subscription. .. warning:: Users should not create a subscription with this constructor, instead they should call :meth:`.Node.create_subscription`. :param subscription_impl: :class:`Subscription` wrapping the underlying ``rcl_subscription_t`` object. :param msg_type: The type of ROS messages the subscription will subscribe to. :param topic: The name of the topic the subscription will subscribe to. :param callback: A user-defined callback function that is called when a message is received by the subscription. :param callback_group: The callback group for the subscription. If ``None``, then the nodes default callback group is used. :param qos_profile: The quality of service profile to apply to the subscription. :param raw: If ``True``, then received messages will be stored in raw binary representation. """ self.__subscription = subscription_impl self.msg_type = msg_type self.topic = topic self.callback = callback self.callback_group = callback_group # True when the callback is ready to fire but has not been "taken" by an executor self._executor_event = False self.qos_profile = qos_profile self.raw = raw self.event_handlers = event_callbacks.create_event_handlers( callback_group, subscription_impl, topic) def get_publisher_count(self) -> int: """Get the number of publishers that this subscription has.""" with self.handle: return self.__subscription.get_publisher_count() @property def handle(self) -> '_rclpy.Subscription[MsgT]': return self.__subscription def destroy(self) -> None: """ Destroy a container for a ROS subscription. .. warning:: Users should not destroy a subscription with this method, instead they should call :meth:`.Node.destroy_subscription`. """ for handler in self.event_handlers: handler.destroy() self.handle.destroy_when_not_in_use() @property def topic_name(self) -> str: with self.handle: return self.__subscription.get_topic_name() @property def callback(self) -> SubscriptionCallbackUnion[MsgT]: return self._callback @callback.setter def callback(self, value: SubscriptionCallbackUnion[MsgT]) -> None: self._callback = value self._callback_type = Subscription.CallbackType.MessageOnly try: inspect.signature(value).bind(object()) return except TypeError: pass try: inspect.signature(value).bind(object(), object()) self._callback_type = Subscription.CallbackType.WithMessageInfo return except TypeError: pass raise RuntimeError( 'Subscription.__init__(): callback should be either be callable with one argument' '(to get only the message) or two (to get message and message info)') @property def logger_name(self) -> str: """Get the name of the logger associated with the node of the subscription.""" with self.handle: return self.__subscription.get_logger_name() @property def is_cft_enabled(self) -> bool: """Check if content filtering is enabled for the subscription.""" with self.handle: return self.__subscription.is_cft_enabled() def set_content_filter(self, filter_expression: str, expression_parameters: list[str]) -> None: """ Set the filter expression and expression parameters for the subscription. :param filter_expression: The filter expression to set. :param expression_parameters: The expression parameters to set. :raises: RCLError if internal error occurred when calling the rcl function. """ with self.handle: self.__subscription.set_content_filter(filter_expression, expression_parameters) def get_content_filter(self) -> ContentFilterOptions: """ Get the filter expression and expression parameters for the subscription. :return: ContentFilterOptions object containing the filter expression and expression parameters. :raises: RCLError if internal error occurred when calling the rcl function. """ with self.handle: return self.__subscription.get_content_filter() def __enter__(self) -> 'Subscription[MsgT]': return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.destroy()
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from typing import List from typing import Optional from unittest.mock import Mock import pytest import rclpy from rclpy.node import Node from rclpy.subscription import Subscription from rclpy.subscription_content_filter_options import ContentFilterOptions from test_msgs.msg import BasicTypes from test_msgs.msg import Empty NODE_NAME = 'test_node' @pytest.fixture(scope='session', autouse=True) def setup_ros() -> None: rclpy.init() @pytest.fixture def test_node(): node = Node(NODE_NAME) yield node node.destroy_node() @pytest.mark.parametrize('topic_name, namespace, expected', [ # No namespaces ('topic', None, '/topic'), ('example/topic', None, '/example/topic'), # Using topics with namespaces ('topic', 'ns', '/ns/topic'), ('example/topic', 'ns', '/ns/example/topic'), ('example/topic', 'my/ns', '/my/ns/example/topic'), ('example/topic', '/my/ns', '/my/ns/example/topic'), # Global topics ('/topic', 'ns', '/topic'), ('/example/topic', 'ns', '/example/topic'), ]) def test_get_subscription_topic_name(topic_name: str, namespace: Optional[str], expected: str) -> None: node = Node('node_name', namespace=namespace, cli_args=None) sub = node.create_subscription( msg_type=Empty, topic=topic_name, callback=lambda _: None, qos_profile=10, ) assert sub.topic_name == expected sub.destroy() node.destroy_node() def test_logger_name_is_equal_to_node_name(test_node): sub = test_node.create_subscription( msg_type=Empty, topic='topic', callback=lambda _: None, qos_profile=10, ) assert sub.logger_name == NODE_NAME @pytest.mark.parametrize('topic_name, namespace, cli_args, expected', [ ('topic', None, ['--ros-args', '--remap', 'topic:=new_topic'], '/new_topic'), ('topic', 'ns', ['--ros-args', '--remap', 'topic:=new_topic'], '/ns/new_topic'), ('topic', 'ns', ['--ros-args', '--remap', 'topic:=example/new_topic'], '/ns/example/new_topic'), ('example/topic', 'ns', ['--ros-args', '--remap', 'example/topic:=new_topic'], '/ns/new_topic'), ]) def test_get_subscription_topic_name_after_remapping(topic_name: str, namespace: Optional[str], cli_args: List[str], expected: str) -> None: node = Node('node_name', namespace=namespace, cli_args=cli_args) sub = node.create_subscription( msg_type=Empty, topic=topic_name, callback=lambda _: None, qos_profile=10, ) assert sub.topic_name == expected sub.destroy() node.destroy_node() def test_subscription_callback_type() -> None: node = Node('test_node', namespace='test_subscription/test_subscription_callback_type') sub = node.create_subscription( msg_type=Empty, topic='test_subscription/test_subscription_callback_type/topic', qos_profile=10, callback=lambda _: None) assert sub._callback_type == Subscription.CallbackType.MessageOnly sub.destroy() sub = node.create_subscription( msg_type=Empty, topic='test_subscription/test_subscription_callback_type/topic', qos_profile=10, callback=lambda _, _2: None) assert sub._callback_type == Subscription.CallbackType.WithMessageInfo sub.destroy() with pytest.raises(RuntimeError): node.create_subscription( msg_type=Empty, topic='test_subscription/test_subscription_callback_type/topic', qos_profile=10, callback=lambda _, _2, _3: None) # type: ignore[arg-type] node.destroy_node() def test_subscription_context_manager() -> None: node = Node('test_node', namespace='test_subscription/test_subscription_callback_type') with node.create_subscription( msg_type=Empty, topic='test_subscription/test_subscription_callback_type/topic', qos_profile=10, callback=lambda _: None) as sub: assert sub._callback_type == Subscription.CallbackType.MessageOnly with node.create_subscription( msg_type=Empty, topic='test_subscription/test_subscription_callback_type/topic', qos_profile=10, callback=lambda _, _2: None) as sub: assert sub._callback_type == Subscription.CallbackType.WithMessageInfo node.destroy_node() def test_subscription_publisher_count() -> None: topic_name = 'test_subscription/test_subscription_publisher_count/topic' node = Node('test_node', namespace='test_subscription/test_subscription_publisher_count') sub = node.create_subscription( msg_type=Empty, topic=topic_name, qos_profile=10, callback=lambda _: None) assert sub.get_publisher_count() == 0 pub = node.create_publisher(Empty, topic_name, 10) max_seconds_to_wait = 5 end_time = time.time() + max_seconds_to_wait while sub.get_publisher_count() != 1: time.sleep(0.05) assert time.time() <= end_time # timeout waiting for pub/sub to discover each other assert sub.get_publisher_count() == 1 pub.destroy() sub.destroy() node.destroy_node() def test_on_new_message_callback(test_node) -> None: topic_name = '/topic' cb = Mock() sub = test_node.create_subscription( msg_type=Empty, topic=topic_name, qos_profile=10, callback=cb) pub = test_node.create_publisher(Empty, topic_name, 10) sub.handle.set_on_new_message_callback(cb) cb.assert_not_called() pub.publish(Empty()) cb.assert_called_once_with(1) sub.handle.clear_on_new_message_callback() pub.publish(Empty()) cb.assert_called_once() def test_subscription_set_content_filter(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and ConnextDDS.') topic_name = '/topic' sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=lambda _: None) filter_expression = 'int32_value > %0' expression_parameters: List[str] = ['10'] # There should not be any exceptions. try: sub.set_content_filter( filter_expression, expression_parameters ) except Exception as e: pytest.fail(f'Unexpected exception raised: {e}') sub.destroy() def test_subscription_is_cft_enabled(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and Connext DDS.') topic_name = '/topic' sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=lambda _: None) sub.set_content_filter( filter_expression='bool_value = %0', expression_parameters=['TRUE'] ) # There should not be any exceptions. try: _ = sub.is_cft_enabled except Exception as e: pytest.fail(f'Unexpected exception raised: {e}') sub.destroy() def test_subscription_get_content_filter(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and ConnextDDS.') topic_name = '/topic' sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=lambda _: None) assert sub.is_cft_enabled is False filter_expression = 'int32_value > %0' expression_parameters: List[str] = ['60'] sub.set_content_filter( filter_expression, expression_parameters ) assert sub.is_cft_enabled is True cf_option = sub.get_content_filter() assert cf_option.filter_expression == filter_expression assert len(cf_option.expression_parameters) == len(expression_parameters) assert cf_option.expression_parameters[0] == expression_parameters[0] sub.destroy() def test_subscription_content_filter_effect(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and ConnextDDS.') topic_name = '/topic' pub = test_node.create_publisher(BasicTypes, topic_name, 10) received_msgs = [] def sub_callback(msg): received_msgs.append(msg.int32_value) sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=sub_callback) assert sub.is_cft_enabled is False def wait_msgs(timeout, expected_msg_count): end_time = time.time() + timeout while rclpy.ok() and time.time() < end_time and len(received_msgs) < expected_msg_count: rclpy.spin_once(test_node, timeout_sec=0.2) # Publish 3 messages def publish_messages(pub): msg = BasicTypes() msg.int32_value = 10 pub.publish(msg) msg.int32_value = 20 pub.publish(msg) msg.int32_value = 30 pub.publish(msg) # Publish messages and them should be all received. publish_messages(pub) # Check within 2 seconds whether the desired number of messages has been received. expected_msg_count = 3 wait_msgs(timeout=2.0, expected_msg_count=expected_msg_count) assert len(received_msgs) == expected_msg_count # Set content filter to filter out messages with int32_value <= 15 sub.set_content_filter( filter_expression='int32_value > %0', expression_parameters=['15'] ) assert sub.is_cft_enabled is True received_msgs = [] # Publish messages again and part of messages should be received. publish_messages(pub) # Check within 2 seconds whether the desired number of messages has been received. expected_msg_count = 2 wait_msgs(timeout=2.0, expected_msg_count=expected_msg_count) assert len(received_msgs) == expected_msg_count assert received_msgs[0] == 20 assert received_msgs[1] == 30 pub.destroy() sub.destroy() def test_subscription_content_filter_reset(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and ConnextDDS.') topic_name = '/topic' pub = test_node.create_publisher(BasicTypes, topic_name, 10) received_msgs = [] def sub_callback(msg): received_msgs.append(msg.int32_value) sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=sub_callback) # Set content filter to filter out messages with int32_value <= 15 sub.set_content_filter( filter_expression='int32_value > %0', expression_parameters=['15'] ) assert sub.is_cft_enabled is True def wait_msgs(timeout, expected_msg_count): end_time = time.time() + timeout while rclpy.ok() and time.time() < end_time and len(received_msgs) < expected_msg_count: rclpy.spin_once(test_node, timeout_sec=0.2) # Publish 3 messages def publish_messages(pub): msg = BasicTypes() msg.int32_value = 10 pub.publish(msg) msg.int32_value = 20 pub.publish(msg) msg.int32_value = 30 pub.publish(msg) publish_messages(pub) expected_msg_count = 2 wait_msgs(timeout=2.0, expected_msg_count=expected_msg_count) assert len(received_msgs) == expected_msg_count received_msgs = [] # Reset content filter sub.set_content_filter( filter_expression='', expression_parameters=[] ) assert sub.is_cft_enabled is False publish_messages(pub) expected_msg_count = 3 wait_msgs(timeout=2.0, expected_msg_count=expected_msg_count) assert len(received_msgs) == expected_msg_count def test_subscription_content_filter_at_create_subscription(test_node) -> None: if rclpy.get_rmw_implementation_identifier() != 'rmw_fastrtps_cpp' and \ rclpy.get_rmw_implementation_identifier() != 'rmw_connextdds': pytest.skip('Content filter is now only supported in FastDDS and ConnextDDS.') topic_name = '/topic' pub = test_node.create_publisher(BasicTypes, topic_name, 10) received_msgs = [] content_filter_options = ContentFilterOptions( filter_expression='int32_value > %0', expression_parameters=['15']) def sub_callback(msg): received_msgs.append(msg.int32_value) sub = test_node.create_subscription( msg_type=BasicTypes, topic=topic_name, qos_profile=10, callback=sub_callback, content_filter_options=content_filter_options) assert sub.is_cft_enabled is True def wait_msgs(timeout, expected_msg_count): end_time = time.time() + timeout while rclpy.ok() and time.time() < end_time and len(received_msgs) < expected_msg_count: rclpy.spin_once(test_node, timeout_sec=0.2) # Publish 3 messages def publish_messages(pub): msg = BasicTypes() msg.int32_value = 10 pub.publish(msg) msg.int32_value = 20 pub.publish(msg) msg.int32_value = 30 pub.publish(msg) # Publish messages and part of messages should be received. publish_messages(pub) # Check within 2 seconds whether the desired number of messages has been received. expected_msg_count = 2 wait_msgs(timeout=2.0, expected_msg_count=expected_msg_count) assert len(received_msgs) == expected_msg_count assert received_msgs[0] == 20 assert received_msgs[1] == 30 pub.destroy() sub.destroy()
rclpy
You are an expert Python testing engineer. Task: Write a unit test for 'Subscription' using 'unittest' and 'unittest.mock'. Context: - Class Name: Subscription - Dependencies to Mock: Enum, inspect, TracebackType, Callable, Generic Requirements: Use @patch for mocks, follow AAA pattern.
python
# Copyright 2023 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional, TYPE_CHECKING import weakref from rcl_interfaces.msg import ParameterDescriptor from rcl_interfaces.msg import ParameterType from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.parameter import Parameter from rclpy.qos import qos_profile_services_default from rclpy.service import Service from rclpy.type_support import check_is_valid_srv_type from rclpy.validate_topic_name import TOPIC_SEPARATOR_STRING from type_description_interfaces.srv import GetTypeDescription START_TYPE_DESCRIPTION_SERVICE_PARAM = 'start_type_description_service' if TYPE_CHECKING: from rclpy.node import Node class TypeDescriptionService: """ Optionally initializes and contains the ~/get_type_description service. The service is implemented in rcl, but should be enabled via parameter and have its callbacks handled via end-client execution framework, such as callback groups and waitsets. This is not intended for use by end users, rather it is a component to be used by Node. """ def __init__(self, node: 'Node'): """Initialize the service, if the parameter is set to true.""" self._node_weak_ref = weakref.ref(node) node_name = node.get_name() self.service_name = TOPIC_SEPARATOR_STRING.join((node_name, 'get_type_description')) self._type_description_srv: Optional[_rclpy.TypeDescriptionService] = None self.enabled = False if not node.has_parameter(START_TYPE_DESCRIPTION_SERVICE_PARAM): descriptor = ParameterDescriptor( name=START_TYPE_DESCRIPTION_SERVICE_PARAM, type=ParameterType.PARAMETER_BOOL, description='If enabled, start the ~/get_type_description service.', read_only=True) node.declare_parameter( START_TYPE_DESCRIPTION_SERVICE_PARAM, True, descriptor) param = node.get_parameter(START_TYPE_DESCRIPTION_SERVICE_PARAM) if param.type_ != Parameter.Type.NOT_SET: if param.type_ == Parameter.Type.BOOL: self.enabled = param.value else: node.get_logger().error( "Invalid type for parameter '{}' {!r} should be bool" .format(START_TYPE_DESCRIPTION_SERVICE_PARAM, param.type_)) else: node.get_logger().debug( 'Parameter {} not set, defaulting to true.' .format(START_TYPE_DESCRIPTION_SERVICE_PARAM)) if self.enabled: self._start_service() def destroy(self) -> None: # Required manual destruction because this is not managed by rclpy.Service if self._type_description_srv is not None: self._type_description_srv.destroy_when_not_in_use() self._type_description_srv = None def _start_service(self) -> None: node = self._get_node() self._type_description_srv = _rclpy.TypeDescriptionService(node.handle) # Because we are creating our own service wrapper, must manually add the service # to the appropriate parts of Node because we cannot call create_service. check_is_valid_srv_type(GetTypeDescription) service = Service( service_impl=self._type_description_srv.impl, srv_type=GetTypeDescription, srv_name=self.service_name, callback=self._service_callback, callback_group=node.default_callback_group, qos_profile=qos_profile_services_default) node.default_callback_group.add_entity(service) node._services.append(service) node._wake_executor() def _service_callback( self, request: GetTypeDescription.Request, response: GetTypeDescription.Response ) -> GetTypeDescription.Response: if self._type_description_srv is None: raise RuntimeError('Cannot handle request if TypeDescriptionService is None.') return self._type_description_srv.handle_request( request, GetTypeDescription.Response, self._get_node().handle) def _get_node(self) -> 'Node': node = self._node_weak_ref() if node is None: raise ReferenceError('Expected valid node weak reference') return node
# Copyright 2023 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import rclpy from rclpy.client import Client import rclpy.context from rclpy.executors import SingleThreadedExecutor from rclpy.qos import qos_profile_services_default from test_msgs.msg import BasicTypes from type_description_interfaces.srv import GetTypeDescription class TestTypeDescriptionService(unittest.TestCase): def setUp(self) -> None: self.context = rclpy.context.Context() rclpy.init(context=self.context) self.test_node = rclpy.create_node( 'test_type_description_service', namespace='/rclpy', context=self.context) self.test_topic = '/rclpy/basic_types' self.test_pub = self.test_node.create_publisher( BasicTypes, self.test_topic, 10) self.get_type_description_client: Client[GetTypeDescription.Request, GetTypeDescription.Response] = \ self.test_node.create_client( GetTypeDescription, '/rclpy/test_parameter_service/get_type_description', qos_profile=qos_profile_services_default) self.executor = SingleThreadedExecutor(context=self.context) self.executor.add_node(self.test_node) def tearDown(self) -> None: self.executor.shutdown() self.test_node.destroy_node() rclpy.shutdown(context=self.context) def test_get_type_description(self) -> None: pub_infos = self.test_node.get_publishers_info_by_topic(self.test_topic) assert len(pub_infos) type_hash = pub_infos[0].topic_type_hash request = GetTypeDescription.Request( type_name='test_msgs/msg/BasicTypes', type_hash=type_hash, include_type_sources=True) future = self.get_type_description_client.call_async(request) self.executor.spin_until_future_complete(future) response = future.result() assert response is not None assert response.successful assert response.type_description.type_description.type_name == 'test_msgs/msg/BasicTypes' assert len(response.type_sources)
rclpy
You are an expert Python testing engineer. Task: Write a unit test for 'TypeDescriptionService' using 'unittest' and 'unittest.mock'. Context: - Class Name: TypeDescriptionService - Dependencies to Mock: TYPE_CHECKING, weakref, ParameterDescriptor, ParameterType, _rclpy Requirements: Use @patch for mocks, follow AAA pattern.
python
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING import weakref from rcl_interfaces.msg import ListParametersResult from rcl_interfaces.msg import SetParametersResult from rcl_interfaces.srv import DescribeParameters, GetParameters, GetParameterTypes from rcl_interfaces.srv import ListParameters, SetParameters, SetParametersAtomically from rclpy.exceptions import ParameterNotDeclaredException, ParameterUninitializedException from rclpy.parameter import Parameter from rclpy.qos import qos_profile_parameters from rclpy.validate_topic_name import TOPIC_SEPARATOR_STRING if TYPE_CHECKING: from rclpy.node import Node class ParameterService: def __init__(self, node: 'Node'): self._node_weak_ref = weakref.ref(node) nodename = node.get_name() describe_parameters_service_name = \ TOPIC_SEPARATOR_STRING.join((nodename, 'describe_parameters')) node.create_service( DescribeParameters, describe_parameters_service_name, self._describe_parameters_callback, qos_profile=qos_profile_parameters ) get_parameters_service_name = TOPIC_SEPARATOR_STRING.join((nodename, 'get_parameters')) node.create_service( GetParameters, get_parameters_service_name, self._get_parameters_callback, qos_profile=qos_profile_parameters ) get_parameter_types_service_name = \ TOPIC_SEPARATOR_STRING.join((nodename, 'get_parameter_types')) node.create_service( GetParameterTypes, get_parameter_types_service_name, self._get_parameter_types_callback, qos_profile=qos_profile_parameters ) list_parameters_service_name = TOPIC_SEPARATOR_STRING.join((nodename, 'list_parameters')) node.create_service( ListParameters, list_parameters_service_name, self._list_parameters_callback, qos_profile=qos_profile_parameters ) set_parameters_service_name = TOPIC_SEPARATOR_STRING.join((nodename, 'set_parameters')) node.create_service( SetParameters, set_parameters_service_name, self._set_parameters_callback, qos_profile=qos_profile_parameters ) set_parameters_atomically_service_name = \ TOPIC_SEPARATOR_STRING.join((nodename, 'set_parameters_atomically')) node.create_service( SetParametersAtomically, set_parameters_atomically_service_name, self._set_parameters_atomically_callback, qos_profile=qos_profile_parameters ) def _describe_parameters_callback( self, request: DescribeParameters.Request, response: DescribeParameters.Response ) -> DescribeParameters.Response: node = self._get_node() for name in request.names: try: descriptor = node.describe_parameter(name) except ParameterNotDeclaredException: response.descriptors = node.describe_parameters([]) return response response.descriptors.append(descriptor) return response def _get_parameters_callback( self, request: GetParameters.Request, response: GetParameters.Response ) -> GetParameters.Response: node = self._get_node() for name in request.names: try: param = node.get_parameter(name) except (ParameterNotDeclaredException, ParameterUninitializedException): response.values = node.get_parameters([]) return response response.values.append(param.get_parameter_value()) return response def _get_parameter_types_callback( self, request: GetParameterTypes.Request, response: GetParameterTypes.Response ) -> GetParameterTypes.Response: node = self._get_node() for name in request.names: try: value = node.get_parameter_type(name) except ParameterNotDeclaredException: response.types = node.get_parameter_types([]) return response response.types.append(value) return response def _list_parameters_callback( self, request: ListParameters.Request, response: ListParameters.Response ) -> ListParameters.Response: node = self._get_node() try: response.result = node.list_parameters(request.prefixes, request.depth) except (TypeError, ValueError): response.result = ListParametersResult() return response def _set_parameters_callback( self, request: SetParameters.Request, response: SetParameters.Response ) -> SetParameters.Response: node = self._get_node() for p in request.parameters: param = Parameter.from_parameter_msg(p) try: result = node.set_parameters_atomically([param]) except ParameterNotDeclaredException as e: result = SetParametersResult( successful=False, reason=str(e) ) response.results.append(result) return response def _set_parameters_atomically_callback( self, request: SetParametersAtomically.Request, response: SetParametersAtomically.Response ) -> SetParametersAtomically.Response: node = self._get_node() try: response.result = node.set_parameters_atomically([ Parameter.from_parameter_msg(p) for p in request.parameters]) except ParameterNotDeclaredException as e: response.result = SetParametersResult( successful=False, reason=str(e) ) return response def _get_node(self) -> 'Node': node = self._node_weak_ref() if node is None: raise ReferenceError('Expected valid node weak reference') return node
# Copyright 2022 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from rcl_interfaces.msg import ParameterType from rcl_interfaces.srv import DescribeParameters from rcl_interfaces.srv import GetParameters import rclpy from rclpy.client import Client import rclpy.context from rclpy.executors import SingleThreadedExecutor from rclpy.parameter import Parameter from rclpy.qos import qos_profile_services_default class TestParameterService(unittest.TestCase): def setUp(self) -> None: self.context = rclpy.context.Context() rclpy.init(context=self.context) self.test_node = rclpy.create_node( 'test_parameter_service', namespace='/rclpy', context=self.context) self.get_parameter_client: Client[GetParameters.Request, GetParameters.Response] = self.test_node.create_client( GetParameters, '/rclpy/test_parameter_service/get_parameters', qos_profile=qos_profile_services_default ) self.describe_parameters_client: Client[DescribeParameters.Response, DescribeParameters.Response] = \ self.test_node.create_client( DescribeParameters, '/rclpy/test_parameter_service/describe_parameters', qos_profile=qos_profile_services_default) self.executor = SingleThreadedExecutor(context=self.context) self.executor.add_node(self.test_node) def tearDown(self) -> None: self.executor.shutdown() self.test_node.destroy_node() rclpy.shutdown(context=self.context) def test_get_uninitialized_parameter(self) -> None: self.test_node.declare_parameter('uninitialized_parameter', Parameter.Type.STRING) # The type in description should be STRING request = DescribeParameters.Request() request.names = ['uninitialized_parameter'] future = self.describe_parameters_client.call_async(request) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert len(results.descriptors) == 1 assert results.descriptors[0].type == ParameterType.PARAMETER_STRING assert results.descriptors[0].name == 'uninitialized_parameter' # The value should be empty request = GetParameters.Request() request.names = ['uninitialized_parameter'] future = self.get_parameter_client.call_async(request) self.executor.spin_until_future_complete(future) results = future.result() assert results is not None assert results.values == [] if __name__ == '__main__': unittest.main()
rclpy
You are an expert Python testing engineer. Task: Write a unit test for 'ParameterService' using 'unittest' and 'unittest.mock'. Context: - Class Name: ParameterService - Dependencies to Mock: TYPE_CHECKING, weakref, ListParametersResult, SetParametersResult, GetParameterTypes Requirements: Use @patch for mocks, follow AAA pattern.
python
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import Optional from typing import Text from typing import Type from typing import TYPE_CHECKING from typing import Union from rcl_interfaces.msg import ParameterDescriptor from rcl_interfaces.msg import SetParametersResult import rclpy from rclpy.duration import Duration from rclpy.exceptions import ParameterAlreadyDeclaredException from rclpy.parameter import Parameter from rclpy.publisher import Publisher from rclpy.qos import QoSDurabilityPolicy from rclpy.qos import QoSHistoryPolicy from rclpy.qos import QoSLivelinessPolicy from rclpy.qos import QoSPolicyKind from rclpy.qos import QoSProfile from rclpy.qos import QoSReliabilityPolicy from rclpy.subscription import Subscription from typing_extensions import TypeAlias if TYPE_CHECKING: from rclpy.node import Node class InvalidQosOverridesError(Exception): pass # Return type of qos validation callbacks QosCallbackResult: TypeAlias = SetParametersResult # Qos callback type annotation QosCallbackType = Callable[[QoSProfile], QosCallbackResult] class QoSOverridingOptions: """Options to customize QoS parameter overrides.""" def __init__( self, policy_kinds: Iterable[QoSPolicyKind], *, callback: Optional[QosCallbackType] = None, entity_id: Optional[Text] = None ): """ Construct a QoSOverridingOptions object. :param policy_kinds: QoS kinds that will have a declared parameter. :param callback: Callback that will be used to validate the QoS profile after the paramter overrides get applied. :param entity_id: Optional identifier, to disambiguate in the case that different QoS policies for the same topic are desired. """ self._policy_kinds = policy_kinds self._callback = callback self._entity_id = entity_id @property def policy_kinds(self) -> Iterable[QoSPolicyKind]: """Get QoS policy kinds that will have a parameter override.""" return self._policy_kinds @property def callback(self) -> Optional[QosCallbackType]: """Get the validation callback.""" return self._callback @property def entity_id(self) -> Optional[Text]: """Get the optional entity ID.""" return self._entity_id @classmethod def with_default_policies( cls, *, callback: Optional[QosCallbackType] = None, entity_id: Optional[Text] = None ) -> 'QoSOverridingOptions': return cls( policy_kinds=(QoSPolicyKind.HISTORY, QoSPolicyKind.DEPTH, QoSPolicyKind.RELIABILITY), callback=callback, entity_id=entity_id, ) def _declare_qos_parameters( entity_type: Union[Type[Publisher[Any]], Type[Subscription[Any]]], node: 'Node', topic_name: Text, qos: QoSProfile, options: QoSOverridingOptions ) -> None: """ Declare QoS parameters for a Publisher or a Subscription. :param entity_type: Either `rclpy.node.Publisher` or `rclpy.node.Subscription`. :param node: Node used to declare the parameters. :param topic_name: Topic name of the entity being created. :param qos: Default QoS settings of the entity being created, that will be overridden with the user provided QoS parameter overrides. :param options: Options that indicates which parameters are going to be declared. """ if not issubclass(entity_type, (Publisher, Subscription)): raise TypeError('Argument `entity_type` should be a subclass of Publisher or Subscription') entity_type_str = 'publisher' if issubclass(entity_type, Publisher) else 'subscription' id_suffix = '' if options.entity_id is None else f'_{options.entity_id}' name = f'qos_overrides.{topic_name}.{entity_type_str}{id_suffix}.' '{}' description = '{}' f' for {entity_type_str} `{topic_name}` with id `{options.entity_id}`' allowed_policies = _get_allowed_policies(entity_type) for policy in options.policy_kinds: if policy not in allowed_policies: continue policy_name = policy.name.lower() descriptor = ParameterDescriptor() descriptor.description = description.format(policy_name) descriptor.read_only = True try: param: Parameter[Any] = node.declare_parameter( name.format(policy_name), _get_qos_policy_parameter(qos, policy), descriptor) except ParameterAlreadyDeclaredException: param = node.get_parameter(name.format(policy_name)) _override_qos_policy_with_param(qos, policy, param) if options.callback is not None: result = options.callback(qos) if not result.successful: raise InvalidQosOverridesError( f"{description.format('Provided QoS overrides')}, are not valid: {result.reason}") def _get_allowed_policies(entity_type: Union[Type[Publisher[Any]], Type[Subscription[Any]]]) -> List[QoSPolicyKind]: allowed_policies = list(QoSPolicyKind.__members__.values()) if issubclass(entity_type, Subscription): allowed_policies.remove(QoSPolicyKind.LIFESPAN) return allowed_policies QoSProfileAttributes = Union[QoSHistoryPolicy, int, QoSReliabilityPolicy, QoSDurabilityPolicy, Duration, QoSLivelinessPolicy, bool] def _get_qos_policy_parameter(qos: QoSProfile, policy: QoSPolicyKind) -> Union[str, int, bool]: value: QoSProfileAttributes = getattr(qos, policy.name.lower()) if isinstance(value, (QoSHistoryPolicy, QoSReliabilityPolicy, QoSDurabilityPolicy, QoSLivelinessPolicy)): return_value: Union[str, int, bool] = value.name.lower() if return_value == 'unknown': raise ValueError('User provided QoS profile is invalid') elif isinstance(value, Duration): return_value = value.nanoseconds else: return_value = value return return_value def _override_qos_policy_with_param(qos: QoSProfile, policy: QoSPolicyKind, param: Parameter[Any]) -> None: value = param.value policy_name = policy.name.lower() if policy in ( QoSPolicyKind.LIVELINESS, QoSPolicyKind.RELIABILITY, QoSPolicyKind.HISTORY, QoSPolicyKind.DURABILITY ): def capitalize_first_letter(x: str) -> str: return x[0].upper() + x[1:] # e.g. `policy=QosPolicyKind.LIVELINESS` -> `policy_enum_class=rclpy.qos.LivelinessPolicy` policy_enum_class = getattr( rclpy.qos, f'{capitalize_first_letter(policy_name)}Policy') try: value = policy_enum_class[value.upper()] except KeyError: raise RuntimeError( f'Unexpected QoS override for policy `{policy.name.lower()}`: `{value}`') if policy in ( QoSPolicyKind.LIFESPAN, QoSPolicyKind.DEADLINE, QoSPolicyKind.LIVELINESS_LEASE_DURATION ): value = Duration(nanoseconds=value) setattr(qos, policy.name.lower(), value)
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Generator import pytest import rclpy from rclpy.duration import Duration from rclpy.node import Node from rclpy.parameter import Parameter from rclpy.publisher import Publisher from rclpy.qos import QoSDurabilityPolicy from rclpy.qos import QoSHistoryPolicy from rclpy.qos import QoSLivelinessPolicy from rclpy.qos import QoSPolicyKind from rclpy.qos import QoSProfile from rclpy.qos import QoSReliabilityPolicy from rclpy.qos_overriding_options import _declare_qos_parameters from rclpy.qos_overriding_options import _get_qos_policy_parameter from rclpy.qos_overriding_options import InvalidQosOverridesError from rclpy.qos_overriding_options import QosCallbackResult from rclpy.qos_overriding_options import QoSOverridingOptions @pytest.fixture(autouse=True) def init_shutdown() -> Generator[None, None, None]: rclpy.init() yield rclpy.shutdown() def test_get_qos_policy_parameter() -> None: qos = QoSProfile( history=QoSHistoryPolicy.KEEP_LAST, depth=10, reliability=QoSReliabilityPolicy.RELIABLE, durability=QoSDurabilityPolicy.VOLATILE, lifespan=Duration(nanoseconds=1e3), deadline=Duration(nanoseconds=1e6), liveliness=QoSLivelinessPolicy.SYSTEM_DEFAULT, liveliness_lease_duration=Duration(nanoseconds=1e9) ) value = _get_qos_policy_parameter(qos, QoSPolicyKind.HISTORY) assert value == 'keep_last' value = _get_qos_policy_parameter(qos, QoSPolicyKind.DEPTH) assert value == qos.depth value = _get_qos_policy_parameter(qos, QoSPolicyKind.RELIABILITY) assert value == 'reliable' value = _get_qos_policy_parameter(qos, QoSPolicyKind.DURABILITY) assert value == 'volatile' value = _get_qos_policy_parameter(qos, QoSPolicyKind.LIFESPAN) assert value == qos.lifespan.nanoseconds value = _get_qos_policy_parameter(qos, QoSPolicyKind.DEADLINE) assert value == qos.deadline.nanoseconds value = _get_qos_policy_parameter(qos, QoSPolicyKind.LIVELINESS) assert value == 'system_default' value = _get_qos_policy_parameter(qos, QoSPolicyKind.LIVELINESS_LEASE_DURATION) assert value == qos.liveliness_lease_duration.nanoseconds def test_declare_qos_parameters() -> None: node = Node('my_node') _declare_qos_parameters( Publisher, node, '/my_topic', QoSProfile(depth=10), QoSOverridingOptions.with_default_policies() ) qos_overrides = node.get_parameters_by_prefix('qos_overrides') assert len(qos_overrides) == 3 expected_params = ( ('/my_topic.publisher.depth', 10), ('/my_topic.publisher.history', 'keep_last'), ('/my_topic.publisher.reliability', 'reliable'), ) for actual, expected in zip( sorted(qos_overrides.items(), key=lambda x: x[0]), expected_params ): assert actual[0] == expected[0] # same param name assert actual[1].value == expected[1] # same param value def test_declare_qos_parameters_with_overrides() -> None: node = Node('my_node', parameter_overrides=[ Parameter('qos_overrides./my_topic.publisher.depth', value=100), Parameter('qos_overrides./my_topic.publisher.reliability', value='best_effort'), ]) for i in range(2): # try twice, the second time the parameters will be get and not declared _declare_qos_parameters( Publisher, node, '/my_topic', QoSProfile(depth=10), QoSOverridingOptions.with_default_policies() ) qos_overrides = node.get_parameters_by_prefix('qos_overrides') assert len(qos_overrides) == 3 expected_params = ( ('/my_topic.publisher.depth', 100), ('/my_topic.publisher.history', 'keep_last'), ('/my_topic.publisher.reliability', 'best_effort'), ) for actual, expected in zip( sorted(qos_overrides.items(), key=lambda x: x[0]), expected_params ): assert actual[0] == expected[0] # same param name assert actual[1].value == expected[1] # same param value def test_declare_qos_parameters_with_happy_callback() -> None: def qos_validation_callback(qos: QoSProfile) -> QosCallbackResult: result = QosCallbackResult() result.successful = True return result node = Node('my_node') _declare_qos_parameters( Publisher, node, '/my_topic', QoSProfile(depth=10), QoSOverridingOptions.with_default_policies(callback=qos_validation_callback) ) qos_overrides = node.get_parameters_by_prefix('qos_overrides') assert len(qos_overrides) == 3 expected_params = ( ('/my_topic.publisher.depth', 10), ('/my_topic.publisher.history', 'keep_last'), ('/my_topic.publisher.reliability', 'reliable'), ) for actual, expected in zip( sorted(qos_overrides.items(), key=lambda x: x[0]), expected_params ): assert actual[0] == expected[0] # same param name assert actual[1].value == expected[1] # same param value def test_declare_qos_parameters_with_unhappy_callback() -> None: def qos_validation_callback(qos: QoSProfile) -> QosCallbackResult: result = QosCallbackResult() result.successful = False result.reason = 'my_custom_error_message' return result node = Node('my_node') with pytest.raises(InvalidQosOverridesError) as err: _declare_qos_parameters( Publisher, node, '/my_topic', QoSProfile(depth=10), QoSOverridingOptions.with_default_policies(callback=qos_validation_callback) ) assert 'my_custom_error_message' in str(err.value) def test_declare_qos_parameters_with_id() -> None: node = Node('my_node') _declare_qos_parameters( Publisher, node, '/my_topic', QoSProfile(depth=10), QoSOverridingOptions.with_default_policies(entity_id='i_have_an_id') ) qos_overrides = node.get_parameters_by_prefix('qos_overrides') assert len(qos_overrides) == 3 expected_params = ( ('/my_topic.publisher_i_have_an_id.depth', 10), ('/my_topic.publisher_i_have_an_id.history', 'keep_last'), ('/my_topic.publisher_i_have_an_id.reliability', 'reliable'), ) for actual, expected in zip( sorted(qos_overrides.items(), key=lambda x: x[0]), expected_params ): assert actual[0] == expected[0] # same param name assert actual[1].value == expected[1] # same param value
rclpy
You are an expert Python testing engineer. Task: Write a unit test for 'QoSOverridingOptions' using 'unittest' and 'unittest.mock'. Context: - Class Name: QoSOverridingOptions - Dependencies to Mock: Any, Callable, Iterable, List, Optional Requirements: Use @patch for mocks, follow AAA pattern.
python
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy def expand_topic_name(topic_name: str, node_name: str, node_namespace: str) -> str: """ Expand a given topic name using given node name and namespace as well. Note that this function can succeed but the expanded topic name may still be invalid. The :py:func:validate_full_topic_name(): should be used on the expanded topic name to ensure it is valid after expansion. :param topic_name: topic name to be expanded :param node_name: name of the node that this topic is associated with :param namespace: namespace that the topic is within :returns: expanded topic name which is fully qualified :raises: ValueError if the topic name, node name or namespace are invalid """ return _rclpy.rclpy_expand_topic_name(topic_name, node_name, node_namespace)
# Copyright 2017 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from rclpy.expand_topic_name import expand_topic_name class TestExpandTopicName(unittest.TestCase): def test_expand_topic_name(self) -> None: tests = { # 'expected output': ['input topic', 'node', '/ns'] '/ns/chatter': ['chatter', 'node_name', '/ns'], '/chatter': ['chatter', 'node_name', '/'], '/ns/node_name/chatter': ['~/chatter', 'node_name', '/ns'], '/node_name/chatter': ['~/chatter', 'node_name', '/'], } for expected_topic, input_tuple in tests.items(): topic, node, namespace = input_tuple expanded_topic = expand_topic_name(topic, node, namespace) self.assertEqual(expanded_topic, expected_topic) def test_expand_topic_name_invalid_node_name(self) -> None: # node name may not contain '?' with self.assertRaisesRegex(ValueError, 'node name'): expand_topic_name('topic', 'invalid_node_name?', '/ns') def test_expand_topic_name_invalid_namespace_empty(self) -> None: # namespace may not be empty with self.assertRaisesRegex(ValueError, 'namespace'): expand_topic_name('topic', 'node_name', '') def test_expand_topic_name_invalid_namespace_relative(self) -> None: # namespace may not be relative with self.assertRaisesRegex(ValueError, 'namespace'): expand_topic_name('topic', 'node_name', 'ns') def test_expand_topic_name_invalid_topic(self) -> None: # topic may not contain '?' with self.assertRaisesRegex(ValueError, 'topic name'): expand_topic_name('invalid/topic?', 'node_name', '/ns') if __name__ == '__main__': unittest.main()
rclpy
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: _rclpy Requirements: Use @patch for mocks, follow AAA pattern.
python
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Type from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy from rclpy.type_support import check_for_type_support, Msg, MsgT def serialize_message(message: Msg) -> bytes: """ Serialize a ROS message. :param message: The ROS message to serialize. :return: The serialized bytes. """ message_type = type(message) # this line imports the typesupport for the message module if not already done check_for_type_support(message_type) return _rclpy.rclpy_serialize(message, message_type) def deserialize_message(serialized_message: bytes, message_type: Type[MsgT]) -> MsgT: """ Deserialize a ROS message. :param serialized_message: The ROS message to deserialize. :param message_type: The type of the serialized ROS message. :return: The deserialized ROS message. """ # this line imports the typesupport for the message module if not already done check_for_type_support(message_type) return _rclpy.rclpy_deserialize(serialized_message, message_type)
# Copyright 2020 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List from typing import Type import pytest from rclpy.serialization import deserialize_message from rclpy.serialization import serialize_message from rclpy.type_support import Msg from test_msgs.message_fixtures import get_test_msg from test_msgs.msg import Arrays from test_msgs.msg import BasicTypes from test_msgs.msg import BoundedSequences from test_msgs.msg import Builtins from test_msgs.msg import Constants from test_msgs.msg import Defaults from test_msgs.msg import Empty from test_msgs.msg import MultiNested from test_msgs.msg import Nested from test_msgs.msg import Strings from test_msgs.msg import UnboundedSequences from test_msgs.msg import WStrings test_msgs = [ (get_test_msg('Arrays'), Arrays), (get_test_msg('BasicTypes'), BasicTypes), (get_test_msg('BoundedSequences'), BoundedSequences), (get_test_msg('Builtins'), Builtins), (get_test_msg('Constants'), Constants), (get_test_msg('Defaults'), Defaults), (get_test_msg('Empty'), Empty), (get_test_msg('MultiNested'), MultiNested), (get_test_msg('Nested'), Nested), (get_test_msg('Strings'), Strings), (get_test_msg('UnboundedSequences'), UnboundedSequences), (get_test_msg('WStrings'), WStrings), ] @pytest.mark.parametrize('msgs,msg_type', test_msgs) def test_serialize_deserialize(msgs: List[Msg], msg_type: Type[Msg]) -> None: """Test message serialization/deserialization.""" for msg in msgs: msg_serialized = serialize_message(msg) msg_deserialized = deserialize_message(msg_serialized, msg_type) assert msg == msg_deserialized def test_set_float32() -> None: """Test message serialization/deserialization of float32 type.""" # During (de)serialization we convert to a C float before converting to a PyObject. # This can result in a loss of precision msg = BasicTypes() msg.float32_value = 1.125 # can be represented without rounding msg_serialized = serialize_message(msg) msg_deserialized = deserialize_message(msg_serialized, BasicTypes) assert msg.float32_value == msg_deserialized.float32_value msg = BasicTypes() msg.float32_value = 3.14 # can NOT be represented without rounding msg_serialized = serialize_message(msg) msg_deserialized = deserialize_message(msg_serialized, BasicTypes) assert msg.float32_value == round(msg_deserialized.float32_value, 2)
rclpy
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Type, _rclpy, MsgT Requirements: Use @patch for mocks, follow AAA pattern.
python
"# Copyright 2017 Open Source Robotics Foundation, Inc.\n#\n# Licensed under the Apache License, Ver(...TRUNCATED)
"# Copyright 2017 Open Source Robotics Foundation, Inc.\n#\n# Licensed under the Apache License, Ver(...TRUNCATED)
rclpy
"You are an expert Python testing engineer.\nTask: Write a unit test for 'MultiThreadedExecutor' usi(...TRUNCATED)
python
"# Copyright 2017 Open Source Robotics Foundation, Inc.\n#\n# Licensed under the Apache License, Ver(...TRUNCATED)
"# Copyright 2017 Open Source Robotics Foundation, Inc.\n#\n# Licensed under the Apache License, Ver(...TRUNCATED)
rclpy
"You are an expert Python testing engineer.\nTask: Write a unit test for 'TargetModule' using 'unitt(...TRUNCATED)
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
16