PythonCoverageEditorSystemComponent.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. #include <AzCore/StringFunc/StringFunc.h>
  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. m_coverageDir = configurationFile["python"]["workspace"]["temp"]["coverage_artifact_dir"].GetString();
  89. // Everything is good to go, await the first python test case
  90. m_coverageState = CoverageState::Idle;
  91. return m_coverageState;
  92. }
  93. void PythonCoverageEditorSystemComponent::WriteCoverageFile()
  94. {
  95. AZStd::string contents;
  96. // Compile the coverage for this test case
  97. const auto coveringModules = GetParentComponentModulesForAllActivatedEntities(m_entityComponents);
  98. if (coveringModules.empty())
  99. {
  100. return;
  101. }
  102. contents = AZStd::string::format(
  103. "%s\n%s\n%s\n%s\n", m_parentScriptPath.c_str(), m_scriptPath.c_str(), m_testFixture.c_str(), m_testCase.c_str());
  104. for (const auto& coveringModule : coveringModules)
  105. {
  106. contents += AZStd::string::format("%s\n", coveringModule.c_str());
  107. }
  108. AZ::IO::SystemFile file;
  109. const AZStd::vector<char> bytes(contents.begin(), contents.end());
  110. if (!file.Open(
  111. m_coverageFile.c_str(),
  112. AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY))
  113. {
  114. AZ_Error(LogCallSite, false, "Couldn't open file '%s' for writing", m_coverageFile.c_str());
  115. return;
  116. }
  117. if (!file.Write(bytes.data(), bytes.size()))
  118. {
  119. AZ_Error(LogCallSite, false, "Couldn't write contents for file '%s'", m_coverageFile.c_str());
  120. return;
  121. }
  122. }
  123. void PythonCoverageEditorSystemComponent::EnumerateAllModuleComponents()
  124. {
  125. AZ::ModuleManagerRequestBus::Broadcast(
  126. &AZ::ModuleManagerRequestBus::Events::EnumerateModules,
  127. [this](const AZ::ModuleData& moduleData)
  128. {
  129. // We can only enumerate shared libs, static libs are invisible to us
  130. if (moduleData.GetDynamicModuleHandle())
  131. {
  132. for (const auto* moduleComponentDescriptor : moduleData.GetModule()->GetComponentDescriptors())
  133. {
  134. m_moduleComponents[moduleComponentDescriptor->GetUuid()] =
  135. m_moduleComponents[moduleComponentDescriptor->GetUuid()] = moduleData.GetDebugName();
  136. }
  137. }
  138. return true;
  139. });
  140. }
  141. void PythonCoverageEditorSystemComponent::EnumerateComponentsForEntity(const AZ::EntityId& entityId)
  142. {
  143. AZ::Entity* entity = nullptr;
  144. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationBus::Events::FindEntity, AZ::EntityId(entityId));
  145. if (entity)
  146. {
  147. for (const auto& entityComponent : entity->GetComponents())
  148. {
  149. const auto componentTypeId = entityComponent->GetUnderlyingComponentType();
  150. AZ::ComponentDescriptor* componentDescriptor = nullptr;
  151. AZ::ComponentDescriptorBus::EventResult(
  152. componentDescriptor, componentTypeId, &AZ::ComponentDescriptorBus::Events::GetDescriptor);
  153. m_entityComponents[componentTypeId] = componentDescriptor;
  154. }
  155. }
  156. }
  157. AZStd::unordered_set<AZStd::string> PythonCoverageEditorSystemComponent::GetParentComponentModulesForAllActivatedEntities(
  158. const AZStd::unordered_map<AZ::Uuid, AZ::ComponentDescriptor*>& entityComponents) const
  159. {
  160. AZStd::unordered_set<AZStd::string> coveringModuleOutputNames;
  161. for (const auto& [uuid, componentDescriptor] : entityComponents)
  162. {
  163. if (const auto moduleComponent = m_moduleComponents.find(uuid); moduleComponent != m_moduleComponents.end())
  164. {
  165. coveringModuleOutputNames.insert(moduleComponent->second);
  166. }
  167. }
  168. return coveringModuleOutputNames;
  169. }
  170. AZStd::string CompileParentFolderName(const AZStd::string& parentScriptPath)
  171. {
  172. // Compile a unique folder name based on the aprent script path
  173. auto parentfolder = parentScriptPath;
  174. AZ::StringFunc::Replace(parentfolder, '/', '_');
  175. AZ::StringFunc::Replace(parentfolder, '\\', '_');
  176. AZ::StringFunc::Replace(parentfolder, '.', '_');
  177. return parentfolder;
  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 auto matcherPattern = AZStd::regex("(.*)::(.*)::(.*)");
  199. const auto strTestCase = AZStd::string(testCase);
  200. AZStd::smatch testCaseMatches;
  201. if (!AZStd::regex_search(strTestCase, testCaseMatches, matcherPattern))
  202. {
  203. AZ_Error(
  204. LogCallSite,
  205. false,
  206. "The test case name '%s' did not comply to the format expected by the coverage gem "
  207. "'parent_script_path::fixture_name::test_case_name', coverage data gathering will be disabled for this test",
  208. strTestCase.c_str());
  209. return;
  210. }
  211. m_parentScriptPath = testCaseMatches[1];
  212. m_testFixture = testCaseMatches[2];
  213. m_testCase = testCaseMatches[3];
  214. m_entityComponents.clear();
  215. m_scriptPath = filename;
  216. const auto coverageFile = m_coverageDir / CompileParentFolderName(m_parentScriptPath) / AZStd::string::format("%s.pycoverage", m_testCase.c_str());
  217. m_coverageFile = coverageFile;
  218. m_coverageState = CoverageState::Gathering;
  219. }
  220. } // namespace PythonCoverage