diff --git a/Tms.Adapter.Core/Configurator/Configurator.cs b/Tms.Adapter.Core/Configurator/Configurator.cs index 4d4545c..3d55deb 100644 --- a/Tms.Adapter.Core/Configurator/Configurator.cs +++ b/Tms.Adapter.Core/Configurator/Configurator.cs @@ -15,7 +15,8 @@ public static class Configurator private const string TmsAutomaticCreationTestCases = "TMS_AUTOMATIC_CREATION_TEST_CASES"; private const string TmsCertValidation = "TMS_CERT_VALIDATION"; private const string ConfigFile = "TMS_CONFIG_FILE"; - + private static readonly JsonSerializerOptions SerializerOptions = new() { PropertyNameCaseInsensitive = true }; + public static TmsSettings GetConfig() { var config = new TmsSettings @@ -28,12 +29,7 @@ public static TmsSettings GetConfig() if (File.Exists(defaultJsonConfigPath)) { - var options = new JsonSerializerOptions - { - PropertyNameCaseInsensitive = true - }; - - var fileConfig = JsonSerializer.Deserialize(File.ReadAllText(defaultJsonConfigPath), options); + var fileConfig = JsonSerializer.Deserialize(File.ReadAllText(defaultJsonConfigPath), SerializerOptions); if (fileConfig != null) { @@ -58,10 +54,10 @@ private static string GetConfigFileName() return envConfigFileName ?? DefaultFileName; } - private static TmsSettings ApplyEnv(TmsSettings settings) + private static void ApplyEnv(TmsSettings settings) { var url = Environment.GetEnvironmentVariable(TmsUrl); - if (Uri.IsWellFormedUriString(url, UriKind.Absolute)) + if (!string.IsNullOrWhiteSpace(url) && Uri.IsWellFormedUriString(url, UriKind.Absolute)) { settings.Url = url; } @@ -73,19 +69,19 @@ private static TmsSettings ApplyEnv(TmsSettings settings) } var projectId = Environment.GetEnvironmentVariable(TmsProjectId); - if (Guid.TryParse(projectId, out var _)) + if (!string.IsNullOrWhiteSpace(projectId) && Guid.TryParse(projectId, out _)) { settings.ProjectId = projectId; } var configurationId = Environment.GetEnvironmentVariable(TmsConfigurationId); - if (Guid.TryParse(configurationId, out var _)) + if (!string.IsNullOrWhiteSpace(configurationId) && Guid.TryParse(configurationId, out _)) { settings.ConfigurationId = configurationId; } var testRunId = Environment.GetEnvironmentVariable(TmsTestRunId); - if (Guid.TryParse(testRunId, out var _)) + if (!string.IsNullOrWhiteSpace(testRunId) && Guid.TryParse(testRunId, out _)) { settings.TestRunId = testRunId; } @@ -106,8 +102,6 @@ private static TmsSettings ApplyEnv(TmsSettings settings) { settings.CertValidation = false; } - - return settings; } private static void Validate(TmsSettings settings) @@ -123,23 +117,25 @@ private static void Validate(TmsSettings settings) throw new ConfigurationErrorsException("Private token is invalid"); } - if (!Guid.TryParse(settings.ProjectId, out var _)) + if (!Guid.TryParse(settings.ProjectId, out _)) { throw new ConfigurationErrorsException("Project id is invalid"); } - if (!Guid.TryParse(settings.ConfigurationId, out var _)) + if (!Guid.TryParse(settings.ConfigurationId, out _)) { throw new ConfigurationErrorsException("Configuration id is invalid"); } - if (!string.IsNullOrWhiteSpace(settings.TestRunId)) + if (string.IsNullOrWhiteSpace(settings.TestRunId)) { - if (!Guid.TryParse(settings.TestRunId, out var _)) - { - throw new ConfigurationErrorsException( - "Config contains not valid test run id."); - } + return; + } + + if (!Guid.TryParse(settings.TestRunId, out _)) + { + throw new ConfigurationErrorsException( + "Config contains not valid test run id."); } } } \ No newline at end of file diff --git a/Tms.Adapter.Core/Models/FixtureResult.cs b/Tms.Adapter.Core/Models/FixtureResult.cs index cbbdb4c..11beda4 100644 --- a/Tms.Adapter.Core/Models/FixtureResult.cs +++ b/Tms.Adapter.Core/Models/FixtureResult.cs @@ -2,5 +2,4 @@ namespace Tms.Adapter.Core.Models; public class FixtureResult : ExecutableItem { - } \ No newline at end of file diff --git a/Tms.Adapter.Core/Models/StepResult.cs b/Tms.Adapter.Core/Models/StepResult.cs index 20f52da..ebecf20 100644 --- a/Tms.Adapter.Core/Models/StepResult.cs +++ b/Tms.Adapter.Core/Models/StepResult.cs @@ -2,5 +2,4 @@ namespace Tms.Adapter.Core.Models; public class StepResult: ExecutableItem { - } \ No newline at end of file diff --git a/Tms.Adapter.CoreTests/Tms.Adapter.CoreTests.csproj b/Tms.Adapter.CoreTests/Tms.Adapter.CoreTests.csproj index 8641626..0080ab2 100644 --- a/Tms.Adapter.CoreTests/Tms.Adapter.CoreTests.csproj +++ b/Tms.Adapter.CoreTests/Tms.Adapter.CoreTests.csproj @@ -36,4 +36,8 @@ + + + + diff --git a/Tms.Adapter.CoreTests/Usings.cs b/Tms.Adapter.CoreTests/Usings.cs deleted file mode 100644 index ab67c7e..0000000 --- a/Tms.Adapter.CoreTests/Usings.cs +++ /dev/null @@ -1 +0,0 @@ -global using Microsoft.VisualStudio.TestTools.UnitTesting; \ No newline at end of file diff --git a/Tms.Adapter.SpecFlowPlugin/LinkItem.cs b/Tms.Adapter.SpecFlowPlugin/LinkItem.cs index 2da54d6..d950e27 100644 --- a/Tms.Adapter.SpecFlowPlugin/LinkItem.cs +++ b/Tms.Adapter.SpecFlowPlugin/LinkItem.cs @@ -1,10 +1,9 @@ -namespace Tms.Adapter.SpecFlowPlugin +namespace Tms.Adapter.SpecFlowPlugin; + +internal class LinkItem { - internal class LinkItem - { - public string? Title { get; set; } - public string Url { get; set; } - public string? Description { get; set; } - public string? Type { get; set; } - } + public string? Title { get; set; } + public string Url { get; set; } + public string? Description { get; set; } + public string? Type { get; set; } } \ No newline at end of file diff --git a/Tms.Adapter.SpecFlowPlugin/TmsBindingInvoker.cs b/Tms.Adapter.SpecFlowPlugin/TmsBindingInvoker.cs index abaade1..6b2a8d3 100644 --- a/Tms.Adapter.SpecFlowPlugin/TmsBindingInvoker.cs +++ b/Tms.Adapter.SpecFlowPlugin/TmsBindingInvoker.cs @@ -7,195 +7,194 @@ using Tms.Adapter.Core.Service; using Tms.Adapter.Core.Utils; -namespace Tms.Adapter.SpecFlowPlugin +namespace Tms.Adapter.SpecFlowPlugin; + +public class TmsBindingInvoker : BindingInvoker { - public class TmsBindingInvoker : BindingInvoker - { - private static readonly AdapterManager Adapter = AdapterManager.Instance; + private static readonly AdapterManager Adapter = AdapterManager.Instance; - public TmsBindingInvoker(SpecFlowConfiguration specFlowConfiguration, IErrorProvider errorProvider, - ISynchronousBindingDelegateInvoker synchronousBindingDelegateInvoker) : base( - specFlowConfiguration, errorProvider, synchronousBindingDelegateInvoker) - { - } + public TmsBindingInvoker(SpecFlowConfiguration specFlowConfiguration, IErrorProvider errorProvider, + ISynchronousBindingDelegateInvoker synchronousBindingDelegateInvoker) : base( + specFlowConfiguration, errorProvider, synchronousBindingDelegateInvoker) + { + } - public override object InvokeBinding(IBinding binding, IContextManager contextManager, object[] arguments, - ITestTracer testTracer, - out TimeSpan duration) - { - if (binding is not HookBinding hook) - return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); + public override object InvokeBinding(IBinding binding, IContextManager contextManager, object[] arguments, + ITestTracer testTracer, + out TimeSpan duration) + { + if (binding is not HookBinding hook) + return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); - var featureContainerId = TmsHelper.GetFeatureContainerId(contextManager.FeatureContext?.FeatureInfo); + var featureContainerId = TmsHelper.GetFeatureContainerId(contextManager.FeatureContext?.FeatureInfo); - switch (hook.HookType) - { - case HookType.BeforeFeature: - if (hook.HookOrder == int.MinValue) + switch (hook.HookType) + { + case HookType.BeforeFeature: + if (hook.HookOrder == int.MinValue) + { + var featureContainer = new ClassContainer { - var featureContainer = new ClassContainer - { - Id = TmsHelper.GetFeatureContainerId(contextManager.FeatureContext?.FeatureInfo) - }; - Adapter.StartTestContainer(featureContainer); + Id = TmsHelper.GetFeatureContainerId(contextManager.FeatureContext?.FeatureInfo) + }; + Adapter.StartTestContainer(featureContainer); - contextManager.FeatureContext.Set(new HashSet()); - contextManager.FeatureContext.Set(new HashSet()); + contextManager.FeatureContext.Set(new HashSet()); + contextManager.FeatureContext.Set(new HashSet()); - return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); - } + return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); + } - try - { - StartFixture(hook, featureContainerId); - var result = base.InvokeBinding(binding, contextManager, arguments, testTracer, - out duration); - Adapter.StopFixture(x => x.Status = Status.Passed); - return result; - } - catch (Exception ex) - { - Adapter.StopFixture(x => x.Status = Status.Failed); + try + { + StartFixture(hook, featureContainerId); + var result = base.InvokeBinding(binding, contextManager, arguments, testTracer, + out duration); + Adapter.StopFixture(x => x.Status = Status.Passed); + return result; + } + catch (Exception ex) + { + Adapter.StopFixture(x => x.Status = Status.Failed); + + var scenarioContainer = + TmsHelper.StartTestContainer(contextManager.FeatureContext, null); - var scenarioContainer = - TmsHelper.StartTestContainer(contextManager.FeatureContext, null); + var scenario = TmsHelper.StartTestCase(scenarioContainer.Id, + contextManager.FeatureContext, null); - var scenario = TmsHelper.StartTestCase(scenarioContainer.Id, - contextManager.FeatureContext, null); + Adapter + .StopTestCase(x => + { + x.Status = Status.Failed; + x.Message = ex.Message; + x.Trace = ex.StackTrace; + }) + .StopTestContainer(scenarioContainer.Id) + .WriteTestCase(scenario.Id, scenarioContainer.Id); + + throw; + } - Adapter - .StopTestCase(x => + case HookType.BeforeStep: + case HookType.AfterStep: + { + var scenario = TmsHelper.GetCurrentTestCase(contextManager.ScenarioContext); + + try + { + return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); + } + catch (Exception ex) + { + Adapter + .UpdateTestCase(scenario.Id, + x => { x.Status = Status.Failed; x.Message = ex.Message; x.Trace = ex.StackTrace; - }) - .StopTestContainer(scenarioContainer.Id) - .WriteTestCase(scenario.Id, scenarioContainer.Id); + }); + throw; + } + } - throw; - } + case HookType.BeforeScenario: + case HookType.AfterScenario: + if (hook.HookOrder == int.MinValue || hook.HookOrder == int.MaxValue) + { + return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); + } - case HookType.BeforeStep: - case HookType.AfterStep: + { + var scenarioContainer = TmsHelper.GetCurrentTestContainer(contextManager.ScenarioContext); + + try { + StartFixture(hook, scenarioContainer.Id); + var result = base.InvokeBinding(binding, contextManager, arguments, testTracer, + out duration); + Adapter.StopFixture(x => x.Status = Status.Passed); + return result; + } + catch (Exception ex) + { + Adapter.StopFixture(x => x.Status = Status.Failed); + var scenario = TmsHelper.GetCurrentTestCase(contextManager.ScenarioContext); - try - { - return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); - } - catch (Exception ex) - { - Adapter - .UpdateTestCase(scenario.Id, - x => - { - x.Status = Status.Failed; - x.Message = ex.Message; - x.Trace = ex.StackTrace; - }); - throw; - } + Adapter.UpdateTestCase(scenario.Id, + x => + { + x.Status = Status.Failed; + x.Message = ex.Message; + x.Trace = ex.StackTrace; + }); + throw; } + } - case HookType.BeforeScenario: - case HookType.AfterScenario: - if (hook.HookOrder == int.MinValue || hook.HookOrder == int.MaxValue) - { - return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); - } - + case HookType.AfterFeature: + if (hook.HookOrder == int.MaxValue) { - var scenarioContainer = TmsHelper.GetCurrentTestContainer(contextManager.ScenarioContext); - - try - { - StartFixture(hook, scenarioContainer.Id); - var result = base.InvokeBinding(binding, contextManager, arguments, testTracer, - out duration); - Adapter.StopFixture(x => x.Status = Status.Passed); - return result; - } - catch (Exception ex) - { - Adapter.StopFixture(x => x.Status = Status.Failed); + WriteScenarios(contextManager); - var scenario = TmsHelper.GetCurrentTestCase(contextManager.ScenarioContext); + return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); + } - Adapter.UpdateTestCase(scenario.Id, + try + { + StartFixture(hook, featureContainerId); + var result = base.InvokeBinding(binding, contextManager, arguments, testTracer, + out duration); + Adapter.StopFixture(x => x.Status = Status.Passed); + return result; + } + catch (Exception ex) + { + var scenario = contextManager.FeatureContext.Get>().Last(); + Adapter + .StopFixture(x => x.Status = Status.Failed) + .UpdateTestCase(scenario.Id, x => { x.Status = Status.Failed; x.Message = ex.Message; x.Trace = ex.StackTrace; }); - throw; - } - } - case HookType.AfterFeature: - if (hook.HookOrder == int.MaxValue) - { - WriteScenarios(contextManager); + WriteScenarios(contextManager); - return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); - } + throw; + } - try - { - StartFixture(hook, featureContainerId); - var result = base.InvokeBinding(binding, contextManager, arguments, testTracer, - out duration); - Adapter.StopFixture(x => x.Status = Status.Passed); - return result; - } - catch (Exception ex) - { - var scenario = contextManager.FeatureContext.Get>().Last(); - Adapter - .StopFixture(x => x.Status = Status.Failed) - .UpdateTestCase(scenario.Id, - x => - { - x.Status = Status.Failed; - x.Message = ex.Message; - x.Trace = ex.StackTrace; - }); - - WriteScenarios(contextManager); - - throw; - } - - case HookType.BeforeScenarioBlock: - case HookType.AfterScenarioBlock: - case HookType.BeforeTestRun: - case HookType.AfterTestRun: - default: - return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); - } + case HookType.BeforeScenarioBlock: + case HookType.AfterScenarioBlock: + case HookType.BeforeTestRun: + case HookType.AfterTestRun: + default: + return base.InvokeBinding(binding, contextManager, arguments, testTracer, out duration); } + } - private static void StartFixture(HookBinding hook, string containerId) - { - if (hook.HookType.ToString().StartsWith("Before")) - Adapter.StartBeforeFixture(containerId, Hash.NewId(), TmsHelper.GetFixtureResult(hook)); - else - Adapter.StartAfterFixture(containerId, Hash.NewId(), TmsHelper.GetFixtureResult(hook)); - } + private static void StartFixture(HookBinding hook, string containerId) + { + if (hook.HookType.ToString().StartsWith("Before")) + Adapter.StartBeforeFixture(containerId, Hash.NewId(), TmsHelper.GetFixtureResult(hook)); + else + Adapter.StartAfterFixture(containerId, Hash.NewId(), TmsHelper.GetFixtureResult(hook)); + } - private static void WriteScenarios(IContextManager contextManager) + private static void WriteScenarios(IContextManager contextManager) + { + foreach (var c in contextManager.FeatureContext.Get>()) { - foreach (var c in contextManager.FeatureContext.Get>()) - { - var testContainer = contextManager.FeatureContext - .Get>().FirstOrDefault(t => c.Children.Contains(t.Id)); + var testContainer = contextManager.FeatureContext + .Get>().FirstOrDefault(t => c.Children.Contains(t.Id)); - Adapter - .StopTestContainer(c.Id) - .WriteTestCase(testContainer?.Id, c.Id); - } + Adapter + .StopTestContainer(c.Id) + .WriteTestCase(testContainer?.Id, c.Id); } } } \ No newline at end of file diff --git a/Tms.Adapter.SpecFlowPlugin/TmsBindings.cs b/Tms.Adapter.SpecFlowPlugin/TmsBindings.cs index 438b658..bd71e21 100644 --- a/Tms.Adapter.SpecFlowPlugin/TmsBindings.cs +++ b/Tms.Adapter.SpecFlowPlugin/TmsBindings.cs @@ -2,66 +2,65 @@ using Tms.Adapter.Core.Models; using Tms.Adapter.Core.Service; -namespace Tms.Adapter.SpecFlowPlugin +namespace Tms.Adapter.SpecFlowPlugin; + +[Binding] +public class TmsBindings { - [Binding] - public class TmsBindings - { - private static readonly AdapterManager Adapter = AdapterManager.Instance; + private static readonly AdapterManager Adapter = AdapterManager.Instance; - private readonly FeatureContext _featureContext; - private readonly ScenarioContext _scenarioContext; + private readonly FeatureContext _featureContext; + private readonly ScenarioContext _scenarioContext; - public TmsBindings(FeatureContext featureContext, ScenarioContext scenarioContext) - { - _featureContext = featureContext; - _scenarioContext = scenarioContext; - } + public TmsBindings(FeatureContext featureContext, ScenarioContext scenarioContext) + { + _featureContext = featureContext; + _scenarioContext = scenarioContext; + } - [BeforeTestRun] - public static void BeforeTestRun() - { - Adapter.CreateTestRun().Wait(); - } + [BeforeTestRun] + public static void BeforeTestRun() + { + Adapter.CreateTestRun().Wait(); + } - [AfterTestRun] - public static void AfterTestRun() - { - Adapter.CompleteTestRun().Wait(); - } + [AfterTestRun] + public static void AfterTestRun() + { + Adapter.CompleteTestRun().Wait(); + } - [BeforeFeature(Order = int.MinValue)] - public static void FirstBeforeFeature() - { - } + [BeforeFeature(Order = int.MinValue)] + public static void FirstBeforeFeature() + { + } - [AfterFeature(Order = int.MaxValue)] - public static void LastAfterFeature() - { - } + [AfterFeature(Order = int.MaxValue)] + public static void LastAfterFeature() + { + } - [BeforeScenario(Order = int.MinValue)] - public void FirstBeforeScenario() - { - TmsHelper.StartTestContainer(_featureContext, _scenarioContext); - } + [BeforeScenario(Order = int.MinValue)] + public void FirstBeforeScenario() + { + TmsHelper.StartTestContainer(_featureContext, _scenarioContext); + } - [BeforeScenario(Order = int.MaxValue)] - public void LastBeforeScenario() - { - var scenarioContainer = TmsHelper.GetCurrentTestContainer(_scenarioContext); - TmsHelper.StartTestCase(scenarioContainer.Id, _featureContext, _scenarioContext); - } + [BeforeScenario(Order = int.MaxValue)] + public void LastBeforeScenario() + { + var scenarioContainer = TmsHelper.GetCurrentTestContainer(_scenarioContext); + TmsHelper.StartTestCase(scenarioContainer.Id, _featureContext, _scenarioContext); + } - [AfterScenario(Order = int.MinValue)] - public void FirstAfterScenario() - { - var scenarioId = TmsHelper.GetCurrentTestCase(_scenarioContext).Id; + [AfterScenario(Order = int.MinValue)] + public void FirstAfterScenario() + { + var scenarioId = TmsHelper.GetCurrentTestCase(_scenarioContext).Id; - Adapter - .UpdateTestCase(scenarioId, - x => x.Status = x.Status == Status.Undefined ? Status.Passed : x.Status) - .StopTestCase(scenarioId); - } + Adapter + .UpdateTestCase(scenarioId, + x => x.Status = x.Status == Status.Undefined ? Status.Passed : x.Status) + .StopTestCase(scenarioId); } } \ No newline at end of file diff --git a/Tms.Adapter.SpecFlowPlugin/TmsHelper.cs b/Tms.Adapter.SpecFlowPlugin/TmsHelper.cs index f129d9a..a5fbf5c 100644 --- a/Tms.Adapter.SpecFlowPlugin/TmsHelper.cs +++ b/Tms.Adapter.SpecFlowPlugin/TmsHelper.cs @@ -6,92 +6,91 @@ using Tms.Adapter.Core.Service; using Tms.Adapter.Core.Utils; -namespace Tms.Adapter.SpecFlowPlugin +namespace Tms.Adapter.SpecFlowPlugin; + +public static class TmsHelper { - public static class TmsHelper - { - private static readonly FeatureInfo EmptyFeatureInfo = new FeatureInfo( - CultureInfo.CurrentCulture, string.Empty, string.Empty, string.Empty); + private static readonly FeatureInfo EmptyFeatureInfo = new FeatureInfo( + CultureInfo.CurrentCulture, string.Empty, string.Empty, string.Empty); - private static readonly ScenarioInfo EmptyScenarioInfo = - new ScenarioInfo("Unknown", string.Empty, Array.Empty(), new OrderedDictionary()); + private static readonly ScenarioInfo EmptyScenarioInfo = + new ScenarioInfo("Unknown", string.Empty, Array.Empty(), new OrderedDictionary()); - internal static FixtureResult GetFixtureResult(HookBinding hook) + internal static FixtureResult GetFixtureResult(HookBinding hook) + { + return new FixtureResult { - return new FixtureResult - { - DisplayName = $"{hook.Method.Name} [{hook.HookOrder}]" - }; - } + DisplayName = $"{hook.Method.Name} [{hook.HookOrder}]" + }; + } - internal static string GetFeatureContainerId(FeatureInfo featureInfo) - { - var id = featureInfo != null - ? featureInfo.GetHashCode().ToString() - : EmptyFeatureInfo.GetHashCode().ToString(); + internal static string GetFeatureContainerId(FeatureInfo featureInfo) + { + var id = featureInfo != null + ? featureInfo.GetHashCode().ToString() + : EmptyFeatureInfo.GetHashCode().ToString(); - return id; - } + return id; + } + + internal static ClassContainer StartTestContainer(FeatureContext featureContext, + ScenarioContext scenarioContext) + { + var containerId = GetFeatureContainerId(featureContext?.FeatureInfo); - internal static ClassContainer StartTestContainer(FeatureContext featureContext, - ScenarioContext scenarioContext) + var scenarioContainer = new ClassContainer { - var containerId = GetFeatureContainerId(featureContext?.FeatureInfo); + Id = Hash.NewId() + }; + AdapterManager.Instance.StartTestContainer(containerId, scenarioContainer); + scenarioContext?.Set(scenarioContainer); + featureContext?.Get>().Add(scenarioContainer); - var scenarioContainer = new ClassContainer - { - Id = Hash.NewId() - }; - AdapterManager.Instance.StartTestContainer(containerId, scenarioContainer); - scenarioContext?.Set(scenarioContainer); - featureContext?.Get>().Add(scenarioContainer); + return scenarioContainer; + } - return scenarioContainer; - } + internal static TestContainer StartTestCase(string containerId, FeatureContext featureContext, + ScenarioContext scenarioContext) + { + var featureInfo = featureContext?.FeatureInfo ?? EmptyFeatureInfo; + var scenarioInfo = scenarioContext?.ScenarioInfo ?? EmptyScenarioInfo; - internal static TestContainer StartTestCase(string containerId, FeatureContext featureContext, - ScenarioContext scenarioContext) + var parameters = GetParameters(scenarioInfo); + var testResult = new TestContainer { - var featureInfo = featureContext?.FeatureInfo ?? EmptyFeatureInfo; - var scenarioInfo = scenarioContext?.ScenarioInfo ?? EmptyScenarioInfo; - - var parameters = GetParameters(scenarioInfo); - var testResult = new TestContainer - { - Id = Hash.NewId(), - Parameters = parameters - }; - testResult = TmsTagParser.AddTags(testResult, featureInfo, scenarioInfo, parameters); + Id = Hash.NewId(), + Parameters = parameters + }; + testResult = TmsTagParser.AddTags(testResult, featureInfo, scenarioInfo, parameters); - AdapterManager.Instance.StartTestCase(containerId, testResult); - scenarioContext?.Set(testResult); - featureContext?.Get>().Add(testResult); + AdapterManager.Instance.StartTestCase(containerId, testResult); + scenarioContext?.Set(testResult); + featureContext?.Get>().Add(testResult); - return testResult; - } + return testResult; + } - private static Dictionary GetParameters(ScenarioInfo scenarioInfo) + private static Dictionary GetParameters(ScenarioInfo scenarioInfo) + { + var parameters = new Dictionary(); + var argumentsEnumerator = scenarioInfo.Arguments.GetEnumerator(); + while (argumentsEnumerator.MoveNext()) { - var parameters = new Dictionary(); - var argumentsEnumerator = scenarioInfo.Arguments.GetEnumerator(); - while (argumentsEnumerator.MoveNext()) - { - parameters.Add(key: argumentsEnumerator.Key.ToString(), value: argumentsEnumerator.Value.ToString()); - } - - return parameters; + parameters.Add(key: argumentsEnumerator.Key.ToString(), value: argumentsEnumerator.Value.ToString()); } - internal static TestContainer GetCurrentTestCase(ScenarioContext context) - { - context.TryGetValue(out TestContainer testContainer); - return testContainer; - } + return parameters; + } - internal static ClassContainer GetCurrentTestContainer(ScenarioContext context) - { - context.TryGetValue(out ClassContainer classContainer); - return classContainer; - } + internal static TestContainer GetCurrentTestCase(ScenarioContext context) + { + context.TryGetValue(out TestContainer testContainer); + return testContainer; + } + + internal static ClassContainer GetCurrentTestContainer(ScenarioContext context) + { + context.TryGetValue(out ClassContainer classContainer); + return classContainer; } } \ No newline at end of file diff --git a/Tms.Adapter.SpecFlowPlugin/TmsPlugin.cs b/Tms.Adapter.SpecFlowPlugin/TmsPlugin.cs index 4a07689..0c4f882 100644 --- a/Tms.Adapter.SpecFlowPlugin/TmsPlugin.cs +++ b/Tms.Adapter.SpecFlowPlugin/TmsPlugin.cs @@ -6,18 +6,17 @@ [assembly: RuntimePlugin(typeof(TmsPlugin))] -namespace Tms.Adapter.SpecFlowPlugin +namespace Tms.Adapter.SpecFlowPlugin; + +public class TmsPlugin : IRuntimePlugin { - public class TmsPlugin : IRuntimePlugin + public void Initialize(RuntimePluginEvents runtimePluginEvents, RuntimePluginParameters runtimePluginParameters, + UnitTestProviderConfiguration unitTestProviderConfiguration) { - public void Initialize(RuntimePluginEvents runtimePluginEvents, RuntimePluginParameters runtimePluginParameters, - UnitTestProviderConfiguration unitTestProviderConfiguration) - { - runtimePluginEvents.CustomizeGlobalDependencies += (_, args) => - args.ObjectContainer.RegisterTypeAs(); + runtimePluginEvents.CustomizeGlobalDependencies += (_, args) => + args.ObjectContainer.RegisterTypeAs(); - runtimePluginEvents.CustomizeTestThreadDependencies += (_, args) => - args.ObjectContainer.RegisterTypeAs(); - } + runtimePluginEvents.CustomizeTestThreadDependencies += (_, args) => + args.ObjectContainer.RegisterTypeAs(); } } \ No newline at end of file diff --git a/Tms.Adapter.SpecFlowPlugin/TmsTagParser.cs b/Tms.Adapter.SpecFlowPlugin/TmsTagParser.cs index 05fd277..ebfa484 100644 --- a/Tms.Adapter.SpecFlowPlugin/TmsTagParser.cs +++ b/Tms.Adapter.SpecFlowPlugin/TmsTagParser.cs @@ -4,153 +4,152 @@ using Tms.Adapter.Core.Models; using Tms.Adapter.Core.Utils; -namespace Tms.Adapter.SpecFlowPlugin +namespace Tms.Adapter.SpecFlowPlugin; + +public static class TmsTagParser { - public static class TmsTagParser + private const string TagDelimiter = "="; + private const string TagValueDelimiter = ","; + private const string ExternalId = "EXTERNALID"; + private const string Title = "TITLE"; + private const string DisplayName = "DISPLAYNAME"; + private const string Description = "DESCRIPTION"; + private const string Labels = "LABELS"; + private const string Links = "LINKS"; + private const string WorkItemIds = "WORKITEMIDS"; + + private static readonly JsonSerializerOptions Options = new JsonSerializerOptions + { PropertyNameCaseInsensitive = true }; + + + public static TestContainer AddTags(TestContainer testContainer, FeatureInfo featureInfo, + ScenarioInfo scenarioInfo, Dictionary parameters) { - private const string TagDelimiter = "="; - private const string TagValueDelimiter = ","; - private const string ExternalId = "EXTERNALID"; - private const string Title = "TITLE"; - private const string DisplayName = "DISPLAYNAME"; - private const string Description = "DESCRIPTION"; - private const string Labels = "LABELS"; - private const string Links = "LINKS"; - private const string WorkItemIds = "WORKITEMIDS"; - - private static readonly JsonSerializerOptions Options = new JsonSerializerOptions - { PropertyNameCaseInsensitive = true }; - - - public static TestContainer AddTags(TestContainer testContainer, FeatureInfo featureInfo, - ScenarioInfo scenarioInfo, Dictionary parameters) - { - var tags = scenarioInfo.Tags - .Union(featureInfo.Tags) - .Distinct(StringComparer.CurrentCultureIgnoreCase); + var tags = scenarioInfo.Tags + .Union(featureInfo.Tags) + .Distinct(StringComparer.CurrentCultureIgnoreCase); - foreach (var tag in tags) + foreach (var tag in tags) + { + if (!tag.Contains(TagDelimiter)) { - if (!tag.Contains(TagDelimiter)) - { - continue; - } - - var tagInfo = tag.Split(TagDelimiter, 2); - - if (tagInfo.Length < 2 || string.IsNullOrWhiteSpace(tagInfo[0]) || - string.IsNullOrWhiteSpace(tagInfo[1])) - { - continue; - } - - var tagName = tagInfo[0]; - var tagValue = tagInfo[1]; - - switch (tagName.ToUpper()) - { - case ExternalId: - testContainer.ExternalId = Replacer.ReplaceParameters(tagValue, parameters); - break; - case Title: - testContainer.Title = Replacer.ReplaceParameters(tagValue, parameters); - break; - case DisplayName: - testContainer.DisplayName = Replacer.ReplaceParameters(tagValue, parameters); - break; - case Description: - testContainer.Description = Replacer.ReplaceParameters(tagValue, parameters); - break; - case Labels: - testContainer.Labels = tagValue - .Split(TagValueDelimiter) - .ToList(); - break; - case Links: - if (IsJson(tagValue)) - { - var link = GetLink(tagValue); - if (link == null) - continue; - testContainer.Links.Add(new Link(link.Url, link.Title, link.Description, - Enum.Parse(link.Type))); - } - else if (IsJsonArray(tagValue)) - { - var links = GetLinks(tagValue); - - links?.ForEach(link => - { - if (link != null) - { - testContainer.Links.Add(new Link(link.Url, link.Title, link.Description, - Enum.Parse(link.Type))); - } - }); - } - - break; - case WorkItemIds: - testContainer.WorkItemIds = tagValue - .Split(TagValueDelimiter) - .ToList(); - break; - } + continue; } - if (string.IsNullOrWhiteSpace(testContainer.DisplayName)) - { - testContainer.DisplayName = scenarioInfo.Title; - } + var tagInfo = tag.Split(TagDelimiter, 2); - if (string.IsNullOrWhiteSpace(testContainer.ExternalId)) + if (tagInfo.Length < 2 || string.IsNullOrWhiteSpace(tagInfo[0]) || + string.IsNullOrWhiteSpace(tagInfo[1])) { - testContainer.ExternalId = Hash.GetStringSha256Hash(featureInfo.Title + testContainer.DisplayName); + continue; } - return testContainer; - } - - private static bool IsJson(this string? source) - { - if (source == null) - return false; + var tagName = tagInfo[0]; + var tagValue = tagInfo[1]; - try + switch (tagName.ToUpper()) { - JsonDocument.Parse(source); - return true; - } - catch (JsonException) - { - return false; + case ExternalId: + testContainer.ExternalId = Replacer.ReplaceParameters(tagValue, parameters); + break; + case Title: + testContainer.Title = Replacer.ReplaceParameters(tagValue, parameters); + break; + case DisplayName: + testContainer.DisplayName = Replacer.ReplaceParameters(tagValue, parameters); + break; + case Description: + testContainer.Description = Replacer.ReplaceParameters(tagValue, parameters); + break; + case Labels: + testContainer.Labels = tagValue + .Split(TagValueDelimiter) + .ToList(); + break; + case Links: + if (IsJson(tagValue)) + { + var link = GetLink(tagValue); + if (link == null) + continue; + testContainer.Links.Add(new Link(link.Url, link.Title, link.Description, + Enum.Parse(link.Type))); + } + else if (IsJsonArray(tagValue)) + { + var links = GetLinks(tagValue); + + links?.ForEach(link => + { + if (link != null) + { + testContainer.Links.Add(new Link(link.Url, link.Title, link.Description, + Enum.Parse(link.Type))); + } + }); + } + + break; + case WorkItemIds: + testContainer.WorkItemIds = tagValue + .Split(TagValueDelimiter) + .ToList(); + break; } } - private static bool IsJsonArray(this string? source) + if (string.IsNullOrWhiteSpace(testContainer.DisplayName)) { - if (source == null) - return false; + testContainer.DisplayName = scenarioInfo.Title; + } - try - { - JsonNode.Parse(source); - return true; - } - catch (JsonException) - { - return false; - } + if (string.IsNullOrWhiteSpace(testContainer.ExternalId)) + { + testContainer.ExternalId = Hash.GetStringSha256Hash(featureInfo.Title + testContainer.DisplayName); } - private static LinkItem? GetLink(string source) + return testContainer; + } + + private static bool IsJson(this string? source) + { + if (source == null) + return false; + + try + { + JsonDocument.Parse(source); + return true; + } + catch (JsonException) { - return JsonSerializer.Deserialize(source, Options); + return false; } + } - private static List? GetLinks(string source) + private static bool IsJsonArray(this string? source) + { + if (source == null) + return false; + + try + { + JsonNode.Parse(source); + return true; + } + catch (JsonException) { - return JsonSerializer.Deserialize>(source, Options); + return false; } } + + private static LinkItem? GetLink(string source) + { + return JsonSerializer.Deserialize(source, Options); + } + + private static List? GetLinks(string source) + { + return JsonSerializer.Deserialize>(source, Options); + } } \ No newline at end of file diff --git a/Tms.Adapter.SpecFlowPlugin/TmsTestTracer.cs b/Tms.Adapter.SpecFlowPlugin/TmsTestTracer.cs index 1158f0b..87c4e95 100644 --- a/Tms.Adapter.SpecFlowPlugin/TmsTestTracer.cs +++ b/Tms.Adapter.SpecFlowPlugin/TmsTestTracer.cs @@ -8,77 +8,76 @@ using Tms.Adapter.Core.Service; using Tms.Adapter.Core.Utils; -namespace Tms.Adapter.SpecFlowPlugin +namespace Tms.Adapter.SpecFlowPlugin; + +public class TmsTestTracer : TestTracer, ITestTracer { - public class TmsTestTracer : TestTracer, ITestTracer - { - private static readonly AdapterManager Adapter = AdapterManager.Instance; - private const string NoMatchingStepMessage = "No matching step definition found for the step"; + private static readonly AdapterManager Adapter = AdapterManager.Instance; + private const string NoMatchingStepMessage = "No matching step definition found for the step"; - public TmsTestTracer(ITraceListener traceListener, IStepFormatter stepFormatter, - IStepDefinitionSkeletonProvider stepDefinitionSkeletonProvider, SpecFlowConfiguration specFlowConfiguration) - : base(traceListener, stepFormatter, stepDefinitionSkeletonProvider, specFlowConfiguration) - { - } + public TmsTestTracer(ITraceListener traceListener, IStepFormatter stepFormatter, + IStepDefinitionSkeletonProvider stepDefinitionSkeletonProvider, SpecFlowConfiguration specFlowConfiguration) + : base(traceListener, stepFormatter, stepDefinitionSkeletonProvider, specFlowConfiguration) + { + } - void ITestTracer.TraceStep(StepInstance stepInstance, bool showAdditionalArguments) - { - TraceStep(stepInstance, showAdditionalArguments); + void ITestTracer.TraceStep(StepInstance stepInstance, bool showAdditionalArguments) + { + TraceStep(stepInstance, showAdditionalArguments); - var stepResult = new StepResult - { - DisplayName = $"{stepInstance.Keyword} {stepInstance.Text}" - }; + var stepResult = new StepResult + { + DisplayName = $"{stepInstance.Keyword} {stepInstance.Text}" + }; - Adapter.StartStep(Hash.NewId(), stepResult); - } + Adapter.StartStep(Hash.NewId(), stepResult); + } - void ITestTracer.TraceStepDone(BindingMatch match, object[] arguments, TimeSpan duration) - { - TraceStepDone(match, arguments, duration); + void ITestTracer.TraceStepDone(BindingMatch match, object[] arguments, TimeSpan duration) + { + TraceStepDone(match, arguments, duration); - Adapter.StopStep(x => x.Status = Status.Passed); - } + Adapter.StopStep(x => x.Status = Status.Passed); + } - void ITestTracer.TraceError(Exception ex, TimeSpan duration) - { - TraceError(ex, duration); + void ITestTracer.TraceError(Exception ex, TimeSpan duration) + { + TraceError(ex, duration); - Adapter.StopStep(x => x.Status = Status.Failed); - Adapter.UpdateTestCase( - x => - { - x.Status = Status.Failed; - x.Message = ex.Message; - x.Trace = ex.StackTrace; - }); - } + Adapter.StopStep(x => x.Status = Status.Failed); + Adapter.UpdateTestCase( + x => + { + x.Status = Status.Failed; + x.Message = ex.Message; + x.Trace = ex.StackTrace; + }); + } - void ITestTracer.TraceStepSkipped() - { - TraceStepSkipped(); + void ITestTracer.TraceStepSkipped() + { + TraceStepSkipped(); - Adapter.StopStep(x => x.Status = Status.Skipped); - } + Adapter.StopStep(x => x.Status = Status.Skipped); + } - void ITestTracer.TraceStepPending(BindingMatch match, object[] arguments) - { - TraceStepPending(match, arguments); + void ITestTracer.TraceStepPending(BindingMatch match, object[] arguments) + { + TraceStepPending(match, arguments); - Adapter.StopStep(x => x.Status = Status.Skipped); - } + Adapter.StopStep(x => x.Status = Status.Skipped); + } - void ITestTracer.TraceNoMatchingStepDefinition(StepInstance stepInstance, ProgrammingLanguage targetLanguage, - CultureInfo bindingCulture, List matchesWithoutScopeCheck) - { - TraceNoMatchingStepDefinition(stepInstance, targetLanguage, bindingCulture, matchesWithoutScopeCheck); + void ITestTracer.TraceNoMatchingStepDefinition(StepInstance stepInstance, ProgrammingLanguage targetLanguage, + CultureInfo bindingCulture, List matchesWithoutScopeCheck) + { + TraceNoMatchingStepDefinition(stepInstance, targetLanguage, bindingCulture, matchesWithoutScopeCheck); - Adapter.StopStep(x => x.Status = Status.Failed); - Adapter.UpdateTestCase(x => - { - x.Status = Status.Failed; - x.Message = NoMatchingStepMessage; - }); - } + Adapter.StopStep(x => x.Status = Status.Failed); + Adapter.UpdateTestCase(x => + { + x.Status = Status.Failed; + x.Message = NoMatchingStepMessage; + }); } } \ No newline at end of file diff --git a/Tms.Adapter.XUnit/StepManager.cs b/Tms.Adapter.XUnit/StepManager.cs index 509b582..60a1bdd 100644 --- a/Tms.Adapter.XUnit/StepManager.cs +++ b/Tms.Adapter.XUnit/StepManager.cs @@ -1,84 +1,83 @@ using Tms.Adapter.Core.Models; using Tms.Adapter.Core.Service; -namespace Tms.Adapter.XUnit +namespace Tms.Adapter.XUnit; + +public static class StepManager { - public static class StepManager - { - private static readonly AsyncLocal TmsAccessor = new(); + private static readonly AsyncLocal TmsAccessor = new(); - internal static ITmsAccessor TestResultAccessor - { - get => TmsAccessor.Value; - set => TmsAccessor.Value = value; - } + internal static ITmsAccessor TestResultAccessor + { + get => TmsAccessor.Value; + set => TmsAccessor.Value = value; + } - public static void StartBeforeFixture(string name) + public static void StartBeforeFixture(string name) + { + var fixtureResult = new FixtureResult { - var fixtureResult = new FixtureResult - { - DisplayName = name, - Stage = Stage.Running, - Start = DateTimeOffset.Now.ToUnixTimeMilliseconds() - }; + DisplayName = name, + Stage = Stage.Running, + Start = DateTimeOffset.Now.ToUnixTimeMilliseconds() + }; - AdapterManager.Instance.StartBeforeFixture(TestResultAccessor.ClassContainer.Id, fixtureResult); - } + AdapterManager.Instance.StartBeforeFixture(TestResultAccessor.ClassContainer.Id, fixtureResult); + } - public static void StartAfterFixture(string name) + public static void StartAfterFixture(string name) + { + var fixtureResult = new FixtureResult { - var fixtureResult = new FixtureResult - { - DisplayName = name, - Stage = Stage.Running, - Start = DateTimeOffset.Now.ToUnixTimeMilliseconds() - }; + DisplayName = name, + Stage = Stage.Running, + Start = DateTimeOffset.Now.ToUnixTimeMilliseconds() + }; - AdapterManager.Instance.StartAfterFixture(TestResultAccessor.ClassContainer.Id, fixtureResult); - } + AdapterManager.Instance.StartAfterFixture(TestResultAccessor.ClassContainer.Id, fixtureResult); + } - public static void StopFixture(Action updateResults = null) + public static void StopFixture(Action updateResults = null) + { + AdapterManager.Instance.StopFixture(result => { - AdapterManager.Instance.StopFixture(result => - { - result.Stage = Stage.Finished; - result.Stop = DateTimeOffset.Now.ToUnixTimeMilliseconds(); - updateResults?.Invoke(result); - }); - } + result.Stage = Stage.Finished; + result.Stop = DateTimeOffset.Now.ToUnixTimeMilliseconds(); + updateResults?.Invoke(result); + }); + } - public static void StopFixtureSuppressTestCase(Action updateResults = null) - { - var newTestResult = TestResultAccessor.TestResult; - StopFixture(updateResults); - AdapterManager.Instance.StartTestCase(TestResultAccessor.ClassContainer.Id, newTestResult); - } + public static void StopFixtureSuppressTestCase(Action updateResults = null) + { + var newTestResult = TestResultAccessor.TestResult; + StopFixture(updateResults); + AdapterManager.Instance.StartTestCase(TestResultAccessor.ClassContainer.Id, newTestResult); + } - public static void StartStep(string name, Action updateResults = null) + public static void StartStep(string name, Action updateResults = null) + { + var stepResult = new StepResult { - var stepResult = new StepResult - { - DisplayName = name, - Stage = Stage.Running, - Start = DateTimeOffset.Now.ToUnixTimeMilliseconds() - }; - updateResults?.Invoke(stepResult); + DisplayName = name, + Stage = Stage.Running, + Start = DateTimeOffset.Now.ToUnixTimeMilliseconds() + }; + updateResults?.Invoke(stepResult); - AdapterManager.Instance.StartStep(stepResult); - } + AdapterManager.Instance.StartStep(stepResult); + } - public static void PassStep(Action updateResults = null) + public static void PassStep(Action updateResults = null) + { + AdapterManager.Instance.StopStep(result => { - AdapterManager.Instance.StopStep(result => - { - result.Status = Status.Passed; - updateResults?.Invoke(result); - }); - } + result.Status = Status.Passed; + updateResults?.Invoke(result); + }); + } - public static void FailStep() - { - AdapterManager.Instance.StopStep(result => { result.Status = Status.Failed; }); - } + public static void FailStep() + { + AdapterManager.Instance.StopStep(result => { result.Status = Status.Failed; }); } } \ No newline at end of file diff --git a/Tms.Adapter/Adapter.cs b/Tms.Adapter/Adapter.cs index ff48875..9280ede 100644 --- a/Tms.Adapter/Adapter.cs +++ b/Tms.Adapter/Adapter.cs @@ -1,72 +1,67 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; +using System.Diagnostics; using System.Text.Json; using Tms.Adapter.Models; -using File = Tms.Adapter.Models.File; -namespace Tms.Adapter +namespace Tms.Adapter; + +public static class Adapter { - public static class Adapter + public static void AddLinks(params Link[] links) { - public static void AddLinks(params Link[] links) - { - Console.WriteLine($"{MessageType.TmsStepLinks}: " + JsonSerializer.Serialize(links)); - } + Console.WriteLine($"{MessageType.TmsStepLinks}: " + JsonSerializer.Serialize(links)); + } - public static void AddLinks(string url, string? title = null, string? description = null, - LinkType? type = null) + public static void AddLinks(string url, string? title = null, string? description = null, + LinkType? type = null) + { + Console.WriteLine($"{MessageType.TmsStepLinks}: " + JsonSerializer.Serialize(new List { - Console.WriteLine($"{MessageType.TmsStepLinks}: " + JsonSerializer.Serialize(new List + new Link { - new Link - { - Title = title, - Url = url, - Description = description, - Type = type - } - })); - } + Title = title, + Url = url, + Description = description, + Type = type + } + })); + } - public static void AddAttachments(string pathToFile) - { - var stackTrace = new StackTrace(); - var memberName = stackTrace.GetFrame(1) - .GetMethod().Name - .Replace("$_executor_", string.Empty); + public static void AddAttachments(string pathToFile) + { + var stackTrace = new StackTrace(); + var memberName = stackTrace.GetFrame(1) + .GetMethod().Name + .Replace("$_executor_", string.Empty); - var fullPath = Path.GetFullPath(pathToFile); + var fullPath = Path.GetFullPath(pathToFile); - Console.WriteLine($"{MessageType.TmsStepAttachment}: " + - JsonSerializer.Serialize(new Models.File - { PathToFile = fullPath, CallerMemberName = memberName })); - } + Console.WriteLine($"{MessageType.TmsStepAttachment}: " + + JsonSerializer.Serialize(new Models.File + { PathToFile = fullPath, CallerMemberName = memberName })); + } - public static void AddAttachments(IEnumerable pathToFile) + public static void AddAttachments(IEnumerable pathToFile) + { + foreach (var path in pathToFile) { - foreach (var path in pathToFile) - { - AddAttachments(path); - } + AddAttachments(path); } + } - public static void AddAttachments(string content, string name) - { - var stackTrace = new StackTrace(); - var memberName = stackTrace.GetFrame(1) - .GetMethod().Name - .Replace("$_executor_", string.Empty); + public static void AddAttachments(string content, string name) + { + var stackTrace = new StackTrace(); + var memberName = stackTrace.GetFrame(1) + .GetMethod().Name + .Replace("$_executor_", string.Empty); - Console.WriteLine($"{MessageType.TmsStepAttachmentAsText}: " + - JsonSerializer.Serialize(new Models.File - { Name = name, Content = content, CallerMemberName = memberName })); - } + Console.WriteLine($"{MessageType.TmsStepAttachmentAsText}: " + + JsonSerializer.Serialize(new Models.File + { Name = name, Content = content, CallerMemberName = memberName })); + } - public static void AddMessage(string message) - { - Console.WriteLine($"{MessageType.TmsStepMessage}: " + message); - } + public static void AddMessage(string message) + { + Console.WriteLine($"{MessageType.TmsStepMessage}: " + message); } } \ No newline at end of file diff --git a/Tms.Adapter/Attributes/BaseAttribute.cs b/Tms.Adapter/Attributes/BaseAttribute.cs index fa8438a..51e35a9 100644 --- a/Tms.Adapter/Attributes/BaseAttribute.cs +++ b/Tms.Adapter/Attributes/BaseAttribute.cs @@ -1,10 +1,7 @@ -using System; +namespace Tms.Adapter.Attributes; -namespace Tms.Adapter.Attributes +[AttributeUsage(AttributeTargets.Method)] +public class BaseAttribute : Attribute { - [AttributeUsage(AttributeTargets.Method)] - public class BaseAttribute : Attribute - { - public T? Value { get; set; } - } -} + public T? Value { get; set; } +} \ No newline at end of file diff --git a/Tms.Adapter/Attributes/DescriptionAttribute.cs b/Tms.Adapter/Attributes/DescriptionAttribute.cs index 6c56a62..8c8e073 100644 --- a/Tms.Adapter/Attributes/DescriptionAttribute.cs +++ b/Tms.Adapter/Attributes/DescriptionAttribute.cs @@ -1,10 +1,9 @@ -namespace Tms.Adapter.Attributes +namespace Tms.Adapter.Attributes; + +public class DescriptionAttribute : BaseAttribute { - public class DescriptionAttribute : BaseAttribute + public DescriptionAttribute(string description) { - public DescriptionAttribute(string description) - { - Value = description; - } + Value = description; } -} +} \ No newline at end of file diff --git a/Tms.Adapter/Attributes/DisplayNameAttribute.cs b/Tms.Adapter/Attributes/DisplayNameAttribute.cs index 28a11be..9687c27 100644 --- a/Tms.Adapter/Attributes/DisplayNameAttribute.cs +++ b/Tms.Adapter/Attributes/DisplayNameAttribute.cs @@ -1,10 +1,9 @@ -namespace Tms.Adapter.Attributes +namespace Tms.Adapter.Attributes; + +public class DisplayNameAttribute : BaseAttribute { - public class DisplayNameAttribute : BaseAttribute + public DisplayNameAttribute(string displayName) { - public DisplayNameAttribute(string displayName) - { - Value = displayName; - } + Value = displayName; } -} +} \ No newline at end of file diff --git a/Tms.Adapter/Attributes/ExternalIdAttribute.cs b/Tms.Adapter/Attributes/ExternalIdAttribute.cs index b8fb40a..e38dd3f 100644 --- a/Tms.Adapter/Attributes/ExternalIdAttribute.cs +++ b/Tms.Adapter/Attributes/ExternalIdAttribute.cs @@ -1,10 +1,9 @@ -namespace Tms.Adapter.Attributes +namespace Tms.Adapter.Attributes; + +public class ExternalIdAttribute : BaseAttribute { - public class ExternalIdAttribute : BaseAttribute + public ExternalIdAttribute(string externalId) { - public ExternalIdAttribute(string externalId) - { - Value = externalId; - } + Value = externalId; } -} +} \ No newline at end of file diff --git a/Tms.Adapter/Attributes/LabelsAttribute.cs b/Tms.Adapter/Attributes/LabelsAttribute.cs index c63d8fa..334bb9e 100644 --- a/Tms.Adapter/Attributes/LabelsAttribute.cs +++ b/Tms.Adapter/Attributes/LabelsAttribute.cs @@ -1,13 +1,9 @@ -using System.Collections.Generic; -using System.Linq; +namespace Tms.Adapter.Attributes; -namespace Tms.Adapter.Attributes +public class LabelsAttribute : BaseAttribute> { - public class LabelsAttribute : BaseAttribute> + public LabelsAttribute(params string[] labels) { - public LabelsAttribute(params string[] labels) - { - Value = labels.ToList(); - } + Value = labels.ToList(); } } \ No newline at end of file diff --git a/Tms.Adapter/Attributes/LinksAttribute.cs b/Tms.Adapter/Attributes/LinksAttribute.cs index b1f76d9..776c946 100644 --- a/Tms.Adapter/Attributes/LinksAttribute.cs +++ b/Tms.Adapter/Attributes/LinksAttribute.cs @@ -1,20 +1,18 @@ -using System; -using Tms.Adapter.Models; +using Tms.Adapter.Models; -namespace Tms.Adapter.Attributes +namespace Tms.Adapter.Attributes; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] +public class LinksAttribute : BaseAttribute { - [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] - public class LinksAttribute : BaseAttribute + public LinksAttribute(string url, LinkType type = 0, string? title = null, string? description = null) { - public LinksAttribute(string url, LinkType type = 0, string? title = null, string? description = null) + Value = new Link { - Value = new Link - { - Url = url, - Type = type, - Title = title, - Description = description - }; - } + Url = url, + Type = type, + Title = title, + Description = description + }; } } \ No newline at end of file diff --git a/Tms.Adapter/Attributes/ParameterizedAttribute.cs b/Tms.Adapter/Attributes/ParameterizedAttribute.cs index 36a59ee..61b0b39 100644 --- a/Tms.Adapter/Attributes/ParameterizedAttribute.cs +++ b/Tms.Adapter/Attributes/ParameterizedAttribute.cs @@ -1,45 +1,41 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.Json; +using System.Text.Json; using MethodBoundaryAspect.Fody.Attributes; using Tms.Adapter.Models; -namespace Tms.Adapter.Attributes +namespace Tms.Adapter.Attributes; + +public class ParameterizedAttribute : OnMethodBoundaryAspect { - public class ParameterizedAttribute : OnMethodBoundaryAspect + public override void OnEntry(MethodExecutionArgs arg) { - public override void OnEntry(MethodExecutionArgs arg) - { - var parameterNames = arg.Method.GetParameters().Select(x => x.Name.ToString()); - var arguments = arg.Arguments.ToStringList(); - var args = parameterNames - .Zip(arguments, (k, v) => new { k, v }) - .ToDictionary(x => x.k, x => x.v); + var parameterNames = arg.Method.GetParameters().Select(x => x.Name.ToString()); + var arguments = arg.Arguments.ToStringList(); + var args = parameterNames + .Zip(arguments, (k, v) => new { k, v }) + .ToDictionary(x => x.k, x => x.v); - Console.WriteLine($"{MessageType.TmsParameters}: " + JsonSerializer.Serialize(args)); - } + Console.WriteLine($"{MessageType.TmsParameters}: " + JsonSerializer.Serialize(args)); } +} - public static class ObjectArrayExtension +public static class ObjectArrayExtension +{ + public static IEnumerable? ToStringList(this object[] objects) { - public static IEnumerable? ToStringList(this object[] objects) - { - var result = new List(); + var result = new List(); - foreach (var obj in objects) + foreach (var obj in objects) + { + if (obj is Array array) { - if (obj is Array array) - { - result.Add(string.Join(", ", array.Cast())); - } - else - { - result.Add(obj.ToString()); - } + result.Add(string.Join(", ", array.Cast())); + } + else + { + result.Add(obj.ToString()); } - - return result; } + + return result; } -} +} \ No newline at end of file diff --git a/Tms.Adapter/Attributes/StepAttribute.cs b/Tms.Adapter/Attributes/StepAttribute.cs index 36775ff..e1cb579 100644 --- a/Tms.Adapter/Attributes/StepAttribute.cs +++ b/Tms.Adapter/Attributes/StepAttribute.cs @@ -1,6 +1,4 @@ -using System; -using System.Diagnostics; -using System.Linq; +using System.Diagnostics; using System.Reflection; using System.Text.Json; using System.Text.RegularExpressions; @@ -8,155 +6,154 @@ using Tms.Adapter.Models; using Tms.Adapter.Utils; -namespace Tms.Adapter.Attributes +namespace Tms.Adapter.Attributes; + +public class StepAttribute : OnMethodBoundaryAspect { - public class StepAttribute : OnMethodBoundaryAspect + private MethodBase? _currentMethod; + private MethodBase? _callerMethod; + private string? _title; + private string? _description; + private CallerMethodType? _callerMethodType; + private CallerMethodType? _currentMethodType; + private DateTime? _startedAt; + private DateTime? _completedAt; + private Guid _guid; + + public override void OnEntry(MethodExecutionArgs arg) { - private MethodBase? _currentMethod; - private MethodBase? _callerMethod; - private string? _title; - private string? _description; - private CallerMethodType? _callerMethodType; - private CallerMethodType? _currentMethodType; - private DateTime? _startedAt; - private DateTime? _completedAt; - private Guid _guid; - - public override void OnEntry(MethodExecutionArgs arg) - { - _startedAt = DateTime.UtcNow; - _guid = Guid.NewGuid(); + _startedAt = DateTime.UtcNow; + _guid = Guid.NewGuid(); - var stackTrace = new StackTrace(); - _currentMethod = arg.Method; - var regex = new Regex("at (.*)\\.([^.]*)\\("); - var caller = regex.Match(stackTrace.ToString().Split(Environment.NewLine)[2]); - var type = arg.Instance?.GetType(); + var stackTrace = new StackTrace(); + _currentMethod = arg.Method; + var regex = new Regex("at (.*)\\.([^.]*)\\("); + var caller = regex.Match(stackTrace.ToString().Split(Environment.NewLine)[2]); + var type = arg.Instance?.GetType(); - if (type is not null) - { - _callerMethod = type.GetMethod(caller.Groups[2].Value); - if (_callerMethod == null) - _callerMethod = type.GetMethod(caller.Groups[2].Value, - BindingFlags.Instance | BindingFlags.NonPublic); - } + if (type is not null) + { + _callerMethod = type.GetMethod(caller.Groups[2].Value); + if (_callerMethod == null) + _callerMethod = type.GetMethod(caller.Groups[2].Value, + BindingFlags.Instance | BindingFlags.NonPublic); + } - var arguments = arg.Arguments - .Select(Convert.ToString) - .ToList(); - var parameters = arg.Method.GetParameters() - .Select(x => x.Name.ToString()) - .Zip(arguments, (k, v) => new { k, v }) - .ToDictionary(x => x.k, x => x.v); + var arguments = arg.Arguments + .Select(Convert.ToString) + .ToList(); + var parameters = arg.Method.GetParameters() + .Select(x => x.Name.ToString()) + .Zip(arguments, (k, v) => new { k, v }) + .ToDictionary(x => x.k, x => x.v); - var currentMethodAttributes = _currentMethod.GetCustomAttributes(false); + var currentMethodAttributes = _currentMethod.GetCustomAttributes(false); - if (currentMethodAttributes is not null) + if (currentMethodAttributes is not null) + { + foreach (var attribute in currentMethodAttributes) { - foreach (var attribute in currentMethodAttributes) + switch (attribute) { - switch (attribute) - { - case TitleAttribute title: - _title = title.Value; - break; - case DescriptionAttribute description: - _description = description.Value; - break; - } + case TitleAttribute title: + _title = title.Value; + break; + case DescriptionAttribute description: + _description = description.Value; + break; + } - var name = attribute.GetType().Name; - switch (name) - { - case "TestInitializeAttribute" or "SetUpAttribute" or "ClassInitializeAttribute": - _currentMethodType = CallerMethodType.Setup; - _callerMethodType = CallerMethodType.Setup; - break; - case "TestCleanupAttribute" or "TearDownAttribute" or "ClassCleanupAttribute": - _currentMethodType = CallerMethodType.Teardown; - _callerMethodType = CallerMethodType.Teardown; - break; - } + var name = attribute.GetType().Name; + switch (name) + { + case "TestInitializeAttribute" or "SetUpAttribute" or "ClassInitializeAttribute": + _currentMethodType = CallerMethodType.Setup; + _callerMethodType = CallerMethodType.Setup; + break; + case "TestCleanupAttribute" or "TearDownAttribute" or "ClassCleanupAttribute": + _currentMethodType = CallerMethodType.Teardown; + _callerMethodType = CallerMethodType.Teardown; + break; } } + } - if (_callerMethodType == default) + if (_callerMethodType == default) + { + if (_callerMethod == null) { - if (_callerMethod == null) - { - _callerMethodType = CallerMethodType.TestMethod; - } - else + _callerMethodType = CallerMethodType.TestMethod; + } + else + { + var callerMethodAttributes = _callerMethod.GetCustomAttributes(false); + if (callerMethodAttributes is not null) { - var callerMethodAttributes = _callerMethod.GetCustomAttributes(false); - if (callerMethodAttributes is not null) + foreach (var attribute in callerMethodAttributes) { - foreach (var attribute in callerMethodAttributes) + var name = attribute.GetType().Name; + _callerMethodType = name switch { - var name = attribute.GetType().Name; - _callerMethodType = name switch - { - "TestInitializeAttribute" or "SetUpAttribute" or "ClassInitializeAttribute" => - CallerMethodType.Setup, - "TestMethodAttribute" or "FactAttribute" or "TestCaseAttribute" or "TestAttribute" => - CallerMethodType.TestMethod, - "TestCleanupAttribute" or "TearDownAttribute" or "ClassCleanupAttribute" => - CallerMethodType.Teardown, - _ => _callerMethodType - }; - } + "TestInitializeAttribute" or "SetUpAttribute" or "ClassInitializeAttribute" => + CallerMethodType.Setup, + "TestMethodAttribute" or "FactAttribute" or "TestCaseAttribute" or "TestAttribute" => + CallerMethodType.TestMethod, + "TestCleanupAttribute" or "TearDownAttribute" or "ClassCleanupAttribute" => + CallerMethodType.Teardown, + _ => _callerMethodType + }; } } } + } - var replacer = new Replacer(); + var replacer = new Replacer(); - var newTitle = string.IsNullOrEmpty(_title) ? _currentMethod.Name : _title; - var newDescription = string.IsNullOrEmpty(_description) - ? null - : replacer.ReplaceParameters(_description, parameters); + var newTitle = string.IsNullOrEmpty(_title) ? _currentMethod.Name : _title; + var newDescription = string.IsNullOrEmpty(_description) + ? null + : replacer.ReplaceParameters(_description, parameters); - var step = new StepDto - { - Guid = _guid, - StartedOn = _startedAt, - Title = replacer.ReplaceParameters(newTitle, parameters), - Description = newDescription, - CurrentMethod = _currentMethod.Name, - CallerMethod = _callerMethod?.Name.Replace("$_executor_", ""), - Instance = arg.Instance?.GetType().Name, - Args = parameters, - CallerMethodType = _callerMethodType, - CurrentMethodType = _currentMethodType - }; - - Console.WriteLine($"{MessageType.TmsStep}: " + JsonSerializer.Serialize(step)); - } - - public override void OnExit(MethodExecutionArgs arg) + var step = new StepDto { - WriteData("Passed", arg.ReturnValue); - } + Guid = _guid, + StartedOn = _startedAt, + Title = replacer.ReplaceParameters(newTitle, parameters), + Description = newDescription, + CurrentMethod = _currentMethod.Name, + CallerMethod = _callerMethod?.Name.Replace("$_executor_", ""), + Instance = arg.Instance?.GetType().Name, + Args = parameters, + CallerMethodType = _callerMethodType, + CurrentMethodType = _currentMethodType + }; + + Console.WriteLine($"{MessageType.TmsStep}: " + JsonSerializer.Serialize(step)); + } - public override void OnException(MethodExecutionArgs arg) - { - WriteData("Failed"); - } + public override void OnExit(MethodExecutionArgs arg) + { + WriteData("Passed", arg.ReturnValue); + } - private void WriteData(string outcome, object result = null) - { - _completedAt = DateTime.UtcNow; + public override void OnException(MethodExecutionArgs arg) + { + WriteData("Failed"); + } - var stepResult = new StepResult - { - Guid = _guid, - CompletedOn = _completedAt, - Duration = (long)((TimeSpan)(_completedAt! - _startedAt!)).TotalMilliseconds, - Result = result?.ToString(), - Outcome = outcome - }; - - Console.WriteLine($"{MessageType.TmsStepResult}: " + JsonSerializer.Serialize(stepResult)); - } + private void WriteData(string outcome, object result = null) + { + _completedAt = DateTime.UtcNow; + + var stepResult = new StepResult + { + Guid = _guid, + CompletedOn = _completedAt, + Duration = (long)((TimeSpan)(_completedAt! - _startedAt!)).TotalMilliseconds, + Result = result?.ToString(), + Outcome = outcome + }; + + Console.WriteLine($"{MessageType.TmsStepResult}: " + JsonSerializer.Serialize(stepResult)); } } \ No newline at end of file diff --git a/Tms.Adapter/Attributes/TitleAttribute.cs b/Tms.Adapter/Attributes/TitleAttribute.cs index 503c654..f6d4217 100644 --- a/Tms.Adapter/Attributes/TitleAttribute.cs +++ b/Tms.Adapter/Attributes/TitleAttribute.cs @@ -1,10 +1,9 @@ -namespace Tms.Adapter.Attributes +namespace Tms.Adapter.Attributes; + +public class TitleAttribute : BaseAttribute { - public class TitleAttribute : BaseAttribute + public TitleAttribute(string title) { - public TitleAttribute(string title) - { - Value = title; - } + Value = title; } -} +} \ No newline at end of file diff --git a/Tms.Adapter/Attributes/WorkItemIdsAttribute.cs b/Tms.Adapter/Attributes/WorkItemIdsAttribute.cs index f412ef3..b6021f8 100644 --- a/Tms.Adapter/Attributes/WorkItemIdsAttribute.cs +++ b/Tms.Adapter/Attributes/WorkItemIdsAttribute.cs @@ -1,13 +1,9 @@ -using System.Collections.Generic; -using System.Linq; +namespace Tms.Adapter.Attributes; -namespace Tms.Adapter.Attributes +public class WorkItemIdsAttribute : BaseAttribute> { - public class WorkItemIdsAttribute : BaseAttribute> + public WorkItemIdsAttribute(params string[] workItemIds) { - public WorkItemIdsAttribute(params string[] workItemIds) - { - Value = workItemIds.ToList(); - } + Value = workItemIds.ToList(); } -} +} \ No newline at end of file diff --git a/Tms.Adapter/Models/File.cs b/Tms.Adapter/Models/File.cs index d8d0ddb..856cec5 100644 --- a/Tms.Adapter/Models/File.cs +++ b/Tms.Adapter/Models/File.cs @@ -1,10 +1,9 @@ -namespace Tms.Adapter.Models +namespace Tms.Adapter.Models; + +public class File { - public class File - { - public string Name { get; set; } - public string Content { get; set; } - public string CallerMemberName { get; set; } - public string PathToFile { get; set; } - } -} + public string Name { get; set; } + public string Content { get; set; } + public string CallerMemberName { get; set; } + public string PathToFile { get; set; } +} \ No newline at end of file diff --git a/Tms.Adapter/Models/Link.cs b/Tms.Adapter/Models/Link.cs index e5c7e4e..22e2bcf 100644 --- a/Tms.Adapter/Models/Link.cs +++ b/Tms.Adapter/Models/Link.cs @@ -1,28 +1,25 @@ -using System; +namespace Tms.Adapter.Models; -namespace Tms.Adapter.Models +public class Link : IEquatable { - public class Link : IEquatable - { - public LinkType? Type { get; set; } + public LinkType? Type { get; set; } - public string Title { get; set; } + public string Title { get; set; } - public string Url { get; set; } + public string Url { get; set; } - public string Description { get; set; } + public string Description { get; set; } - public override bool Equals(object input) => this.Equals(input as Link); + public override bool Equals(object input) => this.Equals(input as Link); - public override int GetHashCode() - { - return HashCode.Combine(Type, Title, Url, Description); - } + public override int GetHashCode() + { + return HashCode.Combine(Type, Title, Url, Description); + } - public bool Equals(Link? other) - { - return Type == other?.Type && Title == other?.Title && Url == other.Url && Description == other.Description; - } + public bool Equals(Link? other) + { + return Type == other?.Type && Title == other?.Title && Url == other.Url && Description == other.Description; } } \ No newline at end of file diff --git a/Tms.Adapter/Models/StepDto.cs b/Tms.Adapter/Models/StepDto.cs index 26f8508..bb4cd97 100644 --- a/Tms.Adapter/Models/StepDto.cs +++ b/Tms.Adapter/Models/StepDto.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; - namespace Tms.Adapter.Models; public class StepDto diff --git a/Tms.Adapter/Models/StepResult.cs b/Tms.Adapter/Models/StepResult.cs index 118a9b4..5bd126c 100644 --- a/Tms.Adapter/Models/StepResult.cs +++ b/Tms.Adapter/Models/StepResult.cs @@ -1,13 +1,10 @@ -using System; +namespace Tms.Adapter.Models; -namespace Tms.Adapter.Models +public class StepResult { - public class StepResult - { - public Guid Guid { get; set; } - public DateTime? CompletedOn { get; set; } - public long Duration { get; set; } - public string? Result { get; set; } - public string Outcome { get; set; } - } -} + public Guid Guid { get; set; } + public DateTime? CompletedOn { get; set; } + public long Duration { get; set; } + public string? Result { get; set; } + public string Outcome { get; set; } +} \ No newline at end of file diff --git a/Tms.Adapter/Utils/Replacer.cs b/Tms.Adapter/Utils/Replacer.cs index efddbc9..3926590 100644 --- a/Tms.Adapter/Utils/Replacer.cs +++ b/Tms.Adapter/Utils/Replacer.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace Tms.Adapter.Utils; public class Replacer diff --git a/TmsRunner/Managers/ConfigurationManager.cs b/TmsRunner/Managers/ConfigurationManager.cs index 5991c6f..263ad1d 100644 --- a/TmsRunner/Managers/ConfigurationManager.cs +++ b/TmsRunner/Managers/ConfigurationManager.cs @@ -67,12 +67,12 @@ private static void Validate(TmsSettings settings) throw new ConfigurationErrorsException("Private token is invalid"); } - if (!Guid.TryParse(settings.ProjectId, out var _)) + if (!Guid.TryParse(settings.ProjectId, out _)) { throw new ConfigurationErrorsException("Project id is invalid"); } - if (!Guid.TryParse(settings.ConfigurationId, out var _)) + if (!Guid.TryParse(settings.ConfigurationId, out _)) { throw new ConfigurationErrorsException("Configuration id is invalid"); } @@ -86,7 +86,7 @@ private static void Validate(TmsSettings settings) { case 0: { - if (!Guid.TryParse(settings.TestRunId, out var _)) + if (!Guid.TryParse(settings.TestRunId, out _)) { throw new ConfigurationErrorsException( "Adapter works in mode 0. Config should contains valid test run id."); @@ -96,7 +96,7 @@ private static void Validate(TmsSettings settings) } case 1: { - if (!Guid.TryParse(settings.TestRunId, out var _)) + if (!Guid.TryParse(settings.TestRunId, out _)) { throw new ConfigurationErrorsException( "Adapter works in mode 1. Config should contains valid test run id."); @@ -105,7 +105,7 @@ private static void Validate(TmsSettings settings) break; } case 2: - if (Guid.TryParse(settings.TestRunId, out var _)) + if (Guid.TryParse(settings.TestRunId, out _)) { throw new ConfigurationErrorsException( "Adapter works in mode 2. Config should not contains test run id."); @@ -113,7 +113,7 @@ private static void Validate(TmsSettings settings) break; default: - throw new Exception($"Incorrect adapter mode: {settings.AdapterMode}"); + throw new ConfigurationErrorsException($"Incorrect adapter mode: {settings.AdapterMode}"); } }