From a3c3f1373fc55ca36eb6aa29d09a8a27e2056530 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 20 Nov 2023 19:04:45 +0000 Subject: [PATCH 01/30] Set up CI with Azure Pipelines [skip ci] --- azure-pipelines.yml | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 azure-pipelines.yml diff --git a/azure-pipelines.yml b/azure-pipelines.yml new file mode 100644 index 0000000..bf56801 --- /dev/null +++ b/azure-pipelines.yml @@ -0,0 +1,34 @@ +# ASP.NET +# Build and test ASP.NET projects. +# Add steps that publish symbols, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4 + +trigger: +- main + +pool: + vmImage: 'windows-latest' + +variables: + solution: '**/*.sln' + buildPlatform: 'Any CPU' + buildConfiguration: 'Release' + +steps: +- task: NuGetToolInstaller@1 + +- task: NuGetCommand@2 + inputs: + restoreSolution: '$(solution)' + +- task: VSBuild@1 + inputs: + solution: '$(solution)' + msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"' + platform: '$(buildPlatform)' + configuration: '$(buildConfiguration)' + +- task: VSTest@2 + inputs: + platform: '$(buildPlatform)' + configuration: '$(buildConfiguration)' From 6be454400bd466f8d2240d1233a0fd75bb74870f Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 20 Nov 2023 19:11:29 +0000 Subject: [PATCH 02/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index bf56801..04d7765 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -32,3 +32,25 @@ steps: inputs: platform: '$(buildPlatform)' configuration: '$(buildConfiguration)' + +# GitHubRelease +# - task: PowerShell@2 +# displayName: 'Get latest SHA commmit from repo' +# inputs: +# targetType: 'inline' +# script: | +# $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/Account/repo/commits" +# $sha = $commits[0].sha +# Write-Host "##vso[task.setvariable variable=sha;]$sha" + +# - task: GitHubRelease@1 +# inputs: +# gitHubConnection: 'example_github' +# repositoryName: 'cpoDesign/APITestingRunner' +# action: 'create' +# target: '$(sha)' +# tagSource: 'userSpecifiedTag' +# tag: '$(tag)' +# title: 'v$(tag)' +# assets: '$(Build.ArtifactStagingDirectory)\release\*.exe' +# addChangeLog: false \ No newline at end of file From 57f7ad2d99dd45dcfb3d94dbed7695a4e9ce4e1a Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 21 Nov 2023 08:52:11 +0000 Subject: [PATCH 03/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 04d7765..04721fe 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -28,10 +28,10 @@ steps: platform: '$(buildPlatform)' configuration: '$(buildConfiguration)' -- task: VSTest@2 - inputs: - platform: '$(buildPlatform)' - configuration: '$(buildConfiguration)' +# - task: VSTest@2 +# inputs: +# platform: '$(buildPlatform)' +# configuration: '$(buildConfiguration)' # GitHubRelease # - task: PowerShell@2 From c4e50e5dad6b7cc89d13612104f8a5bfb6bd22ef Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 21 Nov 2023 08:58:55 +0000 Subject: [PATCH 04/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 04721fe..94ed56e 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -33,15 +33,15 @@ steps: # platform: '$(buildPlatform)' # configuration: '$(buildConfiguration)' -# GitHubRelease -# - task: PowerShell@2 -# displayName: 'Get latest SHA commmit from repo' -# inputs: -# targetType: 'inline' -# script: | -# $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/Account/repo/commits" -# $sha = $commits[0].sha -# Write-Host "##vso[task.setvariable variable=sha;]$sha" +#GitHubRelease +- task: PowerShell@2 + displayName: 'Get latest SHA commmit from repo' + inputs: + targetType: 'inline' + script: | + $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/Account/repo/commits" + $sha = $commits[0].sha + Write-Host "##vso[task.setvariable variable=sha;]$sha" # - task: GitHubRelease@1 # inputs: From d7a48bb54663f50508aa61b7ce8c36ef44d123a9 Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 21 Nov 2023 14:18:27 +0000 Subject: [PATCH 05/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 94ed56e..c07beb7 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -39,7 +39,7 @@ steps: inputs: targetType: 'inline' script: | - $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/Account/repo/commits" + $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/cpoDesign/APITestingRunner/commits" $sha = $commits[0].sha Write-Host "##vso[task.setvariable variable=sha;]$sha" From 8f488fa66e19d16b7e8c525db1b5789d3540cb1a Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 21 Nov 2023 14:19:00 +0000 Subject: [PATCH 06/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index c07beb7..e34546c 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -3,8 +3,6 @@ # Add steps that publish symbols, save build artifacts, deploy, and more: # https://docs.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4 -trigger: -- main pool: vmImage: 'windows-latest' From bc7ff3d825e36ba4c006610f5efa1e8c6aa562a7 Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 21 Nov 2023 14:44:33 +0000 Subject: [PATCH 07/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index e34546c..1ab406f 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -41,14 +41,14 @@ steps: $sha = $commits[0].sha Write-Host "##vso[task.setvariable variable=sha;]$sha" -# - task: GitHubRelease@1 -# inputs: -# gitHubConnection: 'example_github' -# repositoryName: 'cpoDesign/APITestingRunner' -# action: 'create' -# target: '$(sha)' -# tagSource: 'userSpecifiedTag' -# tag: '$(tag)' -# title: 'v$(tag)' -# assets: '$(Build.ArtifactStagingDirectory)\release\*.exe' -# addChangeLog: false \ No newline at end of file +- task: GitHubRelease@1 + inputs: + gitHubConnection: 'github.com_cpoDesign' + repositoryName: 'cpoDesign/APITestingRunner' + action: 'create' + target: '$(sha)' + tagSource: 'userSpecifiedTag' + tag: '$(tag)' + title: 'v$(tag)' + assets: '$(Build.ArtifactStagingDirectory)\release\*.exe' + addChangeLog: false \ No newline at end of file From 3e99be44018fe37512b9228238db058e6d3638c7 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 21:48:55 +0000 Subject: [PATCH 08/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 1ab406f..882b7ed 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -40,7 +40,15 @@ steps: $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/cpoDesign/APITestingRunner/commits" $sha = $commits[0].sha Write-Host "##vso[task.setvariable variable=sha;]$sha" - +- task: gitversion/setup@0 + displayName: 'Install GitTools' + inputs: + versionSpec: '5.3.x' +- task: gitversion/execute@0 + displayName: 'Calculate SemVer' + +- script: echo current version is $(GitVersion.SemVer) + displayName: 'Display calculated version' - task: GitHubRelease@1 inputs: gitHubConnection: 'github.com_cpoDesign' @@ -48,7 +56,7 @@ steps: action: 'create' target: '$(sha)' tagSource: 'userSpecifiedTag' - tag: '$(tag)' - title: 'v$(tag)' + tag: '$(GitVersion.SemVer)' + title: 'v$(GitVersion.SemVer)' assets: '$(Build.ArtifactStagingDirectory)\release\*.exe' addChangeLog: false \ No newline at end of file From 56b1ee0ac5ef7e1b1eebc86f278489cee2db3278 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 21:53:32 +0000 Subject: [PATCH 09/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 882b7ed..672c683 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -41,22 +41,23 @@ steps: $sha = $commits[0].sha Write-Host "##vso[task.setvariable variable=sha;]$sha" - task: gitversion/setup@0 - displayName: 'Install GitTools' + displayName: Install GitVersion inputs: - versionSpec: '5.3.x' -- task: gitversion/execute@0 - displayName: 'Calculate SemVer' + versionSpec: "5.10.x" + +# - task: gitversion/execute@0 +# displayName: 'Calculate SemVer' -- script: echo current version is $(GitVersion.SemVer) - displayName: 'Display calculated version' -- task: GitHubRelease@1 - inputs: - gitHubConnection: 'github.com_cpoDesign' - repositoryName: 'cpoDesign/APITestingRunner' - action: 'create' - target: '$(sha)' - tagSource: 'userSpecifiedTag' - tag: '$(GitVersion.SemVer)' - title: 'v$(GitVersion.SemVer)' - assets: '$(Build.ArtifactStagingDirectory)\release\*.exe' - addChangeLog: false \ No newline at end of file +# - script: echo current version is $(GitVersion.SemVer) +# displayName: 'Display calculated version' +# - task: GitHubRelease@1 +# inputs: +# gitHubConnection: 'github.com_cpoDesign' +# repositoryName: 'cpoDesign/APITestingRunner' +# action: 'create' +# target: '$(sha)' +# tagSource: 'userSpecifiedTag' +# tag: '$(GitVersion.SemVer)' +# title: 'v$(GitVersion.SemVer)' +# assets: '$(Build.ArtifactStagingDirectory)\release\*.exe' +# addChangeLog: true \ No newline at end of file From 08da3a2b106d5ff3fed7377da5edbb2d44b0caae Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 21:57:14 +0000 Subject: [PATCH 10/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 672c683..922c659 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -3,6 +3,7 @@ # Add steps that publish symbols, save build artifacts, deploy, and more: # https://docs.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4 +name: $(date:yyyyMMdd)$(rev:.r)-$(Build.SourceBranchName)-$(GitVersion.SemVer) pool: vmImage: 'windows-latest' @@ -11,6 +12,8 @@ variables: solution: '**/*.sln' buildPlatform: 'Any CPU' buildConfiguration: 'Release' + contentVersion: $(GitVersion.AssemblySemVer) + parameters.semVer.value: $(GitVersion.AssemblySemVer) steps: - task: NuGetToolInstaller@1 @@ -19,12 +22,12 @@ steps: inputs: restoreSolution: '$(solution)' -- task: VSBuild@1 - inputs: - solution: '$(solution)' - msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"' - platform: '$(buildPlatform)' - configuration: '$(buildConfiguration)' +# - task: VSBuild@1 +# inputs: +# solution: '$(solution)' +# msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"' +# platform: '$(buildPlatform)' +# configuration: '$(buildConfiguration)' # - task: VSTest@2 # inputs: @@ -40,10 +43,10 @@ steps: $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/cpoDesign/APITestingRunner/commits" $sha = $commits[0].sha Write-Host "##vso[task.setvariable variable=sha;]$sha" -- task: gitversion/setup@0 - displayName: Install GitVersion - inputs: - versionSpec: "5.10.x" +# - task: gitversion/setup@0 +# displayName: Install GitVersion +# inputs: +# versionSpec: "5.10.x" # - task: gitversion/execute@0 # displayName: 'Calculate SemVer' From f9f3d05789ed5aa742a817028d9795b7933cbb34 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 22:05:11 +0000 Subject: [PATCH 11/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 922c659..5c2579b 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,7 +1,4 @@ -# ASP.NET -# Build and test ASP.NET projects. -# Add steps that publish symbols, save build artifacts, deploy, and more: -# https://docs.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4 +## depends on: https://marketplace.visualstudio.com/items?itemName=gittools.gittools name: $(date:yyyyMMdd)$(rev:.r)-$(Build.SourceBranchName)-$(GitVersion.SemVer) @@ -16,11 +13,11 @@ variables: parameters.semVer.value: $(GitVersion.AssemblySemVer) steps: -- task: NuGetToolInstaller@1 +# - task: NuGetToolInstaller@1 -- task: NuGetCommand@2 - inputs: - restoreSolution: '$(solution)' +# - task: NuGetCommand@2 +# inputs: +# restoreSolution: '$(solution)' # - task: VSBuild@1 # inputs: @@ -43,16 +40,19 @@ steps: $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/cpoDesign/APITestingRunner/commits" $sha = $commits[0].sha Write-Host "##vso[task.setvariable variable=sha;]$sha" -# - task: gitversion/setup@0 -# displayName: Install GitVersion -# inputs: -# versionSpec: "5.10.x" -# - task: gitversion/execute@0 -# displayName: 'Calculate SemVer' +- task: gitversion/setup@0 + displayName: Install GitVersion + inputs: + versionSpec: '5.x' + + +- task: gitversion/execute@0 + displayName: 'Calculate SemVer' + +- script: echo current version is $(GitVersion.SemVer) + displayName: 'Display calculated version' -# - script: echo current version is $(GitVersion.SemVer) -# displayName: 'Display calculated version' # - task: GitHubRelease@1 # inputs: # gitHubConnection: 'github.com_cpoDesign' From 22b86e1dc06cafeee28ae95b088287f2149078bb Mon Sep 17 00:00:00 2001 From: CpoDesign Date: Mon, 27 Nov 2023 22:13:27 +0000 Subject: [PATCH 12/30] Added config file --- APITestingRunner.sln | 9 ++++++--- GitVersion.yml | 1 + 2 files changed, 7 insertions(+), 3 deletions(-) create mode 100644 GitVersion.yml diff --git a/APITestingRunner.sln b/APITestingRunner.sln index a67d9db..12a00ef 100644 --- a/APITestingRunner.sln +++ b/APITestingRunner.sln @@ -3,14 +3,17 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.7.33927.210 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "APITestingRunner", "APITestingRunner\APITestingRunner.csproj", "{1B38DEF9-532D-4D68-90C6-2804BDB1034D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "APITestingRunner", "APITestingRunner\APITestingRunner.csproj", "{1B38DEF9-532D-4D68-90C6-2804BDB1034D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "APITestingRunner.Unit.Tests", "APITestingRunner.Unit.Tests\APITestingRunner.Unit.Tests.csproj", "{3DCD5BAE-89F0-48FD-8F27-006950155B50}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "APITestingRunner.Unit.Tests", "APITestingRunner.Unit.Tests\APITestingRunner.Unit.Tests.csproj", "{3DCD5BAE-89F0-48FD-8F27-006950155B50}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleAPI", "SampleAPI\SampleAPI.csproj", "{B2336816-0B1C-4984-81A4-5F8A3A06B949}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SampleAPI", "SampleAPI\SampleAPI.csproj", "{B2336816-0B1C-4984-81A4-5F8A3A06B949}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{7F6268CA-4D8E-4F64-9949-9552CB63A231}" ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + .gitignore = .gitignore + GitVersion.yml = GitVersion.yml readme.md = readme.md EndProjectSection EndProject diff --git a/GitVersion.yml b/GitVersion.yml new file mode 100644 index 0000000..b2e5e83 --- /dev/null +++ b/GitVersion.yml @@ -0,0 +1 @@ +next-version: 1.0.0 \ No newline at end of file From 674ec200bd569172caf257793bc16f79804ab7ec Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 22:19:23 +0000 Subject: [PATCH 13/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 56 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 48 insertions(+), 8 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 5c2579b..d7b7314 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -13,6 +13,8 @@ variables: parameters.semVer.value: $(GitVersion.AssemblySemVer) steps: +- checkout: self + fetchDepth: 0 # - task: NuGetToolInstaller@1 # - task: NuGetCommand@2 @@ -32,14 +34,14 @@ steps: # configuration: '$(buildConfiguration)' #GitHubRelease -- task: PowerShell@2 - displayName: 'Get latest SHA commmit from repo' - inputs: - targetType: 'inline' - script: | - $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/cpoDesign/APITestingRunner/commits" - $sha = $commits[0].sha - Write-Host "##vso[task.setvariable variable=sha;]$sha" +# - task: PowerShell@2 +# displayName: 'Get latest SHA commmit from repo' +# inputs: +# targetType: 'inline' +# script: | +# $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/cpoDesign/APITestingRunner/commits" +# $sha = $commits[0].sha +# Write-Host "##vso[task.setvariable variable=sha;]$sha" - task: gitversion/setup@0 displayName: Install GitVersion @@ -49,9 +51,47 @@ steps: - task: gitversion/execute@0 displayName: 'Calculate SemVer' + inputs: + useConfigFile: true + - script: echo current version is $(GitVersion.SemVer) displayName: 'Display calculated version' + +- script: | + echo "Major: $(version.major)" + echo "Minor: $(version.minor)" + echo "Patch: $(version.patch)" + echo "PreReleaseTag: $(version.preReleaseTag)" + echo "PreReleaseTagWithDash: $(version.preReleaseTagWithDash)" + echo "PreReleaseLabel: $(version.preReleaseLabel)" + echo "PreReleaseNumber: $(version.preReleaseNumber)" + echo "WeightedPreReleaseNumber: $(version.weightedPreReleaseNumber)" + echo "BuildMetaData: $(version.buildMetaData)" + echo "BuildMetaDataPadded: $(version.buildMetaDataPadded)" + echo "FullBuildMetaData: $(version.fullBuildMetaData)" + echo "MajorMinorPatch: $(version.majorMinorPatch)" + echo "SemVer: $(version.semVer)" + echo "LegacySemVer: $(version.legacySemVer)" + echo "LegacySemVerPadded: $(version.legacySemVerPadded)" + echo "AssemblySemVer: $(version.assemblySemVer)" + echo "AssemblySemFileVer: $(version.assemblySemFileVer)" + echo "FullSemVer: $(version.fullSemVer)" + echo "InformationalVersion: $(version.informationalVersion)" + echo "BranchName: $(version.branchName)" + echo "EscapedBranchName: $(version.escapedBranchName)" + echo "Sha: $(version.sha)" + echo "ShortSha: $(version.shortSha)" + echo "NuGetVersionV2: $(version.nuGetVersionV2)" + echo "NuGetVersion: $(version.nuGetVersion)" + echo "NuGetPreReleaseTagV2: $(version.nuGetPreReleaseTagV2)" + echo "NuGetPreReleaseTag: $(version.nuGetPreReleaseTag)" + echo "VersionSourceSha: $(version.versionSourceSha)" + echo "CommitsSinceVersionSource: $(version.commitsSinceVersionSource)" + echo "CommitsSinceVersionSourcePadded: $(version.commitsSinceVersionSourcePadded)" + echo "UncommittedChanges: $(version.uncommittedChanges)" + echo "CommitDate: $(version.commitDate)" + displayName: Display GitVersion outputs (step output) # - task: GitHubRelease@1 # inputs: From 095dd8051a82b2bb76c462003288fe6fc30ff801 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 22:27:04 +0000 Subject: [PATCH 14/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 100 ++++++++++++++++++++++---------------------- 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index d7b7314..22dcaa3 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -13,8 +13,20 @@ variables: parameters.semVer.value: $(GitVersion.AssemblySemVer) steps: -- checkout: self - fetchDepth: 0 + # Needed for GitVersion (fetchDepth field is critical) + - checkout: self + displayName: Git Checkout + fetchDepth: 0 + persistCredentials: true + + - task: gitversion/setup@0 + displayName: GitVersion Setup + inputs: + versionSpec: 5.x + updateAssemblyInfo: true + - task: gitversion/execute@0 + displayName: GitVersion Execute + # - task: NuGetToolInstaller@1 # - task: NuGetCommand@2 @@ -43,55 +55,43 @@ steps: # $sha = $commits[0].sha # Write-Host "##vso[task.setvariable variable=sha;]$sha" -- task: gitversion/setup@0 - displayName: Install GitVersion - inputs: - versionSpec: '5.x' - - -- task: gitversion/execute@0 - displayName: 'Calculate SemVer' - inputs: - useConfigFile: true - - -- script: echo current version is $(GitVersion.SemVer) - displayName: 'Display calculated version' +# - script: echo current version is $(GitVersion.SemVer) +# displayName: 'Display calculated version' -- script: | - echo "Major: $(version.major)" - echo "Minor: $(version.minor)" - echo "Patch: $(version.patch)" - echo "PreReleaseTag: $(version.preReleaseTag)" - echo "PreReleaseTagWithDash: $(version.preReleaseTagWithDash)" - echo "PreReleaseLabel: $(version.preReleaseLabel)" - echo "PreReleaseNumber: $(version.preReleaseNumber)" - echo "WeightedPreReleaseNumber: $(version.weightedPreReleaseNumber)" - echo "BuildMetaData: $(version.buildMetaData)" - echo "BuildMetaDataPadded: $(version.buildMetaDataPadded)" - echo "FullBuildMetaData: $(version.fullBuildMetaData)" - echo "MajorMinorPatch: $(version.majorMinorPatch)" - echo "SemVer: $(version.semVer)" - echo "LegacySemVer: $(version.legacySemVer)" - echo "LegacySemVerPadded: $(version.legacySemVerPadded)" - echo "AssemblySemVer: $(version.assemblySemVer)" - echo "AssemblySemFileVer: $(version.assemblySemFileVer)" - echo "FullSemVer: $(version.fullSemVer)" - echo "InformationalVersion: $(version.informationalVersion)" - echo "BranchName: $(version.branchName)" - echo "EscapedBranchName: $(version.escapedBranchName)" - echo "Sha: $(version.sha)" - echo "ShortSha: $(version.shortSha)" - echo "NuGetVersionV2: $(version.nuGetVersionV2)" - echo "NuGetVersion: $(version.nuGetVersion)" - echo "NuGetPreReleaseTagV2: $(version.nuGetPreReleaseTagV2)" - echo "NuGetPreReleaseTag: $(version.nuGetPreReleaseTag)" - echo "VersionSourceSha: $(version.versionSourceSha)" - echo "CommitsSinceVersionSource: $(version.commitsSinceVersionSource)" - echo "CommitsSinceVersionSourcePadded: $(version.commitsSinceVersionSourcePadded)" - echo "UncommittedChanges: $(version.uncommittedChanges)" - echo "CommitDate: $(version.commitDate)" - displayName: Display GitVersion outputs (step output) +# - script: | +# echo "Major: $(version.major)" +# echo "Minor: $(version.minor)" +# echo "Patch: $(version.patch)" +# echo "PreReleaseTag: $(version.preReleaseTag)" +# echo "PreReleaseTagWithDash: $(version.preReleaseTagWithDash)" +# echo "PreReleaseLabel: $(version.preReleaseLabel)" +# echo "PreReleaseNumber: $(version.preReleaseNumber)" +# echo "WeightedPreReleaseNumber: $(version.weightedPreReleaseNumber)" +# echo "BuildMetaData: $(version.buildMetaData)" +# echo "BuildMetaDataPadded: $(version.buildMetaDataPadded)" +# echo "FullBuildMetaData: $(version.fullBuildMetaData)" +# echo "MajorMinorPatch: $(version.majorMinorPatch)" +# echo "SemVer: $(version.semVer)" +# echo "LegacySemVer: $(version.legacySemVer)" +# echo "LegacySemVerPadded: $(version.legacySemVerPadded)" +# echo "AssemblySemVer: $(version.assemblySemVer)" +# echo "AssemblySemFileVer: $(version.assemblySemFileVer)" +# echo "FullSemVer: $(version.fullSemVer)" +# echo "InformationalVersion: $(version.informationalVersion)" +# echo "BranchName: $(version.branchName)" +# echo "EscapedBranchName: $(version.escapedBranchName)" +# echo "Sha: $(version.sha)" +# echo "ShortSha: $(version.shortSha)" +# echo "NuGetVersionV2: $(version.nuGetVersionV2)" +# echo "NuGetVersion: $(version.nuGetVersion)" +# echo "NuGetPreReleaseTagV2: $(version.nuGetPreReleaseTagV2)" +# echo "NuGetPreReleaseTag: $(version.nuGetPreReleaseTag)" +# echo "VersionSourceSha: $(version.versionSourceSha)" +# echo "CommitsSinceVersionSource: $(version.commitsSinceVersionSource)" +# echo "CommitsSinceVersionSourcePadded: $(version.commitsSinceVersionSourcePadded)" +# echo "UncommittedChanges: $(version.uncommittedChanges)" +# echo "CommitDate: $(version.commitDate)" +# displayName: Display GitVersion outputs (step output) # - task: GitHubRelease@1 # inputs: From a397b2b30e5aa56008039ee5e5303b3924c5fea1 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 22:27:44 +0000 Subject: [PATCH 15/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 22dcaa3..d010b51 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -21,9 +21,9 @@ steps: - task: gitversion/setup@0 displayName: GitVersion Setup - inputs: - versionSpec: 5.x - updateAssemblyInfo: true + inputs: + versionSpec: 5.x + updateAssemblyInfo: true - task: gitversion/execute@0 displayName: GitVersion Execute From 1119ac9c7877b5df733de9cc5f210248df5b5256 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 22:28:22 +0000 Subject: [PATCH 16/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index d010b51..15a0a67 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -14,18 +14,18 @@ variables: steps: # Needed for GitVersion (fetchDepth field is critical) - - checkout: self - displayName: Git Checkout - fetchDepth: 0 - persistCredentials: true + - checkout: self + displayName: Git Checkout + fetchDepth: 0 + persistCredentials: true - - task: gitversion/setup@0 - displayName: GitVersion Setup - inputs: - versionSpec: 5.x - updateAssemblyInfo: true - - task: gitversion/execute@0 - displayName: GitVersion Execute + - task: gitversion/setup@0 + displayName: GitVersion Setup + inputs: + versionSpec: 5.x + updateAssemblyInfo: true + - task: gitversion/execute@0 + displayName: GitVersion Execute # - task: NuGetToolInstaller@1 From acc9c2804550f9256d726d2527c1ac7babaca56a Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 22:34:34 +0000 Subject: [PATCH 17/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 15a0a67..6228db6 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -27,18 +27,22 @@ steps: - task: gitversion/execute@0 displayName: GitVersion Execute -# - task: NuGetToolInstaller@1 + - task: DotNetCoreCLI@2 + inputs: + command: 'restore' + projects: '**/*.csproj' + feedsToUse: 'select' + noCache: true -# - task: NuGetCommand@2 -# inputs: -# restoreSolution: '$(solution)' + - script: echo current version is $(GitVersion.SemVer) + displayName: 'Display calculated version $(GitVersion.SemVer)' -# - task: VSBuild@1 -# inputs: -# solution: '$(solution)' -# msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"' -# platform: '$(buildPlatform)' -# configuration: '$(buildConfiguration)' + - task: VSBuild@1 + inputs: + solution: '$(solution)' + msbuildArgs: '/p:DeployOnBuild=true /p:Version=$(version.major).$(version.minor).$(version.patch) /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"' + platform: '$(buildPlatform)' + configuration: '$(buildConfiguration)' # - task: VSTest@2 # inputs: From 38bf62e8e663981e6aeaae76928987731901ac57 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 22:38:02 +0000 Subject: [PATCH 18/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 80 ++++++++++++++++++++++----------------------- 1 file changed, 40 insertions(+), 40 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 6228db6..1f88a35 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -37,12 +37,12 @@ steps: - script: echo current version is $(GitVersion.SemVer) displayName: 'Display calculated version $(GitVersion.SemVer)' - - task: VSBuild@1 - inputs: - solution: '$(solution)' - msbuildArgs: '/p:DeployOnBuild=true /p:Version=$(version.major).$(version.minor).$(version.patch) /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"' - platform: '$(buildPlatform)' - configuration: '$(buildConfiguration)' + # - task: VSBuild@1 + # inputs: + # solution: '$(solution)' + # msbuildArgs: '/p:DeployOnBuild=true /p:Version=$(version.major).$(version.minor).$(version.patch) /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"' + # platform: '$(buildPlatform)' + # configuration: '$(buildConfiguration)' # - task: VSTest@2 # inputs: @@ -62,40 +62,40 @@ steps: # - script: echo current version is $(GitVersion.SemVer) # displayName: 'Display calculated version' -# - script: | -# echo "Major: $(version.major)" -# echo "Minor: $(version.minor)" -# echo "Patch: $(version.patch)" -# echo "PreReleaseTag: $(version.preReleaseTag)" -# echo "PreReleaseTagWithDash: $(version.preReleaseTagWithDash)" -# echo "PreReleaseLabel: $(version.preReleaseLabel)" -# echo "PreReleaseNumber: $(version.preReleaseNumber)" -# echo "WeightedPreReleaseNumber: $(version.weightedPreReleaseNumber)" -# echo "BuildMetaData: $(version.buildMetaData)" -# echo "BuildMetaDataPadded: $(version.buildMetaDataPadded)" -# echo "FullBuildMetaData: $(version.fullBuildMetaData)" -# echo "MajorMinorPatch: $(version.majorMinorPatch)" -# echo "SemVer: $(version.semVer)" -# echo "LegacySemVer: $(version.legacySemVer)" -# echo "LegacySemVerPadded: $(version.legacySemVerPadded)" -# echo "AssemblySemVer: $(version.assemblySemVer)" -# echo "AssemblySemFileVer: $(version.assemblySemFileVer)" -# echo "FullSemVer: $(version.fullSemVer)" -# echo "InformationalVersion: $(version.informationalVersion)" -# echo "BranchName: $(version.branchName)" -# echo "EscapedBranchName: $(version.escapedBranchName)" -# echo "Sha: $(version.sha)" -# echo "ShortSha: $(version.shortSha)" -# echo "NuGetVersionV2: $(version.nuGetVersionV2)" -# echo "NuGetVersion: $(version.nuGetVersion)" -# echo "NuGetPreReleaseTagV2: $(version.nuGetPreReleaseTagV2)" -# echo "NuGetPreReleaseTag: $(version.nuGetPreReleaseTag)" -# echo "VersionSourceSha: $(version.versionSourceSha)" -# echo "CommitsSinceVersionSource: $(version.commitsSinceVersionSource)" -# echo "CommitsSinceVersionSourcePadded: $(version.commitsSinceVersionSourcePadded)" -# echo "UncommittedChanges: $(version.uncommittedChanges)" -# echo "CommitDate: $(version.commitDate)" -# displayName: Display GitVersion outputs (step output) +- script: | + echo "Major: $(version.major)" + echo "Minor: $(version.minor)" + echo "Patch: $(version.patch)" + echo "PreReleaseTag: $(version.preReleaseTag)" + echo "PreReleaseTagWithDash: $(version.preReleaseTagWithDash)" + echo "PreReleaseLabel: $(version.preReleaseLabel)" + echo "PreReleaseNumber: $(version.preReleaseNumber)" + echo "WeightedPreReleaseNumber: $(version.weightedPreReleaseNumber)" + echo "BuildMetaData: $(version.buildMetaData)" + echo "BuildMetaDataPadded: $(version.buildMetaDataPadded)" + echo "FullBuildMetaData: $(version.fullBuildMetaData)" + echo "MajorMinorPatch: $(version.majorMinorPatch)" + echo "SemVer: $(version.semVer)" + echo "LegacySemVer: $(version.legacySemVer)" + echo "LegacySemVerPadded: $(version.legacySemVerPadded)" + echo "AssemblySemVer: $(version.assemblySemVer)" + echo "AssemblySemFileVer: $(version.assemblySemFileVer)" + echo "FullSemVer: $(version.fullSemVer)" + echo "InformationalVersion: $(version.informationalVersion)" + echo "BranchName: $(version.branchName)" + echo "EscapedBranchName: $(version.escapedBranchName)" + echo "Sha: $(version.sha)" + echo "ShortSha: $(version.shortSha)" + echo "NuGetVersionV2: $(version.nuGetVersionV2)" + echo "NuGetVersion: $(version.nuGetVersion)" + echo "NuGetPreReleaseTagV2: $(version.nuGetPreReleaseTagV2)" + echo "NuGetPreReleaseTag: $(version.nuGetPreReleaseTag)" + echo "VersionSourceSha: $(version.versionSourceSha)" + echo "CommitsSinceVersionSource: $(version.commitsSinceVersionSource)" + echo "CommitsSinceVersionSourcePadded: $(version.commitsSinceVersionSourcePadded)" + echo "UncommittedChanges: $(version.uncommittedChanges)" + echo "CommitDate: $(version.commitDate)" + displayName: Display GitVersion outputs (step output) # - task: GitHubRelease@1 # inputs: From 17b18cb8adfd47ae7a0b78d24c2d0f7f33640eb4 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 22:39:13 +0000 Subject: [PATCH 19/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 1f88a35..9584d42 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -62,7 +62,7 @@ steps: # - script: echo current version is $(GitVersion.SemVer) # displayName: 'Display calculated version' -- script: | + - script: | echo "Major: $(version.major)" echo "Minor: $(version.minor)" echo "Patch: $(version.patch)" @@ -95,7 +95,7 @@ steps: echo "CommitsSinceVersionSourcePadded: $(version.commitsSinceVersionSourcePadded)" echo "UncommittedChanges: $(version.uncommittedChanges)" echo "CommitDate: $(version.commitDate)" - displayName: Display GitVersion outputs (step output) + displayName: Display GitVersion outputs (step output) # - task: GitHubRelease@1 # inputs: From 69ba626b0c26d87b818fcf7cb61ec728f88afeb7 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 22:47:11 +0000 Subject: [PATCH 20/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 48 +++++++++------------------------------------ 1 file changed, 9 insertions(+), 39 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 9584d42..e701518 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -37,10 +37,18 @@ steps: - script: echo current version is $(GitVersion.SemVer) displayName: 'Display calculated version $(GitVersion.SemVer)' + - task: DotNetCoreCLI@2 + inputs: + command: 'publish' + publishWebProjects: false + projects: '**/*APITestingRunner.csproj' + modifyOutputPath: false + workingDirectory: '$(Build.ArtifactStagingDirectory)\release' + # - task: VSBuild@1 # inputs: # solution: '$(solution)' - # msbuildArgs: '/p:DeployOnBuild=true /p:Version=$(version.major).$(version.minor).$(version.patch) /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"' + # msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"' # platform: '$(buildPlatform)' # configuration: '$(buildConfiguration)' @@ -58,44 +66,6 @@ steps: # $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/cpoDesign/APITestingRunner/commits" # $sha = $commits[0].sha # Write-Host "##vso[task.setvariable variable=sha;]$sha" - -# - script: echo current version is $(GitVersion.SemVer) -# displayName: 'Display calculated version' - - - script: | - echo "Major: $(version.major)" - echo "Minor: $(version.minor)" - echo "Patch: $(version.patch)" - echo "PreReleaseTag: $(version.preReleaseTag)" - echo "PreReleaseTagWithDash: $(version.preReleaseTagWithDash)" - echo "PreReleaseLabel: $(version.preReleaseLabel)" - echo "PreReleaseNumber: $(version.preReleaseNumber)" - echo "WeightedPreReleaseNumber: $(version.weightedPreReleaseNumber)" - echo "BuildMetaData: $(version.buildMetaData)" - echo "BuildMetaDataPadded: $(version.buildMetaDataPadded)" - echo "FullBuildMetaData: $(version.fullBuildMetaData)" - echo "MajorMinorPatch: $(version.majorMinorPatch)" - echo "SemVer: $(version.semVer)" - echo "LegacySemVer: $(version.legacySemVer)" - echo "LegacySemVerPadded: $(version.legacySemVerPadded)" - echo "AssemblySemVer: $(version.assemblySemVer)" - echo "AssemblySemFileVer: $(version.assemblySemFileVer)" - echo "FullSemVer: $(version.fullSemVer)" - echo "InformationalVersion: $(version.informationalVersion)" - echo "BranchName: $(version.branchName)" - echo "EscapedBranchName: $(version.escapedBranchName)" - echo "Sha: $(version.sha)" - echo "ShortSha: $(version.shortSha)" - echo "NuGetVersionV2: $(version.nuGetVersionV2)" - echo "NuGetVersion: $(version.nuGetVersion)" - echo "NuGetPreReleaseTagV2: $(version.nuGetPreReleaseTagV2)" - echo "NuGetPreReleaseTag: $(version.nuGetPreReleaseTag)" - echo "VersionSourceSha: $(version.versionSourceSha)" - echo "CommitsSinceVersionSource: $(version.commitsSinceVersionSource)" - echo "CommitsSinceVersionSourcePadded: $(version.commitsSinceVersionSourcePadded)" - echo "UncommittedChanges: $(version.uncommittedChanges)" - echo "CommitDate: $(version.commitDate)" - displayName: Display GitVersion outputs (step output) # - task: GitHubRelease@1 # inputs: From d99edac8d88d34d6154cad3935ee5781ed29abe4 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 22:53:06 +0000 Subject: [PATCH 21/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index e701518..4f46703 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -42,8 +42,9 @@ steps: command: 'publish' publishWebProjects: false projects: '**/*APITestingRunner.csproj' - modifyOutputPath: false - workingDirectory: '$(Build.ArtifactStagingDirectory)\release' + modifyOutputPath: true + arguments: '-c "Release" /p:OutputPath="$(build.artifactStagingDirectory)\release"' + # - task: VSBuild@1 # inputs: From a464df79b0e72ddadd4cc151c836f3842aa2bd4d Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 22:59:53 +0000 Subject: [PATCH 22/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 4f46703..d044d6a 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -43,8 +43,7 @@ steps: publishWebProjects: false projects: '**/*APITestingRunner.csproj' modifyOutputPath: true - arguments: '-c "Release" /p:OutputPath="$(build.artifactStagingDirectory)\release"' - + arguments: '-c "Release" /p:OutputPath="$(build.artifactStagingDirectory)"' # - task: VSBuild@1 # inputs: From 297bba60a4614fc52179cbb112d3ec02a3986a68 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 23:06:13 +0000 Subject: [PATCH 23/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index d044d6a..eb1a244 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -39,10 +39,9 @@ steps: - task: DotNetCoreCLI@2 inputs: - command: 'publish' + command: 'build' publishWebProjects: false projects: '**/*APITestingRunner.csproj' - modifyOutputPath: true arguments: '-c "Release" /p:OutputPath="$(build.artifactStagingDirectory)"' # - task: VSBuild@1 From fc0daf3ac669d9cf82436a7065a061b698e640d4 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 23:13:18 +0000 Subject: [PATCH 24/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index eb1a244..f8457d2 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -37,12 +37,29 @@ steps: - script: echo current version is $(GitVersion.SemVer) displayName: 'Display calculated version $(GitVersion.SemVer)' + # - task: DotNetCoreCLI@2 + # inputs: + # command: 'build' + # publishWebProjects: false + # projects: '**/*APITestingRunner.csproj' + # arguments: '-c "Release" /p:OutputPath="$(build.artifactStagingDirectory)"' + - task: DotNetCoreCLI@2 inputs: command: 'build' publishWebProjects: false projects: '**/*APITestingRunner.csproj' - arguments: '-c "Release" /p:OutputPath="$(build.artifactStagingDirectory)"' + arguments: '--output "$(build.artifactStagingDirectory)" --runtime win-x64 --configuration Release -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained true' + +# dotnet publish --output "c:/temp/myapp" --runtime win-x64 --configuration Release -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained true + + - task: PublishBuildArtifacts@1 + inputs: + PathtoPublish: '$(Build.ArtifactStagingDirectory)' + ArtifactName: 'drop' + publishLocation: 'Container' + + # - task: VSBuild@1 # inputs: From 150c872491290420f3669a0f20a4470b46abaf97 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 27 Nov 2023 23:18:23 +0000 Subject: [PATCH 25/30] Update azure-pipelines.yml for Azure Pipelines --- azure-pipelines.yml | 42 ++++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index f8457d2..25f9efd 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -51,8 +51,6 @@ steps: projects: '**/*APITestingRunner.csproj' arguments: '--output "$(build.artifactStagingDirectory)" --runtime win-x64 --configuration Release -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained true' -# dotnet publish --output "c:/temp/myapp" --runtime win-x64 --configuration Release -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained true - - task: PublishBuildArtifacts@1 inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)' @@ -73,24 +71,24 @@ steps: # platform: '$(buildPlatform)' # configuration: '$(buildConfiguration)' -#GitHubRelease -# - task: PowerShell@2 -# displayName: 'Get latest SHA commmit from repo' -# inputs: -# targetType: 'inline' -# script: | -# $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/cpoDesign/APITestingRunner/commits" -# $sha = $commits[0].sha -# Write-Host "##vso[task.setvariable variable=sha;]$sha" +# GitHubRelease + - task: PowerShell@2 + displayName: 'Get latest SHA commmit from repo' + inputs: + targetType: 'inline' + script: | + $commits = Invoke-RestMethod -Method GET -Uri "https://api.github.com/repos/cpoDesign/APITestingRunner/commits" + $sha = $commits[0].sha + Write-Host "##vso[task.setvariable variable=sha;]$sha" -# - task: GitHubRelease@1 -# inputs: -# gitHubConnection: 'github.com_cpoDesign' -# repositoryName: 'cpoDesign/APITestingRunner' -# action: 'create' -# target: '$(sha)' -# tagSource: 'userSpecifiedTag' -# tag: '$(GitVersion.SemVer)' -# title: 'v$(GitVersion.SemVer)' -# assets: '$(Build.ArtifactStagingDirectory)\release\*.exe' -# addChangeLog: true \ No newline at end of file + - task: GitHubRelease@1 + inputs: + gitHubConnection: 'github.com_cpoDesign' + repositoryName: 'cpoDesign/APITestingRunner' + action: 'create' + target: '$(sha)' + tagSource: 'userSpecifiedTag' + tag: '$(GitVersion.SemVer)' + title: 'v$(GitVersion.SemVer)' + assets: '$(Build.ArtifactStagingDirectory)' + addChangeLog: true \ No newline at end of file From ad0b429362877fb99990d6455c6057d46eb04517 Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 28 Nov 2023 00:18:07 +0000 Subject: [PATCH 26/30] Added exclusion of publishing except from main branch --- azure-pipelines.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 25f9efd..827f823 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -28,6 +28,7 @@ steps: displayName: GitVersion Execute - task: DotNetCoreCLI@2 + displayName: Restore packages to all projects inputs: command: 'restore' projects: '**/*.csproj' @@ -71,8 +72,9 @@ steps: # platform: '$(buildPlatform)' # configuration: '$(buildConfiguration)' -# GitHubRelease + - task: PowerShell@2 + condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main')) displayName: 'Get latest SHA commmit from repo' inputs: targetType: 'inline' @@ -82,6 +84,7 @@ steps: Write-Host "##vso[task.setvariable variable=sha;]$sha" - task: GitHubRelease@1 + condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main')) inputs: gitHubConnection: 'github.com_cpoDesign' repositoryName: 'cpoDesign/APITestingRunner' From 7b61c35b076e2e48c18b3dab0a4a5b96a2f352fb Mon Sep 17 00:00:00 2001 From: CpoDesign Date: Thu, 30 Nov 2023 08:12:04 +0000 Subject: [PATCH 27/30] Added a new plugin --- .../Plugins/StringPluginTests.cs | 97 +++++++++++++++++ APITestingRunner/APITestingRunner.csproj | 4 +- APITestingRunner/Plugins/StringPlugin.cs | 100 ++++++++++++++++++ 3 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 APITestingRunner.Unit.Tests/Plugins/StringPluginTests.cs create mode 100644 APITestingRunner/Plugins/StringPlugin.cs diff --git a/APITestingRunner.Unit.Tests/Plugins/StringPluginTests.cs b/APITestingRunner.Unit.Tests/Plugins/StringPluginTests.cs new file mode 100644 index 0000000..f262e68 --- /dev/null +++ b/APITestingRunner.Unit.Tests/Plugins/StringPluginTests.cs @@ -0,0 +1,97 @@ +using APITestingRunner.Plugins; +using FluentAssertions; + +namespace APITestingRunner.Unit.Tests.Plugins +{ + [TestClass] + public class StringPluginTests + { + [TestMethod] + public void NoDifferencesReported() + { + var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; + var json2 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; + + var resultDifferences = StringPlugin.CompareStrings(json1, json2); + _ = resultDifferences.Should().BeEmpty(); + } + + [TestMethod] + public void DifferentLength_isReported() + { + var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; + var json2 = "{\"age\":30,\"city\":\"New York\",\"name\":\"John\",\"country\":\"USA\"}"; + + var resultDifferences = StringPlugin.CompareStrings(json1, json2); + _ = resultDifferences.Should().HaveCountGreaterThan(1); + _ = resultDifferences.Should().ContainMatch("Source is different in length: 42 < 58"); + } + + [TestMethod] + public void DifferentLength_KeyMissingIsReported_FromTarget() + { + var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; + var json2 = "{\"age\":30,\"city\":\"New York\",\"name\":\"John\",\"country\":\"USA\"}"; + + var resultDifferences = StringPlugin.CompareStrings(json1, json2); + _ = resultDifferences.Should().HaveCountGreaterThan(1); + _ = resultDifferences.Should().ContainMatch("Difference at path '.country' for property 'country'"); + _ = resultDifferences.Should().ContainMatch("Missing path in source at path: '.country' for property 'country'"); + } + + [TestMethod] + public void DifferentLength_KeyMissingIsReported_FromSource() + { + var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\", \"country\":\"USA\"}"; + var json2 = "{\"age\":30,\"city\":\"New York\",\"name\":\"John\"}"; + + var resultDifferences = StringPlugin.CompareStrings(json1, json2); + _ = resultDifferences.Should().HaveCountGreaterThan(1); + _ = resultDifferences.Should().ContainMatch("Difference at path '.country' for property 'country'"); + _ = resultDifferences.Should().ContainMatch("Missing path in source at path: '.country' for property 'country'"); + } + + [TestMethod] + public void Different_DifferentValueIsReported() + { + var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; + var json2 = "{\"name\":\"John\",\"age\":30,\"city\":\"New Yorks\"}"; + + var resultDifferences = StringPlugin.CompareStrings(json1, json2); + _ = resultDifferences.Should().HaveCount(4); + _ = resultDifferences.Should().ContainMatch("Difference at path '' for property 'Root'"); + _ = resultDifferences.Should().ContainMatch("Difference at path '.city' for property 'city'"); + _ = resultDifferences.Should().ContainMatch("DiffValue is: New York <> New Yorks"); + } + [TestMethod] + public void StringPlugin_ArrayValues() + { + var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\",\"hobbies\":[\"reading\",\"traveling\"]}"; + var json2 = "{\"age\":30,\"city\":\"New York\",\"name\":\"John\",\"hobbies\":[\"reading\",\"cooking\"]}"; + + var resultDifferences = StringPlugin.CompareStrings(json1, json2); + _ = resultDifferences.Should().HaveCount(5); + _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies' for property 'hobbies'"); + _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[1]' for property 'hobbies'"); + _ = resultDifferences.Should().ContainMatch("DiffValue is: traveling <> cooking"); + } + + [TestMethod] + public void Different_DeepArrayNestingComparison() + { + var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\",\"hobbies\":[{\"type\":\"reading\",\"locations\":[{\"name\":\"Library\",\"hours\":9},{\"name\":\"Park\",\"hours\":5}]}]}"; + var json2 = "{\"age\":30,\"city\":\"New York\",\"name\":\"John\",\"hobbies\":[{\"type\":\"reading\",\"locations\":[{\"name\":\"Library\",\"hours\":9},{\"name\":\"Beach\",\"hours\":8}]}]}"; + + var resultDifferences = StringPlugin.CompareStrings(json1, json2); + _ = resultDifferences.Should().HaveCount(9); + + _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies' for property 'hobbies'"); + _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[0]' for property 'hobbies'"); + _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[0].locations' for property 'locations'"); + _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[0].locations[1]' for property 'locations'"); + _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[0].locations[1].name' for property 'name'"); + _ = resultDifferences.Should().ContainMatch("DiffValue is: Park <> Beach"); + _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[0].locations[1].hours' for property 'hours'"); + } + } +} diff --git a/APITestingRunner/APITestingRunner.csproj b/APITestingRunner/APITestingRunner.csproj index 9f2ca3a..0c44f56 100644 --- a/APITestingRunner/APITestingRunner.csproj +++ b/APITestingRunner/APITestingRunner.csproj @@ -1,4 +1,4 @@ - + Exe @@ -18,10 +18,12 @@ + + diff --git a/APITestingRunner/Plugins/StringPlugin.cs b/APITestingRunner/Plugins/StringPlugin.cs new file mode 100644 index 0000000..3f49cd8 --- /dev/null +++ b/APITestingRunner/Plugins/StringPlugin.cs @@ -0,0 +1,100 @@ +using Newtonsoft.Json.Linq; + +namespace APITestingRunner.Plugins +{ + public class StringPlugin + { + public static List CompareStrings(string string1, string string2) + { + var differencesResult = new List(); + _ = GetJsonDifferences(string1, string2, differencesResult); + + return differencesResult; + } + + private static List GetJsonDifferences(string json1, string json2, List differences) + { + var token1 = JToken.Parse(json1); + var token2 = JToken.Parse(json2); + + if (json1.Length > json2.Length) + { + differences.Add($"Source is different in length: {json1.Length} > {json2.Length}"); + } + else if (json1.Length < json2.Length) + { + differences.Add($"Source is different in length: {json1.Length} < {json2.Length}"); + } + + FindDifferences(token1, token2, differences, string.Empty, "Root"); + return differences; + } + + private static void FindDifferences(JToken token1, JToken token2, List differences, string path, string propertyName) + { + if (!JToken.DeepEquals(token1, token2)) + { + differences.Add($"Difference at path '{path}' for property '{propertyName}'"); + + var diffValue = string.Empty; + var diffValue2 = string.Empty; + + if (token1 != null && token2 != null) + { + if (token1.Type == JTokenType.String || token2.Type == JTokenType.String) + { + if (token1.Type == JTokenType.String) + { + diffValue = ((JValue)token1).Value?.ToString(); + } + + if (token2.Type == JTokenType.String) + { + diffValue2 = ((JValue)token2).Value?.ToString(); + } + + differences.Add($"DiffValue is: {diffValue} <> {diffValue2}"); + } + } + } + + if (token1 == null || token2 == null) + { + differences.Add($"Missing path in source at path: '{path}' for property '{propertyName}'"); + } + else if (token1.Type == JTokenType.Object) + { + var props1 = (JObject)token1; + var props2 = (JObject)token2; + + var allPropertyNames = props1.Properties().Select(p => p.Name).Union(props2.Properties().Select(p => p.Name)); + + foreach (var propName in allPropertyNames) + { + FindDifferences( + props1.GetValue(propName, StringComparison.OrdinalIgnoreCase), + props2.GetValue(propName, StringComparison.OrdinalIgnoreCase), + differences, + $"{path}.{propName}", + propName + ); + } + } + else if (token1.Type == JTokenType.Array) + { + var array1 = (JArray)token1; + var array2 = (JArray)token2; + + var maxLength = Math.Max(array1.Count, array2.Count); + + for (var i = 0; i < maxLength; i++) + { + var element1 = i < array1.Count ? array1[i] : null; + var element2 = i < array2.Count ? array2[i] : null; + + FindDifferences(element1, element2, differences, $"{path}[{i}]", propertyName); + } + } + } + } +} \ No newline at end of file From cc5bdb31d91670be8e2df097964adebd4977a4f6 Mon Sep 17 00:00:00 2001 From: CpoDesign Date: Fri, 1 Dec 2023 00:29:43 +0000 Subject: [PATCH 28/30] Updated implementation to add enhanced comparissonOnJsonValues --- .../Plugins/StringPluginTests.cs | 146 +++++++++++++---- .../TestRunnerTests/DataComparisonTests.cs | 37 ++--- .../PopulateRequestBodyTests.cs | 2 +- ...sWithConfigAPIBasedOnDatabaseCallsTests.cs | 153 ++---------------- APITestingRunner/APICallResultComparison.cs | 46 ++++++ APITestingRunner/ApiRequest/ApiCallResult.cs | 41 ++--- APITestingRunner/ApiTesterRunner.cs | 8 +- APITestingRunner/DataComparison.cs | 23 --- .../Plugins/ContentReplacements.cs | 19 ++- APITestingRunner/Plugins/IPlugin.cs | 17 +- .../Plugins/StringComparisonPlugin.cs | 150 +++++++++++++++++ APITestingRunner/Plugins/StringPlugin.cs | 100 ------------ APITestingRunner/ProcessingFileResult.cs | 5 +- APITestingRunner/TestRunner.cs | 45 +++--- 14 files changed, 419 insertions(+), 373 deletions(-) create mode 100644 APITestingRunner/APICallResultComparison.cs delete mode 100644 APITestingRunner/DataComparison.cs create mode 100644 APITestingRunner/Plugins/StringComparisonPlugin.cs delete mode 100644 APITestingRunner/Plugins/StringPlugin.cs diff --git a/APITestingRunner.Unit.Tests/Plugins/StringPluginTests.cs b/APITestingRunner.Unit.Tests/Plugins/StringPluginTests.cs index f262e68..6cc7a6b 100644 --- a/APITestingRunner.Unit.Tests/Plugins/StringPluginTests.cs +++ b/APITestingRunner.Unit.Tests/Plugins/StringPluginTests.cs @@ -1,30 +1,74 @@ -using APITestingRunner.Plugins; +using APITestingRunner.ApiRequest; +using APITestingRunner.Configuration; +using APITestingRunner.IoOperations; +using APITestingRunner.Plugins; using FluentAssertions; +using Microsoft.Extensions.Logging; +using Moq; namespace APITestingRunner.Unit.Tests.Plugins { [TestClass] public class StringPluginTests { + private IPlugin? _stringComparisonPlugin = new StringComparisonPlugin(); + + private TestLogger _logger = new(); + + [TestInitialize] + public void Initialize() + { + _stringComparisonPlugin = new StringComparisonPlugin(); + IConfig baseConfig = new Config() + { + UrlBase = "http://localhost:7055", + CompareUrlBase = string.Empty, + CompareUrlPath = string.Empty, + UrlPath = "/WeatherForecast", + UrlParam = null, + RequestBody = null, + HeaderParam = null, + DBConnectionString = null, + DBQuery = null, + DBFields = null, + RequestType = RequestType.GET, + ResultsStoreOption = StoreResultsOption.None, + ConfigMode = TesterConfigMode.Run, + OutputLocation = DirectoryServices.AssemblyDirectory, + ResultFileNamePattern = null, + ContentReplacements = null + }; + + _logger = new TestLogger(); + _stringComparisonPlugin.ApplyConfig(ref baseConfig, _logger); + } + [TestMethod] public void NoDifferencesReported() { var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; var json2 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; + var apiResult1 = CreateApiResultForJsonResponse(json1); + var apiResult2 = CreateApiResultForJsonResponse(json2); - var resultDifferences = StringPlugin.CompareStrings(json1, json2); - _ = resultDifferences.Should().BeEmpty(); + _ = _stringComparisonPlugin.ProcessComparison(apiResult1, apiResult2, ComparisonStatus.NewFile); + _ = _logger.Messages.Should().HaveCount(1); + _ = _logger.Messages.First().Item2.Should().Contain("Source and target has same length."); } + [TestMethod] public void DifferentLength_isReported() { var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; var json2 = "{\"age\":30,\"city\":\"New York\",\"name\":\"John\",\"country\":\"USA\"}"; + var apiResult1 = CreateApiResultForJsonResponse(json1); + var apiResult2 = CreateApiResultForJsonResponse(json2); - var resultDifferences = StringPlugin.CompareStrings(json1, json2); - _ = resultDifferences.Should().HaveCountGreaterThan(1); - _ = resultDifferences.Should().ContainMatch("Source is different in length: 42 < 58"); + _ = _stringComparisonPlugin.ProcessComparison(apiResult1, apiResult2, ComparisonStatus.NewFile); + var loggerMessages = _logger.Messages.Select(x => x.Item2); + _ = loggerMessages.Should().HaveCountGreaterThan(1); + _ = loggerMessages.Should().ContainMatch("Source is different in length: 42 < 58"); } [TestMethod] @@ -33,10 +77,14 @@ public void DifferentLength_KeyMissingIsReported_FromTarget() var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; var json2 = "{\"age\":30,\"city\":\"New York\",\"name\":\"John\",\"country\":\"USA\"}"; - var resultDifferences = StringPlugin.CompareStrings(json1, json2); - _ = resultDifferences.Should().HaveCountGreaterThan(1); - _ = resultDifferences.Should().ContainMatch("Difference at path '.country' for property 'country'"); - _ = resultDifferences.Should().ContainMatch("Missing path in source at path: '.country' for property 'country'"); + var apiResult1 = CreateApiResultForJsonResponse(json1); + var apiResult2 = CreateApiResultForJsonResponse(json2); + + var loggerMessages = _logger.Messages.Select(x => x.Item2); + _ = _stringComparisonPlugin.ProcessComparison(apiResult1, apiResult2, ComparisonStatus.NewFile); + _ = _logger.Messages.Should().HaveCountGreaterThan(1); + _ = loggerMessages.Should().ContainMatch("Difference at path '.country' for property 'country'"); + _ = loggerMessages.Should().ContainMatch("Missing path in source at path: '.country' for property 'country'"); } [TestMethod] @@ -45,10 +93,16 @@ public void DifferentLength_KeyMissingIsReported_FromSource() var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\", \"country\":\"USA\"}"; var json2 = "{\"age\":30,\"city\":\"New York\",\"name\":\"John\"}"; - var resultDifferences = StringPlugin.CompareStrings(json1, json2); - _ = resultDifferences.Should().HaveCountGreaterThan(1); - _ = resultDifferences.Should().ContainMatch("Difference at path '.country' for property 'country'"); - _ = resultDifferences.Should().ContainMatch("Missing path in source at path: '.country' for property 'country'"); + var apiResult1 = CreateApiResultForJsonResponse(json1); + var apiResult2 = CreateApiResultForJsonResponse(json2); + + _ = _stringComparisonPlugin.ProcessComparison(apiResult1, apiResult2, ComparisonStatus.NewFile); + + var loggerMessages = _logger.Messages.Select(x => x.Item2); + + _ = loggerMessages.Should().HaveCountGreaterThan(1); + _ = loggerMessages.Should().ContainMatch("Difference at path '.country' for property 'country'"); + _ = loggerMessages.Should().ContainMatch("Missing path in source at path: '.country' for property 'country'"); } [TestMethod] @@ -57,11 +111,15 @@ public void Different_DifferentValueIsReported() var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; var json2 = "{\"name\":\"John\",\"age\":30,\"city\":\"New Yorks\"}"; - var resultDifferences = StringPlugin.CompareStrings(json1, json2); - _ = resultDifferences.Should().HaveCount(4); - _ = resultDifferences.Should().ContainMatch("Difference at path '' for property 'Root'"); - _ = resultDifferences.Should().ContainMatch("Difference at path '.city' for property 'city'"); - _ = resultDifferences.Should().ContainMatch("DiffValue is: New York <> New Yorks"); + var apiResult1 = CreateApiResultForJsonResponse(json1); + var apiResult2 = CreateApiResultForJsonResponse(json2); + + _ = _stringComparisonPlugin.ProcessComparison(apiResult1, apiResult2, ComparisonStatus.NewFile); + var loggerMessages = _logger.Messages.Select(x => x.Item2); + _ = loggerMessages.Should().HaveCount(4); + _ = loggerMessages.Should().ContainMatch("Difference at path '' for property 'Root'"); + _ = loggerMessages.Should().ContainMatch("Difference at path '.city' for property 'city'"); + _ = loggerMessages.Should().ContainMatch("DiffValue is: New York <> New Yorks"); } [TestMethod] public void StringPlugin_ArrayValues() @@ -69,11 +127,15 @@ public void StringPlugin_ArrayValues() var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\",\"hobbies\":[\"reading\",\"traveling\"]}"; var json2 = "{\"age\":30,\"city\":\"New York\",\"name\":\"John\",\"hobbies\":[\"reading\",\"cooking\"]}"; - var resultDifferences = StringPlugin.CompareStrings(json1, json2); - _ = resultDifferences.Should().HaveCount(5); - _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies' for property 'hobbies'"); - _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[1]' for property 'hobbies'"); - _ = resultDifferences.Should().ContainMatch("DiffValue is: traveling <> cooking"); + var apiResult1 = CreateApiResultForJsonResponse(json1); + var apiResult2 = CreateApiResultForJsonResponse(json2); + + _ = _stringComparisonPlugin.ProcessComparison(apiResult1, apiResult2, ComparisonStatus.NewFile); + var loggerMessages = _logger.Messages.Select(x => x.Item2); + _ = loggerMessages.Should().HaveCount(5); + _ = loggerMessages.Should().ContainMatch("Difference at path '.hobbies' for property 'hobbies'"); + _ = loggerMessages.Should().ContainMatch("Difference at path '.hobbies[1]' for property 'hobbies'"); + _ = loggerMessages.Should().ContainMatch("DiffValue is: traveling <> cooking"); } [TestMethod] @@ -82,16 +144,34 @@ public void Different_DeepArrayNestingComparison() var json1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\",\"hobbies\":[{\"type\":\"reading\",\"locations\":[{\"name\":\"Library\",\"hours\":9},{\"name\":\"Park\",\"hours\":5}]}]}"; var json2 = "{\"age\":30,\"city\":\"New York\",\"name\":\"John\",\"hobbies\":[{\"type\":\"reading\",\"locations\":[{\"name\":\"Library\",\"hours\":9},{\"name\":\"Beach\",\"hours\":8}]}]}"; - var resultDifferences = StringPlugin.CompareStrings(json1, json2); - _ = resultDifferences.Should().HaveCount(9); + var apiResult1 = CreateApiResultForJsonResponse(json1); + var apiResult2 = CreateApiResultForJsonResponse(json2); - _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies' for property 'hobbies'"); - _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[0]' for property 'hobbies'"); - _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[0].locations' for property 'locations'"); - _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[0].locations[1]' for property 'locations'"); - _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[0].locations[1].name' for property 'name'"); - _ = resultDifferences.Should().ContainMatch("DiffValue is: Park <> Beach"); - _ = resultDifferences.Should().ContainMatch("Difference at path '.hobbies[0].locations[1].hours' for property 'hours'"); + _ = _stringComparisonPlugin.ProcessComparison(apiResult1, apiResult2, ComparisonStatus.NewFile); + _ = _logger.Messages.Should().HaveCount(9); + var loggerMessages = _logger.Messages.Select(x => x.Item2); + _ = loggerMessages.Should().ContainMatch("Difference at path '.hobbies' for property 'hobbies'"); + _ = loggerMessages.Should().ContainMatch("Difference at path '.hobbies[0]' for property 'hobbies'"); + _ = loggerMessages.Should().ContainMatch("Difference at path '.hobbies[0].locations' for property 'locations'"); + _ = loggerMessages.Should().ContainMatch("Difference at path '.hobbies[0].locations[1]' for property 'locations'"); + _ = loggerMessages.Should().ContainMatch("Difference at path '.hobbies[0].locations[1].name' for property 'name'"); + _ = loggerMessages.Should().ContainMatch("DiffValue is: Park <> Beach"); + _ = loggerMessages.Should().ContainMatch("Difference at path '.hobbies[0].locations[1].hours' for property 'hours'"); + } + + + private static ApiCallResult CreateApiResultForJsonResponse(string json1) + { + return new ApiCallResult + { + StatusCode = System.Net.HttpStatusCode.Continue, + ResponseContent = json1, + Headers = new List>(), + Url = string.Empty, + DataQueryResult = new Database.DataQueryResult(), + IsSuccessStatusCode = true, + CompareResults = new List() + }; } } } diff --git a/APITestingRunner.Unit.Tests/TestRunnerTests/DataComparisonTests.cs b/APITestingRunner.Unit.Tests/TestRunnerTests/DataComparisonTests.cs index 4db77a7..50a9f26 100644 --- a/APITestingRunner.Unit.Tests/TestRunnerTests/DataComparisonTests.cs +++ b/APITestingRunner.Unit.Tests/TestRunnerTests/DataComparisonTests.cs @@ -1,56 +1,57 @@ using APITestingRunner.ApiRequest; using FluentAssertions; -namespace APITestingRunner.Unit.Tests +namespace APITestingRunner.Unit.Tests.TestRunnerTests { [TestClass] public class DataComparisonTests { - //TODO: Review together tests for any that shoudl be type-safe + //TODO: Review together tests for any that shoudl be type-safe [TestMethod] public void CompareAPiResults_ShouldReturnMatching() { - var apiResult = new ApiCallResult(System.Net.HttpStatusCode.OK, string.Empty, null, null, null, true, null) { ResponseContent = string.Empty }; - var fileResult = new ApiCallResult(System.Net.HttpStatusCode.OK, string.Empty, null, null, null, true, null) { ResponseContent = string.Empty }; - var expectedResult = ComparissonStatus.Matching; + // -> StatusCode = response.StatusCode, Headers = responseHeaders, Url = pathAndQuery, Item = item, IsSuccessStatusCode = response.IsSuccessStatusCode, ResponseContent = content } + var apiResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = string.Empty }; + var fileResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = string.Empty }; + var expectedResult = ComparisonStatus.Matching; - var result = DataComparison.CompareAPiResults(apiResult, fileResult); + var result = new APICallResultComparison().ProcessComparison(apiResult, fileResult, ComparisonStatus.NewFile); _ = result.Should().Be(expectedResult); } [TestMethod] public void CompareAPiResults_ShouldReturnDifferent() { - var apiResult = new ApiCallResult(System.Net.HttpStatusCode.OK, string.Empty, null, null, null, true, null) { ResponseContent = string.Empty }; - var fileResult = new ApiCallResult(System.Net.HttpStatusCode.OK, "test", null, null, null, true, null) { ResponseContent = "test" }; - var expectedResult = ComparissonStatus.Different; + var apiResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = string.Empty }; + var fileResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = "test" }; + var expectedResult = ComparisonStatus.Different; - var result = DataComparison.CompareAPiResults(apiResult, fileResult); + var result = new APICallResultComparison().ProcessComparison(apiResult, fileResult, ComparisonStatus.NewFile); _ = result.Should().Be(expectedResult); } [TestMethod] public void CompareAPiResults_ShouldReturnDifferent_StatusCodeIsDifferent() { - var apiResult = new ApiCallResult(System.Net.HttpStatusCode.OK, string.Empty, null, null, null, true, null) { ResponseContent = string.Empty }; - var fileResult = new ApiCallResult(System.Net.HttpStatusCode.Accepted, "test", null, null, null, true, null) { ResponseContent = "test" }; - var expectedResult = ComparissonStatus.Different; + var apiResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = string.Empty }; + var fileResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.Accepted, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = "test" }; + var expectedResult = ComparisonStatus.Different; - var result = DataComparison.CompareAPiResults(apiResult, fileResult); + var result = new APICallResultComparison().ProcessComparison(apiResult, fileResult, ComparisonStatus.NewFile); _ = result.Should().Be(expectedResult); } [TestMethod] public void CompareAPiResults_ShouldReturnDifferent_IsSuccessCodeIsDifferent() { - var apiResult = new ApiCallResult(System.Net.HttpStatusCode.OK, string.Empty, null, null, null, true, null) { ResponseContent = string.Empty }; - var fileResult = new ApiCallResult(System.Net.HttpStatusCode.OK, "test", null, null, null, false, null) { ResponseContent = "test" }; - var expectedResult = ComparissonStatus.Different; + var apiResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = false, ResponseContent = "test" }; + var fileResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = "test" }; + var expectedResult = ComparisonStatus.Different; - var result = DataComparison.CompareAPiResults(apiResult, fileResult); + var result = new APICallResultComparison().ProcessComparison(apiResult, fileResult, ComparisonStatus.NewFile); _ = result.Should().Be(expectedResult); } } diff --git a/APITestingRunner.Unit.Tests/TestRunnerTests/PopulateRequestBodyTests.cs b/APITestingRunner.Unit.Tests/TestRunnerTests/PopulateRequestBodyTests.cs index fff6776..1d0396c 100644 --- a/APITestingRunner.Unit.Tests/TestRunnerTests/PopulateRequestBodyTests.cs +++ b/APITestingRunner.Unit.Tests/TestRunnerTests/PopulateRequestBodyTests.cs @@ -47,7 +47,7 @@ public void PopulateRequestBody_ShouldThrowExcpetion_becauseOfNoDataQueryResult( Action action = () => TestRunner.PopulateRequestBody(config, null); - _ = action.Should().Throw().WithMessage("Value cannot be null. (Parameter 'dataQueryResult')"); + _ = action.Should().Throw().WithMessage("Value cannot be null. (Parameter 'DataQueryResult')"); } [TestMethod] diff --git a/APITestingRunner.Unit.Tests/TestRunnerTests/TestRunnerWithOptionsWithConfigAPIBasedOnDatabaseCallsTests.cs b/APITestingRunner.Unit.Tests/TestRunnerTests/TestRunnerWithOptionsWithConfigAPIBasedOnDatabaseCallsTests.cs index dc5c198..e6b1ac1 100644 --- a/APITestingRunner.Unit.Tests/TestRunnerTests/TestRunnerWithOptionsWithConfigAPIBasedOnDatabaseCallsTests.cs +++ b/APITestingRunner.Unit.Tests/TestRunnerTests/TestRunnerWithOptionsWithConfigAPIBasedOnDatabaseCallsTests.cs @@ -187,7 +187,6 @@ public async Task ValidateImplementationFor_SingleAPICallAsync_ShouldMakeAnAPICa [TestCategory("ResultCompare")] public async Task ValidateImplementationFor_SingleAPICallAsync_ShouldMakeAnAPICall_WithResult_200_ShouldStoreAllRequest_withFileNamingBasedOnDbResult() { - server.Given( WireMock.RequestBuilders.Request.Create() .WithPath("/WeatherForecast") @@ -199,7 +198,7 @@ public async Task ValidateImplementationFor_SingleAPICallAsync_ShouldMakeAnAPICa Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") - .WithBody("Hello, world!") + .WithBody("{\"name\":\"John\",\"age\":30,\"city\":\"New York\",\"hobbies\":[{\"type\":\"reading\",\"locations\":[{\"name\":\"Library\",\"hours\":9},{\"name\":\"Park\",\"hours\":5}]}]}") ); Config apiTesterConfig = new() @@ -265,15 +264,16 @@ public async Task ValidateImplementationFor_SingleAPICallAsync_ShouldMakeAnAPICa .RunTests(apiTesterConfig); _ = testRunner.Errors.Should().BeEmpty(); - _ = logger.Messages.Count.Should().Be(7); + var loggerMessages = logger.Messages.Select(x => x.Item2); + _ = loggerMessages.Should().HaveCount(17); - _ = logger.Messages[0].Item2.Should().ContainEquivalentOf("Validating database based data source start"); - _ = logger.Messages[1].Item2.Should().ContainEquivalentOf("Found database connection string"); - _ = logger.Messages[2].Item2.Should().ContainEquivalentOf("Found database query and db fields. Attempting to load data from database."); - _ = logger.Messages[3].Item2.Should().ContainEquivalentOf("/WeatherForecast?urlkey=configKey&id=1 200 success Results/request-music-1.json Matching"); - _ = logger.Messages[4].Item2.Should().ContainEquivalentOf("/WeatherForecast?urlkey=configKey&id=2 200 success Results/request-software-2.json NewFile"); - _ = logger.Messages[5].Item2.Should().ContainEquivalentOf("/WeatherForecast?urlkey=configKey&id=3 200 success Results/request-software-3.json Matching"); - _ = logger.Messages[6].Item2.Should().Contain("Total process took:"); + _ = loggerMessages.Should().ContainEquivalentOf("Validating database based data source start"); + _ = loggerMessages.Should().ContainEquivalentOf("Found database connection string"); + _ = loggerMessages.Should().ContainEquivalentOf("Found database query and db fields. Attempting to load data from database."); + _ = loggerMessages.Should().ContainEquivalentOf("GET /WeatherForecast?urlKey=configKey&id=1 200 success Results/request-music-1.json Matching"); + + _ = loggerMessages.Should().ContainEquivalentOf("GET /WeatherForecast?urlKey=configKey&id=2 200 success Results/request-software-2.json NewFile"); + _ = loggerMessages.Should().ContainEquivalentOf("GET /WeatherForecast?urlKey=configKey&id=3 200 success Results/request-software-3.json Matching"); _ = Path.Combine(testDirectory, "request-music-1.json"); _ = Path.Combine(testDirectory, "request-software-2.json"); @@ -334,138 +334,5 @@ public async Task ValidateImplementationFor_SingleAPICallAsync_ShouldAppendIdToU _ = logger.Messages[3].Item2.Should().ContainEquivalentOf("/WeatherForecast/1 200 success"); _ = logger.Messages[4].Item2.Should().Contain("Total process took:"); } - - //[TestMethod] - //public async Task CreateConfigForSingleAPICallWithUrlParam() - //{ - // _ = new Config() - // { - // UrlBase = "https://localhost:7055", - // CompareUrlBase = string.Empty, - // CompareUrlPath = string.Empty, - // UrlPath = "/WeatherForecast/GetWeatherForecastForLocation", - // UrlParam = new List - // { - // new Param("location","UK") - // }, - // HeaderParam = new List { - // new Param("accept","application/json") - //}, - // RequestBody = null, - // DBConnectionString = null, - // DBQuery = null, - // DBFields = null, - // RequestType = RequestType.GET, - // ResultsStoreOption = StoreResultsOption.None, - // ConfigMode = TesterConfigMode.Run, - // LogLocation = DirectoryServices.AssemblyDirectory - // }; - // Assert.Fail(); - //} - - ////[DataRow(StoreResultsOption.None)] - ////[DataRow(StoreResultsOption.FailuresOnly)] - ////[DataRow(StoreResultsOption.All)] - ////public async Task CreateConfigForDatabaseBasedAPICall(StoreResultsOption storeResultsOption) - ////{ - //[TestMethod] - //public async Task CreateConfigForDatabaseBasedAPICall() - //{ - // StoreResultsOption storeResultsOption = StoreResultsOption.All; - - // string sqlCon = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\code\cpoDesign\APITestingRunner\APITestingRunner.Unit.Tests\SampleDb.mdf;Integrated Security=True"; - - // Config config = new() - // { - // UrlBase = "https://localhost:7055", - // CompareUrlBase = string.Empty, - // CompareUrlPath = string.Empty, - // UrlPath = "/Data", - // UrlParam = new List - //{ - // new Param("urlKey", "test"), - // new Param("id", "sqlId") - //}, - // HeaderParam = new List { - // new Param("accept","application/json") - //}, - // RequestBody = null, - // DBConnectionString = sqlCon, - // DBQuery = "select id as sqlId from dbo.sampleTable;", - // DBFields = new List - //{ - // new Param("sqlId", "sqlId") - //}, - // RequestType = RequestType.GET, - // ResultsStoreOption = storeResultsOption, - // ConfigMode = TesterConfigMode.Run, - // LogLocation = DirectoryServices.AssemblyDirectory - // }; - - // _ = await IndividualActions.RunTests(config); - //} - - //[TestMethod] - //public async Task CreateConfigForDatabaseBasedAPIComparrisonCall() - //{ - // Config config = new() - // { - // UrlBase = "https://localhost:7055", - // CompareUrlBase = "https://localhost:7055", - // UrlPath = "/Data", - // CompareUrlPath = "/DataV2", - // UrlParam = new List - //{ - // new Param("urlKey", "test"), - // new Param("id", "sqlId") - //}, - // HeaderParam = new List { - // new Param("accept","application/json") - //}, - // RequestBody = null, - // DBConnectionString = "Server=127.0.0.1; Database=test; User Id=sa; Password=;TrustServerCertificate=True;", - // DBQuery = "select id as sqlId from dbo.sampleTable;", - // DBFields = new List - //{ - // new Param("sqlId", "sqlId") - //}, - // RequestType = RequestType.GET, - // ResultsStoreOption = StoreResultsOption.None, - // ConfigMode = TesterConfigMode.APICompare, - // LogLocation = DirectoryServices.AssemblyDirectory - // }; - - // await IndividualActions.RunTests(config); - //} - - //[TestMethod] - //public async Task CreateConfigForSingleAPICallWithUrlParamAndBodyModel() - //{ - - // Config config = new() - // { - // UrlBase = "https://localhost:7055", - // CompareUrlBase = string.Empty, - // CompareUrlPath = string.Empty, - // UrlPath = "/datamodel/123456789", - // UrlParam = new List - // { - // new Param("location","UK") - // }, - // HeaderParam = new List { - // new Param("accept","application/json") - //}, - // RequestBody = "{Id={sqlId},StaticData=\"data\"}", - // DBConnectionString = null, - // DBQuery = null, - // DBFields = null, - // RequestType = RequestType.GET, - // ResultsStoreOption = StoreResultsOption.None, - // ConfigMode = TesterConfigMode.Run, - // LogLocation = DirectoryServices.AssemblyDirectory - // }; - - // await IndividualActions.RunTests(config); - //} } } \ No newline at end of file diff --git a/APITestingRunner/APICallResultComparison.cs b/APITestingRunner/APICallResultComparison.cs new file mode 100644 index 0000000..0bb8f1e --- /dev/null +++ b/APITestingRunner/APICallResultComparison.cs @@ -0,0 +1,46 @@ +// See https://aka.ms/new-console-template for more information + +using APITestingRunner.ApiRequest; +using APITestingRunner.Configuration; +using APITestingRunner.Plugins; +using Microsoft.Extensions.Logging; + +namespace APITestingRunner +{ + /// + /// Simple data comparison plugin. + /// + public class APICallResultComparison : IPlugin + { + /// + public string Name => "APICallResultStatus"; + + /// + public string Description => "Validates if API call has been successful as the source API result"; + + /// + public void ApplyConfig(ref IConfig config, ILogger logger) + { + + } + + /// + public string ProcessBeforeSave(string apiResponseString) + { + return apiResponseString; + } + + /// + public ComparisonStatus ProcessComparison(ApiCallResult apiCallResult, ApiCallResult fileSourceResult, ComparisonStatus comparisonStatus) + { + + return comparisonStatus; + } + + /// + public string ProcessValidation(string value) + { + return value; + } + } +} \ No newline at end of file diff --git a/APITestingRunner/ApiRequest/ApiCallResult.cs b/APITestingRunner/ApiRequest/ApiCallResult.cs index f693518..02837e8 100644 --- a/APITestingRunner/ApiRequest/ApiCallResult.cs +++ b/APITestingRunner/ApiRequest/ApiCallResult.cs @@ -4,25 +4,26 @@ using System.Net; namespace APITestingRunner.ApiRequest -{ - - /// - /// Container for an api call result. - /// - /// - /// - /// - /// - /// - /// - /// - public record ApiCallResult(HttpStatusCode StatusCode, - string ResponseContent, - List> Headers, - string Url, - DataQueryResult? Item, - bool IsSuccessStatusCode, - List? CompareResults = null) { - public required string ResponseContent { get; set; } +{ + + /// + /// Container for an api call result. + /// + /// + /// + /// + /// + /// + /// + /// + public record ApiCallResult + { + public HttpStatusCode StatusCode { get; set; } + public string ResponseContent { get; set; } + public List>? Headers { get; set; } + public string? Url { get; set; } + public DataQueryResult? DataQueryResult { get; set; } + public bool IsSuccessStatusCode { get; set; } + public List? CompareResults { get; set; } } } \ No newline at end of file diff --git a/APITestingRunner/ApiTesterRunner.cs b/APITestingRunner/ApiTesterRunner.cs index b8499fa..a829d4a 100644 --- a/APITestingRunner/ApiTesterRunner.cs +++ b/APITestingRunner/ApiTesterRunner.cs @@ -19,7 +19,9 @@ public class ApiTesterRunner(ILogger logger) private readonly IList PluginList = new List(){ - new ContentReplacements() + new ContentReplacements(), + new StringComparisonPlugin(), + //new APICallResultComparison(), }; @@ -41,7 +43,7 @@ public async Task RunTests(string pathConfigJson) _ = _logger ?? throw new ArgumentNullException(nameof(_logger)); var configSettings = await ConfigurationManager.GetConfigAsync(pathConfigJson); - var testRunner = await this.RunTestWithPlugins(configSettings); + var testRunner = await RunTestWithPlugins(configSettings); _ = await testRunner.PrintResultsSummary(); return; @@ -64,7 +66,7 @@ private async Task RunTestWithPlugins(Config config) stopwatch.Start(); testRunner.ApplyConfig(config); - testRunner.RegisterPlugin(this.PluginList); + testRunner.RegisterPlugin(PluginList); _ = await testRunner.RunTestsAsync(); stopwatch.Stop(); _logger.LogInformation($"Total process took: {stopwatch.Elapsed:mm\\:ss\\.ff}"); diff --git a/APITestingRunner/DataComparison.cs b/APITestingRunner/DataComparison.cs deleted file mode 100644 index 36f18b7..0000000 --- a/APITestingRunner/DataComparison.cs +++ /dev/null @@ -1,23 +0,0 @@ -// See https://aka.ms/new-console-template for more information - -using APITestingRunner.ApiRequest; - -namespace APITestingRunner -{ - public class DataComparison - { - public static ComparissonStatus CompareAPiResults(ApiCallResult apiCallResult, ApiCallResult fileSourceResult) - { - var status = ComparissonStatus.Different; - - if ((apiCallResult.StatusCode == fileSourceResult.StatusCode) - && (apiCallResult.IsSuccessStatusCode == fileSourceResult.IsSuccessStatusCode) - && (apiCallResult.ResponseContent == fileSourceResult.ResponseContent)) - { - status = ComparissonStatus.Matching; - } - - return status; - } - } -} \ No newline at end of file diff --git a/APITestingRunner/Plugins/ContentReplacements.cs b/APITestingRunner/Plugins/ContentReplacements.cs index 7f62721..199a3a5 100644 --- a/APITestingRunner/Plugins/ContentReplacements.cs +++ b/APITestingRunner/Plugins/ContentReplacements.cs @@ -1,4 +1,5 @@ -using APITestingRunner.Configuration; +using APITestingRunner.ApiRequest; +using APITestingRunner.Configuration; using Microsoft.Extensions.Logging; namespace APITestingRunner.Plugins @@ -16,7 +17,6 @@ public class ContentReplacements() : IPlugin string IPlugin.Name => "ContentReplacements"; - //TODO: Review this pattern - need reason not to put this into the constructor - which improves the code tightness public void ApplyConfig(ref IConfig config, ILogger logger) { @@ -48,13 +48,16 @@ private string ProcessValueWithFilters(bool filterConfigurationByStoreInFile, st private List ApplySavedFilter(bool filterConfigurationByStoreInFile) { - if (_config.ContentReplacements == null) - return []; - - if (!filterConfigurationByStoreInFile) - return _config.ContentReplacements.ToList(); + return _config.ContentReplacements == null + ? (List)([]) + : !filterConfigurationByStoreInFile + ? _config.ContentReplacements.ToList() + : _config.ContentReplacements.Where(x => x.StoreInFile).ToList(); + } - return _config.ContentReplacements.Where(x => x.StoreInFile).ToList(); + public ComparisonStatus ProcessComparison(ApiCallResult apiCallResult, ApiCallResult fileSourceResult, ComparisonStatus comparisonStatus) + { + return comparisonStatus; } } } diff --git a/APITestingRunner/Plugins/IPlugin.cs b/APITestingRunner/Plugins/IPlugin.cs index fe4f98d..1b33eb4 100644 --- a/APITestingRunner/Plugins/IPlugin.cs +++ b/APITestingRunner/Plugins/IPlugin.cs @@ -1,4 +1,5 @@ -using APITestingRunner.Configuration; +using APITestingRunner.ApiRequest; +using APITestingRunner.Configuration; using Microsoft.Extensions.Logging; namespace APITestingRunner.Plugins @@ -9,7 +10,12 @@ public interface IPlugin /// Name of the plugin /// string Name { get; } + + /// + /// Description of the plugin. + /// string Description { get; } + void ApplyConfig(ref IConfig config, ILogger logger); /// @@ -19,6 +25,15 @@ public interface IPlugin /// Returns a processed string. string ProcessBeforeSave(string apiResponseString); + /// + /// Compare api call results implementation + /// + /// + /// + /// Current status of comparing files. + /// ComparisonStatus. + ComparisonStatus ProcessComparison(ApiCallResult apiCallResult, ApiCallResult fileSourceResult, ComparisonStatus comparisonStatus); + /// /// Processes validation string. /// diff --git a/APITestingRunner/Plugins/StringComparisonPlugin.cs b/APITestingRunner/Plugins/StringComparisonPlugin.cs new file mode 100644 index 0000000..3abf3dc --- /dev/null +++ b/APITestingRunner/Plugins/StringComparisonPlugin.cs @@ -0,0 +1,150 @@ +using APITestingRunner.ApiRequest; +using APITestingRunner.Configuration; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json.Linq; + +namespace APITestingRunner.Plugins +{ + public class StringComparisonPlugin : IPlugin + { + public string Name => "StringPlugin"; + + public string Description => "Compare string into greater detail"; + + private ILogger? _logger; + private IConfig? _config; + private ComparisonStatus _comparisonStatus; + + public void ApplyConfig(ref IConfig config, ILogger logger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _config = config ?? throw new ArgumentNullException(nameof(config)); + } + + public string ProcessBeforeSave(string apiResponseString) + { + return apiResponseString; + } + + public string ProcessValidation(string value) + { + return value; + } + + public ComparisonStatus ProcessComparison(ApiCallResult apiCallResult, ApiCallResult fileSourceResult, ComparisonStatus comparisonStatus) + { + _comparisonStatus = comparisonStatus; + if ((apiCallResult.StatusCode == fileSourceResult.StatusCode) + && (apiCallResult.IsSuccessStatusCode == fileSourceResult.IsSuccessStatusCode) + && (apiCallResult.ResponseContent == fileSourceResult.ResponseContent)) + { + _comparisonStatus = ComparisonStatus.Matching; + } + + if (apiCallResult.ResponseContent == null || fileSourceResult.ResponseContent == null) return _comparisonStatus; + GetJsonDifferences(apiCallResult.ResponseContent, fileSourceResult.ResponseContent); + return _comparisonStatus; + } + private void GetJsonDifferences(string json1, string json2) + { + if (json1 == null && json2 == null) + { + return; + } + else if (json1 == null && json2 != null) + { + return; + } + else if (json1 != null && json2 == null) + { + return; + } + + if (json1.Length > json2.Length) + { + _comparisonStatus = ComparisonStatus.Different; + _logger.LogInformation($"Source is different in length: {json1.Length} > {json2.Length}"); + } + else if (json1.Length < json2.Length) + { + _comparisonStatus = ComparisonStatus.Different; + _logger.LogInformation($"Source is different in length: {json1.Length} < {json2.Length}"); + } + else + { + _logger.LogInformation("Source and target has same length."); + } + + var token1 = JToken.Parse(json1); + var token2 = JToken.Parse(json2); + FindDifferences(token1, token2, string.Empty, "Root"); + } + + private void FindDifferences(JToken token1, JToken token2, string path, string propertyName) + { + if (!JToken.DeepEquals(token1, token2)) + { + _logger.LogInformation($"Difference at path '{path}' for property '{propertyName}'"); + + var diffValue = string.Empty; + var diffValue2 = string.Empty; + + if (token1 != null && token2 != null) + { + if (token1.Type == JTokenType.String || token2.Type == JTokenType.String) + { + if (token1.Type == JTokenType.String) + { + diffValue = ((JValue)token1).Value?.ToString(); + } + + if (token2.Type == JTokenType.String) + { + diffValue2 = ((JValue)token2).Value?.ToString(); + } + + _comparisonStatus = ComparisonStatus.Different; + _logger.LogInformation($"DiffValue is: {diffValue} <> {diffValue2}"); + } + } + } + + if (token1 == null || token2 == null) + { + _logger.LogInformation($"Missing path in source at path: '{path}' for property '{propertyName}'"); + } + else if (token1.Type == JTokenType.Object) + { + var props1 = (JObject)token1; + var props2 = (JObject)token2; + + var allPropertyNames = props1.Properties().Select(p => p.Name).Union(props2.Properties().Select(p => p.Name)); + + foreach (var propName in allPropertyNames) + { + FindDifferences( + props1.GetValue(propName, StringComparison.OrdinalIgnoreCase), + props2.GetValue(propName, StringComparison.OrdinalIgnoreCase), + $"{path}.{propName}", + propName + ); + } + } + else if (token1.Type == JTokenType.Array) + { + var array1 = (JArray)token1; + var array2 = (JArray)token2; + + var maxLength = Math.Max(array1.Count, array2.Count); + + for (var i = 0; i < maxLength; i++) + { + var element1 = i < array1.Count ? array1[i] : null; + var element2 = i < array2.Count ? array2[i] : null; + + FindDifferences(element1, element2, $"{path}[{i}]", propertyName); + } + } + } + } +} \ No newline at end of file diff --git a/APITestingRunner/Plugins/StringPlugin.cs b/APITestingRunner/Plugins/StringPlugin.cs deleted file mode 100644 index 3f49cd8..0000000 --- a/APITestingRunner/Plugins/StringPlugin.cs +++ /dev/null @@ -1,100 +0,0 @@ -using Newtonsoft.Json.Linq; - -namespace APITestingRunner.Plugins -{ - public class StringPlugin - { - public static List CompareStrings(string string1, string string2) - { - var differencesResult = new List(); - _ = GetJsonDifferences(string1, string2, differencesResult); - - return differencesResult; - } - - private static List GetJsonDifferences(string json1, string json2, List differences) - { - var token1 = JToken.Parse(json1); - var token2 = JToken.Parse(json2); - - if (json1.Length > json2.Length) - { - differences.Add($"Source is different in length: {json1.Length} > {json2.Length}"); - } - else if (json1.Length < json2.Length) - { - differences.Add($"Source is different in length: {json1.Length} < {json2.Length}"); - } - - FindDifferences(token1, token2, differences, string.Empty, "Root"); - return differences; - } - - private static void FindDifferences(JToken token1, JToken token2, List differences, string path, string propertyName) - { - if (!JToken.DeepEquals(token1, token2)) - { - differences.Add($"Difference at path '{path}' for property '{propertyName}'"); - - var diffValue = string.Empty; - var diffValue2 = string.Empty; - - if (token1 != null && token2 != null) - { - if (token1.Type == JTokenType.String || token2.Type == JTokenType.String) - { - if (token1.Type == JTokenType.String) - { - diffValue = ((JValue)token1).Value?.ToString(); - } - - if (token2.Type == JTokenType.String) - { - diffValue2 = ((JValue)token2).Value?.ToString(); - } - - differences.Add($"DiffValue is: {diffValue} <> {diffValue2}"); - } - } - } - - if (token1 == null || token2 == null) - { - differences.Add($"Missing path in source at path: '{path}' for property '{propertyName}'"); - } - else if (token1.Type == JTokenType.Object) - { - var props1 = (JObject)token1; - var props2 = (JObject)token2; - - var allPropertyNames = props1.Properties().Select(p => p.Name).Union(props2.Properties().Select(p => p.Name)); - - foreach (var propName in allPropertyNames) - { - FindDifferences( - props1.GetValue(propName, StringComparison.OrdinalIgnoreCase), - props2.GetValue(propName, StringComparison.OrdinalIgnoreCase), - differences, - $"{path}.{propName}", - propName - ); - } - } - else if (token1.Type == JTokenType.Array) - { - var array1 = (JArray)token1; - var array2 = (JArray)token2; - - var maxLength = Math.Max(array1.Count, array2.Count); - - for (var i = 0; i < maxLength; i++) - { - var element1 = i < array1.Count ? array1[i] : null; - var element2 = i < array2.Count ? array2[i] : null; - - FindDifferences(element1, element2, differences, $"{path}[{i}]", propertyName); - } - } - } - } -} \ No newline at end of file diff --git a/APITestingRunner/ProcessingFileResult.cs b/APITestingRunner/ProcessingFileResult.cs index db3ecd5..33f5e52 100644 --- a/APITestingRunner/ProcessingFileResult.cs +++ b/APITestingRunner/ProcessingFileResult.cs @@ -4,14 +4,15 @@ namespace APITestingRunner { public class ProcessingFileResult { - public ComparissonStatus ComparissonStatus { get; set; } + public ComparisonStatus ComparissonStatus { get; set; } public bool DisplayFilePathInLog { get; internal set; } } - public enum ComparissonStatus + public enum ComparisonStatus { NewFile = 1, Matching = 2, Different = 3, + NotApplicable = 4, } } \ No newline at end of file diff --git a/APITestingRunner/TestRunner.cs b/APITestingRunner/TestRunner.cs index 27cd175..0176daf 100644 --- a/APITestingRunner/TestRunner.cs +++ b/APITestingRunner/TestRunner.cs @@ -286,7 +286,7 @@ private async Task MakeApiForCollectionCall(HttpClient client, DataQueryResult i fileName = TestRunner.GenerateResultName(item, _config.ResultFileNamePattern); result = await ProcessResultCaptureAndCompareIfRequested( - new ApiCallResult(response.StatusCode, content, responseHeaders, pathAndQuery, item, response.IsSuccessStatusCode) { ResponseContent = content }); + new ApiCallResult() { StatusCode = response.StatusCode, Headers = responseHeaders, Url = pathAndQuery, DataQueryResult = item, IsSuccessStatusCode = response.IsSuccessStatusCode, ResponseContent = content }); if (result.DisplayFilePathInLog) { onScreenMessage += $" {TestConstants.TestOutputDirectory}/{fileName}"; @@ -297,7 +297,7 @@ private async Task MakeApiForCollectionCall(HttpClient client, DataQueryResult i fileName = TestRunner.GenerateResultName(item, _config.ResultFileNamePattern); - result = await ProcessResultCaptureAndCompareIfRequested(new ApiCallResult(response.StatusCode, content, responseHeaders, pathAndQuery, item, response.IsSuccessStatusCode) { ResponseContent = content }); + result = await ProcessResultCaptureAndCompareIfRequested(new ApiCallResult { StatusCode = response.StatusCode, Headers = responseHeaders, Url = pathAndQuery, DataQueryResult = item, IsSuccessStatusCode = response.IsSuccessStatusCode, ResponseContent = content }); if (result.DisplayFilePathInLog) { @@ -428,7 +428,7 @@ private async Task ProcessResultCaptureAndCompareIfRequest //TODO: Review what this is for? _ = $"{apiCallResult.StatusCode} - {apiCallResult.ResponseContent}"; - var fileCompareStatus = ComparissonStatus.NewFile; + var fileCompareStatus = ComparisonStatus.NewFile; var result = new ProcessingFileResult { ComparissonStatus = fileCompareStatus }; if (_config.ConfigMode is TesterConfigMode.Capture or TesterConfigMode.CaptureAndCompare) @@ -470,7 +470,7 @@ private async Task ProcessResultCaptureAndCompareIfRequest /// /// /// Boolean result checking if file already exists. - private async Task LogIntoFileAsync(string logLocation, ApiCallResult apiCallResult) + private async Task LogIntoFileAsync(string logLocation, ApiCallResult apiCallResult) { ArgumentNullException.ThrowIfNull(_config); @@ -482,8 +482,8 @@ private async Task LogIntoFileAsync(string logLocation, ApiCa _ = Directory.CreateDirectory(resultsDirectory); } - var status = ComparissonStatus.NewFile; - var fileName = GenerateResultName(apiCallResult.Item, _config.ResultFileNamePattern); + var status = ComparisonStatus.NewFile; + var fileName = GenerateResultName(apiCallResult.DataQueryResult, _config.ResultFileNamePattern); var fileOperations = new FileOperations(); var filePath = Path.Combine(resultsDirectory, fileName); @@ -495,38 +495,41 @@ private async Task LogIntoFileAsync(string logLocation, ApiCa apiCallResult.ResponseContent = plugin.ProcessBeforeSave(apiCallResult.ResponseContent); } } - - var apiResult = JsonSerializer.Serialize(apiCallResult); - + + var apiResult = JsonSerializer.Serialize(apiCallResult); + if (FileOperations.ValidateIfFileExists(filePath)) { var compareFileData = FileOperations.GetFileData(filePath); - if (plugins != null) - { - foreach (var plugin in plugins) - { - compareFileData = plugin.ProcessValidation(compareFileData); - } - } - var fileSourceResult = JsonSerializer.Deserialize(compareFileData); if (fileSourceResult is not null) - { - status = DataComparison.CompareAPiResults(apiCallResult, fileSourceResult); + { + // because the file is loaded lets make it same. then plugin can decided to make it different + status = ComparisonStatus.Matching; + + if (plugins != null) + { + foreach (var plugin in plugins) + { + _logger.LogInformation($"Processing comparison using:{plugin.Name}"); + status = plugin.ProcessComparison(fileSourceResult, apiCallResult, status); + _logger.LogInformation($"Processing comparison using:{plugin.Name} with result {status}"); + } + } } } else { await FileOperations.WriteFile(filePath, apiResult); - } + } + return status; } catch (Exception ex) { Debug.WriteLine(ex); - Errors.Add("Failed to capture logs into a file"); throw; } From 96d0b407186963144c922773f404656836426768 Mon Sep 17 00:00:00 2001 From: CpoDesign Date: Fri, 1 Dec 2023 00:44:44 +0000 Subject: [PATCH 29/30] Solved last issues with comparison --- .../TestRunnerTests/CustomResponse.cs | 45 +++++++++++ ...sWithConfigAPIBasedOnDatabaseCallsTests.cs | 75 ++++++++++++++++++- 2 files changed, 119 insertions(+), 1 deletion(-) create mode 100644 APITestingRunner.Unit.Tests/TestRunnerTests/CustomResponse.cs diff --git a/APITestingRunner.Unit.Tests/TestRunnerTests/CustomResponse.cs b/APITestingRunner.Unit.Tests/TestRunnerTests/CustomResponse.cs new file mode 100644 index 0000000..80bbf7a --- /dev/null +++ b/APITestingRunner.Unit.Tests/TestRunnerTests/CustomResponse.cs @@ -0,0 +1,45 @@ +using System.Text; +using WireMock; +using WireMock.ResponseBuilders; +using WireMock.ResponseProviders; +using WireMock.Settings; +using WireMock.Types; +using WireMock.Util; + +namespace APITestingRunner.Unit.Tests.TestRunnerTests +{ + public class CustomResponse : IResponseProvider + { + private static int _count = 0; + public async Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IMapping mapping, IRequestMessage requestMessage, WireMockServerSettings settings) + { + ResponseMessage response; + if (_count % 2 == 0) + { + response = new ResponseMessage() { StatusCode = 200 }; + SetBody(response, @"{ ""msg"": ""Hello from wiremock!"" }"); + } + else + { + response = new ResponseMessage() { StatusCode = 500 }; + SetBody(response, @"{ ""msg"": ""Hello some error from wiremock!"" }"); + } + + _count++; + (ResponseMessage, IMapping) tuple = (response, null); + return await Task.FromResult(tuple); + } + + + private void SetBody(ResponseMessage response, string body) + { + response.BodyDestination = BodyDestinationFormat.SameAsSource; + response.BodyData = new BodyData + { + Encoding = Encoding.UTF8, + DetectedBodyType = BodyType.String, + BodyAsString = body + }; + } + } +} \ No newline at end of file diff --git a/APITestingRunner.Unit.Tests/TestRunnerTests/TestRunnerWithOptionsWithConfigAPIBasedOnDatabaseCallsTests.cs b/APITestingRunner.Unit.Tests/TestRunnerTests/TestRunnerWithOptionsWithConfigAPIBasedOnDatabaseCallsTests.cs index e6b1ac1..57b62c5 100644 --- a/APITestingRunner.Unit.Tests/TestRunnerTests/TestRunnerWithOptionsWithConfigAPIBasedOnDatabaseCallsTests.cs +++ b/APITestingRunner.Unit.Tests/TestRunnerTests/TestRunnerWithOptionsWithConfigAPIBasedOnDatabaseCallsTests.cs @@ -61,7 +61,8 @@ public async Task ValidateImplementationFor_SingleAPICallAsync_ShouldMakeAnAPICa .UsingGet() ) .RespondWith( - Response.Create() + Response + .Create() .WithStatusCode(200) .WithHeader("Content-Type", "text/plain") .WithBody("Hello, world!") @@ -334,5 +335,77 @@ public async Task ValidateImplementationFor_SingleAPICallAsync_ShouldAppendIdToU _ = logger.Messages[3].Item2.Should().ContainEquivalentOf("/WeatherForecast/1 200 success"); _ = logger.Messages[4].Item2.Should().Contain("Total process took:"); } + + [TestMethod] + [TestCategory("SimpleAPICallBasedOnDbSource")] + [TestCategory("dbcapture")] + public async Task ValidateImplementationFor_WireMockTest() + { + //note https://github.com/WireMock-Net/WireMock.Net/wiki/Scenarios-and-States + server.Given( + WireMock.RequestBuilders.Request.Create() + .WithPath("/WeatherForecast/1") + + .UsingGet() + ) + .RespondWith(new CustomResponse()); + + Config apiTesterConfig = new() + { + UrlBase = "http://localhost:7055", + CompareUrlBase = string.Empty, + CompareUrlPath = string.Empty, + UrlPath = "/WeatherForecast/{bindingId}", + RequestBody = null, + HeaderParam = [ + new Param("accept","application/json") + ], + UrlParam = null!, + DBConnectionString = _dbConnectionStringForTests, + DBQuery = "select top 1 id as bindingId from dbo.sampleTable;", + DBFields = [ + new Param("bindingId", "bindingId"), + ], + RequestType = RequestType.GET, + ResultsStoreOption = StoreResultsOption.All, + ConfigMode = TesterConfigMode.CaptureAndCompare, + OutputLocation = DirectoryServices.AssemblyDirectory, + }; + + TestLogger logger = new(); + + var testRunner = await new ApiTesterRunner(logger) + .RunTests(apiTesterConfig); + + _ = testRunner.Errors.Should().BeEmpty(); + _ = logger.Messages.Count.Should().Be(5); + + _ = logger.Messages[0].Item2.Should().ContainEquivalentOf("Validating database based data source start"); + _ = logger.Messages[1].Item2.Should().ContainEquivalentOf("Found database connection string"); + _ = logger.Messages[2].Item2.Should().ContainEquivalentOf("Found database query and db fields. Attempting to load data from database."); + _ = logger.Messages[3].Item2.Should().ContainEquivalentOf("/WeatherForecast/1 200 success"); + _ = logger.Messages[4].Item2.Should().Contain("Total process took:"); + + logger = new(); + testRunner = await new ApiTesterRunner(logger) + .RunTests(apiTesterConfig); + + _ = testRunner.Errors.Should().BeEmpty(); + _ = logger.Messages.Count.Should().Be(13); + var messages = logger.Messages.Select(x => x.Item2).ToList(); + + _ = messages.Should().ContainEquivalentOf("Validating database based data source start"); + _ = messages.Should().ContainEquivalentOf("Found database connection string"); + _ = messages.Should().ContainEquivalentOf("Found database query and db fields. Attempting to load data from database."); + _ = messages.Should().ContainEquivalentOf("Processing comparison using:ContentReplacements"); + _ = messages.Should().ContainEquivalentOf("Processing comparison using:ContentReplacements with result Matching"); + _ = messages.Should().ContainEquivalentOf("Processing comparison using:StringPlugin"); + _ = messages.Should().ContainEquivalentOf("Source is different in length: 33 < 44"); + _ = messages.Should().ContainEquivalentOf("Difference at path '' for property 'Root'"); + _ = messages.Should().ContainEquivalentOf("Difference at path '.msg' for property 'msg'"); + _ = messages.Should().ContainEquivalentOf("DiffValue is: Hello from wiremock! <> Hello some error from wiremock!"); + _ = messages.Should().ContainEquivalentOf("Processing comparison using:StringPlugin with result Different"); + _ = messages.Should().ContainEquivalentOf("GET /WeatherForecast/1 500 fail Results/request-1.json Different"); + } } } \ No newline at end of file From 5e796315190a34917f149a60eb451156398028c3 Mon Sep 17 00:00:00 2001 From: CpoDesign Date: Fri, 1 Dec 2023 00:46:51 +0000 Subject: [PATCH 30/30] Removed redundant tests --- .../TestRunnerTests/DataComparisonTests.cs | 58 ------------------- APITestingRunner/APICallResultComparison.cs | 46 --------------- 2 files changed, 104 deletions(-) delete mode 100644 APITestingRunner.Unit.Tests/TestRunnerTests/DataComparisonTests.cs delete mode 100644 APITestingRunner/APICallResultComparison.cs diff --git a/APITestingRunner.Unit.Tests/TestRunnerTests/DataComparisonTests.cs b/APITestingRunner.Unit.Tests/TestRunnerTests/DataComparisonTests.cs deleted file mode 100644 index 50a9f26..0000000 --- a/APITestingRunner.Unit.Tests/TestRunnerTests/DataComparisonTests.cs +++ /dev/null @@ -1,58 +0,0 @@ -using APITestingRunner.ApiRequest; -using FluentAssertions; - -namespace APITestingRunner.Unit.Tests.TestRunnerTests -{ - - [TestClass] - public class DataComparisonTests - { - - //TODO: Review together tests for any that shoudl be type-safe - [TestMethod] - public void CompareAPiResults_ShouldReturnMatching() - { - // -> StatusCode = response.StatusCode, Headers = responseHeaders, Url = pathAndQuery, Item = item, IsSuccessStatusCode = response.IsSuccessStatusCode, ResponseContent = content } - var apiResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = string.Empty }; - var fileResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = string.Empty }; - var expectedResult = ComparisonStatus.Matching; - - var result = new APICallResultComparison().ProcessComparison(apiResult, fileResult, ComparisonStatus.NewFile); - _ = result.Should().Be(expectedResult); - } - - [TestMethod] - public void CompareAPiResults_ShouldReturnDifferent() - { - var apiResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = string.Empty }; - var fileResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = "test" }; - var expectedResult = ComparisonStatus.Different; - - - var result = new APICallResultComparison().ProcessComparison(apiResult, fileResult, ComparisonStatus.NewFile); - _ = result.Should().Be(expectedResult); - } - - [TestMethod] - public void CompareAPiResults_ShouldReturnDifferent_StatusCodeIsDifferent() - { - var apiResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = string.Empty }; - var fileResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.Accepted, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = "test" }; - var expectedResult = ComparisonStatus.Different; - - var result = new APICallResultComparison().ProcessComparison(apiResult, fileResult, ComparisonStatus.NewFile); - _ = result.Should().Be(expectedResult); - } - - [TestMethod] - public void CompareAPiResults_ShouldReturnDifferent_IsSuccessCodeIsDifferent() - { - var apiResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = false, ResponseContent = "test" }; - var fileResult = new ApiCallResult { StatusCode = System.Net.HttpStatusCode.OK, Headers = null, Url = null, DataQueryResult = null, IsSuccessStatusCode = true, ResponseContent = "test" }; - var expectedResult = ComparisonStatus.Different; - - var result = new APICallResultComparison().ProcessComparison(apiResult, fileResult, ComparisonStatus.NewFile); - _ = result.Should().Be(expectedResult); - } - } -} \ No newline at end of file diff --git a/APITestingRunner/APICallResultComparison.cs b/APITestingRunner/APICallResultComparison.cs deleted file mode 100644 index 0bb8f1e..0000000 --- a/APITestingRunner/APICallResultComparison.cs +++ /dev/null @@ -1,46 +0,0 @@ -// See https://aka.ms/new-console-template for more information - -using APITestingRunner.ApiRequest; -using APITestingRunner.Configuration; -using APITestingRunner.Plugins; -using Microsoft.Extensions.Logging; - -namespace APITestingRunner -{ - /// - /// Simple data comparison plugin. - /// - public class APICallResultComparison : IPlugin - { - /// - public string Name => "APICallResultStatus"; - - /// - public string Description => "Validates if API call has been successful as the source API result"; - - /// - public void ApplyConfig(ref IConfig config, ILogger logger) - { - - } - - /// - public string ProcessBeforeSave(string apiResponseString) - { - return apiResponseString; - } - - /// - public ComparisonStatus ProcessComparison(ApiCallResult apiCallResult, ApiCallResult fileSourceResult, ComparisonStatus comparisonStatus) - { - - return comparisonStatus; - } - - /// - public string ProcessValidation(string value) - { - return value; - } - } -} \ No newline at end of file