PythonCoverageEditorSystemComponent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. 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 = AZStd::string::format(
  108. "%s\n%s\n%s\n%s\n", m_parentScriptPath.c_str(), m_scriptPath.c_str(), m_testFixture.c_str(), m_testCase.c_str());
  109. for (const auto& coveringModule : coveringModules)
  110. {
  111. contents += AZStd::string::format("%s\n", coveringModule.c_str());
  112. }
  113. AZ::IO::SystemFile file;
  114. const AZStd::vector<char> bytes(contents.begin(), contents.end());
  115. if (!file.Open(
  116. m_coverageFile.c_str(),
  117. AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY))
  118. {
  119. AZ_Error(LogCallSite, false, "Couldn't open file '%s' for writing", m_coverageFile.c_str());
  120. return;
  121. }
  122. if (!file.Write(bytes.data(), bytes.size()))
  123. {
  124. AZ_Error(LogCallSite, false, "Couldn't write contents for file '%s'", m_coverageFile.c_str());
  125. return;
  126. }
  127. }
  128. void PythonCoverageEditorSystemComponent::EnumerateAllModuleComponents()
  129. {
  130. AZ::ModuleManagerRequestBus::Broadcast(
  131. &AZ::ModuleManagerRequestBus::Events::EnumerateModules,
  132. [this](const AZ::ModuleData& moduleData)
  133. {
  134. // We can only enumerate shared libs, static libs are invisible to us
  135. if (moduleData.GetDynamicModuleHandle())
  136. {
  137. for (const auto* moduleComponentDescriptor : moduleData.GetModule()->GetComponentDescriptors())
  138. {
  139. m_moduleComponents[moduleComponentDescriptor->GetUuid()] = moduleData.GetDebugName();
  140. }
  141. }
  142. return true;
  143. });
  144. }
  145. void PythonCoverageEditorSystemComponent::EnumerateComponentsForEntity(const AZ::EntityId& entityId)
  146. {
  147. AZ::Entity* entity = nullptr;
  148. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationBus::Events::FindEntity, AZ::EntityId(entityId));
  149. if (entity)
  150. {
  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. m_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. AZStd::string CompileParentFolderName(const AZStd::string& parentScriptPath)
  175. {
  176. // Compile a unique folder name based on the aprent script path
  177. auto parentfolder = parentScriptPath;
  178. AZ::StringFunc::Replace(parentfolder, '/', '_');
  179. AZ::StringFunc::Replace(parentfolder, '\\', '_');
  180. AZ::StringFunc::Replace(parentfolder, '.', '_');
  181. return parentfolder;
  182. }
  183. void PythonCoverageEditorSystemComponent::OnStartExecuteByFilenameAsTest(AZStd::string_view filename, AZStd::string_view testCase, [[maybe_unused]] const AZStd::vector<AZStd::string_view>& args)
  184. {
  185. if (m_coverageState == CoverageState::Disabled)
  186. {
  187. return;
  188. }
  189. if (m_coverageState == CoverageState::Gathering)
  190. {
  191. // Dump any existing coverage data to disk
  192. WriteCoverageFile();
  193. m_coverageState = CoverageState::Idle;
  194. }
  195. if (testCase.empty())
  196. {
  197. // We need to be able to pinpoint the coverage data to the specific test case names otherwise we will not be able
  198. // to specify which specific tests should be run in the future (filename does not necessarily equate to test case name)
  199. AZ_Error(LogCallSite, false, "No test case specified, coverage data gathering will be disabled for this test");
  200. return;
  201. }
  202. const auto matcherPattern = AZStd::regex("(.*)::(.*)::(.*)");
  203. const auto strTestCase = AZStd::string(testCase);
  204. AZStd::smatch testCaseMatches;
  205. if (!AZStd::regex_search(strTestCase, testCaseMatches, matcherPattern))
  206. {
  207. AZ_Error(
  208. LogCallSite,
  209. false,
  210. "The test case name '%s' did not comply to the format expected by the coverage gem "
  211. "'parent_script_path::fixture_name::test_case_name', coverage data gathering will be disabled for this test",
  212. strTestCase.c_str());
  213. return;
  214. }
  215. m_parentScriptPath = testCaseMatches[1];
  216. m_testFixture = testCaseMatches[2];
  217. m_testCase = testCaseMatches[3];
  218. m_entityComponents.clear();
  219. m_scriptPath = filename;
  220. const auto coverageFile = m_coverageDir / CompileParentFolderName(m_parentScriptPath) / AZStd::string::format("%s.pycoverage", m_testCase.c_str());
  221. m_coverageFile = coverageFile;
  222. m_coverageState = CoverageState::Gathering;
  223. }
  224. } // namespace PythonCoverage