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