PythonCoverageEditorSystemComponent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. #if defined(LY_TEST_IMPACT_DEFAULT_CONFIG_FILE)
  63. const AZStd::string configFilePath = LY_TEST_IMPACT_DEFAULT_CONFIG_FILE;
  64. if (configFilePath.empty())
  65. {
  66. AZ_Warning(LogCallSite, false, "No test impact analysis framework config file specified.");
  67. return m_coverageState;
  68. }
  69. const auto fileSize = AZ::IO::SystemFile::Length(configFilePath.c_str());
  70. if(!fileSize)
  71. {
  72. AZ_Error(LogCallSite, false, "Test impact analysis framework config file '%s' does not exist", configFilePath.c_str());
  73. return m_coverageState;
  74. }
  75. AZStd::vector<char> buffer(fileSize + 1);
  76. buffer[fileSize] = '\0';
  77. if (!AZ::IO::SystemFile::Read(configFilePath.c_str(), buffer.data()))
  78. {
  79. AZ_Error(LogCallSite, false, "Could not read contents of test impact analysis framework config file '%s'", configFilePath.c_str());
  80. return m_coverageState;
  81. }
  82. const AZStd::string configurationData = AZStd::string(buffer.begin(), buffer.end());
  83. rapidjson::Document configurationFile;
  84. if (configurationFile.Parse(configurationData.c_str()).HasParseError())
  85. {
  86. AZ_Error(LogCallSite, false, "Could not parse test impact analysis framework config file data, JSON has errors");
  87. return m_coverageState;
  88. }
  89. m_coverageDir = configurationFile["python"]["workspace"]["temp"]["coverage_artifact_dir"].GetString();
  90. // Everything is good to go, await the first python test case
  91. m_coverageState = CoverageState::Idle;
  92. #endif
  93. return m_coverageState;
  94. }
  95. void PythonCoverageEditorSystemComponent::WriteCoverageFile()
  96. {
  97. AZStd::string contents;
  98. // Compile the coverage for this test case
  99. const auto coveringModules = GetParentComponentModulesForAllActivatedEntities(m_entityComponents);
  100. if (coveringModules.empty())
  101. {
  102. return;
  103. }
  104. contents = AZStd::string::format(
  105. "%s\n%s\n%s\n%s\n", m_parentScriptPath.c_str(), m_scriptPath.c_str(), m_testFixture.c_str(), m_testCase.c_str());
  106. for (const auto& coveringModule : coveringModules)
  107. {
  108. contents += AZStd::string::format("%s\n", coveringModule.c_str());
  109. }
  110. AZ::IO::SystemFile file;
  111. const AZStd::vector<char> bytes(contents.begin(), contents.end());
  112. if (!file.Open(
  113. m_coverageFile.c_str(),
  114. AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY))
  115. {
  116. AZ_Error(LogCallSite, false, "Couldn't open file '%s' for writing", m_coverageFile.c_str());
  117. return;
  118. }
  119. if (!file.Write(bytes.data(), bytes.size()))
  120. {
  121. AZ_Error(LogCallSite, false, "Couldn't write contents for file '%s'", m_coverageFile.c_str());
  122. return;
  123. }
  124. }
  125. void PythonCoverageEditorSystemComponent::EnumerateAllModuleComponents()
  126. {
  127. AZ::ModuleManagerRequestBus::Broadcast(
  128. &AZ::ModuleManagerRequestBus::Events::EnumerateModules,
  129. [this](const AZ::ModuleData& moduleData)
  130. {
  131. // We can only enumerate shared libs, static libs are invisible to us
  132. if (moduleData.GetDynamicModuleHandle())
  133. {
  134. for (const auto* moduleComponentDescriptor : moduleData.GetModule()->GetComponentDescriptors())
  135. {
  136. m_moduleComponents[moduleComponentDescriptor->GetUuid()] = moduleData.GetDebugName();
  137. }
  138. }
  139. return true;
  140. });
  141. }
  142. void PythonCoverageEditorSystemComponent::EnumerateComponentsForEntity(const AZ::EntityId& entityId)
  143. {
  144. AZ::Entity* entity = nullptr;
  145. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationBus::Events::FindEntity, AZ::EntityId(entityId));
  146. if (entity)
  147. {
  148. for (const auto& entityComponent : entity->GetComponents())
  149. {
  150. const auto componentTypeId = entityComponent->GetUnderlyingComponentType();
  151. AZ::ComponentDescriptor* componentDescriptor = nullptr;
  152. AZ::ComponentDescriptorBus::EventResult(
  153. componentDescriptor, componentTypeId, &AZ::ComponentDescriptorBus::Events::GetDescriptor);
  154. m_entityComponents[componentTypeId] = componentDescriptor;
  155. }
  156. }
  157. }
  158. AZStd::unordered_set<AZStd::string> PythonCoverageEditorSystemComponent::GetParentComponentModulesForAllActivatedEntities(
  159. const AZStd::unordered_map<AZ::Uuid, AZ::ComponentDescriptor*>& entityComponents) const
  160. {
  161. AZStd::unordered_set<AZStd::string> coveringModuleOutputNames;
  162. for (const auto& [uuid, componentDescriptor] : entityComponents)
  163. {
  164. if (const auto moduleComponent = m_moduleComponents.find(uuid); moduleComponent != m_moduleComponents.end())
  165. {
  166. coveringModuleOutputNames.insert(moduleComponent->second);
  167. }
  168. }
  169. return coveringModuleOutputNames;
  170. }
  171. AZStd::string CompileParentFolderName(const AZStd::string& parentScriptPath)
  172. {
  173. // Compile a unique folder name based on the parent script path
  174. auto parentfolder = parentScriptPath;
  175. AZ::StringFunc::Replace(parentfolder, '/', '_');
  176. AZ::StringFunc::Replace(parentfolder, '\\', '_');
  177. AZ::StringFunc::Replace(parentfolder, '.', '_');
  178. return parentfolder;
  179. }
  180. void PythonCoverageEditorSystemComponent::OnStartExecuteByFilenameAsTest(AZStd::string_view filename, AZStd::string_view testCase, [[maybe_unused]] const AZStd::vector<AZStd::string_view>& args)
  181. {
  182. if (m_coverageState == CoverageState::Disabled)
  183. {
  184. return;
  185. }
  186. if (m_coverageState == CoverageState::Gathering)
  187. {
  188. // Dump any existing coverage data to disk
  189. WriteCoverageFile();
  190. m_coverageState = CoverageState::Idle;
  191. }
  192. if (testCase.empty())
  193. {
  194. // We need to be able to pinpoint the coverage data to the specific test case names otherwise we will not be able
  195. // to specify which specific tests should be run in the future (filename does not necessarily equate to test case name)
  196. AZ_Error(LogCallSite, false, "No test case specified, coverage data gathering will be disabled for this test");
  197. return;
  198. }
  199. const auto matcherPattern = AZStd::regex("(.*)::(.*)::(.*)");
  200. const auto strTestCase = AZStd::string(testCase);
  201. AZStd::smatch testCaseMatches;
  202. if (!AZStd::regex_search(strTestCase, testCaseMatches, matcherPattern))
  203. {
  204. AZ_Error(
  205. LogCallSite,
  206. false,
  207. "The test case name '%s' did not comply to the format expected by the coverage gem "
  208. "'parent_script_path::fixture_name::test_case_name', coverage data gathering will be disabled for this test",
  209. strTestCase.c_str());
  210. return;
  211. }
  212. m_parentScriptPath = testCaseMatches[1];
  213. m_testFixture = testCaseMatches[2];
  214. m_testCase = testCaseMatches[3];
  215. m_entityComponents.clear();
  216. m_scriptPath = filename;
  217. const auto coverageFile = m_coverageDir / CompileParentFolderName(m_parentScriptPath) / AZStd::string::format("%s.pycoverage", m_testCase.c_str());
  218. #ifdef MAX_PATH
  219. if (strlen(coverageFile.c_str()) >= (MAX_PATH - 1))
  220. {
  221. AZ_Error(
  222. LogCallSite,
  223. false,
  224. "The generated python coverage file path '%s' is too long for the current file system to write. "
  225. "Use a shorter folder name or shorten the class name.",
  226. coverageFile.c_str());
  227. return;
  228. }
  229. #endif
  230. m_coverageFile = coverageFile;
  231. m_coverageState = CoverageState::Gathering;
  232. }
  233. } // namespace PythonCoverage