InterfacesTest.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <AzCore/Component/ComponentApplication.h>
  9. #include <AzCore/Component/ComponentApplicationBus.h>
  10. #include <AzCore/Component/Entity.h>
  11. #include <AzCore/Component/EntityId.h>
  12. #include <AzCore/RTTI/RTTIMacros.h>
  13. #include <AzCore/Serialization/SerializeContext.h>
  14. #include <AzCore/Slice/SliceAssetHandler.h>
  15. #include <AzCore/UserSettings/UserSettingsComponent.h>
  16. #include <AzCore/std/containers/array.h>
  17. #include <AzCore/std/string/string_view.h>
  18. #include <AzQtComponents/Utilities/QtPluginPaths.h>
  19. #include <AzTest/GemTestEnvironment.h>
  20. #include <AzToolsFramework/Entity/EditorEntityContextComponent.h>
  21. #include <AzToolsFramework/ToolsComponents/TransformComponent.h>
  22. #include <AzToolsFramework/UnitTest/ToolsTestApplication.h>
  23. #include <Clients/ROS2SimulationInterfacesSystemComponent.h>
  24. #include <ROS2/ROS2Bus.h>
  25. #include <Services/DeleteEntityServiceHandler.h>
  26. #include <Services/GetEntitiesServiceHandler.h>
  27. #include <Services/GetEntitiesStatesServiceHandler.h>
  28. #include <Services/GetEntityStateServiceHandler.h>
  29. #include <Services/GetSimulationFeaturesServiceHandler.h>
  30. #include <Services/GetSimulationStateServiceHandler.h>
  31. #include <Services/GetSpawnablesServiceHandler.h>
  32. #include <Services/ROS2ServiceBase.h>
  33. #include <Services/ResetSimulationServiceHandler.h>
  34. #include <Services/SetEntityStateServiceHandler.h>
  35. #include <Services/SetSimulationStateServiceHandler.h>
  36. #include <Services/SpawnEntityServiceHandler.h>
  37. #include <Services/StepSimulationServiceHandler.h>
  38. #include "Mocks/SimulationEntityManagerMock.h"
  39. #include "Mocks/SimulationFeaturesAggregatorRequestsHandlerMock.h"
  40. #include "Mocks/SimulationManagerMock.h"
  41. #include <QApplication>
  42. #include <rclcpp/publisher.hpp>
  43. #include <rclcpp/rclcpp.hpp>
  44. #include <rclcpp_action/create_client.hpp>
  45. #include <simulation_interfaces/action/simulate_steps.hpp>
  46. #include <simulation_interfaces/msg/simulator_features.hpp>
  47. #include <std_msgs/msg/string.hpp>
  48. #include <gtest/gtest.h>
  49. #include <memory>
  50. #include <string>
  51. #include <string_view>
  52. #include <vector>
  53. namespace UnitTest
  54. {
  55. class SimulationInterfaceROS2TestEnvironment : public AZ::Test::GemTestEnvironment
  56. {
  57. // AZ::Test::GemTestEnvironment overrides ...
  58. void AddGemsAndComponents() override;
  59. AZ::ComponentApplication* CreateApplicationInstance() override;
  60. void PostSystemEntityActivate() override;
  61. public:
  62. SimulationInterfaceROS2TestEnvironment() = default;
  63. ~SimulationInterfaceROS2TestEnvironment() override = default;
  64. };
  65. void SimulationInterfaceROS2TestEnvironment::AddGemsAndComponents()
  66. {
  67. using namespace ROS2SimulationInterfaces;
  68. AddActiveGems(AZStd::to_array<AZStd::string_view>({ "ROS2" }));
  69. AddDynamicModulePaths({ "ROS2" });
  70. AddComponentDescriptors(AZStd::initializer_list<AZ::ComponentDescriptor*>{
  71. ROS2SimulationInterfacesSystemComponent::CreateDescriptor(),
  72. });
  73. AddRequiredComponents(AZStd::to_array<AZ::TypeId const>({ ROS2SimulationInterfacesSystemComponent::TYPEINFO_Uuid() }));
  74. }
  75. AZ::ComponentApplication* SimulationInterfaceROS2TestEnvironment::CreateApplicationInstance()
  76. {
  77. // Using ToolsTestApplication to have AzFramework and AzToolsFramework components.
  78. return aznew UnitTest::ToolsTestApplication("SimulationInterfaceROS2TestEnvironment");
  79. }
  80. void SimulationInterfaceROS2TestEnvironment::PostSystemEntityActivate()
  81. {
  82. AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize);
  83. }
  84. class SimulationInterfaceROS2TestFixture : public ::testing::Test
  85. {
  86. protected:
  87. std::shared_ptr<rclcpp::Node> GetRos2Node()
  88. {
  89. auto interface = ROS2::ROS2Interface::Get();
  90. AZ_Assert(interface, "ROS2 interface is not available.");
  91. auto node = interface->GetNode();
  92. AZ_Assert(node, "Node is not available.");
  93. return node;
  94. }
  95. void SpinAppSome(int numberOfTicks = 50)
  96. {
  97. AZ::ComponentApplication* app = nullptr;
  98. AZ::ComponentApplicationBus::BroadcastResult(app, &AZ::ComponentApplicationBus::Events::GetApplication);
  99. AZ_Assert(app, "Application pointer is not available.");
  100. for (int i = 0; i < numberOfTicks; ++i)
  101. {
  102. app->Tick();
  103. }
  104. }
  105. template <typename Future>void SpinAppUntilFuture(Future &future)
  106. {
  107. AZ::ComponentApplication* app = nullptr;
  108. AZ::ComponentApplicationBus::BroadcastResult(app, &AZ::ComponentApplicationBus::Events::GetApplication);
  109. AZ_Assert(app, "Application pointer is not available.");
  110. constexpr int MaximumTicks = 1000;
  111. for (int i = 0; i < MaximumTicks; ++i)
  112. {
  113. app->Tick();
  114. if (future.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
  115. {
  116. return;
  117. }
  118. }
  119. }
  120. };
  121. //! Perform a smoke test to check if the ROS2 node is available from ROS2 gem
  122. TEST_F(SimulationInterfaceROS2TestFixture, TestIfROS2NodeIsAvailable)
  123. {
  124. ASSERT_NE(GetRos2Node(), nullptr) << "ROS2 node is not available.";
  125. }
  126. //! Perform a smoke test to check if the ROS2 domain is working
  127. TEST_F(SimulationInterfaceROS2TestFixture, SmokeTestROS2Domain)
  128. {
  129. auto node = GetRos2Node();
  130. auto pub = node->create_publisher<std_msgs::msg::String>("hello", 20);
  131. int receivedMsgs = 0;
  132. auto sub = node->create_subscription<std_msgs::msg::String>(
  133. "hello",
  134. 10,
  135. [&receivedMsgs](const std_msgs::msg::String& msg)
  136. {
  137. receivedMsgs++;
  138. });
  139. std_msgs::msg::String msg;
  140. msg.data = "Hello World!";
  141. for (int i = 0; i < 10; ++i)
  142. {
  143. pub->publish(msg);
  144. }
  145. SpinAppSome();
  146. EXPECT_EQ(receivedMsgs, 10) << "Did not receive all messages.";
  147. }
  148. //! Check if expected services are available and has the default name
  149. TEST_F(SimulationInterfaceROS2TestFixture, TestIfServicesAvailableInROS2Domain)
  150. {
  151. auto node = GetRos2Node();
  152. auto services = node->get_service_names_and_types();
  153. ASSERT_FALSE(services.empty()) << "No services available.";
  154. EXPECT_NE(services.find("/delete_entity"), services.end());
  155. EXPECT_NE(services.find("/get_entities"), services.end());
  156. EXPECT_NE(services.find("/get_entities_states"), services.end());
  157. EXPECT_NE(services.find("/get_entity_state"), services.end());
  158. EXPECT_NE(services.find("/get_spawnables"), services.end());
  159. EXPECT_NE(services.find("/set_entity_state"), services.end());
  160. EXPECT_NE(services.find("/spawn_entity"), services.end());
  161. EXPECT_NE(services.find("/get_simulation_features"), services.end());
  162. EXPECT_NE(services.find("/step_simulation"), services.end());
  163. }
  164. //! Test if the service call succeeds when the entity is found
  165. TEST_F(SimulationInterfaceROS2TestFixture, TestDeleteEntity_01)
  166. {
  167. using ::testing::_;
  168. auto node = GetRos2Node();
  169. auto mock = std::make_shared<SimulationEntityManagerMockedHandler>();
  170. auto client = node->create_client<simulation_interfaces::srv::DeleteEntity>("/delete_entity");
  171. auto request = std::make_shared<simulation_interfaces::srv::DeleteEntity::Request>();
  172. const char TestEntityName[] = "test_entity";
  173. request->entity = std::string(TestEntityName);
  174. const AZStd::string entityName = AZStd::string(TestEntityName);
  175. EXPECT_CALL(*mock, DeleteEntity(entityName, _))
  176. .WillOnce(::testing::Invoke(
  177. [](const AZStd::string& name, SimulationInterfaces::DeletionCompletedCb completedCb)
  178. {
  179. EXPECT_EQ(name, "test_entity");
  180. completedCb(AZ::Success());
  181. }));
  182. auto future = client->async_send_request(request);
  183. SpinAppUntilFuture(future);
  184. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  185. auto response = future.get();
  186. EXPECT_EQ(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  187. }
  188. //! Test if the service call fails when the entity is not found
  189. TEST_F(SimulationInterfaceROS2TestFixture, TestDeleteEntity_02)
  190. {
  191. using ::testing::_;
  192. auto node = GetRos2Node();
  193. SimulationEntityManagerMockedHandler mock;
  194. auto client = node->create_client<simulation_interfaces::srv::DeleteEntity>("/delete_entity");
  195. auto request = std::make_shared<simulation_interfaces::srv::DeleteEntity::Request>();
  196. const char TestEntityName[] = "test_entity";
  197. request->entity = std::string(TestEntityName);
  198. const AZStd::string entityName = AZStd::string(TestEntityName);
  199. EXPECT_CALL(mock, DeleteEntity(entityName, _))
  200. .WillOnce(::testing::Invoke(
  201. [](const AZStd::string& name, SimulationInterfaces::DeletionCompletedCb completedCb)
  202. {
  203. EXPECT_EQ(name, "test_entity");
  204. FailedResult failedResult;
  205. failedResult.m_errorCode = simulation_interfaces::msg::Result::RESULT_NOT_FOUND,
  206. failedResult.m_errorString = "FooBar not found.";
  207. completedCb(AZ::Failure(failedResult));
  208. }));
  209. auto future = client->async_send_request(request);
  210. SpinAppUntilFuture(future);
  211. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  212. auto response = future.get();
  213. EXPECT_EQ(response->result.result, simulation_interfaces::msg::Result::RESULT_NOT_FOUND);
  214. }
  215. //! Happy path test for GetEntities with a sphere shape
  216. //! Test if the service is called with a sphere shape and Posix filter is passed through
  217. TEST_F(SimulationInterfaceROS2TestFixture, GetEntitiesWithShapeSphereAndFilterValid)
  218. {
  219. using ::testing::_;
  220. auto node = GetRos2Node();
  221. SimulationEntityManagerMockedHandler mock;
  222. auto client = node->create_client<simulation_interfaces::srv::GetEntities>("/get_entities");
  223. auto request = std::make_shared<simulation_interfaces::srv::GetEntities::Request>();
  224. request->filters.bounds.points.resize(2);
  225. const AZ::Vector3 point1(1.0f, 2.0f, 3.0f);
  226. request->filters.bounds.points[0].x = point1.GetX();
  227. request->filters.bounds.points[0].y = point1.GetY();
  228. request->filters.bounds.points[0].z = point1.GetZ();
  229. request->filters.bounds.points[1].x = 99.0f;
  230. request->filters.bounds.type = simulation_interfaces::msg::Bounds::TYPE_SPHERE;
  231. request->filters.filter = "FooBarFilter";
  232. EXPECT_CALL(mock, GetEntities(_))
  233. .WillOnce(::testing::Invoke(
  234. [=](const EntityFilters& filter)
  235. {
  236. EXPECT_NE(filter.m_boundsShape, nullptr);
  237. if (filter.m_boundsShape)
  238. {
  239. EXPECT_EQ(filter.m_boundsShape->GetShapeType(), Physics::ShapeType::Sphere);
  240. Physics::SphereShapeConfiguration* sphereShape =
  241. azdynamic_cast<Physics::SphereShapeConfiguration*>(filter.m_boundsShape.get());
  242. EXPECT_EQ(sphereShape->m_radius, 99.0f);
  243. EXPECT_EQ(sphereShape->m_scale, AZ::Vector3(1.0f));
  244. }
  245. auto loc = filter.m_boundsPose.GetTranslation();
  246. EXPECT_EQ(loc.GetX(), point1.GetX());
  247. EXPECT_EQ(loc.GetY(), point1.GetY());
  248. EXPECT_EQ(loc.GetZ(), point1.GetZ());
  249. EXPECT_EQ(filter.m_nameFilter, "FooBarFilter");
  250. return AZ::Success(EntityNameList{ "FooBar" });
  251. }));
  252. auto future = client->async_send_request(request);
  253. SpinAppUntilFuture(future);
  254. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  255. auto response = future.get();
  256. EXPECT_EQ(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  257. }
  258. //! Try to call the service with invalid data (too few points) for the sphere shape
  259. TEST_F(SimulationInterfaceROS2TestFixture, GetEntitiesWithShapeSphereWithInvalidData)
  260. {
  261. using ::testing::_;
  262. auto node = GetRos2Node();
  263. [[maybe_unused]] testing::StrictMock<SimulationEntityManagerMockedHandler> mock;
  264. auto client = node->create_client<simulation_interfaces::srv::GetEntities>("/get_entities");
  265. auto request = std::make_shared<simulation_interfaces::srv::GetEntities::Request>();
  266. request->filters.bounds.points.resize(1); // too few points
  267. request->filters.bounds.type = simulation_interfaces::msg::Bounds::TYPE_SPHERE;
  268. auto future = client->async_send_request(request);
  269. SpinAppUntilFuture(future);
  270. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  271. auto response = future.get();
  272. EXPECT_NE(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  273. }
  274. //! Happy path test for GetEntities with a box shape
  275. TEST_F(SimulationInterfaceROS2TestFixture, GetEntitiesWithShapeBox)
  276. {
  277. using ::testing::_;
  278. auto node = GetRos2Node();
  279. testing::NiceMock<SimulationEntityManagerMockedHandler> mock;
  280. auto client = node->create_client<simulation_interfaces::srv::GetEntities>("/get_entities");
  281. auto request = std::make_shared<simulation_interfaces::srv::GetEntities::Request>();
  282. request->filters.bounds.points.resize(2);
  283. const AZ::Vector3 point1(1.0f, 2.0f, 3.0f);
  284. const AZ::Vector3 dims(4.0f, 5.0f, 6.0f);
  285. const AZ::Vector3 point2 = point1 + dims;
  286. request->filters.bounds.points[0].x = point1.GetX();
  287. request->filters.bounds.points[0].y = point1.GetY();
  288. request->filters.bounds.points[0].z = point1.GetZ();
  289. request->filters.bounds.points[1].x = point2.GetX();
  290. request->filters.bounds.points[1].y = point2.GetY();
  291. request->filters.bounds.points[1].z = point2.GetZ();
  292. request->filters.bounds.type = simulation_interfaces::msg::Bounds::TYPE_BOX;
  293. EXPECT_CALL(mock, GetEntities(_))
  294. .WillOnce(::testing::Invoke(
  295. [=](const EntityFilters& filter)
  296. {
  297. EXPECT_NE(filter.m_boundsShape, nullptr);
  298. if (filter.m_boundsShape)
  299. {
  300. EXPECT_EQ(filter.m_boundsShape->GetShapeType(), Physics::ShapeType::Box);
  301. Physics::BoxShapeConfiguration* boxShape =
  302. azdynamic_cast<Physics::BoxShapeConfiguration*>(filter.m_boundsShape.get());
  303. EXPECT_EQ(boxShape->m_dimensions.GetX(), dims.GetX());
  304. EXPECT_EQ(boxShape->m_dimensions.GetY(), dims.GetY());
  305. EXPECT_EQ(boxShape->m_dimensions.GetZ(), dims.GetZ());
  306. }
  307. auto loc = filter.m_boundsPose.GetTranslation();
  308. EXPECT_EQ(loc, AZ::Vector3::CreateZero());
  309. return AZ::Success(EntityNameList{ "FooBar" });
  310. }));
  311. auto future = client->async_send_request(request);
  312. SpinAppUntilFuture(future);
  313. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  314. auto response = future.get();
  315. EXPECT_EQ(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  316. }
  317. //! Try to call the service with invalid data (first point is greater than second point in box)
  318. TEST_F(SimulationInterfaceROS2TestFixture, GetEntitiesWithShapeBoxInvalid)
  319. {
  320. using ::testing::_;
  321. auto node = GetRos2Node();
  322. // strict mock, since we don't want to call the real implementation in this test
  323. [[maybe_unused]] testing::StrictMock<SimulationEntityManagerMockedHandler> mock;
  324. auto client = node->create_client<simulation_interfaces::srv::GetEntities>("/get_entities");
  325. auto request = std::make_shared<simulation_interfaces::srv::GetEntities::Request>();
  326. request->filters.bounds.points.resize(2);
  327. request->filters.bounds.points[0].x = 2.0f;
  328. request->filters.bounds.points[0].y = 3.0f;
  329. request->filters.bounds.points[0].z = 4.0f;
  330. request->filters.bounds.points[1].x = -2.0f;
  331. request->filters.bounds.points[1].y = -3.0f;
  332. request->filters.bounds.points[1].z = 5.0f;
  333. request->filters.bounds.type = simulation_interfaces::msg::Bounds::TYPE_BOX;
  334. auto future = client->async_send_request(request);
  335. SpinAppUntilFuture(future);
  336. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  337. auto response = future.get();
  338. EXPECT_NE(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  339. }
  340. //! check if capabilities vector is empty when no features are provided by SimulationInterfaces gem
  341. TEST_F(SimulationInterfaceROS2TestFixture, GetSimulationFeaturesNoFeaturesProvidedByGem)
  342. {
  343. using ::testing::_;
  344. auto node = GetRos2Node();
  345. auto client = node->create_client<simulation_interfaces::srv::GetSimulatorFeatures>("/get_simulation_features");
  346. auto request = std::make_shared<simulation_interfaces::srv::GetSimulatorFeatures::Request>();
  347. auto future = client->async_send_request(request);
  348. SpinAppUntilFuture(future);
  349. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  350. auto response = future.get();
  351. EXPECT_TRUE(response->features.features.empty()) << "Features vector is not empty.";
  352. }
  353. //! check if features are returned when the feature is provided by SimulationFeaturesAggregator
  354. //! and the feature is not in the list of features provided by the gem
  355. TEST_F(SimulationInterfaceROS2TestFixture, GetSimulationFeaturesSomeFeaturesProvided)
  356. {
  357. SimulationFeaturesAggregatorRequestsMockedHandler mockAggregator;
  358. using ::testing::_;
  359. auto node = GetRos2Node();
  360. AZStd::unordered_set<SimulationFeatureType> features{
  361. simulation_interfaces::msg::SimulatorFeatures::SPAWNING,
  362. static_cast<SimulationFeatureType>(0xFE), // invalid feature, should be ignored
  363. static_cast<SimulationFeatureType>(0xFF), // invalid feature, should be ignored
  364. };
  365. EXPECT_CALL(mockAggregator, GetSimulationFeatures())
  366. .WillOnce(::testing::Invoke(
  367. [&](void)
  368. {
  369. return features;
  370. }));
  371. auto client = node->create_client<simulation_interfaces::srv::GetSimulatorFeatures>("/get_simulation_features");
  372. auto request = std::make_shared<simulation_interfaces::srv::GetSimulatorFeatures::Request>();
  373. auto future = client->async_send_request(request);
  374. SpinAppUntilFuture(future);
  375. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  376. auto response = future.get();
  377. ASSERT_FALSE(response->features.features.empty()) << "Features vector is empty.";
  378. EXPECT_EQ(response->features.features.size(), 1) << "Features vector should contain one feature only.";
  379. EXPECT_EQ(response->features.features[0], simulation_interfaces::msg::SimulatorFeatures::SPAWNING) << "Feature is not SPAWNING.";
  380. }
  381. //! Check if service succeeds when the name is valid
  382. TEST_F(SimulationInterfaceROS2TestFixture, TryToSpawnWithValidName)
  383. {
  384. using ::testing::_;
  385. SimulationEntityManagerMockedHandler mock;
  386. auto node = GetRos2Node();
  387. auto client = node->create_client<simulation_interfaces::srv::SpawnEntity>("/spawn_entity");
  388. auto request = std::make_shared<simulation_interfaces::srv::SpawnEntity::Request>();
  389. request->name = "valid_name";
  390. request->uri = "test_uri";
  391. request->entity_namespace = "test_namespace";
  392. request->allow_renaming = true;
  393. auto future = client->async_send_request(request);
  394. EXPECT_CALL(mock, SpawnEntity(_, _, _, _, _, _))
  395. .WillOnce(::testing::Invoke(
  396. [](const AZStd::string& name,
  397. const AZStd::string& uri,
  398. const AZStd::string& entityNamespace,
  399. const AZ::Transform& initialPose,
  400. const bool allowRename,
  401. SpawnCompletedCb completedCb)
  402. {
  403. EXPECT_EQ(name, "valid_name");
  404. EXPECT_EQ(uri, "test_uri");
  405. EXPECT_EQ(entityNamespace, "test_namespace");
  406. EXPECT_TRUE(allowRename);
  407. completedCb(AZ::Success("valid_name"));
  408. }));
  409. SpinAppUntilFuture(future);
  410. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  411. auto response = future.get();
  412. EXPECT_EQ(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  413. }
  414. //! Check if service fails when the name is invalid
  415. TEST_F(SimulationInterfaceROS2TestFixture, TryToSpawnWithInvalidName)
  416. {
  417. // strict mock, since we don't want to call the real implementation in this test
  418. [[maybe_unused]] testing::StrictMock<SimulationEntityManagerMockedHandler> mock;
  419. auto node = GetRos2Node();
  420. auto client = node->create_client<simulation_interfaces::srv::SpawnEntity>("/spawn_entity");
  421. auto request = std::make_shared<simulation_interfaces::srv::SpawnEntity::Request>();
  422. request->name = "invalid name"; // invalid name
  423. request->uri = "test_uri";
  424. request->entity_namespace = "test_namespace";
  425. auto future = client->async_send_request(request);
  426. SpinAppUntilFuture(future);
  427. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  428. auto response = future.get();
  429. EXPECT_EQ(response->result.result, simulation_interfaces::srv::SpawnEntity::Response::NAME_INVALID)
  430. << "Service call should fail with invalid name.";
  431. }
  432. //! Check if service fails when the namespace is invalid
  433. TEST_F(SimulationInterfaceROS2TestFixture, TryToSpawnWithInvalidNamespace)
  434. {
  435. // strict mock, since we don't want to call the real implementation in this test
  436. [[maybe_unused]] testing::StrictMock<SimulationEntityManagerMockedHandler> mock;
  437. auto node = GetRos2Node();
  438. auto client = node->create_client<simulation_interfaces::srv::SpawnEntity>("/spawn_entity");
  439. auto request = std::make_shared<simulation_interfaces::srv::SpawnEntity::Request>();
  440. request->name = "valid_name";
  441. request->uri = "test_uri";
  442. request->entity_namespace = "invalid namespace";
  443. auto future = client->async_send_request(request);
  444. SpinAppUntilFuture(future);
  445. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  446. auto response = future.get();
  447. EXPECT_EQ(response->result.result, simulation_interfaces::srv::SpawnEntity::Response::NAMESPACE_INVALID)
  448. << "Service call should fail with invalid name.";
  449. }
  450. TEST_F(SimulationInterfaceROS2TestFixture, SimulationStepsSuccess)
  451. {
  452. using ::testing::_;
  453. auto node = GetRos2Node();
  454. SimulationManagerMockedHandler mock;
  455. auto client = rclcpp_action::create_client<simulation_interfaces::action::SimulateSteps>(node, "/simulate_steps");
  456. auto goal = std::make_shared<simulation_interfaces::action::SimulateSteps::Goal>();
  457. constexpr AZ::u64 steps = 10;
  458. goal->steps = steps;
  459. ASSERT_TRUE(client->wait_for_action_server(std::chrono::seconds(0)) == true) << "Action server is unavailable";
  460. EXPECT_CALL(mock, IsSimulationPaused())
  461. .WillOnce(::testing::Invoke(
  462. []()
  463. {
  464. return true;
  465. }));
  466. EXPECT_CALL(mock, StepSimulation(steps));
  467. EXPECT_CALL(mock, IsSimulationStepsActive())
  468. .WillOnce(::testing::Invoke(
  469. []()
  470. {
  471. return false;
  472. }));
  473. auto future = client->async_send_goal(*goal);
  474. SpinAppUntilFuture(future);
  475. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  476. auto goalHandle = future.get();
  477. ASSERT_NE(goalHandle, nullptr);
  478. auto result = client->async_get_result(goalHandle);
  479. SpinAppUntilFuture(result);
  480. ASSERT_TRUE(result.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  481. EXPECT_EQ(result.get().result->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  482. }
  483. TEST_F(SimulationInterfaceROS2TestFixture, SimulationStepsFailureSimulationIsNotPaused)
  484. {
  485. using ::testing::_;
  486. auto node = GetRos2Node();
  487. SimulationManagerMockedHandler mock;
  488. auto client = rclcpp_action::create_client<simulation_interfaces::action::SimulateSteps>(node, "/simulate_steps");
  489. auto goal = std::make_shared<simulation_interfaces::action::SimulateSteps::Goal>();
  490. goal->steps = 10;
  491. ASSERT_TRUE(client->wait_for_action_server(std::chrono::seconds(0)) == true) << "Action server is unavailable";
  492. EXPECT_CALL(mock, IsSimulationPaused())
  493. .WillOnce(::testing::Invoke(
  494. []()
  495. {
  496. return false;
  497. }));
  498. auto future = client->async_send_goal(*goal);
  499. SpinAppUntilFuture(future);
  500. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  501. auto goalHandle = future.get();
  502. ASSERT_NE(goalHandle, nullptr);
  503. auto result = client->async_get_result(goalHandle);
  504. SpinAppUntilFuture(result);
  505. ASSERT_TRUE(result.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  506. EXPECT_EQ(result.get().result->result.result, simulation_interfaces::msg::Result::RESULT_OPERATION_FAILED);
  507. }
  508. TEST_F(SimulationInterfaceROS2TestFixture, SimulationStepsCancelled)
  509. {
  510. using ::testing::_;
  511. auto node = GetRos2Node();
  512. SimulationManagerMockedHandler mock;
  513. auto client = rclcpp_action::create_client<simulation_interfaces::action::SimulateSteps>(node, "/simulate_steps");
  514. auto goal = std::make_shared<simulation_interfaces::action::SimulateSteps::Goal>();
  515. constexpr AZ::u64 steps = 10;
  516. goal->steps = steps;
  517. ASSERT_TRUE(client->wait_for_action_server(std::chrono::seconds(0)) == true) << "Action server is unavailable";
  518. EXPECT_CALL(mock, IsSimulationPaused())
  519. .WillOnce(::testing::Invoke(
  520. []()
  521. {
  522. return true;
  523. }));
  524. EXPECT_CALL(mock, StepSimulation(steps));
  525. EXPECT_CALL(mock, IsSimulationStepsActive())
  526. .WillRepeatedly(::testing::Invoke(
  527. []()
  528. {
  529. return true;
  530. }));
  531. EXPECT_CALL(mock, CancelStepSimulation());
  532. auto future = client->async_send_goal(*goal);
  533. SpinAppUntilFuture(future);
  534. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  535. auto goalHandle = future.get();
  536. ASSERT_NE(goalHandle, nullptr);
  537. auto cancelFuture = client->async_cancel_goal(goalHandle);
  538. SpinAppUntilFuture(cancelFuture);
  539. ASSERT_TRUE(cancelFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  540. }
  541. } // namespace UnitTest
  542. // required to support running integration tests with Qt and PhysX
  543. AZTEST_EXPORT int AZ_UNIT_TEST_HOOK_NAME(int argc, char** argv)
  544. {
  545. ::testing::InitGoogleMock(&argc, argv);
  546. AzQtComponents::PrepareQtPaths();
  547. QApplication app(argc, argv);
  548. AZ::Test::printUnusedParametersWarning(argc, argv);
  549. AZ::Test::addTestEnvironments({ new UnitTest::SimulationInterfaceROS2TestEnvironment() });
  550. int result = RUN_ALL_TESTS();
  551. return result;
  552. }
  553. IMPLEMENT_TEST_EXECUTABLE_MAIN();