InterfacesTest.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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>
  106. void SpinAppUntilFuture(Future& future)
  107. {
  108. AZ::ComponentApplication* app = nullptr;
  109. AZ::ComponentApplicationBus::BroadcastResult(app, &AZ::ComponentApplicationBus::Events::GetApplication);
  110. AZ_Assert(app, "Application pointer is not available.");
  111. constexpr int MaximumTicks = 1000;
  112. for (int i = 0; i < MaximumTicks; ++i)
  113. {
  114. app->Tick();
  115. if (future.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
  116. {
  117. return;
  118. }
  119. }
  120. }
  121. };
  122. //! Perform a smoke test to check if the ROS2 node is available from ROS2 gem
  123. TEST_F(SimulationInterfaceROS2TestFixture, TestIfROS2NodeIsAvailable)
  124. {
  125. ASSERT_NE(GetRos2Node(), nullptr) << "ROS2 node is not available.";
  126. }
  127. //! Perform a smoke test to check if the ROS2 domain is working
  128. TEST_F(SimulationInterfaceROS2TestFixture, SmokeTestROS2Domain)
  129. {
  130. auto node = GetRos2Node();
  131. auto pub = node->create_publisher<std_msgs::msg::String>("hello", 20);
  132. int receivedMsgs = 0;
  133. auto sub = node->create_subscription<std_msgs::msg::String>(
  134. "hello",
  135. 10,
  136. [&receivedMsgs](const std_msgs::msg::String& msg)
  137. {
  138. receivedMsgs++;
  139. });
  140. std_msgs::msg::String msg;
  141. msg.data = "Hello World!";
  142. for (int i = 0; i < 10; ++i)
  143. {
  144. pub->publish(msg);
  145. }
  146. SpinAppSome();
  147. EXPECT_EQ(receivedMsgs, 10) << "Did not receive all messages.";
  148. }
  149. //! Check if expected services are available and has the default name
  150. TEST_F(SimulationInterfaceROS2TestFixture, TestIfServicesAvailableInROS2Domain)
  151. {
  152. auto node = GetRos2Node();
  153. auto services = node->get_service_names_and_types();
  154. ASSERT_FALSE(services.empty()) << "No services available.";
  155. EXPECT_NE(services.find("/delete_entity"), services.end());
  156. EXPECT_NE(services.find("/get_entities"), services.end());
  157. EXPECT_NE(services.find("/get_entities_states"), services.end());
  158. EXPECT_NE(services.find("/get_entity_state"), services.end());
  159. EXPECT_NE(services.find("/get_spawnables"), services.end());
  160. EXPECT_NE(services.find("/set_entity_state"), services.end());
  161. EXPECT_NE(services.find("/spawn_entity"), services.end());
  162. EXPECT_NE(services.find("/get_simulation_features"), services.end());
  163. EXPECT_NE(services.find("/step_simulation"), services.end());
  164. }
  165. //! Test if the service call succeeds when the entity is found
  166. TEST_F(SimulationInterfaceROS2TestFixture, TestDeleteEntity_01)
  167. {
  168. using ::testing::_;
  169. auto node = GetRos2Node();
  170. auto mock = std::make_shared<SimulationEntityManagerMockedHandler>();
  171. auto client = node->create_client<simulation_interfaces::srv::DeleteEntity>("/delete_entity");
  172. auto request = std::make_shared<simulation_interfaces::srv::DeleteEntity::Request>();
  173. const char TestEntityName[] = "test_entity";
  174. request->entity = std::string(TestEntityName);
  175. const AZStd::string entityName = AZStd::string(TestEntityName);
  176. EXPECT_CALL(*mock, DeleteEntity(entityName, _))
  177. .WillOnce(::testing::Invoke(
  178. [](const AZStd::string& name, SimulationInterfaces::DeletionCompletedCb completedCb)
  179. {
  180. EXPECT_EQ(name, "test_entity");
  181. completedCb(AZ::Success());
  182. }));
  183. auto future = client->async_send_request(request);
  184. SpinAppUntilFuture(future);
  185. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  186. auto response = future.get();
  187. EXPECT_EQ(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  188. }
  189. //! Test if the service call fails when the entity is not found
  190. TEST_F(SimulationInterfaceROS2TestFixture, TestDeleteEntity_02)
  191. {
  192. using ::testing::_;
  193. auto node = GetRos2Node();
  194. SimulationEntityManagerMockedHandler mock;
  195. auto client = node->create_client<simulation_interfaces::srv::DeleteEntity>("/delete_entity");
  196. auto request = std::make_shared<simulation_interfaces::srv::DeleteEntity::Request>();
  197. const char TestEntityName[] = "test_entity";
  198. request->entity = std::string(TestEntityName);
  199. const AZStd::string entityName = AZStd::string(TestEntityName);
  200. EXPECT_CALL(mock, DeleteEntity(entityName, _))
  201. .WillOnce(::testing::Invoke(
  202. [](const AZStd::string& name, SimulationInterfaces::DeletionCompletedCb completedCb)
  203. {
  204. EXPECT_EQ(name, "test_entity");
  205. FailedResult failedResult;
  206. failedResult.m_errorCode = simulation_interfaces::msg::Result::RESULT_NOT_FOUND,
  207. failedResult.m_errorString = "FooBar not found.";
  208. completedCb(AZ::Failure(failedResult));
  209. }));
  210. auto future = client->async_send_request(request);
  211. SpinAppUntilFuture(future);
  212. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  213. auto response = future.get();
  214. EXPECT_EQ(response->result.result, simulation_interfaces::msg::Result::RESULT_NOT_FOUND);
  215. }
  216. //! Happy path test for GetEntities with a sphere shape
  217. //! Test if the service is called with a sphere shape and Posix filter is passed through
  218. TEST_F(SimulationInterfaceROS2TestFixture, GetEntitiesWithShapeSphereAndFilterValid)
  219. {
  220. using ::testing::_;
  221. auto node = GetRos2Node();
  222. SimulationEntityManagerMockedHandler mock;
  223. auto client = node->create_client<simulation_interfaces::srv::GetEntities>("/get_entities");
  224. auto request = std::make_shared<simulation_interfaces::srv::GetEntities::Request>();
  225. request->filters.bounds.points.resize(2);
  226. const AZ::Vector3 point1(1.0f, 2.0f, 3.0f);
  227. request->filters.bounds.points[0].x = point1.GetX();
  228. request->filters.bounds.points[0].y = point1.GetY();
  229. request->filters.bounds.points[0].z = point1.GetZ();
  230. request->filters.bounds.points[1].x = 99.0f;
  231. request->filters.bounds.type = simulation_interfaces::msg::Bounds::TYPE_SPHERE;
  232. request->filters.filter = "FooBarFilter";
  233. EXPECT_CALL(mock, GetEntities(_))
  234. .WillOnce(::testing::Invoke(
  235. [=](const EntityFilters& filter)
  236. {
  237. EXPECT_NE(filter.m_boundsShape, nullptr);
  238. if (filter.m_boundsShape)
  239. {
  240. EXPECT_EQ(filter.m_boundsShape->GetShapeType(), Physics::ShapeType::Sphere);
  241. Physics::SphereShapeConfiguration* sphereShape =
  242. azdynamic_cast<Physics::SphereShapeConfiguration*>(filter.m_boundsShape.get());
  243. EXPECT_EQ(sphereShape->m_radius, 99.0f);
  244. EXPECT_EQ(sphereShape->m_scale, AZ::Vector3(1.0f));
  245. }
  246. auto loc = filter.m_boundsPose.GetTranslation();
  247. EXPECT_EQ(loc.GetX(), point1.GetX());
  248. EXPECT_EQ(loc.GetY(), point1.GetY());
  249. EXPECT_EQ(loc.GetZ(), point1.GetZ());
  250. EXPECT_EQ(filter.m_nameFilter, "FooBarFilter");
  251. return AZ::Success(EntityNameList{ "FooBar" });
  252. }));
  253. auto future = client->async_send_request(request);
  254. SpinAppUntilFuture(future);
  255. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  256. auto response = future.get();
  257. EXPECT_EQ(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  258. }
  259. //! Try to call the service with invalid data (too few points) for the sphere shape
  260. TEST_F(SimulationInterfaceROS2TestFixture, GetEntitiesWithShapeSphereWithInvalidData)
  261. {
  262. using ::testing::_;
  263. auto node = GetRos2Node();
  264. [[maybe_unused]] testing::StrictMock<SimulationEntityManagerMockedHandler> mock;
  265. auto client = node->create_client<simulation_interfaces::srv::GetEntities>("/get_entities");
  266. auto request = std::make_shared<simulation_interfaces::srv::GetEntities::Request>();
  267. request->filters.bounds.points.resize(1); // too few points
  268. request->filters.bounds.type = simulation_interfaces::msg::Bounds::TYPE_SPHERE;
  269. auto future = client->async_send_request(request);
  270. SpinAppUntilFuture(future);
  271. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  272. auto response = future.get();
  273. EXPECT_NE(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  274. }
  275. //! Happy path test for GetEntities with a box shape
  276. TEST_F(SimulationInterfaceROS2TestFixture, GetEntitiesWithShapeBox)
  277. {
  278. using ::testing::_;
  279. auto node = GetRos2Node();
  280. testing::NiceMock<SimulationEntityManagerMockedHandler> mock;
  281. auto client = node->create_client<simulation_interfaces::srv::GetEntities>("/get_entities");
  282. auto request = std::make_shared<simulation_interfaces::srv::GetEntities::Request>();
  283. request->filters.bounds.points.resize(2);
  284. const AZ::Vector3 point1(1.0f, 2.0f, 3.0f);
  285. const AZ::Vector3 dims(4.0f, 5.0f, 6.0f);
  286. const AZ::Vector3 point2 = point1 + dims;
  287. request->filters.bounds.points[0].x = point1.GetX();
  288. request->filters.bounds.points[0].y = point1.GetY();
  289. request->filters.bounds.points[0].z = point1.GetZ();
  290. request->filters.bounds.points[1].x = point2.GetX();
  291. request->filters.bounds.points[1].y = point2.GetY();
  292. request->filters.bounds.points[1].z = point2.GetZ();
  293. request->filters.bounds.type = simulation_interfaces::msg::Bounds::TYPE_BOX;
  294. EXPECT_CALL(mock, GetEntities(_))
  295. .WillOnce(::testing::Invoke(
  296. [=](const EntityFilters& filter)
  297. {
  298. EXPECT_NE(filter.m_boundsShape, nullptr);
  299. if (filter.m_boundsShape)
  300. {
  301. EXPECT_EQ(filter.m_boundsShape->GetShapeType(), Physics::ShapeType::Box);
  302. Physics::BoxShapeConfiguration* boxShape =
  303. azdynamic_cast<Physics::BoxShapeConfiguration*>(filter.m_boundsShape.get());
  304. EXPECT_EQ(boxShape->m_dimensions.GetX(), dims.GetX());
  305. EXPECT_EQ(boxShape->m_dimensions.GetY(), dims.GetY());
  306. EXPECT_EQ(boxShape->m_dimensions.GetZ(), dims.GetZ());
  307. }
  308. auto loc = filter.m_boundsPose.GetTranslation();
  309. EXPECT_EQ(loc, AZ::Vector3::CreateZero());
  310. return AZ::Success(EntityNameList{ "FooBar" });
  311. }));
  312. auto future = client->async_send_request(request);
  313. SpinAppUntilFuture(future);
  314. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  315. auto response = future.get();
  316. EXPECT_EQ(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  317. }
  318. //! Try to call the service with invalid data (first point is greater than second point in box)
  319. TEST_F(SimulationInterfaceROS2TestFixture, GetEntitiesWithShapeBoxInvalid)
  320. {
  321. using ::testing::_;
  322. auto node = GetRos2Node();
  323. // strict mock, since we don't want to call the real implementation in this test
  324. [[maybe_unused]] testing::StrictMock<SimulationEntityManagerMockedHandler> mock;
  325. auto client = node->create_client<simulation_interfaces::srv::GetEntities>("/get_entities");
  326. auto request = std::make_shared<simulation_interfaces::srv::GetEntities::Request>();
  327. request->filters.bounds.points.resize(2);
  328. request->filters.bounds.points[0].x = 2.0f;
  329. request->filters.bounds.points[0].y = 3.0f;
  330. request->filters.bounds.points[0].z = 4.0f;
  331. request->filters.bounds.points[1].x = -2.0f;
  332. request->filters.bounds.points[1].y = -3.0f;
  333. request->filters.bounds.points[1].z = 5.0f;
  334. request->filters.bounds.type = simulation_interfaces::msg::Bounds::TYPE_BOX;
  335. auto future = client->async_send_request(request);
  336. SpinAppUntilFuture(future);
  337. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  338. auto response = future.get();
  339. EXPECT_NE(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  340. }
  341. //! check if capabilities vector is empty when no features are provided by SimulationInterfaces gem
  342. TEST_F(SimulationInterfaceROS2TestFixture, GetSimulationFeaturesNoFeaturesProvidedByGem)
  343. {
  344. using ::testing::_;
  345. auto node = GetRos2Node();
  346. auto client = node->create_client<simulation_interfaces::srv::GetSimulatorFeatures>("/get_simulation_features");
  347. auto request = std::make_shared<simulation_interfaces::srv::GetSimulatorFeatures::Request>();
  348. auto future = client->async_send_request(request);
  349. SpinAppUntilFuture(future);
  350. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  351. auto response = future.get();
  352. EXPECT_TRUE(response->features.features.empty()) << "Features vector is not empty.";
  353. }
  354. //! check if features are returned when the feature is provided by SimulationFeaturesAggregator
  355. //! and the feature is not in the list of features provided by the gem
  356. TEST_F(SimulationInterfaceROS2TestFixture, GetSimulationFeaturesSomeFeaturesProvided)
  357. {
  358. SimulationFeaturesAggregatorRequestsMockedHandler mockAggregator;
  359. using ::testing::_;
  360. auto node = GetRos2Node();
  361. AZStd::unordered_set<SimulationFeatureType> features{
  362. simulation_interfaces::msg::SimulatorFeatures::SPAWNING,
  363. static_cast<SimulationFeatureType>(0xFE), // invalid feature, should be ignored
  364. static_cast<SimulationFeatureType>(0xFF), // invalid feature, should be ignored
  365. };
  366. EXPECT_CALL(mockAggregator, GetSimulationFeatures())
  367. .WillOnce(::testing::Invoke(
  368. [&](void)
  369. {
  370. return features;
  371. }));
  372. auto client = node->create_client<simulation_interfaces::srv::GetSimulatorFeatures>("/get_simulation_features");
  373. auto request = std::make_shared<simulation_interfaces::srv::GetSimulatorFeatures::Request>();
  374. auto future = client->async_send_request(request);
  375. SpinAppUntilFuture(future);
  376. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  377. auto response = future.get();
  378. ASSERT_FALSE(response->features.features.empty()) << "Features vector is empty.";
  379. EXPECT_EQ(response->features.features.size(), 1) << "Features vector should contain one feature only.";
  380. EXPECT_EQ(response->features.features[0], simulation_interfaces::msg::SimulatorFeatures::SPAWNING) << "Feature is not SPAWNING.";
  381. }
  382. //! Check if service succeeds when the name is valid
  383. TEST_F(SimulationInterfaceROS2TestFixture, TryToSpawnWithValidName)
  384. {
  385. using ::testing::_;
  386. SimulationEntityManagerMockedHandler mock;
  387. auto node = GetRos2Node();
  388. auto client = node->create_client<simulation_interfaces::srv::SpawnEntity>("/spawn_entity");
  389. auto request = std::make_shared<simulation_interfaces::srv::SpawnEntity::Request>();
  390. request->name = "valid_name";
  391. request->uri = "test_uri";
  392. request->entity_namespace = "test_namespace";
  393. request->allow_renaming = true;
  394. auto future = client->async_send_request(request);
  395. EXPECT_CALL(mock, SpawnEntity(_, _, _, _, _, _))
  396. .WillOnce(::testing::Invoke(
  397. [](const AZStd::string& name,
  398. const AZStd::string& uri,
  399. const AZStd::string& entityNamespace,
  400. const AZ::Transform& initialPose,
  401. const bool allowRename,
  402. SpawnCompletedCb completedCb)
  403. {
  404. EXPECT_EQ(name, "valid_name");
  405. EXPECT_EQ(uri, "test_uri");
  406. EXPECT_EQ(entityNamespace, "test_namespace");
  407. EXPECT_TRUE(allowRename);
  408. completedCb(AZ::Success("valid_name"));
  409. }));
  410. SpinAppUntilFuture(future);
  411. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  412. auto response = future.get();
  413. EXPECT_EQ(response->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  414. }
  415. //! Check if service fails when the name is invalid
  416. TEST_F(SimulationInterfaceROS2TestFixture, TryToSpawnWithInvalidName)
  417. {
  418. // strict mock, since we don't want to call the real implementation in this test
  419. [[maybe_unused]] testing::StrictMock<SimulationEntityManagerMockedHandler> mock;
  420. auto node = GetRos2Node();
  421. auto client = node->create_client<simulation_interfaces::srv::SpawnEntity>("/spawn_entity");
  422. auto request = std::make_shared<simulation_interfaces::srv::SpawnEntity::Request>();
  423. request->name = "invalid name"; // invalid name
  424. request->uri = "test_uri";
  425. request->entity_namespace = "test_namespace";
  426. auto future = client->async_send_request(request);
  427. SpinAppUntilFuture(future);
  428. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  429. auto response = future.get();
  430. EXPECT_EQ(response->result.result, simulation_interfaces::srv::SpawnEntity::Response::NAME_INVALID)
  431. << "Service call should fail with invalid name.";
  432. }
  433. //! Check if service fails when the namespace is invalid
  434. TEST_F(SimulationInterfaceROS2TestFixture, TryToSpawnWithInvalidNamespace)
  435. {
  436. // strict mock, since we don't want to call the real implementation in this test
  437. [[maybe_unused]] testing::StrictMock<SimulationEntityManagerMockedHandler> mock;
  438. auto node = GetRos2Node();
  439. auto client = node->create_client<simulation_interfaces::srv::SpawnEntity>("/spawn_entity");
  440. auto request = std::make_shared<simulation_interfaces::srv::SpawnEntity::Request>();
  441. request->name = "valid_name";
  442. request->uri = "test_uri";
  443. request->entity_namespace = "invalid namespace";
  444. auto future = client->async_send_request(request);
  445. SpinAppUntilFuture(future);
  446. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Service call timed out.";
  447. auto response = future.get();
  448. EXPECT_EQ(response->result.result, simulation_interfaces::srv::SpawnEntity::Response::NAMESPACE_INVALID)
  449. << "Service call should fail with invalid name.";
  450. }
  451. TEST_F(SimulationInterfaceROS2TestFixture, SimulationStepsSuccess)
  452. {
  453. using ::testing::_;
  454. auto node = GetRos2Node();
  455. SimulationManagerMockedHandler mock;
  456. auto client = rclcpp_action::create_client<simulation_interfaces::action::SimulateSteps>(node, "/simulate_steps");
  457. auto goal = std::make_shared<simulation_interfaces::action::SimulateSteps::Goal>();
  458. constexpr AZ::u64 steps = 10;
  459. goal->steps = steps;
  460. ASSERT_TRUE(client->wait_for_action_server(std::chrono::seconds(0)) == true) << "Action server is unavailable";
  461. EXPECT_CALL(mock, IsSimulationPaused())
  462. .WillOnce(::testing::Invoke(
  463. []()
  464. {
  465. return true;
  466. }));
  467. EXPECT_CALL(mock, StepSimulation(steps));
  468. EXPECT_CALL(mock, IsSimulationStepsActive())
  469. .WillOnce(::testing::Invoke(
  470. []()
  471. {
  472. return false;
  473. }));
  474. auto future = client->async_send_goal(*goal);
  475. SpinAppUntilFuture(future);
  476. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  477. auto goalHandle = future.get();
  478. ASSERT_NE(goalHandle, nullptr);
  479. auto result = client->async_get_result(goalHandle);
  480. SpinAppUntilFuture(result);
  481. ASSERT_TRUE(result.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  482. EXPECT_EQ(result.get().result->result.result, simulation_interfaces::msg::Result::RESULT_OK);
  483. }
  484. TEST_F(SimulationInterfaceROS2TestFixture, SimulationStepsFailureSimulationIsNotPaused)
  485. {
  486. using ::testing::_;
  487. auto node = GetRos2Node();
  488. SimulationManagerMockedHandler mock;
  489. auto client = rclcpp_action::create_client<simulation_interfaces::action::SimulateSteps>(node, "/simulate_steps");
  490. auto goal = std::make_shared<simulation_interfaces::action::SimulateSteps::Goal>();
  491. goal->steps = 10;
  492. ASSERT_TRUE(client->wait_for_action_server(std::chrono::seconds(0)) == true) << "Action server is unavailable";
  493. EXPECT_CALL(mock, IsSimulationPaused())
  494. .WillOnce(::testing::Invoke(
  495. []()
  496. {
  497. return false;
  498. }));
  499. auto future = client->async_send_goal(*goal);
  500. SpinAppUntilFuture(future);
  501. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  502. auto goalHandle = future.get();
  503. ASSERT_NE(goalHandle, nullptr);
  504. auto result = client->async_get_result(goalHandle);
  505. SpinAppUntilFuture(result);
  506. ASSERT_TRUE(result.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  507. EXPECT_EQ(result.get().result->result.result, simulation_interfaces::msg::Result::RESULT_OPERATION_FAILED);
  508. }
  509. TEST_F(SimulationInterfaceROS2TestFixture, SimulationStepsCancelled)
  510. {
  511. using ::testing::_;
  512. auto node = GetRos2Node();
  513. SimulationManagerMockedHandler mock;
  514. auto client = rclcpp_action::create_client<simulation_interfaces::action::SimulateSteps>(node, "/simulate_steps");
  515. auto goal = std::make_shared<simulation_interfaces::action::SimulateSteps::Goal>();
  516. constexpr AZ::u64 steps = 10;
  517. goal->steps = steps;
  518. ASSERT_TRUE(client->wait_for_action_server(std::chrono::seconds(0)) == true) << "Action server is unavailable";
  519. EXPECT_CALL(mock, IsSimulationPaused())
  520. .WillOnce(::testing::Invoke(
  521. []()
  522. {
  523. return true;
  524. }));
  525. EXPECT_CALL(mock, StepSimulation(steps));
  526. EXPECT_CALL(mock, IsSimulationStepsActive())
  527. .WillRepeatedly(::testing::Invoke(
  528. []()
  529. {
  530. return true;
  531. }));
  532. EXPECT_CALL(mock, CancelStepSimulation());
  533. auto future = client->async_send_goal(*goal);
  534. SpinAppUntilFuture(future);
  535. ASSERT_TRUE(future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  536. auto goalHandle = future.get();
  537. ASSERT_NE(goalHandle, nullptr);
  538. auto cancelFuture = client->async_cancel_goal(goalHandle);
  539. SpinAppUntilFuture(cancelFuture);
  540. ASSERT_TRUE(cancelFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) << "Action call timed out.";
  541. }
  542. } // namespace UnitTest
  543. // required to support running integration tests with Qt and PhysX
  544. AZTEST_EXPORT int AZ_UNIT_TEST_HOOK_NAME(int argc, char** argv)
  545. {
  546. ::testing::InitGoogleMock(&argc, argv);
  547. AzQtComponents::PrepareQtPaths();
  548. QApplication app(argc, argv);
  549. AZ::Test::printUnusedParametersWarning(argc, argv);
  550. AZ::Test::addTestEnvironments({ new UnitTest::SimulationInterfaceROS2TestEnvironment() });
  551. int result = RUN_ALL_TESTS();
  552. return result;
  553. }
  554. IMPLEMENT_TEST_EXECUTABLE_MAIN();