Testing, Continuous Integration, and Continuous Deployment with ROS 2
local graph
Chapter 13 — Testing, Continuous Integration, and Continuous Deployment with ROS 2
Section titled “Chapter 13 — Testing, Continuous Integration, and Continuous Deployment with ROS 2”During a project, developers often make continuous changes to the same source code to add new features. To prevent introducing bugs or compilation errors, it’s essential to have reliable tools that can automatically detect issues early. These tools should run before sharing the updated code with the rest of the team or integrating it into a larger system to avoid disrupting a functioning setup.
This chapter will cover two key practices: code testing, which ensures the code performs as expected, and Continuous Integration (CI) and Continuous Deployment (CD), which automate code integration and deployment to check for bugs and streamline the release process. Numerous tools are available for these tasks, and in this chapter, we will use ROS 2 nodes and packages with these tools. For testing, we’ll utilize the Google Test (GTest) framework, and for CI/CD, we’ll leverage a GitHub feature called GitHub Actions, which can be accessed directly through the GitHub website.
As such, we will cover the following main topics in the chapter:
- Testing ROS 2 nodes using GTest
- Integrating ROS 2 APIs in the GTest framework
- Implementing CI/CD for ROS 2 packages
Technical requirements
Section titled “Technical requirements”To follow this chapter, you should have one of the following setups on your computer:
- A standard computer running the Ubuntu 24.04 LTS operating system
- A Linux machine with a ROS 2 Jazzy version installed or with a running Docker container configured, as discussed in
Chapter 2 - A personal account on GitHub: https://github.com
The reference code for this chapter can be found in the Chapter13 folder of the following book code repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter13.
Testing ROS 2 nodes using GTest
Section titled “Testing ROS 2 nodes using GTest”Automated unit testing in ROS 2 offers several key advantages. By running tests after each change, you can make small code updates with confidence that interdependencies across ROS 2 packages won’t introduce unexpected issues. This also allows you to refactor code without fear of introducing bugs, as passing tests confirms that functionality remains intact. There are different kinds of testing methods, each devoted to testing a particular aspect of the source code. Among them, unit testing is the test type that helps developers ensure that their code works as expected in both basic and corner cases. It involves writing tests for small, self-contained pieces of code, typically functions or methods, to ensure they generate the expected output values. These tests are usually automated and can be run frequently throughout the development process. They can be defined by the developer themself, ensuring that both basic functionalities and critical aspects of a function are tested.
A common library to perform unit testing is GTest, and we can easily integrate GTest in ROS 2 nodes written in C++. As for the unit test, we can additionally classify two different types of tests: black box and white box. Unit testing with GTest in ROS 2 is primarily white-box testing. In white-box testing, developers have knowledge of the internal structure and code, allowing them to test specific functions, conditions, and branches within the code. Since unit tests in ROS 2 using GTest focus on individual functions, nodes, and components with a direct understanding of the internal implementation, they fall under this category. On the other hand, black-box testing applies to integration, system, or acceptance tests, where the internal workings of the components may not be fully visible to the tester. In black-box testing, the focus is on validating the outputs against expected results based on inputs without considering the internal code structure.
Exploring the GTest features and programming pipeline
Section titled “Exploring the GTest features and programming pipeline”GTest provides a rich set of features that make it easy to create robust and efficient tests for C++ applications, including those built on ROS 2. The main elements of the GTest library are the following:
- XML test reporting: After the execution of the tests, you can generate XML reports of test results, making it easy to analyze the success or failure of given tests.
- Test fixtures: GTest allows you to create test fixtures, which are reusable setup and teardown routines that can be shared across multiple tests. This is useful for initializing complex objects or resources that multiple tests might use.
- Assertions: The framework provides a variety of assertions to check conditions in your tests, such as
EXPECT_EQ,ASSERT_TRUE,EXPECT_NE, and more. We will discuss these assertions in more detail in the code examples. However, they help you validate that your code behaves as intended. - Parameterized tests: GTest supports parameterized tests, allowing you to run the same test logic with different inputs. This is useful for testing functions with multiple edge cases.
- Death tests: You can write tests to verify that your code handles fatal failures correctly, ensuring that your application behaves as expected even under error conditions.
Before implementing our first example of code testing associated with ROS 2, let’s briefly discuss the typical GTest programming pipeline:
- Set up: Include the GTest library in your ROS 2 package, and you can define your tests in a separate source file.
- Write tests: Write test cases using the GTest framework, defining specific input and expected output scenarios. Each test case is usually encapsulated in a function that begins with
TEST(), followed by the test name. - Run tests: Compile the test code and run the tests using the provided ROS 2 test tools or directly through GTest, which gives a detailed report of passed and failed tests.
- Check results: Analyze the report files generated from the GTest library to eventually know which tests have been passed or not.
We are now ready to implement our first examples using GTest and ROS 2.
Integrating GTest with ROS 2 for robust testing
Section titled “Integrating GTest with ROS 2 for robust testing”First, let’s create a ROS 2 package to store our tests. In this first example, we will not use any function from the ROS 2 API, such as services, publishers, or subscribers; we will just use the GTest framework to test the result of a basic function that translates a given angle from radians to degrees, bounding it in the interval –pi, pi (-1.57, 1.57). We can create this package as a normal ROS 2 package:
$ ros2 pkg create first_gtest --dependencies rclcpp std_msgsThe source code of the package is placed in the src folder of a package, while the test files must be placed in the test folder. Let’s create a test folder and a test source file called first_test.cpp:
$ cd first_gtest$ mkdir test && touch first_test.cppThe content of this file is as follows:
- As already said, we don’t need to use ROS 2 API functions, so we will not include a header from it. We will include the
gtest.hheader (already installed with the desktop version of ROS 2):#include <gtest/gtest.h> - We initialize a
constexprvariable and a function. These expressions are evaluated at compile time and can be used to define true constant values in a type-safe way. We define the value of pi and a function to convert a given degree value to radians. This requires the constant pi (approximately 3.1415), which can be obtained using theM_PIsymbol from the<cmath>header:constexpr double DEG_TO_RAD = M_PI / 180.0; - We can now define the function to test. This function takes a degree value as input and returns the corresponding radian value. Additionally, it ensures that the output is bounded within the interval [
-pi;pi). This notation excludes one of the two boundaries to guarantee a unique representation of the 180 and –180 angles. In practical applications such as robotics, graphics, and physics, this convention is preferred because it eliminates redundancy and ensures a consistent representation of angles.
Restricting a robot’s estimated angle in this interval is helpful for different reasons. For example:
- Avoids ambiguity: This keeps the angle unique, as values such as
2piand0are equivalent but can otherwise appear different. - Simplifies rotational calculations: Limiting the angle range helps calculate angular differences easily, always choosing the shortest path without multiple rotations.
- Prevents discontinuities: As a robot rotates continuously, the angle could grow indefinitely; keeping it in this range avoids instability.
The degreesToRadians function is used to perform the conversion:
double degreesToRadians(double degrees) { double radians = degrees * DEG_TO_RAD; while (radians >= PI) radians -= 2.0 * PI; while (radians < -PI) radians += 2.0 * PI; return radians;}- Until now, we showed a simple C++ code. Let’s define the test functions. We can define different tests that prove the robustness of the code. The
TESTkeyword is used to define a function containing a desired number of tests. TheTESTfunction accepts two input values: the suite and the test names. The suite name specifies a group of related tests. For example, in theAngleConversionTestsuite, we want to test the conversion in radians in the desired interval for positive angles (HandlesPositiveAngles):TEST(AngleConversionTest, HandlesPositiveAngles) { - To check that the function generates the correct value, we use the
EXPECT_NEARmacro, which is used to check whether two floating-point values are nearly equal, accounting for small differences due to floating-point precision. In the first line, for example, we check that the conversion of0degrees is0radians. In this case, we can assume that the result of the conversion is exactly0.0, while, in other cases, some numbers can be placed in the floating part of the number. WithEXPECT_NEAR, we request that the output value and the checked one differ by a maximum of0.000000001:EXPECT_NEAR(degreesToRadians(0), 0.0, 1e-9);EXPECT_NEAR(degreesToRadians(180), PI, 1e-9);EXPECT_NEAR(degreesToRadians(90), PI / 2.0, 1e-9);EXPECT_NEAR(degreesToRadians(360), 0.0, 1e-9);} - We can add different other tests:
TEST(AngleConversionTest, HandlesNegativeAngles) {EXPECT_NEAR(degreesToRadians(-180), -PI, 1e-9);EXPECT_NEAR(degreesToRadians(-90), -PI / 2.0, 1e-9);EXPECT_NEAR(degreesToRadians(-360), 0.0, 1e-9);}TEST(AngleConversionTest, HandlesOverflowAngles) {EXPECT_NEAR(degreesToRadians(720), 0.0, 1e-9);EXPECT_NEAR(degreesToRadians(540), PI, 1e-9);EXPECT_NEAR(degreesToRadians(-540), -PI, 1e-9);}TEST(AngleConversionTest, HandlesSmallAngles) {EXPECT_NEAR(degreesToRadians(1), DEG_TO_RAD, 1e-9);EXPECT_NEAR(degreesToRadians(-1), -DEG_TO_RAD, 1e-9);}
- In the main function, we initialize the GTest framework and request to start all the tests defined in the test file. The framework automatically detects all the
TESTfunctions defined in the test source file, executing them in a sequential way:int main(int argc, char** argv) {testing::InitGoogleTest(&argc, argv);return RUN_ALL_TESTS();}
Before running these tests, we need to configure the CMakeLists.txt file to compile them. Tests are not treated as executables in ROS 2, so we cannot define them using the standard executable definition. Instead, we use ament_add_gtest to define the test. We’ll place the test in the BUILD_TESTING section of CMakeLists.txt, which is enabled by default in the colcon build system. After adding first_test.cpp to this section, we also specify its dependencies:
if(BUILD_TESTING) find_package(ament_cmake_gtest REQUIRED) ament_add_gtest(first_test test/first_test.cpp) ament_target_dependencies(first_test std_msgs )endif()To run the tests, you must follow these steps:
- Compile the workspace to generate the test executables:
$ colcon build --symlink-install
- Run the test. Here, we can optionally specify the package:
$ colcon test --ctest-args tests first_gtest
- Check the results:
$ colcon test-result --all --verbose
The output of the previous command is quite long and difficult to read. However, you should be able to notice the following lines:
Failure The difference between degreesToRadians(540) and 3.14159265358979323846 is 6.2831853071795862, which exceeds 1e-9, where degreesToRadians(540) evaluates to -3.1415926535897931, 3.14159265358979323846 evaluates to 3.1415926535897931, and 1e-9 evaluates to 1.0000000000000001e-09.As you can see from the previous output, the result of the degreesToRadians function on the 540 input and the check value pi=3.1415 differ by 6.2831, which is higher than the allowed threshold of 1e-9. In fact, the output of the function is pi and not –pi. Our function works correctly; the error here is in the test definition. We included this test solely to demonstrate how to detect a failure. However, this example highlights an important point: we must carefully consider the test design and input values. Otherwise, we risk identifying bugs that don’t actually exist in our code.
- Inspect the
.xmlfile. For each test, an.xmlreport is generated that contains the same information already shown in the terminal with the previous command. The file is placed inside thebuildfolder. In our case, it will be placed in the following location:
ros2_ws/build/first_gtest/test_results/first_gtest/first_test.gtest.xml
We completed our first GTest on a very simple function. Let’s discuss another example, in which the ROS 2 API functions are integrated into the GTest framework.
Integrating ROS 2 APIs in the GTest framework
Section titled “Integrating ROS 2 APIs in the GTest framework”In the previous example, we learned how to run GTest using ROS 2 commands. However, in a real robotic application, that example may not be very practical. Let’s take our use of GTest a step further with a new example. In this example, we’ll test the output of a ROS 2 node that publishes to a ROS 2 topic. The purpose of the node is to convert an input string (received on a topic) to all lowercase letters. For instance, the string INpUt would be converted to input. To start, we need to create a package and the node we want to test. We’ll create the following source files:
to_lowercase.hto store the definition of the ROS 2 node class and its variablesto_lowercase.cppto implement the functions to convert the letters from uppercase to lowercasemain.cppto instantiate and spin the ROS 2 node
We will separate the class and function definitions into different source files, allowing us to replace the main function with the one defined in the test file, as we will discuss later in the chapter.
Exploring the content of the source files
Section titled “Exploring the content of the source files”Let’s start by discussing the header file and then move on to the other two:
to_lowercase.h:- Here, we just include the node headers and define the
ToLowercaseclass:#include <rclcpp/rclcpp.hpp>#include <std_msgs/msg/string.hpp>#include <algorithm>class ToLowercase : public rclcpp::Node {public:ToLowercase() : Node("lowercase_string_node") {- The node receives the string to convert on the
/inputtopic while publishing the output on the/outputtopic:
_input_sub = this->create_subscription<std_msgs::msg::String> ("input", 10, std::bind(&ToLowercase::input_str_cb, this, std::placeholders::_1));_output_pub = this->create_publisher<std_msgs::msg::String>("output", 10);}void input_str_cb(const std_msgs::msg::String::SharedPtr msg);private:rclcpp::Subscription<std_msgs::msg::String>::SharedPtr _input_sub;rclcpp::Publisher<std_msgs::msg::String>::SharedPtr _output_pub;}; - The node receives the string to convert on the
- Here, we just include the node headers and define the
to_lowercase.cpp:- In the source file, we just write the body of the input callback, convert the string, and republish it into a lowercase one:
#include "to_lowercase.h"void ToLowercase::input_str_cb(const std_msgs::msg::String::SharedPtr msg) {std::string lowercase_str = msg->data;
- To do this, the function
transformis used. Finally, the resultant string is published:
std::transform(lowercase_str.begin(), lowercase_str.end(), lowercase_str.begin(), ::tolower);auto message = std_msgs::msg::String();message.data = lowercase_str;_output_pub->publish(message);} - To do this, the function
- In the source file, we just write the body of the input callback, convert the string, and republish it into a lowercase one:
main.cpp: In themain.cppfile, we just spin the ROS 2 node implemented with the defined class (ToLowercase):#include "to_lowercase.h"int main(int argc, char **argv) {rclcpp::init(argc, argv);auto node = std::make_shared<ToLowercase>();rclcpp::spin(node);rclcpp::shutdown();return 0;}
Before defining a test for this ROS 2 node, let’s execute it to check how it works. Add the executable to the CMakeLists.txt file:
add_executable(to_lowercase src/to_lowercase.cpp src/main.cpp)ament_target_dependencies(to_lowercase rclcpp std_msgs)install(TARGETS to_lowercase DESTINATION lib/${PROJECT_NAME})Finally, compile the workspace, source it, and run the node:
$ colcon build --symlink-install$ source install/setup.bash$ ros2 run to_lowercase to_lowercaseCheck the output by reading the output topic:
$ ros2 topic echo /outputOn another terminal, publish the string tOLoWER:
$ ros2 topic pub /input std_msgs/msg/String "data: tOLoWER" --onceAs you can see from the topic output, the code works as expected. But what if we slightly modify the code, changing how the string is converted? While this example is simple, it gives us an idea of the potential of the GTest framework. We can automatically define tests to run after any code change, helping us ensure everything still functions correctly.
Implementing automatic testing using GTest
Section titled “Implementing automatic testing using GTest”Let’s define a test for this ROS 2 node. Create a directory called test in the to_lowercase package, containing a test file called to_lowercase_test.cpp. Its content is described here:
- In addition to the ROS 2 headers, we need to include the header file where the ROS 2 node is defined, using a relative path. Since the files are in the same package, this approach will not cause any compilation errors, even on other machines:
#include <algorithm>#include <gtest/gtest.h>#include <rclcpp/rclcpp.hpp>#include <std_msgs/msg/string.hpp>#include "../src/to_lowercase.h"
- We are going to define only one test and one test suite, the
package_nametest, which will be automatically translated with the name of the package, and theUpperToLowersuite, to test the effectiveness of the ROS 2 node:TEST(package_name, UpperToLower) { - First, we must create the ROS 2 node, spinning it with an executor. This will allow the node to work correctly with the callbacks:
auto to_lowercase_node = std::make_shared<ToLowercase>();rclcpp::executors::SingleThreadedExecutor executor;executor.add_node(to_lowercase_node);
- We must define a callback that receives the output of the publisher on which the result of the string conversion is published. We will use a lambda function in this test. A lambda function is useful for short, one-time operations, often passed as arguments to other functions, without needing a full function definition. We will pass the function two variables—a Boolean one that is set to
truewhen the output of the conversion is received, and a string that stores the output of the conversion:bool ready = false;std::string value;auto output_callback = [this, &ready, &value](const std_msgs::msg::String::SharedPtr msg) {value = msg->data;ready = true;}; - We define the publisher and the subscriber next:
rclcpp::Subscription<std_msgs::msg::String>::SharedPtr output_sub;output_sub = to_lowercase_node->create_subscription<std_msgs::msg::String>("/output", 10, output_callback);rclcpp::Publisher<std_msgs::msg::String>::SharedPtr string_pub;string_pub = to_lowercase_node->create_publisher<std_msgs::msg::String>("/input", 10);
- The string ROS 2 message is initialized and published. In this first test, we use the string
TOLOWER:std_msgs::msg::String s;s.data = "TOLOWER";string_pub->publish( s ); - After publishing the string, we must only wait for the conversion to be performed and published on the
/outputtopic:rclcpp::Rate rate(5); // Set rate to 1 Hz (once per second)while( !ready ) {executor.spin_once(std::chrono::milliseconds(100)); // Process callbacks with a timeout of 100 msrate.sleep();} - Now, we can evaluate the test result. If the conversion output is the string
tolower, the test is considered passed. We’ve added awhileloop, which could run indefinitely if the string is never published for some reason. However, the GTest framework includes a timeout feature: if the test takes longer than expected, it will be automatically aborted. To check the value of the generated string, we use theASSERT_EQkeyword, which checks the exact value of the control value:ASSERT_EQ(value, "tolower"); - We can test with another string that could be considered more complex,
TO-LOWER-2:ready = false;s.data = "TO-LOWER-2";string_pub->publish( s );while( !ready ) {executor.spin_once(std::chrono::milliseconds(100)); // Process callbacks with a timeout of 100 msrate.sleep();}ASSERT_EQ(value, "to-lower-2");} - Like the previous test, in the main function, we must just initialize the GTest framework and run the tests. Before running the tests, we must also initialize the ROS 2 system:
int main(int argc, char** argv) {testing::InitGoogleTest(&argc, argv);rclcpp::init(argc, argv);return RUN_ALL_TESTS();}
As already done in the previous test, we must modify the CMakeLists.txt to compile the test. The source code must be included in ament_add_gtest. In this case, we must add not only the test file discussed above but also the source file in which the ROS 2 node to test is implemented (to_lowercase.cpp):
ament_add_gtest(to_lowercase_test test/to_lowercase_test.cpp src/to_lowercase.cpp)ament_target_dependencies(to_lowercase_test rclcpp std_msgs)Now, you can use the commands already seen so far to compile, run, and inspect the results of the test:
$ colcon build --symlink-install$ colcon test --ctest-args tests to_lowercase$ colcon test-result --all –verboseWhat you should see is the result of all the tests of your ROS 2 workspace. Regarding the ROS 2 node just developed, the output will be the following:
build/to_lowercase/Testing/20241031-1639/Test.xml: 1 test, 0 errors, 0 failures, 0 skippedbuild/to_lowercase/test_results/to_lowercase/to_lowercase_test.gtest.xml: 1 test, 0 errors, 0 failures, 0 skippedAs you can see from the output, the .xml is generated, reporting a list of tests done with their status (errors, failures, or skipped).
These tests must be executed by the developers every time a new feature is added, and the source code must be shared or integrated into a more complex system. Unit testing is not the only method available for developers to be sure that the new code is ready to be deployed and distributed. In the next section, we will discuss the CI/CD process that automates and manages the entire code testing and deployment pipeline.
Implementing CI/CD for ROS 2 packages
Section titled “Implementing CI/CD for ROS 2 packages”As shown in the previous section, unit testing involves testing individual code components or functions to ensure they work as expected. Here we will introduce a new tool for developers, called CI/CD. This is a broader process that automates code integration, testing, and deployment, ensuring that changes are tested and deployed reliably and quickly.
If your code has a compilation error or depends on other system packages, you need an automated tool to prevent deployment and distribution if it fails to compile or causes issues for other packages. This is where a CI/CD tool comes in. Here, we’ll use GitHub Actions, a feature provided by GitHub, to implement these testing mechanisms. However, there are many tools available for this purpose, such as the following:
- Jenkins: This is the most famous one. It is an open-source automation server and is highly customizable with plugins for various CI/CD workflows.
- GitHub Actions: This is integrated directly into GitHub, enabling easy setup of CI/CD pipelines with GitHub repositories.
- GitLab CI/CD: This is built into GitLab, offering robust CI/CD capabilities directly within the GitLab environment.
- CircleCI: This is a cloud-based CI/CD tool known for its speed and Docker support.
- Azure DevOps: This is Microsoft’s CI/CD platform, integrated with Azure for easy deployment to cloud services.
- Bitbucket Pipelines: This is built into Bitbucket, enabling seamless CI/CD pipelines within Bitbucket repositories.
- AWS CodePipeline: This is part of AWS services, enabling CI/CD pipelines within the AWS ecosystem.
The use of GitHub Actions is interesting because, to use it, you only need a GitHub account without any premium subscription. But in a few words, what is Github Actions? It is a feature of GitHub that allows you to automate tasks in your development workflow directly in your GitHub repository. It enables you to set up CI/CD pipelines and automate actions such as running tests, building and deploying code, or handling project management tasks whenever specific events occur (such as pushes, pull requests, or new issues). GitHub Actions uses YAML configuration files (stored in .github/workflows) to define workflows, which specify what triggers the action, the jobs it runs, and the steps within each job. This can range from simple automation to complex workflows and is easily integrated with other services and APIs to create a custom workflow.
Using GitHub Actions for code compilation
Section titled “Using GitHub Actions for code compilation”To add a new GitHub action to test code compilation, follow these steps:
- Write your code
- Create a GitHub repository
- Write the GitHub action
- Commit and push your code to the repository
This action should be configured to trigger whenever new changes are pushed to the repository. The trigger depends on the specific action you want to implement, but a key first step is ensuring your code has no compilation errors. Even if your code is compiling correctly in your own workspace, this check is essential. A successful compilation locally doesn’t guarantee that others won’t have issues. For example, dependencies may be incorrectly linked, missing, or not present in their workspace. The purpose of this action is to confirm that anyone who downloads the repository and follows the provided compilation instructions can compile it without issues.
Let’s implement the steps listed above:
- Write your code: Let’s create a new ROS 2 package called
ros2_ci_cd. This package will contain a simple node publishing a string, just to have a basic ROS 2C++node:$ ros2 pkg create ros2_ci_cd --dependencies rclcpp std_msgs$ cd ros2_ci_cd/src && touch str_pub.cpp- Let’s delve into the content of the source. It is a very basic code. In this code, we start a timer in which a string is published:
#include "rclcpp/rclcpp.hpp"#include "std_msgs/msg/string.hpp"#include <chrono>using namespace std::chrono_literals;class StringPublisher : public rclcpp::Node {public:StringPublisher() : Node("cicd_test") {_str_pub = this->create_publisher<std_msgs::msg::String>("topic", 10);_timer = this->create_wall_timer(500ms, std::bind(&StringPublisher::publish_string, this));}private:void publish_string() {std_msgs::msg::String msg;msg.data = "CI/CD using ROS 2 and github actions";_str_pub->publish(msg);}rclcpp::Publisher<std_msgs::msg::String>::SharedPtr _str_pub;rclcpp::TimerBase::SharedPtr _timer;};int main(int argc, char *argv[]) {rclcpp::init(argc, argv);auto node = std::make_shared<StringPublisher>();rclcpp::spin(node); rclcpp::shutdown();return 0;}
- Then, modify the
CMakeLists.txtto compile the node. Add the following lines:
add_executable(string_publisher src/str_pub.cpp)ament_target_dependencies(string_publisher rclcpp std_msgs)install(TARGETS string_publisherDESTINATION lib/${PROJECT_NAME})install(TARGETSstring_publisherDESTINATION lib/${PROJECT_NAME}) - Then, modify the
- Let’s delve into the content of the source. It is a very basic code. In this code, we start a timer in which a string is published:
- Create a GitHub repository: To create a new repository, you should log in to the GitHub page using your account. Then, follow these steps:
- Start a new repository: On the GitHub home page, click the New button near your repository list, or go to. The creation page is shown in Figure 13.1 and guides you through the repository creation.

- Start a new repository: On the GitHub home page, click the New button near your repository list, or go to. The creation page is shown in Figure 13.1 and guides you through the repository creation.
Figure 13.1: GitHub page for repository creation
Figure 13.1: GitHub page for repository creation
- Name your repository: Enter a short, clear name for your project in the Repository name field. Optionally, you can add a description explaining the project’s purpose.
- Choose privacy settings:
- Public: Anyone can see this repository.
- Private: Only you (and collaborators you invite) can see it.
- Public: Anyone can see this repository.
- Create the repository: Click the Create repository button, and your repository will be ready.
- Add code: Once the repository is created, you’ll get instructions to add code from your computer or create files directly in GitHub.
- Write the GitHub action: After uploading the code to the repository, it will be shown on the GitHub page. On the same page, there is a menu in which you can handle the repository. In this menu, you can add new actions, as shown in Figure 13.2.

Figure 13.2: GitHub button to add actions
Figure 13.2: GitHub button to add actions
Using the Actions button on the GitHub page, you can create a new Actions file by clicking on the Skip this and set up a workflow yourself link. This will open an online editor.
Follow these steps to set up the workflow using the newly created action:
- At the start, we define a name for this action:
name: ros2-pipeline-test
- We need to define the trigger, which specifies when this action should be executed. For example, we might want the action to run whenever new code is pushed. Additionally, we can specify the branch this applies to—in this case, the action should run only when the master branch is updated:
on:push:branches: [ "master" ]
- In the jobs section, we specify the steps to perform. Note that these tests run in a virtual environment that exists only during the action’s execution, so we must include all the steps needed to compile the package as if it were on a completely new computer. First, we must select on which operating system this action must be executed. We will select Ubuntu 24.04, which is the one used for ROS 2 Jazzy:
jobs:build:runs-on: ubuntu-24.04
- The first step is to install ROS 2 and configure the workspace.
steps:- run: |# Set up sourcessudo apt update && sudo apt install -y curl gnupg lsb-releasesudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key | sudo apt-key add -sudo sh -c 'echo "deb [arch=$(dpkg --print-architecture)] http://packages.ros.org/ros2/ubuntu $(lsb_release -cs) main" > /etc/apt/sources.list.d/ros2-latest.list'- Install ROS 2 Jazzy packages:
sudo apt updatesudo apt install -y ros-jazzy-desktop- Source ROS 2 environment
sudo apt install python3-colcon-common-extensions- run: |echo "source /opt/ros/jazzy/setup.bash" >> ~/.bashrcsource ~/.bashrcmkdir -p ros2_ws/src/ros2_ci_cdcd ros2_wscolcon buildsource install/setup.bash - Now that ROS 2 is installed and the workspace configured, we can clone the repository:
- uses: actions/checkout@v3with:path: ros2_ws/src/ros2_ci_cd- run: |source /opt/ros/jazzy/setup.bashsudo apt install python3-rosdepsudo rosdep initrosdep update --include-eol-distroscd ros2_wsrosdep install --from-paths src -y --ignore-src
- Finally, we can compile the workspace:
colcon build
- We can now commit the change, using the top-right button, as shown in Figure 13.3.

Figure 13.3: GitHub button to commit the change
Figure 13.3: GitHub button to commit the change
- The action is now on the server. Since we are pushed to a new version of the repository (where the action is now present), the same action is triggered. We can monitor its state by clicking on the action and selecting the last commit performed, as shown at the top of Figure 13.4. After clicking on the desired commit, you can check the status of the action. We have requested to install ROS 2 and other libraries, which means that the action will require several minutes to be executed.

Figure 13.4: Actions related to the commits and their status
Figure 13.4: Actions related to the commits and their status
- By clicking on the current status (bottom of Figure 13.4), you can follow the currently executed line as included in the
main.ymlfile, as shown in Figure 13.5.
Figure 13.5: Monitoring the action execution
Figure 13.5: Monitoring the action execution
A common way to track the status of the actions is by adding to the repository page a status badge. Let’s explore how to do that next.
Adding a status badge
Section titled “Adding a status badge”With a status badge, you can easily check that your software integrates well with the rest of the system, without causing issues that might corrupt the installation or deployment. A status badge gives both you and the team a quick indicator of whether the system is functioning correctly by displaying whether actions have completed successfully or failed, preventing the pipeline from completing.
To add a status badge, generate Markdown text and place it in the repository’s README.md file. Markdown is a simple formatting language that converts plain text into formatted documents and is commonly used for documentation. The README.md file, typically found in the root of a GitHub repository, provides an overview of the project, instructions, and key details for users. By including a status badge in the README, you can quickly inform your team that your code is free from compilation or integration issues. This badge is a small image in README that shows the status of a GitHub action (e.g., passing or failing) and updates automatically to reflect the current build or test status. We can add the status badge directly generating the Markdown text from GitHub by clicking on the desired action and clicking the three dots on the top-right bar (see Figure 13.6). Here, you can click on the Create status badge button. This will open a new popup with Markdown text.

Figure 13.6: Button to create a status badge
Figure 13.6: Button to create a status badge
Create a file called README.md in the root of your ROS 2 package and put the code reported in the Create status badge panel. An example of this code is reported here:
[](https://github.com/jocacace/ros2_ci_cd/actions/workflows/main.yml)
This Markdown snippet adds a badge to your GitHub README that shows the status of a CI/CD workflow for a ROS 2 project. The badge links to the specific workflow file (.yml) in your repository, making it easy to check the build status directly from your project’s page.
After adding this text to the README file and uploading the repository, the actions will run again, and the badge will update to show the result. You can test this by intentionally creating a compilation error in your code—notice that the badge color changes from green to red, indicating a failure. An example of the two badge states is shown in Figure 13.7.

Figure 13.7: Button to create a status badge
Figure 13.7: Button to create a status badge
Adding the status badge is a good practice also in open-source projects to inform the developers your work can be quickly used without any issues.
Summary
Section titled “Summary”In this chapter, we explored tools for automatically evaluating the status of a ROS 2 package. First, we discussed automatic unit testing, which allows developers to define a set of test cases that continually verify the correct behavior of the code, even as new features are added. Unit testing can also verify the output of a ROS 2 node when it publishes to topics. ROS 2 is already integrated with the GTest framework, a testing library developed by Google. For more advanced testing strategies, developers can refer to the official GTest documentation, which covers topics such as writing test fixtures and using mocks to simulate dependencies.
Beyond unit testing, another essential approach is CI/CD, which helps ensure that code doesn’t introduce compilation or integration errors. We used GitHub Actions to easily create automatic checks that run when the code is updated. This provides a quick way to inform developers and the community about the repository’s status. Additionally, for more advanced CI/CD workflows—such as publishing Docker images—GitHub Secrets can be used to securely store credentials for services such as Docker Hub.
While using these methods isn’t mandatory—especially if you work primarily on your own code—they’re invaluable when collaborating with other developers who rely on your code’s stability and integration with other modules. Rapidly detecting issues allows you to address bugs or compilation problems promptly.
In the next chapter, we’ll discuss another important and emerging area in robotics and artificial intelligence: the use of Large Language Models (LLMs) for planning and executing robotic actions.