I am running the tests for my ROS C++ node using rostest/gtest.
Currently I have a problem where I have a class method that I need/want to test that out of date data based on the value of ros::Time::now();
. Since the data that I am using for this test has a predefined date I need/want to mock the value returned by ros::Time::now();
. I have seen that I should be able to achieve this by setting /use_sim_time
to true
for example in the launch file and then publishing in the /clock
topic.
However when doing this the test execution does not return and simply times out, even when nothing is really being tested. The test execution runs fine without this.
I am executing my tests with catkin run_tests
.
In this scenario:
- Setting
<param name="/use_sim_time" value="true"/>
in the launch file. - On the
main
of my unittests node, I am publishing a message to/clock
withmsg.clock = ros::Time(1678456559, 0);
.
Then I get the following executing the test.
[ WARN] [1709049828.959657287]: Main ros::Time::now() = 0.000000
[ WARN] [1709049828.960573171, 1678456559.000000000]: Test class Constructor ros::Time::now() = 1678456559.000000
[ WARN] [1709049828.960620129, 1678456559.000000000]: Test class SetUp ros::Time::now() = 1678456559.000000
It's weird that the first log has ros::Time::now() has a value of 0.0
even though it is after the message has been published.
ros::NodeHandle nh;
rosgraph_msgs::Clock msg;
msg.clock = ros::Time(1678456559, 0);
ros::Publisher clock_pub = nh.advertise<rosgraph_msgs::Clock>("/clock", 1);
clock_pub.publish(msg);
ros::spinOnce();
ROS_WARN("Main ros::Time::now() = %f", ros::Time::now().toSec());
Then it's also weird that there are two timestamps in the log messages from then on. The values are correct however, but the code hangs when I create the unique_ptr
to my class.
test_pr = std::make_unique<MyClassTest>();
What am I doing wrong/missing?
Thank you all in advance
Edit: After a bit more debugging it seems that what I did initially was correct. However I found that one the classes that I'm testing, initializes an object that has a small sleep in the constructor. Since with use_sim_time
the time is "stopped" this sleep would never complete and it would time out.
I added a new thread that published to the clock topic to overcome this and it seems to work. Now I can set the initial time and make sure it doesn't stop.