Testing Node Classes

Even though a lot of errors are harder to make and/or easier to catch with ros_bt_py than with other libraries, you should still test any new node classes you make.

The easiest way to to this is by adding tests to your ROS2 package. To do that, you simply create a new folder, slap some test scripts in there, and add a few lines to your CMakeLists.txt or setup.py, and package.xml. I’ll walk you through it:

Creating a Test Folder and Unit Test Script

The most common way to write Python unit tests in ROS2 is the pytest module.

So, within your ROS package, create a new folder called tests/. Next, create a new file called test_my_node.py and put the following code in it

 1import pytest
 2
 3# Useful to have the state names to compare against
 4from ros_bt_py_interfaces.msg import Node as NodeMsg
 5
 6from my_pacakge.nodes.my_awesome_node import MyAwesomeNode
 7
 8def test_setup():
 9  awesome = MyAwesomeNode()
10  awesome.setup()
11
12  # Any node should be IDLE after calling setup()
13  assert awesome.state == NodeMsg.IDLE

A lot of the names here are important, because pytest uses the function name to find and run tests. Your test script must start with the word “test”.

Running your Unit Tests

Now, to actually run your unit tests, simply go to the package folder and run

pytest

Adding your Unit Tests to CMakeLists.txt

If you want your tests to be run by the CI pipeline (and who doesn’t?) and you use CMakeLists.txt to build your package, you’ll also have to tell the build system about them.

More info can be found in the ROS2 tutorials .

Don’t worry, it’s easy - just add the following lines to your CMakeLists.txt, and nose will do the rest

 1if (BUILD_TESTING)
 2  find_package(ament_cmake_pytest REQUIRED)
 3
 4  # Add the python test files you wrote here:
 5  set(_pytest_tests
 6    tests/test_a.py
 7    tests/test_b.py
 8    # Add other test files here
 9  )
10  foreach(_test_path ${_pytest_tests})
11    get_filename_component(_test_name ${_test_path} NAME_WE)
12    ament_add_pytest_test(${_test_name} ${_test_path}
13      APPEND_ENV PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}
14      TIMEOUT 60
15      WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
16    )
17  endforeach()
18endif()

Adding your Unit Tests to setup.py

When using an ament_python package, pytest based tests are automatically picked up by the system. No additional steps should be required.

Running Tests via colcon

Now that you’ve registered your tests with ROS2 and colcon, you can use colcon to run them

colcon test