Example #1
0
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, )
Example #2
0
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)
Example #3
0
def main(argv=sys.argv[1:]):
    """Run demo nodes via launch."""
    ld = LaunchDescription([
        launch_ros.actions.Node(package='demo_nodes_cpp',
                                executable='talker',
                                output='screen',
                                remappings=[('chatter', 'my_chatter')]),
        launch_ros.actions.Node(package='demo_nodes_cpp',
                                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(ld)
    return ls.run()
Example #4
0
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 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())
Example #6
0
    def __init__(self,
                 gen_launch_description_fn,
                 test_module,
                 launch_file_arguments=[],
                 debug=False):
        """
        Create an ApexRunner object.

        :param callable gen_launch_description_fn: A function that returns a ros2 LaunchDesription
        for launching the processes under test.  This function should take a callable as a
        parameter which will be called when the processes under test are ready for the test to
        start
        """
        self._gen_launch_description_fn = gen_launch_description_fn
        self._test_module = test_module
        self._launch_service = LaunchService(debug=debug)
        self._processes_launched = threading.Event(
        )  # To signal when all processes started
        self._tests_completed = threading.Event(
        )  # To signal when all the tests have finished
        self._launch_file_arguments = launch_file_arguments

        # Can't run LaunchService.run on another thread :-(
        # See https://github.com/ros2/launch/issues/126
        # Instead, we'll let the tests run on another thread
        self._test_tr = threading.Thread(target=self._run_test,
                                         name="test_runner_thread",
                                         daemon=True)
Example #7
0
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, )
Example #8
0
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
Example #9
0
        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, )
Example #10
0
    def __init__(self,
                 test_run,
                 test_run_preamble,
                 launch_file_arguments=[],
                 debug=False):
        self._test_run = test_run
        self._test_run_preamble = test_run_preamble
        self._launch_service = LaunchService(debug=debug)
        self._processes_launched = threading.Event(
        )  # To signal when all processes started
        self._tests_completed = threading.Event(
        )  # To signal when all the tests have finished
        self._launch_file_arguments = launch_file_arguments

        # Can't run LaunchService.run on another thread :-(
        # See https://github.com/ros2/launch/issues/126
        #
        # It would be simpler if we could run the pre-shutdown test and the post-shutdown tests on
        # one thread, and run the launch on another thead.
        #
        # Instead, we'll run the pre-shutdown tests on a background thread concurrent with the
        # launch on the main thread.  Once the launch is stopped, we'll run the post-shutdown
        # tests on the main thread
        self._test_tr = threading.Thread(target=self._run_test,
                                         name='test_runner_thread',
                                         daemon=True)
Example #11
0
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
Example #12
0
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']
Example #13
0
 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
Example #14
0
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)
Example #17
0
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()
Example #19
0
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 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)
Example #21
0
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)
Example #23
0
    def launch(self):
        components_launch_description_list = map(
            lambda c: c.launch_description, self._components_list)
        launch_description = LaunchDescription(
            components_launch_description_list)

        self._launch_service = LaunchService(argv=argv)
        self._launch_service.include_launch_description(launch_description)

        self._loop = osrf_pycommon.process_utils.get_loop()
        self._launch_task = self._loop.create_task(
            self._launch_service.run_async())
        self._loop.run_until_complete(self._launch_task)
Example #24
0
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)
Example #26
0
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)
Example #27
0
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)
Example #28
0
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
Example #29
0
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()
Example #30
0
def main(argv=sys.argv[1:]):
    ld = generate_launch_description()

    # TODO(orduno) remove duplicated definition of robots on `generate_launch_description`
    test1_action = ExecuteProcess(
        cmd=[os.path.join(os.getenv('TEST_DIR'), 'tester_node.py'),
             '-rs', 'robot1', '0.0', '0.5', '1.0', '0.5',
             '-rs', 'robot2', '0.0', '-0.5', '1.0', '-0.5'],
        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)