PythonCoverageEditorSystemComponent.cpp 10 KB

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