PythonCoverageEditorSystemComponent.cpp 9.9 KB

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