PythonCoverageEditorSystemComponent.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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/IO/Path/Path.h>
  9. #include <AzCore/JSON/document.h>
  10. #include <AzCore/Module/ModuleManagerBus.h>
  11. #include <AzCore/Module/Module.h>
  12. #include <AzCore/Module/DynamicModuleHandle.h>
  13. #include <AzCore/Serialization/SerializeContext.h>
  14. #include <PythonCoverageEditorSystemComponent.h>
  15. namespace PythonCoverage
  16. {
  17. static constexpr char* const LogCallSite = "PythonCoverageEditorSystemComponent";
  18. void PythonCoverageEditorSystemComponent::Reflect(AZ::ReflectContext* context)
  19. {
  20. if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  21. {
  22. serializeContext->Class<PythonCoverageEditorSystemComponent, AZ::Component>()->Version(1);
  23. }
  24. }
  25. void PythonCoverageEditorSystemComponent::Activate()
  26. {
  27. AzToolsFramework::EditorPythonScriptNotificationsBus::Handler::BusConnect();
  28. AZ::EntitySystemBus::Handler::BusConnect();
  29. // If no output directory discovered, coverage gathering will be disabled
  30. if (ParseCoverageOutputDirectory() == CoverageState::Disabled)
  31. {
  32. return;
  33. }
  34. EnumerateAllModuleComponents();
  35. }
  36. void PythonCoverageEditorSystemComponent::Deactivate()
  37. {
  38. AZ::EntitySystemBus::Handler::BusDisconnect();
  39. AzToolsFramework::EditorPythonScriptNotificationsBus::Handler::BusDisconnect();
  40. }
  41. void PythonCoverageEditorSystemComponent::OnEntityActivated(const AZ::EntityId& entityId)
  42. {
  43. if (m_coverageState == CoverageState::Disabled)
  44. {
  45. return;
  46. }
  47. EnumerateComponentsForEntity(entityId);
  48. // There is currently no way to receive a graceful exit signal in order to properly handle the coverage end of life so
  49. // instead we have to serialize the data on-the-fly with blocking disk writes on the main thread... if this adversely
  50. // affects performance in a measurable way then this could potentially be put on a worker thread, although it remains to
  51. // be seen whether the asynchronous nature of such a thread results in queued up coverage being lost due to the hard exit
  52. if (m_coverageState == CoverageState::Gathering)
  53. {
  54. WriteCoverageFile();
  55. }
  56. }
  57. PythonCoverageEditorSystemComponent::CoverageState PythonCoverageEditorSystemComponent::ParseCoverageOutputDirectory()
  58. {
  59. m_coverageState = CoverageState::Disabled;
  60. const AZStd::string configFilePath = LY_TEST_IMPACT_DEFAULT_CONFIG_FILE;
  61. if (configFilePath.empty())
  62. {
  63. AZ_Warning(LogCallSite, false, "No test impact analysis framework config file specified.");
  64. return m_coverageState;
  65. }
  66. const auto fileSize = AZ::IO::SystemFile::Length(configFilePath.c_str());
  67. if(!fileSize)
  68. {
  69. AZ_Error(LogCallSite, false, "Test impact analysis framework config file '%s' does not exist", configFilePath.c_str());
  70. return m_coverageState;
  71. }
  72. AZStd::vector<char> buffer(fileSize + 1);
  73. buffer[fileSize] = '\0';
  74. if (!AZ::IO::SystemFile::Read(configFilePath.c_str(), buffer.data()))
  75. {
  76. AZ_Error(LogCallSite, false, "Could not read contents of test impact analysis framework config file '%s'", configFilePath.c_str());
  77. return m_coverageState;
  78. }
  79. const AZStd::string configurationData = AZStd::string(buffer.begin(), buffer.end());
  80. rapidjson::Document configurationFile;
  81. if (configurationFile.Parse(configurationData.c_str()).HasParseError())
  82. {
  83. AZ_Error(LogCallSite, false, "Could not parse test impact analysis framework config file data, JSON has errors");
  84. return m_coverageState;
  85. }
  86. const auto& tempConfig = configurationFile["workspace"]["temp"];
  87. // Temp directory root path is absolute
  88. const AZ::IO::Path tempWorkspaceRootDir = tempConfig["root"].GetString();
  89. // Artifact directory is relative to temp directory root
  90. const AZ::IO::Path artifactRelativeDir = tempConfig["relative_paths"]["artifact_dir"].GetString();
  91. m_coverageDir = tempWorkspaceRootDir / artifactRelativeDir;
  92. // Everything is good to go, await the first python test case
  93. m_coverageState = CoverageState::Idle;
  94. return m_coverageState;
  95. }
  96. void PythonCoverageEditorSystemComponent::WriteCoverageFile()
  97. {
  98. AZStd::string contents;
  99. // Compile the coverage for all test cases in this script
  100. for (const auto& [testCase, entityComponents] : m_entityComponentMap)
  101. {
  102. const auto coveringModules = GetParentComponentModulesForAllActivatedEntities(entityComponents);
  103. if (coveringModules.empty())
  104. {
  105. return;
  106. }
  107. contents = testCase + "\n";
  108. for (const auto& coveringModule : coveringModules)
  109. {
  110. contents += AZStd::string::format(" %s\n", coveringModule.c_str());
  111. }
  112. }
  113. AZ::IO::SystemFile file;
  114. const AZStd::vector<char> bytes(contents.begin(), contents.end());
  115. if (!file.Open(
  116. m_coverageFile.c_str(),
  117. AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY))
  118. {
  119. AZ_Error(LogCallSite, false, "Couldn't open file '%s' for writing", m_coverageFile.c_str());
  120. return;
  121. }
  122. if (!file.Write(bytes.data(), bytes.size()))
  123. {
  124. AZ_Error(LogCallSite, false, "Couldn't write contents for file '%s'", m_coverageFile.c_str());
  125. return;
  126. }
  127. }
  128. void PythonCoverageEditorSystemComponent::EnumerateAllModuleComponents()
  129. {
  130. AZ::ModuleManagerRequestBus::Broadcast(
  131. &AZ::ModuleManagerRequestBus::Events::EnumerateModules,
  132. [this](const AZ::ModuleData& moduleData)
  133. {
  134. // We can only enumerate shared libs, static libs are invisible to us
  135. if (moduleData.GetDynamicModuleHandle())
  136. {
  137. for (const auto* moduleComponentDescriptor : moduleData.GetModule()->GetComponentDescriptors())
  138. {
  139. m_moduleComponents[moduleComponentDescriptor->GetUuid()] = moduleData.GetDebugName();
  140. }
  141. }
  142. return true;
  143. });
  144. }
  145. void PythonCoverageEditorSystemComponent::EnumerateComponentsForEntity(const AZ::EntityId& entityId)
  146. {
  147. AZ::Entity* entity = nullptr;
  148. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationBus::Events::FindEntity, AZ::EntityId(entityId));
  149. if (entity)
  150. {
  151. auto& entityComponents = m_entityComponentMap[m_testCase];
  152. for (const auto& entityComponent : entity->GetComponents())
  153. {
  154. const auto componentTypeId = entityComponent->GetUnderlyingComponentType();
  155. AZ::ComponentDescriptor* componentDescriptor = nullptr;
  156. AZ::ComponentDescriptorBus::EventResult(
  157. componentDescriptor, componentTypeId, &AZ::ComponentDescriptorBus::Events::GetDescriptor);
  158. entityComponents[componentTypeId] = componentDescriptor;
  159. }
  160. }
  161. }
  162. AZStd::unordered_set<AZStd::string> PythonCoverageEditorSystemComponent::GetParentComponentModulesForAllActivatedEntities(
  163. const AZStd::unordered_map<AZ::Uuid, AZ::ComponentDescriptor*>& entityComponents) const
  164. {
  165. AZStd::unordered_set<AZStd::string> coveringModuleOutputNames;
  166. for (const auto& [uuid, componentDescriptor] : entityComponents)
  167. {
  168. if (const auto moduleComponent = m_moduleComponents.find(uuid); moduleComponent != m_moduleComponents.end())
  169. {
  170. coveringModuleOutputNames.insert(moduleComponent->second);
  171. }
  172. }
  173. return coveringModuleOutputNames;
  174. }
  175. void PythonCoverageEditorSystemComponent::OnStartExecuteByFilenameAsTest(AZStd::string_view filename, AZStd::string_view testCase, [[maybe_unused]] const AZStd::vector<AZStd::string_view>& args)
  176. {
  177. if (m_coverageState == CoverageState::Disabled)
  178. {
  179. return;
  180. }
  181. if (m_coverageState == CoverageState::Gathering)
  182. {
  183. // Dump any existing coverage data to disk
  184. WriteCoverageFile();
  185. m_coverageState = CoverageState::Idle;
  186. }
  187. if (testCase.empty())
  188. {
  189. // We need to be able to pinpoint the coverage data to the specific test case names otherwise we will not be able
  190. // to specify which specific tests should be run in the future (filename does not necessarily equate to test case name)
  191. AZ_Error(LogCallSite, false, "No test case specified, coverage data gathering will be disabled for this test");
  192. return;
  193. }
  194. const AZStd::string scriptName = AZ::IO::Path(filename).Stem().Native();
  195. const auto coverageFile = m_coverageDir / AZStd::string::format("%s.pycoverage", scriptName.c_str());
  196. // If this is a different python script we clear the existing entity components and start afresh
  197. if (m_coverageFile != coverageFile)
  198. {
  199. m_entityComponentMap.clear();
  200. m_coverageFile = coverageFile;
  201. }
  202. m_testCase = testCase;
  203. m_coverageState = CoverageState::Gathering;
  204. }
  205. } // namespace PythonCoverage