Provisional implementation of PythonCoverage gem

Signed-off-by: John <jonawals@amazon.com>
This commit is contained in:
John
2021-06-21 16:21:47 +01:00
parent cfe4a49136
commit 0e0f266fdd
59 changed files with 1077 additions and 8 deletions
@@ -0,0 +1,40 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "PythonCoverageEditorModule.h"
#include "PythonCoverageEditorSystemComponent.h"
namespace PythonCoverage
{
AZ_CLASS_ALLOCATOR_IMPL(PythonCoverageEditorModule, AZ::SystemAllocator, 0)
PythonCoverageEditorModule::PythonCoverageEditorModule()
: PythonCoverageModule()
{
// push results of [MyComponent]::CreateDescriptor() into m_descriptors here
m_descriptors.insert(
m_descriptors.end(),
{
PythonCoverageEditorSystemComponent::CreateDescriptor()
});
}
PythonCoverageEditorModule::~PythonCoverageEditorModule() = default;
AZ::ComponentTypeList PythonCoverageEditorModule::GetRequiredSystemComponents() const
{
// add required SystemComponents to the SystemEntity
return AZ::ComponentTypeList{ azrtti_typeid<PythonCoverageEditorSystemComponent>() };
}
} // namespace PythonCoverage
AZ_DECLARE_MODULE_CLASS(Gem_PythonCoverageEditor, PythonCoverage::PythonCoverageEditorModule)
@@ -0,0 +1,31 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include "PythonCoverageModule.h"
namespace PythonCoverage
{
class PythonCoverageEditorModule : public PythonCoverageModule
{
public:
AZ_CLASS_ALLOCATOR_DECL
AZ_RTTI(PythonCoverageEditorModule, "{32C0FFEA-09A7-460F-9257-5BDEF74FCD5B}", PythonCoverageModule);
PythonCoverageEditorModule();
~PythonCoverageEditorModule();
// PythonCoverageModule ...
AZ::ComponentTypeList GetRequiredSystemComponents() const override;
};
} // namespace WhiteBox
@@ -0,0 +1,228 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzCore/Module/ModuleManagerBus.h>
#include <AzCore/Module/Module.h>
#include <AzCore/Module/DynamicModuleHandle.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/IO/Path/Path.h>
#include <AzCore/JSON/document.h>
#include <PythonCoverageEditorSystemComponent.h>
#pragma optimize("", off)
namespace PythonCoverage
{
constexpr char* const Caller = "PythonCoverageEditorSystemComponent";
void PythonCoverageEditorSystemComponent::Reflect(AZ::ReflectContext* context)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<PythonCoverageEditorSystemComponent, AZ::Component>()->Version(1);
}
}
void PythonCoverageEditorSystemComponent::Activate()
{
AzToolsFramework::EditorPythonScriptNotificationsBus::Handler::BusConnect();
AZ::EntitySystemBus::Handler::BusConnect();
ParseCoverageOutputDirectory();
EnumerateAllModuleComponents();
}
void PythonCoverageEditorSystemComponent::Deactivate()
{
AZ::EntitySystemBus::Handler::BusDisconnect();
AzToolsFramework::EditorPythonScriptNotificationsBus::Handler::BusDisconnect();
}
void PythonCoverageEditorSystemComponent::OnEntityActivated(const AZ::EntityId& entityId)
{
EnumerateComponentsForEntity(entityId);
WriteCoverageFile();
}
void PythonCoverageEditorSystemComponent::ParseCoverageOutputDirectory()
{
m_coverageState = CoverageState::Disabled;
const AZStd::string configFilePath = LY_TEST_IMPACT_DEFAULT_CONFIG_FILE;
if (configFilePath.empty())
{
AZ_Warning(Caller, false, "No test impact analysis framework config found.");
return;
}
const auto fileSize = AZ::IO::SystemFile::Length(configFilePath.c_str());
if(!fileSize)
{
AZ_Error(Caller, false, "File %s does not exist", configFilePath.c_str());
return;
}
AZStd::vector<char> buffer(fileSize + 1);
buffer[fileSize] = '\0';
if (!AZ::IO::SystemFile::Read(configFilePath.c_str(), buffer.data()))
{
AZ_Error(Caller, false, "Could not read contents of file %s", configFilePath.c_str());
return;
}
const AZStd::string configurationData = AZStd::string(buffer.begin(), buffer.end());
rapidjson::Document configurationFile;
if (configurationFile.Parse(configurationData.c_str()).HasParseError())
{
AZ_Error(Caller, false, "Could not parse runtimeConfig data, JSON has errors");
return;
}
const AZ::IO::Path tempWorkspaceRootDir = configurationFile["workspace"]["temp"]["root"].GetString();
const AZ::IO::Path artifactRelativeDir = configurationFile["workspace"]["temp"]["relative_paths"]["artifact_dir"].GetString();
m_coverageDir = tempWorkspaceRootDir / artifactRelativeDir;
m_coverageState = CoverageState::Idle;
}
void PythonCoverageEditorSystemComponent::WriteCoverageFile()
{
// Yes, we're doing blocking file operations on the main thread... If this becomes an issue this can be offloaded
// to a worker thread
if (m_coverageState == CoverageState::Gathering)
{
AZStd::string contents;
for (const auto& [testCase, entityComponents] : m_entityComponentMap)
{
const auto coveringModules = GetParentComponentModulesForAllActivatedEntities(entityComponents);
if (coveringModules.empty())
{
return;
}
contents = testCase + "\n";
for (const auto& coveringModule : coveringModules)
{
contents += AZStd::string::format(" %s\n", coveringModule.c_str());
}
}
AZ::IO::SystemFile file;
const AZStd::vector<char> bytes(contents.begin(), contents.end());
if (!file.Open(
m_coverageFile.c_str(),
AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY))
{
AZ_Error(
Caller, false,
"Couldn't open file %s for writing", m_coverageFile.c_str());
return;
}
if (!file.Write(bytes.data(), bytes.size()))
{
AZ_Error(
Caller, false,
"Couldn't write contents for file %s", m_coverageFile.c_str());
return;
}
}
}
void PythonCoverageEditorSystemComponent::EnumerateAllModuleComponents()
{
AZ::ModuleManagerRequestBus::Broadcast(
&AZ::ModuleManagerRequestBus::Events::EnumerateModules,
[this](const AZ::ModuleData& moduleData)
{
const AZStd::string moduleName = moduleData.GetDebugName();
if (moduleData.GetDynamicModuleHandle())
{
const auto fileName = moduleData.GetDynamicModuleHandle()->GetFilename();
for (const auto* moduleComponentDescriptor : moduleData.GetModule()->GetComponentDescriptors())
{
m_moduleComponents[moduleComponentDescriptor->GetUuid()] = moduleData.GetDebugName();
}
}
return true;
});
}
void PythonCoverageEditorSystemComponent::EnumerateComponentsForEntity(const AZ::EntityId& entityId)
{
AZ::Entity* entity = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationBus::Events::FindEntity, AZ::EntityId(entityId));
if (entity)
{
auto& entityComponents = m_entityComponentMap[m_testCase];
for (const auto& entityComponent : entity->GetComponents())
{
const auto componentTypeId = entityComponent->GetUnderlyingComponentType();
AZ::ComponentDescriptor* componentDescriptor = nullptr;
AZ::ComponentDescriptorBus::EventResult(
componentDescriptor, componentTypeId, &AZ::ComponentDescriptorBus::Events::GetDescriptor);
entityComponents[componentTypeId] = componentDescriptor;
}
}
}
AZStd::unordered_set<AZStd::string> PythonCoverageEditorSystemComponent::GetParentComponentModulesForAllActivatedEntities(
const AZStd::unordered_map<AZ::Uuid, AZ::ComponentDescriptor*>& entityComponents) const
{
AZStd::unordered_set<AZStd::string> coveringModuleOutputNames;
for (const auto& [uuid, componentDescriptor] : entityComponents)
{
if (const auto moduleComponent = m_moduleComponents.find(uuid); moduleComponent != m_moduleComponents.end())
{
coveringModuleOutputNames.insert(moduleComponent->second);
}
}
return coveringModuleOutputNames;
}
void PythonCoverageEditorSystemComponent::OnExecuteByFilenameAsTest(AZStd::string_view filename, AZStd::string_view testCase, [[maybe_unused]] const AZStd::vector<AZStd::string_view>& args)
{
if (m_coverageState == CoverageState::Disabled)
{
return;
}
if (m_coverageState == CoverageState::Gathering)
{
// Dump any existing coverage data to disk
WriteCoverageFile();
m_coverageState = CoverageState::Idle;
}
if (testCase.empty())
{
// We need to be able to pinpoint the coverage data to the specific test case names otherwise we will not be able
// to specify which specific tests should be run in the future (filename does not necessarily equate to test case name)
AZ_Error(Caller, false, "No test case specified, coverage data gathering will be disabled for this test");
return;
}
const AZStd::string scriptName = AZ::IO::Path(filename).Stem().Native();
const auto coverageFile = m_coverageDir / AZStd::string::format("%s.pycoverage", scriptName.c_str());
// If this is a different python script we clear the existing entity components and start afresh
if (m_coverageFile != coverageFile)
{
m_entityComponentMap.clear();
m_coverageFile = coverageFile;
}
m_testCase = testCase;
m_coverageState = CoverageState::Gathering;
}
} // namespace PythonCoverage
@@ -0,0 +1,87 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/Component.h>
#include <AzCore/Component/EntityBus.h>
#include <AzCore/IO/Path/Path.h>
#include <AzCore/std/optional.h>
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
#include <AzToolsFramework/API/EditorPythonScriptNotificationsBus.h>
namespace AZ
{
class ComponentDescriptor;
}
namespace PythonCoverage
{
//! System component for PythonCoverage editor.
class PythonCoverageEditorSystemComponent
: public AZ::Component
, private AZ::EntitySystemBus::Handler
, private AzToolsFramework::EditorPythonScriptNotificationsBus::Handler
{
public:
AZ_COMPONENT(PythonCoverageEditorSystemComponent, "{33370075-3aea-49c4-823d-476f8ac95b6f}");
static void Reflect(AZ::ReflectContext* context);
PythonCoverageEditorSystemComponent() = default;
private:
// AZ::Component
void Activate() override;
void Deactivate() override;
// AZ::EntitySystemBus ...
void OnEntityActivated(const AZ::EntityId& entityId) override;
// AZ::EditorPythonScriptNotificationsBus ...
void OnExecuteByFilenameAsTest(AZStd::string_view filename, AZStd::string_view testCase, const AZStd::vector<AZStd::string_view>& args) override;
//! Attempts to parse the test impact analysis framework configuration file.
//! If either the test impact analysis framework is disabled or the configuration file cannot be parsed, python coverage
//! is disabled.
void ParseCoverageOutputDirectory();
//! Enumerates all of the loaded shared library modules and the component descriptors that belong to them.
void EnumerateAllModuleComponents();
//! Enumerates all of the component descriptors for the specified entity.
void EnumerateComponentsForEntity(const AZ::EntityId& entityId);
//! Returns all of the shared library modules that parent the component descriptors of the specified set of activated entities.
//! @note Entity component descriptors are still retrieved even if the entity in question has since been deactivated.
//! @param entityComponents The set of activated entities and their component descriptors to get the parent modules for.
AZStd::unordered_set<AZStd::string> GetParentComponentModulesForAllActivatedEntities(
const AZStd::unordered_map<AZ::Uuid, AZ::ComponentDescriptor*>& entityComponents) const;
//!
void WriteCoverageFile();
enum class CoverageState : AZ::u8
{
Disabled, //!< Python coverage is disabled.
Idle, //!< Python coverage is enabled but not actively gathering coverage data.
Gathering //!< Python coverage is enabled and actively gathering coverage data.
};
CoverageState m_coverageState = CoverageState::Disabled; //!< Current coverage state.
AZStd::unordered_map<AZStd::string, AZStd::unordered_map<AZ::Uuid, AZ::ComponentDescriptor*>> m_entityComponentMap; //!< Map of
//!< component IDs to component descriptors for all activated entities, organized by test cases.
AZStd::unordered_map<AZ::Uuid, AZStd::string> m_moduleComponents; //!< Map of component IDs to module names for all modules.
AZ::IO::Path m_coverageDir; //!< Directory to write coverage data to.
AZ::IO::Path m_coverageFile; //!< Full file path to write coverage data to.
AZStd::string m_testCase; //!< Name of current test case that coverage data is being gathered for.
};
} // namespace PythonCoverage
@@ -0,0 +1,26 @@
#include <PythonCoverageModule.h>
#pragma optimize("", off)
namespace PythonCoverage
{
PythonCoverageModule::PythonCoverageModule()
: AZ::Module()
{
// Push results of [MyComponent]::CreateDescriptor() into m_descriptors here.
m_descriptors.insert(
m_descriptors.end(),
{ PythonCoverageSystemComponent::CreateDescriptor() });
}
AZ::ComponentTypeList PythonCoverageModule::GetRequiredSystemComponents() const
{
return AZ::ComponentTypeList{
azrtti_typeid<PythonCoverageSystemComponent>(),
};
}
}// namespace PythonCoverage
#if !defined(PYTHON_COVERAGE_EDITOR)
AZ_DECLARE_MODULE_CLASS(Gem_PythonCoverage, PythonCoverage::PythonCoverageModule)
#endif // !defined(PYTHON_COVERAGE_EDITOR)
@@ -0,0 +1,26 @@
#include <AzCore/Memory/SystemAllocator.h>
#include <AzCore/Module/Module.h>
#include <PythonCoverageSystemComponent.h>
#pragma once
#pragma optimize("", off)
namespace PythonCoverage
{
class PythonCoverageModule : public AZ::Module
{
public:
AZ_RTTI(PythonCoverageModule, "{dc706de0-22c4-4b05-9b99-438692afc082}", AZ::Module);
AZ_CLASS_ALLOCATOR(PythonCoverageModule, AZ::SystemAllocator, 0);
PythonCoverageModule();
/**
* Add required SystemComponents to the SystemEntity.
*/
AZ::ComponentTypeList GetRequiredSystemComponents() const override;
};
} // namespace PythonCoverage
@@ -0,0 +1,70 @@
#include <PythonCoverageSystemComponent.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/Serialization/EditContextConstants.inl>
namespace PythonCoverage
{
void PythonCoverageSystemComponent::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context))
{
serialize->Class<PythonCoverageSystemComponent, AZ::Component>()
->Version(0)
;
if (AZ::EditContext* ec = serialize->GetEditContext())
{
ec->Class<PythonCoverageSystemComponent>("PythonCoverage", "[Description of functionality provided by this System Component]")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System"))
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
;
}
}
}
void PythonCoverageSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("PythonCoverageService"));
}
void PythonCoverageSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("PythonCoverageService"));
}
void PythonCoverageSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
AZ_UNUSED(required);
}
void PythonCoverageSystemComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent)
{
AZ_UNUSED(dependent);
}
void PythonCoverageSystemComponent::Init()
{
}
void PythonCoverageSystemComponent::Activate()
{
PythonCoverageRequestBus::Handler::BusConnect();
AZ::TickBus::Handler::BusConnect();
}
void PythonCoverageSystemComponent::Deactivate()
{
AZ::TickBus::Handler::BusDisconnect();
PythonCoverageRequestBus::Handler::BusDisconnect();
}
void PythonCoverageSystemComponent::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/)
{
}
} // namespace PythonCoverage
@@ -0,0 +1,44 @@
#pragma once
#include <AzCore/Component/Component.h>
#include <AzCore/Component/TickBus.h>
#include <PythonCoverage/PythonCoverageBus.h>
namespace PythonCoverage
{
class PythonCoverageSystemComponent
: public AZ::Component
, protected PythonCoverageRequestBus::Handler
, public AZ::TickBus::Handler
{
public:
AZ_COMPONENT(PythonCoverageSystemComponent, "{b2f692ae-1047-4a6d-a4ed-27b1aac40ba5}");
static void Reflect(AZ::ReflectContext* context);
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided);
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible);
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required);
static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent);
protected:
////////////////////////////////////////////////////////////////////////
// PythonCoverageRequestBus interface implementation
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// AZ::Component interface implementation
void Init() override;
void Activate() override;
void Deactivate() override;
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// AZTickBus interface implementation
void OnTick(float deltaTime, AZ::ScriptTimePoint time) override;
////////////////////////////////////////////////////////////////////////
};
} // namespace PythonCoverage