what is sync and async mode in ros2
- User
what is sync and async mode in ros2
- Assistant
- User
How do you write a unittestcase using gmock for a function which has hardware calls for eg.ioctl calls
- Assistant
- User
- Assistant
what is sync and async mode in ros2
How do you write a unittestcase using gmock for a function which has hardware calls for eg.ioctl calls
In ROS 2 (Robot Operating System 2), synchronous (sync) and asynchronous (async) modes refer to how communication and execution are handled, particularly in the context of callbacks, services, and operations.
Synchronous mode involves operations that block the execution flow until they complete. This is useful when you need a sequence of operations to happen in a specific order, and each operation must wait for its predecessor to finish. In ROS 2, synchronous mode can be seen in the following contexts:
Services:
response = client.call(request)
Callbacks and Spinning:
rclpy.spin(node) function in Python or rclcpp::spin(node) in C++ will block and process callbacks until the node is shut down. This is considered a synchronous way of handling callbacks.Asynchronous mode involves operations that do not block the execution flow. Instead, they happen concurrently, allowing other operations to proceed without waiting. This is useful for handling tasks that may take an unpredictable amount of time or when you want to increase overall throughput by parallelizing work. In ROS 2, asynchronous mode can be seen in the following contexts:
Future and Callbacks:
future = client.call_async(request)
while not future.done():
rclpy.spin_once(node)
response = future.result()
Timers and Multi-threading:
timer = node.create_timer(1.0, timer_callback)
Executors:
MultiThreadedExecutor allows for concurrent execution of callbacks in multiple threads, making the system more responsive and capable of handling multiple tasks concurrently.executor = MultiThreadedExecutor()
executor.add_node(node)
executor.spin()
Choosing between sync and async modes depends on the specific requirements and constraints of your application.
Writing a unit test case using Google Mock (gMock) for a function that makes hardware calls, such as ioctl calls, involves creating a mock class to simulate the hardware interactions. This allows you to focus on testing the logic of your function without actually performing hardware operations.
Below is a step-by-step guide on how to achieve this:
First, define an abstract interface for the hardware operations, which includes the ioctl or any other hardware calls your function uses. This allows you to mock these interactions in your tests.
// hardware_interface.h
#ifndef HARDWARE_INTERFACE_H
#define HARDWARE_INTERFACE_H
class HardwareInterface {
public:
virtual ~HardwareInterface() = default;
virtual int ioctl(int fd, unsigned long request, void* argp) = 0;
};
#endif // HARDWARE_INTERFACE_H
Next, implement the real hardware interface.
// real_hardware_interface.cpp
#include "hardware_interface.h"
#include <sys/ioctl.h>
class RealHardwareInterface : public HardwareInterface {
public:
int ioctl(int fd, unsigned long request, void* argp) override {
return ::ioctl(fd, request, argp); // Call the actual ioctl system call
}
};
Refactor your function to use the HardwareInterface instead of directly calling ioctl.
// device_controller.h
#ifndef DEVICE_CONTROLLER_H
#define DEVICE_CONTROLLER_H
#include "hardware_interface.h"
class DeviceController {
public:
DeviceController(HardwareInterface* hw_interface);
bool performAction(int fd);
private:
HardwareInterface* hw_interface_;
};
#endif // DEVICE_CONTROLLER_H
// device_controller.cpp
#include "device_controller.h"
DeviceController::DeviceController(HardwareInterface* hw_interface)
: hw_interface_(hw_interface) {
}
bool DeviceController::performAction(int fd) {
unsigned long request = 1234; // replace with actual request code
void* argp = nullptr; // replace with actual argument if needed
int result = hw_interface_->ioctl(fd, request, argp);
return (result == 0);
}
Create a mock class using gMock.
// mock_hardware_interface.h
#ifndef MOCK_HARDWARE_INTERFACE_H
#define MOCK_HARDWARE_INTERFACE_H
#include <gmock/gmock.h>
#include "hardware_interface.h"
class MockHardwareInterface : public HardwareInterface {
public:
MOCK_METHOD(int, ioctl, (int fd, unsigned long request, void* argp), (override));
};
#endif // MOCK_HARDWARE_INTERFACE_H
Write a unit test using Google Test and Google Mock.
// device_controller_test.cpp
#include <gtest/gtest.h>
#include "mock_hardware_interface.h"
#include "device_controller.h"
using ::testing::_;
using ::testing::Return;
TEST(DeviceControllerTest, PerformActionSuccess) {
MockHardwareInterface mock_hw;
DeviceController controller(&mock_hw);
int fd = 1; // file descriptor
unsigned long request = 1234; // request code
void* argp = nullptr; // argument
EXPECT_CALL(mock_hw, ioctl(fd, request, argp))
.WillOnce(Return(0)); // Simulate successful ioctl call
bool result = controller.performAction(fd);
EXPECT_TRUE(result);
}
TEST(DeviceControllerTest, PerformActionFailure) {
MockHardwareInterface mock_hw;
DeviceController controller(&mock_hw);
int fd = 1; // file descriptor
unsigned long request = 1234; // request code
void* argp = nullptr; // argument
EXPECT_CALL(mock_hw, ioctl(fd, request, argp))
.WillOnce(Return(-1)); // Simulate failed ioctl call
bool result = controller.performAction(fd);
EXPECT_FALSE(result);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
To test a function with hardware calls using gMock:
This way, your unit tests can effectively isolate the hardware dependencies and focus on the logic of your code.
/***********************************************************************************************************************
DISCLAIMER
This software is supplied by Renesas Electronics Corporation and is only
intended for use with Renesas products. No other uses are authorized. This
software is owned by Renesas Electronics Corporation and is protected under
all applicable laws, including copyright laws.
THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING
THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT
LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.
TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS
ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE
FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR
ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
Renesas reserves the right, without notice, to make changes to this software
and to discontinue the availability of this software. By using this software,
you agree to the additional terms and conditions found by accessing the
following link:
Copyright (C) 2022-2023 Renesas Electronics Corporation. All rights reserved.
This code is added as part of Fast-DDS which is Licensed under Apache License, Version 2.0 / /
File Name : PCIeInterface.cpp
Version : 1.0
Description : PCIe Interface Source File
The function banners of the functions are present in the corresponding function declarations in File "PCIeInterface.h" / /
History : DD.MM.YYYY Version Description
: 30.04.2024 1.0 First Release
***********************************************************************************************************************/ #include <condition_variable> #include #include <errno.h> #include <fcntl.h> #include #include #include #include #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include #include <sys/ioctl.h> #include <sys/mman.h> #include <unistd.h> #include <rtps/transport/PCIeInterface.h> #include <fastdds/dds/log/Log.hpp>
//Device name is hard coded here, May be passed through xml configurations. static std::string device = "/dev/pci-endpoint-test.0";
PCIeInterface* PCIeInterface::instance = nullptr;
void PCIeInterface::startPCIeRx(void) { while (pcie_alive) { size_t size = read(pcie_dev, NULL, 0); std::lock_guardstd::mutex lock(rxMtx);
portList.clearReadStatus();
rx_data_size = 0;
uint32_t port = 0;
if (size > sizeof(port))
{
std::memcpy(&port, recv_buff, sizeof(port));
rx_data_size = size - PCIE_PORT_MSG_OFFSET;
portList.updateReadStatus(port);
}
dataOK.notify_all();
}
}
int PCIeInterface::InitPCIe( uint32_t send_size, uint32_t recv_size) { send_buff_size = send_size; recv_buff_size = recv_size;
struct pci_endpoint_test_xfer_param param;
int ret = -EINVAL;
logPcieInfo(PCIE_INTERFACE, "PCIeInterface init");
pcie_dev = open(device.c_str(), O_RDWR);
if (pcie_dev == -1)
{
logError(PCIE_INTERFACE, "Failed to open device file");
return ret;
}
txMtx = sem_open("/pcie_tx_mtx", O_CREAT, 0644, 1);
if(txMtx == SEM_FAILED){
logError(PCIE_INTERFACE, "Failed to create/open named mutex");
return -ENXIO;
}
param.size = send_buff_size;
param.flags = SEND_FLAG;
//Register send buffer in kernel space
ret = ioctl(pcie_dev, PCITEST_REGISTER_MEM, ¶m);
if (ret < 1)
{
logError(PCIE_INTERFACE_IOCTL, "send memory mapping failed");
return ret;
}
//mapping send buffer from kernal space to user space
send_buff = mmap(NULL, param.size, PROT_READ | PROT_WRITE, MAP_SHARED, pcie_dev, 0);
if (send_buff == MAP_FAILED)
{
logError(PCIE_INTERFACE_MMAP, "sendbuff mapping failed");
return -ENXIO;
}
logPcieInfo(PCIE_INTERFACE_MMAP, "sendbuff mapping success");
param.size = recv_buff_size;
param.flags = RECV_FLAG;
//Register receive buffer in kernel space
ret = ioctl(pcie_dev, PCITEST_REGISTER_MEM, ¶m);
if (ret < 1)
{
logError(PCIE_INTERFACE_IOCTL, "recv memory mapping failed");
return ret;
}
//mapping receive buffer from kernal space to user space
recv_buff = mmap(NULL, param.size, PROT_READ | PROT_WRITE, MAP_SHARED, pcie_dev, 0);
if (recv_buff == MAP_FAILED)
{
logError(PCIE_INTERFACE_MMAP, "recvbuff mapping failed");
return -ENXIO;
}
logPcieInfo(PCIE_INTERFACE_MMAP, "recvbuff mapping success");
pcie_alive = true;
std::thread listeningThread(&PCIeInterface::startPCIeRx, this);
listeningThread.detach();
return 0;
}
int PCIeInterface::DeinitPCIe(void) { struct pci_endpoint_test_xfer_param param; pcie_alive = false;
param.size = send_buff_size;
param.flags = SEND_FLAG;
ioctl(pcie_dev, PCITEST_UNREGISTER_MEM, ¶m);
param.size = recv_buff_size;
param.flags = RECV_FLAG;
ioctl(pcie_dev, PCITEST_UNREGISTER_MEM, ¶m);
sem_close(txMtx);
sem_unlink("/pcie_tx_mtx");
munmap(send_buff, send_buff_size);
munmap(recv_buff, recv_buff_size);
close(pcie_dev);
dataOK.notify_all();
return 0;
}
size_t PCIeInterface::PCIeSendBytes( unsigned char* DDSSendBuff, size_t size, uint32_t port) { int ret = -EINVAL; struct pci_endpoint_test_xfer_param param;
sem_wait(txMtx);
std::memcpy(send_buff, &port, sizeof(port));
std::memcpy((unsigned char*)send_buff + PCIE_PORT_MSG_OFFSET, DDSSendBuff, size);
size+=sizeof(port);
param.size = size;
#ifdef USE_PCIE_DMA param.flags = PCITEST_FLAGS_USE_DMA; #endif ret = ioctl(pcie_dev, PCITEST_WRITE, ¶m);
if (ret < 0)
{
logError(PCIE_INTERFACE_IOCTL, " IOCTL OPERATION FAILED");
return 0;
}
sem_post(txMtx);
return size;
}
size_t PCIeInterface::PCIeRecvBytes( unsigned char* DDSRecvBuff, size_t maxSize, uint32_t port) { (void)DDSRecvBuff; std::unique_lockstd::mutex lock(rxMtx); dataOK.wait(lock, [this, port]{return portList.isReadStatusTrue(port) || !pcie_alive; });
portList.clearReadStatus(port);
lock.unlock();
if (rx_data_size > maxSize)
{
return 0;
}
return rx_data_size;
}
Generate unittestcase for the above given code
Creating unit test cases for the provided code, particularly for classes and functions that interact with hardware through ioctl and other system calls, involves simulating those interactions. As demonstrated in the previous example, this can be achieved using mock objects with Google Mock (gMock).
Let's proceed by creating a unit test case for the PCIeInterface class using Google Test and Google Mock. This example will showcase how to mock the system calls and test the InitPCIe method.
We'll create a mock interface for the system calls that PCIeInterface uses.
// mock_system_calls.h
#ifndef MOCK_SYSTEM_CALLS_H
#define MOCK_SYSTEM_CALLS_H
#include <gmock/gmock.h>
#include <sys/ioctl.h>
#include <semaphore.h>
#include <sys/mman.h>
// Mock class for system calls
class MockSystemCalls {
public:
MOCK_METHOD(int, open, (const char*, int), ());
MOCK_METHOD(int, close, (int), ());
MOCK_METHOD(int, ioctl, (int, unsigned long, void*), ());
MOCK_METHOD(void*, mmap, (void*, size_t, int, int, int, off_t), ());
MOCK_METHOD(int, munmap, (void*, size_t), ());
MOCK_METHOD(sem_t*, sem_open, (const char*, int, mode_t, unsigned int), ());
MOCK_METHOD(int, sem_close, (sem_t*), ());
MOCK_METHOD(int, sem_unlink, (const char*), ());
MOCK_METHOD(int, sem_wait, (sem_t*), ());
MOCK_METHOD(int, sem_post, (sem_t*), ());
};
#endif // MOCK_SYSTEM_CALLS_H
We need to allow PCIeInterface to use the mock system calls. This can be achieved by dependency injection, where we inject the mock object into PCIeInterface.
// PCIeInterface.h (Updated)
#ifndef PCIEINTERFACE_H
#define PCIEINTERFACE_H
#include "mock_system_calls.h"
#include <semaphore.h>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
class PCIeInterface {
public:
// Constructor that accepts the mock system calls
PCIeInterface(MockSystemCalls* sysCalls);
int InitPCIe(uint32_t send_size, uint32_t recv_size);
int DeinitPCIe(void);
size_t PCIeSendBytes(unsigned char* DDSSendBuff, size_t size, uint32_t port);
size_t PCIeRecvBytes(unsigned char* DDSRecvBuff, size_t maxSize, uint32_t port);
static PCIeInterface* instance;
private:
void startPCIeRx(void);
MockSystemCalls* sysCalls_; // pointer to the mock system calls
// other private members...
int pcie_dev;
bool pcie_alive;
sem_t* txMtx;
void* send_buff;
void* recv_buff;
size_t send_buff_size;
size_t recv_buff_size;
std::mutex rxMtx;
std::condition_variable dataOK;
uint32_t rx_data_size;
// ... other private members
};
#endif // PCIEINTERFACE_H
Update the PCIeInterface methods to use the injected MockSystemCalls object instead of direct system calls.
// PCIeInterface.cpp (Updated)
#include "PCIeInterface.h"
#include <cstring>
#include <errno.h>
#include <fastdds/dds/log/Log.hpp>
//Device name is hard coded here, May be passed through xml configurations.
static std::string device = "/dev/pci-endpoint-test.0";
PCIeInterface* PCIeInterface::instance = nullptr;
PCIeInterface::PCIeInterface(MockSystemCalls* sysCalls) : sysCalls_(sysCalls), pcie_alive(false), pcie_dev(-1), txMtx(nullptr), send_buff(nullptr), recv_buff(nullptr), send_buff_size(0), recv_buff_size(0) {}
void PCIeInterface::startPCIeRx(void) {
// implementation as before...
}
int PCIeInterface::InitPCIe(uint32_t send_size, uint32_t recv_size) {
// Use the mock calls
struct pci_endpoint_test_xfer_param param;
int ret = -EINVAL;
logPcieInfo(PCIE_INTERFACE, "PCIeInterface init");
// Open the device using the mock call
pcie_dev = sysCalls_->open(device.c_str(), O_RDWR);
if (pcie_dev == -1) {
logError(PCIE_INTERFACE, "Failed to open device file");
return ret;
}
// Create/open the semaphore using the mock call
txMtx = sysCalls_->sem_open("/pcie_tx_mtx", O_CREAT, 0644, 1);
if (txMtx == SEM_FAILED) {
logError(PCIE_INTERFACE, "Failed to create/open named mutex");
return -ENXIO;
}
// Other initialization code...
return 0;
}
int PCIeInterface::DeinitPCIe(void) {
// implementation as before...
}
size_t PCIeInterface::PCIeSendBytes(unsigned char* DDSSendBuff, size_t size, uint32_t port) {
// implementation as before...
}
size_t PCIeInterface::PCIeRecvBytes(unsigned char* DDSRecvBuff, size_t maxSize, uint32_t port) {
// implementation as before...
}
Now let’s write the unit test using Google Test and Google Mock.
// PCIeInterface_test.cpp
#include <gtest/gtest.h>
#include "PCIeInterface.h"
#include "mock_system_calls.h"
using ::testing::_;
using ::testing::Return;
class PCIeInterfaceTest : public testing::Test {
protected:
MockSystemCalls mockSysCalls;
PCIeInterface* pcieInterface;
void SetUp() override {
pcieInterface = new PCIeInterface(&mockSysCalls);
}
void TearDown() override {
delete pcieInterface;
}
};
TEST_F(PCIeInterfaceTest, InitPCIESuccess) {
EXPECT_CALL(mockSysCalls, open(_, _)).WillOnce(Return(3));
EXPECT_CALL(mockSysCalls, sem_open(_, _, _, _)).WillOnce(Return(reinterpret_cast<sem_t*>(1)));
EXPECT_CALL(mockSysCalls, ioctl(_, _, _)).WillOnce(Return(0)).WillOnce(Return(0));
EXPECT_CALL(mockSysCalls, mmap(_, _, _, _, _, _)).WillOnce(Return(reinterpret_cast<void*>(1))).WillOnce(Return(reinterpret_cast<void*>(2)));
EXPECT_CALL(mockSysCalls, munmap(_, _)).Times(0);
EXPECT_CALL(mockSysCalls, close(_)).Times(0);
EXPECT_CALL(mockSysCalls, sem_close(_)).Times(0);
EXPECT_CALL(mockSysCalls, sem_unlink(_)).Times(0);
int ret = pcieInterface->InitPCIe(1024, 2048);
EXPECT_EQ(ret, 0);
}
TEST_F(PCIeInterfaceTest, InitPCIeFailureOpen) {
EXPECT_CALL(mockSysCalls, open(_, _)).WillOnce(Return(-1));
int ret = pcieInterface->InitPCIe(1024, 2048);
EXPECT_EQ(ret, -EINVAL);
}
// Add more tests for different scenarios...
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
PCIeInterface to use the mock system calls.InitPCIe use injected mock objects.This setup allows you to effectively unit test the PCIeInterface class without performing actual hardware interactions.
Not yet included in a published release.