mrs_lib
Various reusable classes, functions and utilities for use in MRS projects
Loading...
Searching...
No Matches
ros_fixtures.hpp
1#ifndef MRS_LIB_TESTING_ROS_FIXTURES_HPP_
2#define MRS_LIB_TESTING_ROS_FIXTURES_HPP_
3
4
5#include <gtest/gtest.h>
6
7#include <memory>
8#include <utility>
9
10#include <rclcpp/executor.hpp>
11#include <rclcpp/executors/single_threaded_executor.hpp>
12#include <rclcpp/node_options.hpp>
13#include <rclcpp/utilities.hpp>
14
15
16namespace mrs_lib_testing
17{
18
19 class RosInitAndShutdownFixture : public ::testing::Test
20 {
21 public:
22 RosInitAndShutdownFixture()
23 {
24 rclcpp::init(0, nullptr);
25 }
26
27 ~RosInitAndShutdownFixture()
28 {
29 rclcpp::shutdown();
30 }
31
32 RosInitAndShutdownFixture(const RosInitAndShutdownFixture&) = delete;
33 RosInitAndShutdownFixture(RosInitAndShutdownFixture&&) = delete;
34 RosInitAndShutdownFixture& operator=(const RosInitAndShutdownFixture&) = delete;
35 RosInitAndShutdownFixture& operator=(RosInitAndShutdownFixture&&) = delete;
36 };
37
38 template <typename ExecutorT = rclcpp::executors::SingleThreadedExecutor>
39 class RosExecutorFixture : public RosInitAndShutdownFixture
40 {
41 public:
42 template <typename... ExecutorArgs>
43 RosExecutorFixture(ExecutorArgs&&... args)
44 : executor_(std::make_shared<ExecutorT>(std::forward<ExecutorArgs>(args)...)), spin_thread_([this]() { executor_->spin(); })
45 {
46 while (!executor_->is_spinning())
47 {
48 using namespace std::chrono_literals;
49 std::cout << "Waiting for executor to start...\n" << std::flush;
50 std::this_thread::sleep_for(1ms);
51 }
52 }
53
54 ~RosExecutorFixture()
55 {
56 executor_->cancel();
57
58 if (spin_thread_.joinable())
59 {
60 spin_thread_.join();
61 }
62 }
63
64 RosExecutorFixture(const RosExecutorFixture&) = delete;
65 RosExecutorFixture(RosExecutorFixture&&) = delete;
66 RosExecutorFixture& operator=(const RosExecutorFixture&) = delete;
67 RosExecutorFixture& operator=(RosExecutorFixture&&) = delete;
68
69 rclcpp::Executor& get_executor()
70 {
71 return *executor_;
72 }
73
74 private:
75 std::shared_ptr<rclcpp::Executor> executor_;
76
77 std::jthread spin_thread_;
78 };
79
80} // namespace mrs_lib_testing
81
82#endif // MRS_LIB_TESTING_ROS_FIXTURES_HPP_