def test_env(): ld = LaunchDescription() launch_test = LaunchTestService() env = os.environ.copy() try: sub_env = os.environ.copy() sub_env['testenv1'] = 'testval1' os.environ['testenv2'] = 'testval2' launch_test.add_test_action( ld, ExecuteProcess( cmd=[ sys.executable, os.path.join(os.path.abspath(os.path.dirname(__file__)), 'check_env.py') ], name='test_env', env=sub_env, )) launch_service = LaunchService() launch_service.include_launch_description(ld) return_code = launch_test.run(launch_service) finally: os.environ = env assert return_code == 0, 'Launch failed with exit code %r' % ( return_code, )
def test_func(node_fixture): """Run an executable with cli_args and coroutine test in the same asyncio loop.""" # Create a command launching a name_maker executable specified by the pytest fixture command = [node_fixture['executable']] # format command line arguments with random string from test fixture for arg in cli_args: command.append( arg.format(random_string=node_fixture['random_string'])) # Execute python files using same python used to start this test env = dict(os.environ) if command[0][-3:] == '.py': command.insert(0, sys.executable) env['PYTHONUNBUFFERED'] = '1' ld = LaunchDescription() launch_test = LaunchTestService() launch_test.add_fixture_action( ld, ExecuteProcess(cmd=command, name='name_maker_' + coroutine_test.__name__, env=env)) launch_test.add_test_action( ld, OpaqueCoroutine(coroutine=coroutine_test, args=[node_fixture], ignore_context=True)) launch_service = LaunchService() launch_service.include_launch_description(ld) return_code = launch_test.run(launch_service) assert return_code == 0, 'Launch failed with exit code %r' % ( return_code, )
def test_executable(): """Parse executable yaml example.""" yaml_file = \ """\ launch: - executable: cmd: ls -l -a -s cwd: '/' name: my_ls shell: true output: log launch_prefix: $(env LAUNCH_PREFIX) env: - name: var value: '1' """ yaml_file = textwrap.dedent(yaml_file) root_entity, parser = Parser.load(io.StringIO(yaml_file)) ld = parser.parse_description(root_entity) executable = ld.entities[0] cmd = [i[0].perform(None) for i in executable.cmd] assert( cmd == ['ls', '-l', '-a', '-s']) assert(executable.cwd[0].perform(None) == '/') assert(executable.name[0].perform(None) == 'my_ls') assert(executable.shell is True) assert(executable.output == 'log') key, value = executable.additional_env[0] key = key[0].perform(None) value = value[0].perform(None) assert(key == 'var') assert(value == '1') ls = LaunchService() ls.include_launch_description(ld) assert(0 == ls.run())
def main(argv=sys.argv[1:]): testExecutable = os.getenv('TEST_EXECUTABLE') ld = LaunchDescription([ launch_ros.actions.Node(package='nav2_navfn_planner', node_executable='navfn_planner', output='screen'), ]) test1_action = ExecuteProcess(cmd=[testExecutable], name='test_planner_node', output='screen') run_lifecycle_manager = launch_ros.actions.Node( package='nav2_lifecycle_manager', node_executable='lifecycle_manager', node_name='lifecycle_manager', output='screen', parameters=[{ 'node_names': ['navfn_planner'] }, { 'autostart': True }]) lts = LaunchTestService() lts.add_test_action(ld, test1_action) lts.add_test_action(ld, run_lifecycle_manager) ls = LaunchService(argv=argv) ls.include_launch_description(ld) return lts.run(ls)
def main(argv=sys.argv[1:]): """Main.""" ld = LaunchDescription([ launch_ros.actions.Node(package='demo_nodes_cpp', node_executable='talker', output='screen', remappings=[('chatter', 'my_chatter')]), launch_ros.actions.Node(package='demo_nodes_cpp', node_executable='listener', output='screen', remappings=[('chatter', 'my_chatter')]), ]) print('Starting introspection of launch description...') print('') print(LaunchIntrospector().format_launch_description(ld)) print('') print('Starting launch of launch description...') print('') # ls = LaunchService(debug=True) ls = LaunchService() ls.include_launch_description( get_default_launch_description(prefix_output_with_name=False)) ls.include_launch_description(ld) return ls.run()
def test_matching(): # This temporary directory and files contained in it # will be deleted when the process ends. tempdir = tempfile.mkdtemp() output_file = tempdir + os.sep + 'testfile' full_output_file = output_file + '.regex' with open(full_output_file, 'w+') as f: f.write(r'this is line \d\nthis is line [a-z]') executable_command = [ sys.executable, os.path.join(os.path.abspath(os.path.dirname(__file__)), 'matching.py') ] ld = LaunchDescription() launch_test = LaunchTestService() action = launch_test.add_fixture_action( ld, ExecuteProcess(cmd=executable_command, output='screen')) launch_test.add_output_test(ld, action, create_output_test_from_file(output_file)) launch_service = LaunchService() launch_service.include_launch_description(ld) return_code = launch_test.run(launch_service) assert return_code == 0, 'Launch failed with exit code %r' % ( return_code, )
def test_execute_process_with_respawn(): """Test launching a process with a respawn and respawn_delay attribute.""" def on_exit_callback(event, context): on_exit_callback.called_count = on_exit_callback.called_count + 1 on_exit_callback.called_count = 0 respawn_delay = 2.0 shutdown_time = 3.0 # to shutdown the launch service, so that the process only respawn once expected_called_count = 2 # normal exit and respawn exit def generate_launch_description(): return LaunchDescription([ ExecuteProcess(cmd=[sys.executable, '-c', "print('action')"], respawn=True, respawn_delay=respawn_delay, on_exit=on_exit_callback), TimerAction(period=shutdown_time, actions=[Shutdown(reason='Timer expired')]) ]) ls = LaunchService() ls.include_launch_description(generate_launch_description()) assert 0 == ls.run() assert expected_called_count == on_exit_callback.called_count
def main(argv=sys.argv[1:]): launchFile = os.path.join(os.getenv('TEST_LAUNCH_DIR'), 'costmap_map_server.launch.py') testExecutable = os.getenv('TEST_EXECUTABLE') lifecycle_manager = launch_ros.actions.Node( package='nav2_lifecycle_manager', executable='lifecycle_manager', name='lifecycle_manager', output='screen', parameters=[{ 'node_names': ['map_server'] }, { 'autostart': True }]) ld = LaunchDescription([ IncludeLaunchDescription(PythonLaunchDescriptionSource([launchFile])), lifecycle_manager ]) test1_action = ExecuteProcess(cmd=[testExecutable], name='costmap_tests', output='screen') lts = LaunchTestService() lts.add_test_action(ld, test1_action) ls = LaunchService(argv=argv) ls.include_launch_description(ld) return lts.run(ls)
def test_execute_process_with_on_exit_behavior(): """Test a process' on_exit callback and actions are processed.""" def on_exit_callback(event, context): on_exit_callback.called = True on_exit_callback.called = False executable_with_on_exit_callback = ExecuteProcess( cmd=[sys.executable, '-c', "print('callback')"], output='screen', on_exit=on_exit_callback) assert len(executable_with_on_exit_callback.get_sub_entities()) == 0 def on_exit_function(context): on_exit_function.called = True on_exit_function.called = False on_exit_action = OpaqueFunction(function=on_exit_function) executable_with_on_exit_action = ExecuteProcess( cmd=[sys.executable, '-c', "print('action')"], output='screen', on_exit=[on_exit_action]) assert executable_with_on_exit_action.get_sub_entities() == [ on_exit_action ] ld = LaunchDescription( [executable_with_on_exit_callback, executable_with_on_exit_action]) ls = LaunchService() ls.include_launch_description(ld) assert 0 == ls.run() assert on_exit_callback.called assert on_exit_function.called
def check_launch_namespace(file): root_entity, parser = Parser.load(file) ld = parser.parse_description(root_entity) ls = LaunchService() ls.include_launch_description(ld) assert 0 == ls.run() assert 'ros_namespace' in ls.context.launch_configurations assert '/asd' == ls.context.launch_configurations['ros_namespace']
def _assert_launch_frontend_no_errors(self, file) -> Trace: root_entity, parser = Parser.load(file) ld = parser.parse_description(root_entity) ls = LaunchService() ls.include_launch_description(ld) assert 0 == ls.run() trace_action = ld.describe_sub_entities()[0] return trace_action
def check_launch_node(file): root_entity, parser = Parser.load(file) ld = parser.parse_description(root_entity) ls = LaunchService() ls.include_launch_description(ld) assert(0 == ls.run()) evaluated_parameters = evaluate_parameters( ls.context, ld.describe_sub_entities()[3]._Node__parameters ) assert len(evaluated_parameters) == 3 assert isinstance(evaluated_parameters[0], dict) assert isinstance(evaluated_parameters[1], dict) assert isinstance(evaluated_parameters[2], pathlib.Path) assert 'param1' in evaluated_parameters[0] assert evaluated_parameters[0]['param1'] == 'ads' param_dict = evaluated_parameters[1] assert 'param_group1.param_group2.param2' in param_dict assert 'param_group1.param3' in param_dict assert 'param_group1.param4' in param_dict assert 'param_group1.param5' in param_dict assert 'param_group1.param6' in param_dict assert 'param_group1.param7' in param_dict assert 'param_group1.param8' in param_dict assert 'param_group1.param9' in param_dict assert 'param_group1.param10' in param_dict assert 'param_group1.param11' in param_dict assert 'param_group1.param12' in param_dict assert 'param_group1.param13' in param_dict assert 'param_group1.param14' in param_dict assert 'param_group1.param15' in param_dict assert param_dict['param_group1.param_group2.param2'] == 2 assert param_dict['param_group1.param3'] == [2, 5, 8] assert param_dict['param_group1.param4'] == [2, 5, 8] assert param_dict['param_group1.param5'] == '[2, 5, 8]' assert param_dict['param_group1.param6'] == [2., 5., 8.] assert param_dict['param_group1.param7'] == ['2', '5', '8'] assert param_dict['param_group1.param8'] == ["'2'", "'5'", "'8'"] assert param_dict['param_group1.param9'] == ["'2'", "'5'", "'8'"] assert param_dict['param_group1.param10'] == ["'asd'", "'bsd'", "'csd'"] assert param_dict['param_group1.param11'] == ['asd', 'bsd', 'csd'] assert param_dict['param_group1.param12'] == '' assert param_dict['param_group1.param13'] == '100' assert param_dict['param_group1.param14'] == ["'2'", "'5'", "'8'"] assert param_dict['param_group1.param15'] == ['2', '5', '8'] # Check remappings exist remappings = ld.describe_sub_entities()[3]._Node__remappings assert remappings is not None assert len(remappings) == 2 listener_node_action = ld.describe_sub_entities()[4] listener_node_cmd = listener_node_action.process_details['cmd'] assert [ sys.executable, '-c', 'import sys; print(sys.argv[1:])' ] == listener_node_cmd[:3]
def test_node_frontend(file): """Parse node xml example.""" root_entity, parser = Parser.load(io.StringIO(file)) ld = parser.parse_description(root_entity) ls = LaunchService() ls.include_launch_description(ld) assert 0 == ls.run() assert 'ros_namespace' in ls.context.launch_configurations assert '/asd' == ls.context.launch_configurations['ros_namespace']
def main(argv=sys.argv[1:]): mapFile = os.getenv('TEST_MAP') testExecutable = os.getenv('TEST_EXECUTABLE') world = os.getenv('TEST_WORLD') launch_gazebo = launch.actions.ExecuteProcess(cmd=[ 'gzserver', '-s', 'libgazebo_ros_init.so', '--minimal_comms', world ], output='screen') link_footprint = launch_ros.actions.Node( package='tf2_ros', node_executable='static_transform_publisher', output='screen', arguments=[ '0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link' ]) footprint_scan = launch_ros.actions.Node( package='tf2_ros', node_executable='static_transform_publisher', output='screen', arguments=['0', '0', '0', '0', '0', '0', 'base_link', 'base_scan']) run_map_server = launch_ros.actions.Node(package='nav2_map_server', node_executable='map_server', node_name='map_server', output='screen', parameters=[{ 'yaml_filename': mapFile }]) run_amcl = launch_ros.actions.Node(package='nav2_amcl', node_executable='amcl', output='screen') run_lifecycle_manager = launch_ros.actions.Node( package='nav2_lifecycle_manager', node_executable='lifecycle_manager', node_name='lifecycle_manager', output='screen', parameters=[{ 'node_names': ['map_server', 'amcl'] }, { 'autostart': True }]) ld = LaunchDescription([ launch_gazebo, link_footprint, footprint_scan, run_map_server, run_amcl, run_lifecycle_manager ]) test1_action = ExecuteProcess(cmd=[testExecutable], name='test_localization_node', output='screen') lts = LaunchTestService() lts.add_test_action(ld, test1_action) ls = LaunchService(argv=argv) ls.include_launch_description(ld) return lts.run(ls)
def test_launch_service_emit_event(): """ Test the emitting of events in the LaunchService class. Also covers basic tests for include_launch_description(), run(), and shutdown(). """ ls = LaunchService(debug=True) assert ls._LaunchService__context._event_queue.qsize() == 0 from launch.actions import OpaqueFunction from launch.actions import RegisterEventHandler from launch.event_handler import EventHandler handled_events = queue.Queue() ld = LaunchDescription([ RegisterEventHandler(EventHandler( matcher=lambda event: True, entities=OpaqueFunction( function=lambda context: handled_events.put(context.locals.event), ), )) ]) ls.include_launch_description(ld) assert ls._LaunchService__context._event_queue.qsize() == 1 class MockEvent: name = 'Event' ls.emit_event(MockEvent()) assert ls._LaunchService__context._event_queue.qsize() == 2 assert handled_events.qsize() == 0 t = threading.Thread(target=ls.run, kwargs={'shutdown_when_idle': False}) t.start() # First event (after including description of event handler). handled_events.get(block=True, timeout=5.0) # Emit and then check for a second event. ls.emit_event(MockEvent()) handled_events.get(block=True, timeout=5.0) # Shutdown (generates a third event) and join the thread. ls.shutdown() t.join() # Check that the shutdown event was handled. handled_events.get(block=False) assert handled_events.qsize() == 0 ls.emit_event(MockEvent()) assert handled_events.qsize() == 0 assert ls.run(shutdown_when_idle=True) == 0 handled_events.get(block=False)
def _launch(launch_description): loop = osrf_pycommon.process_utils.get_loop() ls = LaunchService() ls.include_launch_description(launch_description) launch_task = loop.create_task(ls.run_async()) loop.run_until_complete(asyncio.sleep(5, loop=loop)) if not launch_task.done(): loop.create_task(ls.shutdown()) loop.run_until_complete(launch_task) return ls.context
def launch_gtest(test_path): """Launch a gtest.""" ld = LaunchDescription([ GTest(path=str(test_path), timeout=5.0, on_exit=[EmitEvent(event=Shutdown())]) ]) ls = LaunchService() ls.include_launch_description(ld) assert 0 == ls.run()
def test_execute_process_with_env(): """Test launching a process with an environment variable.""" ld = LaunchDescription([ ExecuteProcess( cmd=[sys.executable, 'TEST_PROCESS_WITH_ENV'], output='screen', env={'TEST_PROCESS_WITH_ENV': 'Hello World'}, ) ]) ls = LaunchService() ls.include_launch_description(ld) assert 0 == ls.run()
def start_launch_servide_process(ld): """Starts a Launch Service process. To be called from subclasses. Args: ld : LaunchDescription obj. """ # Create the LauchService and feed the LaunchDescription obj. to it. ls = LaunchService() ls.include_launch_description(ld) p = Process(target=ls.run) p.daemon = True #The daemon process is terminated automatically before the main program exits, to avoid leaving orphaned processes running p.start()
def launch(shutdown_pipe, package_name, launch_file_name, launch_arguments, debug): """Launch a ROS system.""" event_loop = asyncio.new_event_loop() asyncio.set_event_loop(event_loop) # based on ros2launch/command/launch.py:main if package_name is None: single_file = True else: single_file = False get_package_prefix(package_name) path = None launch_arguments = [] if single_file: if os.path.exists(package_name): path = package_name else: raise ValueError(package_name) if launch_file_name is not None: launch_arguments.append(launch_file_name) else: try: path = get_share_file_path_from_package(package_name=package_name, file_name=launch_file_name) except PackageNotFoundError as exc: raise RuntimeError("Package '{}' not found: {}".format( package_name, exc)) except (FileNotFoundError, MultipleLaunchFilesError) as exc: raise RuntimeError(str(exc)) launch_arguments.extend(launch_arguments) launch_service = LaunchService(argv=launch_arguments, debug=debug) launch_description = LaunchDescription([ IncludeLaunchDescription( AnyLaunchDescriptionSource(path), launch_arguments={}, ), ]) launch_service.include_launch_description(launch_description) finished = False def shutdown(): while not finished and not shutdown_pipe.poll(1): pass launch_service.shutdown() t = threading.Thread(target=shutdown) t.start() launch_service.run(shutdown_when_idle=True) finished = True t.join() event_loop.close()
def main(argv=sys.argv[1:]): testExecutable = os.getenv('TEST_EXECUTABLE') ld = LaunchDescription([]) test1_action = ExecuteProcess(cmd=[testExecutable], name='test_planner_costmaps_node', output='screen') lts = LaunchTestService() lts.add_test_action(ld, test1_action) ls = LaunchService(argv=argv) ls.include_launch_description(ld) return lts.run(ls)
def main(argv=sys.argv[1:]): ld = generate_launch_description() test1_action = launch.actions.ExecuteProcess( cmd=[os.path.join(os.getenv('TEST_DIR'), 'test_system_node.py')], name='test_system_node', output='screen') lts = LaunchTestService() lts.add_test_action(ld, test1_action) ls = LaunchService(argv=argv) ls.include_launch_description(ld) return lts.run(ls)
def main(argv=sys.argv[1:]): ld = generate_launch_description() test1_action = ExecuteProcess( cmd=[get_package_prefix('robot_localization') + '/lib/robot_localization/test_filter_base_diagnostics_timestamps'], output='screen', ) lts = LaunchTestService() lts.add_test_action(ld, test1_action) ls = LaunchService(argv=argv) ls.include_launch_description(ld) return lts.run(ls)
def _assert_launch_no_errors(actions, *, timeout_sec=5): ld = LaunchDescription(actions) ls = LaunchService(debug=True) ls.include_launch_description(ld) loop = osrf_pycommon.process_utils.get_loop() launch_task = loop.create_task(ls.run_async()) loop.run_until_complete(asyncio.sleep(timeout_sec)) if not launch_task.done(): loop.create_task(ls.shutdown()) loop.run_until_complete(launch_task) assert 0 == launch_task.result() return ls.context
def run_and_trace( base_path: str, session_name_prefix: str, ros_events: List[str], kernel_events: List[str], package_name: str, node_names: List[str], additional_actions: Union[List[Action], Action] = [], ) -> Tuple[int, str]: """ Run a node while tracing. :param base_path: the base path where to put the trace directory :param session_name_prefix: the session name prefix for the trace directory :param ros_events: the list of ROS UST events to enable :param kernel_events: the list of kernel events to enable :param package_name: the name of the package to use :param node_names: the names of the nodes to execute :param additional_actions: the list of additional actions to prepend :return: exit code, full generated path """ session_name = append_timestamp(session_name_prefix) full_path = os.path.join(base_path, session_name) if not isinstance(additional_actions, list): additional_actions = [additional_actions] launch_actions = additional_actions # Add trace action launch_actions.append( Trace( session_name=session_name, append_timestamp=False, base_path=base_path, events_ust=ros_events, events_kernel=kernel_events, )) # Add nodes for node_name in node_names: n = Node( package=package_name, executable=node_name, output='screen', ) launch_actions.append(n) ld = LaunchDescription(launch_actions) ls = LaunchService() ls.include_launch_description(ld) exit_code = ls.run() return exit_code, full_path
def main(argv=sys.argv[1:]): testExecutable = os.getenv('TEST_EXECUTABLE') ld = generate_launch_description() test1_action = ExecuteProcess( cmd=[testExecutable], name='test_dynamic_params_client', ) lts = LaunchTestService() lts.add_test_action(ld, test1_action) ls = LaunchService(argv=argv) ls.include_launch_description(ld) return lts.run(ls)
def main(argv=sys.argv[1:]): ld = generate_launch_description() testExecutable = os.getenv('TEST_EXECUTABLE') test1_action = ExecuteProcess(cmd=[testExecutable], name='test_spin_recovery_fake_node', output='screen') lts = LaunchTestService() lts.add_test_action(ld, test1_action) ls = LaunchService(argv=argv) ls.include_launch_description(ld) return lts.run(ls)
def main(argv): ld = generate_launch_description() print('Starting introspection of launch description...') print('') print(LaunchIntrospector().format_launch_description(ld)) print('') print('Starting launch of launch description...') print('') ls = LaunchService() ls.include_launch_description(ld) return ls.run()
def main(argv=sys.argv[1:]): ld = generate_launch_description() test1_action = ExecuteProcess(cmd=[ os.path.join(os.getenv('TEST_DIR'), os.getenv('TESTER')), '-r', '-2.0', '-0.5', '0.0', '2.0', '-e', 'True' ], name='tester_node', output='screen') lts = LaunchTestService() lts.add_test_action(ld, test1_action) ls = LaunchService(argv=argv) ls.include_launch_description(ld) return lts.run(ls)
def startLaunchServiceProcess(launchDesc): """Starts a Launch Service process. To be called from subclasses. Args: launchDesc : LaunchDescription obj. """ # Create the LauchService and feed the LaunchDescription obj. to it. launchService = LaunchService() launchService.include_launch_description(launchDesc) process = Process(target=launchService.run) # The daemon process is terminated automatically before the main program exits, # to avoid leaving orphaned processes running process.daemon = True process.start() return process