PythonCoverageEditorSystemComponent.cpp 9.6 KB

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