diff --git a/.editorconfig b/.editorconfig index b78e7a35b8..39f9dc14c9 100644 --- a/.editorconfig +++ b/.editorconfig @@ -105,8 +105,8 @@ dotnet_style_prefer_compound_assignment = true:warning # not default, default i dotnet_diagnostic.IDE0074.severity = warning # not default, set in accordance to previous setting # IDE0032: Use auto property -dotnet_style_prefer_auto_properties = true:warning # not default, default is true:suggestion, increased severity to ensure it is used -dotnet_diagnostic.IDE0032.severity = warning # not default, set in accordance to previous setting +dotnet_style_prefer_auto_properties = true:suggestion # not default, default is true:suggestion, increased severity to ensure it is used +dotnet_diagnostic.IDE0032.severity = suggestion # not default, set in accordance to previous setting # Field preferences dotnet_style_readonly_field = true:warning diff --git a/.github/workflows/AzureDevOps.yml b/.github/workflows/AzureDevOps.yml index d497856f1e..ec1dd85b71 100644 --- a/.github/workflows/AzureDevOps.yml +++ b/.github/workflows/AzureDevOps.yml @@ -4,20 +4,44 @@ on: issues: types: [labeled] #, opened, edited, deleted, closed, reopened, labeled, unlabeled, assigned + issue_comment: + types: [created, edited, deleted] + +concurrency: + group: issue-${{ github.event.issue.number }} + cancel-in-progress: false + +# Extra permissions needed to login with Entra ID service principal via federated identity +permissions: + id-token: write + issues: write jobs: updateAzDO: if: github.event.label.name == 'sprint' runs-on: ubuntu-latest + environment: ado steps: + - name: Login to Azure + uses: azure/login@v2 + with: + client-id: ${{ secrets.ENTRA_APP_CLIENT_ID }} + tenant-id: ${{ secrets.ENTRA_APP_TENANT_ID }} + allow-no-subscriptions: true + - name: Get Azure DevOps token + id: get_ado_token + run: + # The resource ID for Azure DevOps is always 499b84ac-1321-427f-aa17-267ca6975798 + # https://learn.microsoft.com/azure/devops/integrate/get-started/authentication/service-principal-managed-identity + echo "ado_token=$(az account get-access-token --resource 499b84ac-1321-427f-aa17-267ca6975798 --query "accessToken" --output tsv)" >> $GITHUB_ENV - uses: pavelhorak/github-actions-issue-to-work-item@main env: - ado_token: "${{ secrets.ADO_PERSONAL_ACCESS_TOKEN }}" + ado_token: "${{ env.ado_token }}" github_token: "${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}" ado_organization: "${{ secrets.ADO_ORGANIZATION }}" ado_project: "${{ secrets.ADO_PROJECT }}" ado_area_path: "${{ secrets.ADO_AREA_PATH }}" - ado_iteration_path: "${{ secrets.ADO_ITERATION_PATH }}" # this doesn't work: "@CurrentIteration('[DevDiv]\\.NET DevExp Prague')" + ado_iteration_path: "${{ secrets.ADO_ITERATION_PATH }}" ado_wit: "User Story" ado_new_state: "Committed" ado_active_state: "In Progress" diff --git a/Directory.Build.props b/Directory.Build.props index 1d8854a6ba..94e7a2ac6d 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -45,18 +45,7 @@ preview true - - $(NoWarn);CA1416;RS0037;CS1570;CS1572;CS1573;CS1574;CS1591 + $(NoWarn);CA1416;RS0037 diff --git a/Directory.Build.targets b/Directory.Build.targets index d38dee58b5..5aee4dd768 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,6 +1,10 @@ - + + + <_NetFrameworkHostedCompilersVersion Condition="'$(_NetFrameworkHostedCompilersVersion)' == ''">4.11.0-3.24280.3 + + - + https://github.com/dotnet/diagnostics - 33d8bf23a6566cd3fb9055acfc9f1141391d5421 + 513150c2f25077b1fcb194407e53c433c975f39b - + https://github.com/dotnet/source-build-externals - 7db00527ef8fbbe61f67e9295beebddf187efff8 + 2cef086137a68586fdd69848261e2a8cf8c48b73 - + https://github.com/dotnet/source-build-reference-packages - 9ae78a4e6412926d19ba97cfed159bf9de70b538 + cc732c57199f725857c201da146525e3be6bc504 @@ -33,8 +33,8 @@ 30ab651fcb4354552bd4891619a0bdd81e0ebdbf - - https://github.com/dotnet/core-setup + + https://github.com/dotnet/runtime 7d57652f33493fa022125b7f63aad0d70c52d810 @@ -44,14 +44,14 @@ - + https://github.com/dotnet/arcade - 7507f80c8db285bbc9939c1dff522a761cf4edc0 + 60ae233c3d77f11c5fdb53e570b64d503b13ba59 - + https://github.com/dotnet/arcade - 7507f80c8db285bbc9939c1dff522a761cf4edc0 + 60ae233c3d77f11c5fdb53e570b64d503b13ba59 @@ -62,9 +62,9 @@ https://github.com/dotnet/symreader-converter c5ba7c88f92e2dde156c324a8c8edc04d9fa4fe0 - + https://github.com/dotnet/arcade - 7507f80c8db285bbc9939c1dff522a761cf4edc0 + 60ae233c3d77f11c5fdb53e570b64d503b13ba59 diff --git a/eng/Versions.props b/eng/Versions.props index 76f8b0f8b1..d7260e0cea 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -8,8 +8,13 @@ is trying to parse that version and will consider any version with more than 4 `.` in it as invalid. --> true - 17.11.0 - preview + + false + 17.12.0 + release @@ -35,11 +40,11 @@ 3.11.0-beta1.23525.2 3.11.0-beta1.23525.2 17.7.0 - 0.2.0-preview.24307.1 - 3.0.0 + 0.2.0-preview.24416.1 + 3.1.0 2.0.0 17.9.0-beta.24058.4 - 17.11.3 + 17.12.5 17.10.34924.118 $(MicrosoftVisualStudioDiagnosticsUtilitiesVersion) 17.10.525-preview.1 @@ -66,9 +71,10 @@ 17.9.0 - 3.3.1 - 3.3.1 + 3.4.3 + 3.4.3 1.0.3-preview + 2.4.2 2.4.5 2.4.2 @@ -81,9 +87,9 @@ These versions need to be "statically" readable because we read this file as xml in our build and tests. --> - [3.3.1] - [3.3.1] - [3.2.2] + [3.4.3] + [3.4.3] + [3.3.1] [2.2.10] [2.2.10] [1.4.0] @@ -91,9 +97,9 @@ See Invoke-TestAssetsBuild in scripts/build.ps1. Exact versions are used to avoid Nuget substituting them by closest match, if we make a typo. These versions need to be "statically" readable because we read this file as xml in our build and tests. --> - [17.10.0-release-24177-07] - [17.9.0] - [17.8.0] + [17.10.0] + [17.10.0] + [17.9.0] [17.6.2] [16.11.0] [15.9.2] diff --git a/eng/common/SetupNugetSources.ps1 b/eng/common/SetupNugetSources.ps1 index c07f6a5260..2b0a5c9e66 100644 --- a/eng/common/SetupNugetSources.ps1 +++ b/eng/common/SetupNugetSources.ps1 @@ -1,32 +1,31 @@ # This script adds internal feeds required to build commits that depend on internal package sources. For instance, # dotnet6-internal would be added automatically if dotnet6 was found in the nuget.config file. In addition also enables # disabled internal Maestro (darc-int*) feeds. -# -# Optionally, this script also adds a credential entry for each of the internal feeds if supplied. This credential -# is added via the standard environment variable VSS_NUGET_EXTERNAL_FEED_ENDPOINTS. See -# https://github.com/microsoft/artifacts-credprovider/tree/v1.1.1?tab=readme-ov-file#environment-variables for more details +# +# Optionally, this script also adds a credential entry for each of the internal feeds if supplied. # # See example call for this script below. # # - task: PowerShell@2 -# displayName: Setup Internal Feeds +# displayName: Setup Private Feeds Credentials # condition: eq(variables['Agent.OS'], 'Windows_NT') # inputs: # filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 -# arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -# - task: NuGetAuthenticate@1 -# +# arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -Password $Env:Token +# env: +# Token: $(dn-bot-dnceng-artifact-feeds-rw) +# # Note that the NuGetAuthenticate task should be called after SetupNugetSources. # This ensures that: # - Appropriate creds are set for the added internal feeds (if not supplied to the scrupt) -# - The credential provider is installed +# - The credential provider is installed. # # This logic is also abstracted into enable-internal-sources.yml. [CmdletBinding()] param ( [Parameter(Mandatory = $true)][string]$ConfigFile, - [string]$Password + $Password ) $ErrorActionPreference = "Stop" @@ -35,23 +34,12 @@ Set-StrictMode -Version 2.0 . $PSScriptRoot\tools.ps1 -$feedEndpoints = $null - -# If a credential is provided, ensure that we don't overwrite the current set of -# credentials that may have been provided by a previous call to the credential provider. -if ($Password -and $null -ne $env:VSS_NUGET_EXTERNAL_FEED_ENDPOINTS) { - $feedEndpoints = $env:VSS_NUGET_EXTERNAL_FEED_ENDPOINTS | ConvertFrom-Json -} elseif ($Password) { - $feedEndpoints = @{ endpointCredentials = @() } -} - # Add source entry to PackageSources -function AddPackageSource($sources, $SourceName, $SourceEndPoint, $pwd) { +function AddPackageSource($sources, $SourceName, $SourceEndPoint, $creds, $Username, $pwd) { $packageSource = $sources.SelectSingleNode("add[@key='$SourceName']") - if ($null -eq $packageSource) + if ($packageSource -eq $null) { - Write-Host "`tAdding package source" $SourceName $packageSource = $doc.CreateElement("add") $packageSource.SetAttribute("key", $SourceName) $packageSource.SetAttribute("value", $SourceEndPoint) @@ -61,33 +49,63 @@ function AddPackageSource($sources, $SourceName, $SourceEndPoint, $pwd) { Write-Host "Package source $SourceName already present." } - if ($pwd) { - $feedEndpoints.endpointCredentials = AddCredential -endpointCredentials $feedEndpoints.endpointCredentials -source $SourceEndPoint -pwd $pwd - } + AddCredential -Creds $creds -Source $SourceName -Username $Username -pwd $pwd } -# Add a new feed endpoint credential -function AddCredential([array]$endpointCredentials, $source, $pwd) { - $endpointCredentials += @{ - endpoint = $source; - password = $pwd +# Add a credential node for the specified source +function AddCredential($creds, $source, $username, $pwd) { + # If no cred supplied, don't do anything. + if (!$pwd) { + return; } - return $endpointCredentials + + # Looks for credential configuration for the given SourceName. Create it if none is found. + $sourceElement = $creds.SelectSingleNode($Source) + if ($sourceElement -eq $null) + { + $sourceElement = $doc.CreateElement($Source) + $creds.AppendChild($sourceElement) | Out-Null + } + + # Add the node to the credential if none is found. + $usernameElement = $sourceElement.SelectSingleNode("add[@key='Username']") + if ($usernameElement -eq $null) + { + $usernameElement = $doc.CreateElement("add") + $usernameElement.SetAttribute("key", "Username") + $sourceElement.AppendChild($usernameElement) | Out-Null + } + $usernameElement.SetAttribute("value", $Username) + + # Add the to the credential if none is found. + # Add it as a clear text because there is no support for encrypted ones in non-windows .Net SDKs. + # -> https://github.com/NuGet/Home/issues/5526 + $passwordElement = $sourceElement.SelectSingleNode("add[@key='ClearTextPassword']") + if ($passwordElement -eq $null) + { + $passwordElement = $doc.CreateElement("add") + $passwordElement.SetAttribute("key", "ClearTextPassword") + $sourceElement.AppendChild($passwordElement) | Out-Null + } + + $passwordElement.SetAttribute("value", $pwd) } -function InsertMaestroInternalFeedCredentials($Sources, $pwd) { - $maestroInternalSources = $Sources.SelectNodes("add[contains(@key,'darc-int')]") +function InsertMaestroPrivateFeedCredentials($Sources, $Creds, $Username, $pwd) { + $maestroPrivateSources = $Sources.SelectNodes("add[contains(@key,'darc-int')]") - ForEach ($PackageSource in $maestroInternalSources) { - Write-Host "`tAdding credential for Maestro's feed:" $PackageSource.Key - $feedEndpoints.endpointCredentials = AddCredential -endpointCredentials $feedEndpoints.endpointCredentials -source $PackageSource.value -pwd $pwd + Write-Host "Inserting credentials for $($maestroPrivateSources.Count) Maestro's private feeds." + + ForEach ($PackageSource in $maestroPrivateSources) { + Write-Host "`tInserting credential for Maestro's feed:" $PackageSource.Key + AddCredential -Creds $creds -Source $PackageSource.Key -Username $Username -pwd $pwd } } -function EnableInternalPackageSources($DisabledPackageSources) { - $maestroInternalSources = $DisabledPackageSources.SelectNodes("add[contains(@key,'darc-int')]") - ForEach ($DisabledPackageSource in $maestroInternalSources) { - Write-Host "`tEnsuring internal source '$($DisabledPackageSource.key)' is enabled by deleting it from disabledPackageSource" +function EnablePrivatePackageSources($DisabledPackageSources) { + $maestroPrivateSources = $DisabledPackageSources.SelectNodes("add[contains(@key,'darc-int')]") + ForEach ($DisabledPackageSource in $maestroPrivateSources) { + Write-Host "`tEnsuring private source '$($DisabledPackageSource.key)' is enabled by deleting it from disabledPackageSource" # Due to https://github.com/NuGet/Home/issues/10291, we must actually remove the disabled entries $DisabledPackageSources.RemoveChild($DisabledPackageSource) } @@ -105,27 +123,38 @@ $doc.Load($filename) # Get reference to or create one if none exist already $sources = $doc.DocumentElement.SelectSingleNode("packageSources") -if ($null -eq $sources) { +if ($sources -eq $null) { $sources = $doc.CreateElement("packageSources") $doc.DocumentElement.AppendChild($sources) | Out-Null } +$creds = $null +if ($Password) { + # Looks for a node. Create it if none is found. + $creds = $doc.DocumentElement.SelectSingleNode("packageSourceCredentials") + if ($creds -eq $null) { + $creds = $doc.CreateElement("packageSourceCredentials") + $doc.DocumentElement.AppendChild($creds) | Out-Null + } +} + # Check for disabledPackageSources; we'll enable any darc-int ones we find there $disabledSources = $doc.DocumentElement.SelectSingleNode("disabledPackageSources") -if ($null -ne $disabledSources) { +if ($disabledSources -ne $null) { Write-Host "Checking for any darc-int disabled package sources in the disabledPackageSources node" - EnableInternalPackageSources -DisabledPackageSources $disabledSources + EnablePrivatePackageSources -DisabledPackageSources $disabledSources } -if ($Password) { - InsertMaestroInternalFeedCredentials -Sources $sources -pwd $Password -} +$userName = "dn-bot" + +# Insert credential nodes for Maestro's private feeds +InsertMaestroPrivateFeedCredentials -Sources $sources -Creds $creds -Username $userName -pwd $Password # 3.1 uses a different feed url format so it's handled differently here $dotnet31Source = $sources.SelectSingleNode("add[@key='dotnet3.1']") -if ($null -ne $dotnet31Source) { - AddPackageSource -Sources $sources -SourceName "dotnet3.1-internal" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal/nuget/v3/index.json" -pwd $Password - AddPackageSource -Sources $sources -SourceName "dotnet3.1-internal-transport" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal-transport/nuget/v3/index.json" -pwd $Password +if ($dotnet31Source -ne $null) { + AddPackageSource -Sources $sources -SourceName "dotnet3.1-internal" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal/nuget/v2" -Creds $creds -Username $userName -pwd $Password + AddPackageSource -Sources $sources -SourceName "dotnet3.1-internal-transport" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal-transport/nuget/v2" -Creds $creds -Username $userName -pwd $Password } $dotnetVersions = @('5','6','7','8') @@ -133,18 +162,10 @@ $dotnetVersions = @('5','6','7','8') foreach ($dotnetVersion in $dotnetVersions) { $feedPrefix = "dotnet" + $dotnetVersion; $dotnetSource = $sources.SelectSingleNode("add[@key='$feedPrefix']") - if ($dotnetSource) { - AddPackageSource -Sources $sources -SourceName "$feedPrefix-internal" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/internal/_packaging/$feedprefix-internal/nuget/v3/index.json" -pwd $Password - AddPackageSource -Sources $sources -SourceName "$feedPrefix-internal-transport" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/internal/_packaging/$feedPrefix-internal-transport/nuget/v3/index.json" -pwd $Password + if ($dotnetSource -ne $null) { + AddPackageSource -Sources $sources -SourceName "$feedPrefix-internal" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/internal/_packaging/$feedPrefix-internal/nuget/v2" -Creds $creds -Username $userName -pwd $Password + AddPackageSource -Sources $sources -SourceName "$feedPrefix-internal-transport" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/internal/_packaging/$feedPrefix-internal-transport/nuget/v2" -Creds $creds -Username $userName -pwd $Password } } $doc.Save($filename) - -# If any credentials were added or altered, update the VSS_NUGET_EXTERNAL_FEED_ENDPOINTS environment variable -if ($null -ne $feedEndpoints) { - # ci is set to true so vso logging commands will be used. - $ci = $true - Write-PipelineSetVariable -Name 'VSS_NUGET_EXTERNAL_FEED_ENDPOINTS' -Value $($feedEndpoints | ConvertTo-Json) -IsMultiJobVariable $false - Write-PipelineSetVariable -Name 'NUGET_CREDENTIALPROVIDER_SESSIONTOKENCACHE_ENABLED' -Value "False" -IsMultiJobVariable $false -} \ No newline at end of file diff --git a/eng/common/SetupNugetSources.sh b/eng/common/SetupNugetSources.sh index 16c1e29ea3..b493479a1d 100644 --- a/eng/common/SetupNugetSources.sh +++ b/eng/common/SetupNugetSources.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -# This script adds internal feeds required to build commits that depend on intenral package sources. For instance, +# This script adds internal feeds required to build commits that depend on internal package sources. For instance, # dotnet6-internal would be added automatically if dotnet6 was found in the nuget.config file. In addition also enables # disabled internal Maestro (darc-int*) feeds. # diff --git a/eng/common/core-templates/job/job.yml b/eng/common/core-templates/job/job.yml index 7df5852797..c732bee9f4 100644 --- a/eng/common/core-templates/job/job.yml +++ b/eng/common/core-templates/job/job.yml @@ -24,12 +24,11 @@ parameters: enablePublishTestResults: false enablePublishUsingPipelines: false enableBuildRetry: false - disableComponentGovernance: '' - componentGovernanceIgnoreDirectories: '' mergeTestResults: false testRunTitle: '' testResultsFormat: '' name: '' + componentGovernanceSteps: [] preSteps: [] artifactPublishSteps: [] runAsPublic: false @@ -170,17 +169,8 @@ jobs: uploadRichNavArtifacts: ${{ coalesce(parameters.richCodeNavigationUploadArtifacts, false) }} continueOnError: true - - template: /eng/common/core-templates/steps/component-governance.yml - parameters: - is1ESPipeline: ${{ parameters.is1ESPipeline }} - ${{ if eq(parameters.disableComponentGovernance, '') }}: - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.runAsPublic, 'false'), or(startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'), startsWith(variables['Build.SourceBranch'], 'refs/heads/dotnet/'), startsWith(variables['Build.SourceBranch'], 'refs/heads/microsoft/'), eq(variables['Build.SourceBranch'], 'refs/heads/main'))) }}: - disableComponentGovernance: false - ${{ else }}: - disableComponentGovernance: true - ${{ else }}: - disableComponentGovernance: ${{ parameters.disableComponentGovernance }} - componentGovernanceIgnoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} + - ${{ each step in parameters.componentGovernanceSteps }}: + - ${{ step }} - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: @@ -190,14 +180,6 @@ jobs: continueOnError: ${{ parameters.continueOnError }} env: TeamName: $(_TeamName) - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.enableSbom, 'true')) }}: - - template: /eng/common/core-templates/steps/generate-sbom.yml - parameters: - is1ESPipeline: ${{ parameters.is1ESPipeline }} - PackageVersion: ${{ parameters.packageVersion}} - BuildDropPath: ${{ parameters.buildDropPath }} - IgnoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} - publishArtifacts: false # Publish test results - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'xunit')) }}: diff --git a/eng/common/core-templates/job/publish-build-assets.yml b/eng/common/core-templates/job/publish-build-assets.yml index 8fe9299542..3d3356e319 100644 --- a/eng/common/core-templates/job/publish-build-assets.yml +++ b/eng/common/core-templates/job/publish-build-assets.yml @@ -87,13 +87,15 @@ jobs: - task: NuGetAuthenticate@1 - - task: PowerShell@2 + - task: AzureCLI@2 displayName: Publish Build Assets inputs: - filePath: eng\common\sdk-task.ps1 + azureSubscription: "Darc: Maestro Production" + scriptType: ps + scriptLocation: scriptPath + scriptPath: $(Build.SourcesDirectory)/eng/common/sdk-task.ps1 arguments: -task PublishBuildAssets -restore -msbuildEngine dotnet /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' - /p:BuildAssetRegistryToken=$(MaestroAccessToken) /p:MaestroApiEndpoint=https://maestro.dot.net /p:PublishUsingPipelines=${{ parameters.publishUsingPipelines }} /p:OfficialBuildId=$(Build.BuildNumber) @@ -111,38 +113,19 @@ jobs: Add-Content -Path $filePath -Value "$(DefaultChannels)" Add-Content -Path $filePath -Value $(IsStableBuild) - - template: /eng/common/core-templates/steps/publish-build-artifacts.yml - parameters: - is1ESPipeline: ${{ parameters.is1ESPipeline }} - args: - displayName: Publish ReleaseConfigs Artifact - pathToPublish: '$(Build.StagingDirectory)/ReleaseConfigs' - publishLocation: Container - artifactName: ReleaseConfigs - - - task: powershell@2 - displayName: Check if SymbolPublishingExclusionsFile.txt exists - inputs: - targetType: inline - script: | $symbolExclusionfile = "$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt" - if(Test-Path -Path $symbolExclusionfile) + if (Test-Path -Path $symbolExclusionfile) { Write-Host "SymbolExclusionFile exists" - Write-Host "##vso[task.setvariable variable=SymbolExclusionFile]true" - } - else{ - Write-Host "Symbols Exclusion file does not exist" - Write-Host "##vso[task.setvariable variable=SymbolExclusionFile]false" + Copy-Item -Path $symbolExclusionfile -Destination "$(Build.StagingDirectory)/ReleaseConfigs" } - template: /eng/common/core-templates/steps/publish-build-artifacts.yml parameters: is1ESPipeline: ${{ parameters.is1ESPipeline }} args: - displayName: Publish SymbolPublishingExclusionsFile Artifact - condition: eq(variables['SymbolExclusionFile'], 'true') - pathToPublish: '$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt' + displayName: Publish ReleaseConfigs Artifact + pathToPublish: '$(Build.StagingDirectory)/ReleaseConfigs' publishLocation: Container artifactName: ReleaseConfigs @@ -153,14 +136,17 @@ jobs: PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} is1ESPipeline: ${{ parameters.is1ESPipeline }} - - task: PowerShell@2 + - task: AzureCLI@2 displayName: Publish Using Darc inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 - arguments: -BuildId $(BARBuildId) + azureSubscription: "Darc: Maestro Production" + scriptType: ps + scriptLocation: scriptPath + scriptPath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 + arguments: > + -BuildId $(BARBuildId) -PublishingInfraVersion 3 - -AzdoToken '$(publishing-dnceng-devdiv-code-r-build-re)' - -MaestroToken '$(MaestroApiAccessToken)' + -AzdoToken '$(System.AccessToken)' -WaitPublishingFinish true -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' diff --git a/eng/common/core-templates/job/source-index-stage1.yml b/eng/common/core-templates/job/source-index-stage1.yml index 8328e52ab1..205fb5b3a3 100644 --- a/eng/common/core-templates/job/source-index-stage1.yml +++ b/eng/common/core-templates/job/source-index-stage1.yml @@ -34,10 +34,12 @@ jobs: pool: ${{ if eq(variables['System.TeamProject'], 'public') }}: name: $(DncEngPublicBuildPool) - image: windows.vs2022.amd64.open + image: 1es-windows-2022-open + os: windows ${{ if eq(variables['System.TeamProject'], 'internal') }}: name: $(DncEngInternalBuildPool) - image: windows.vs2022.amd64 + image: 1es-windows-2022 + os: windows steps: - ${{ if eq(parameters.is1ESPipeline, '') }}: @@ -69,23 +71,11 @@ jobs: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: AzureCLI@2 - displayName: Get stage 1 auth token + displayName: Log in to Azure and upload stage1 artifacts to source index inputs: azureSubscription: 'SourceDotNet Stage1 Publish' addSpnToEnvironment: true scriptType: 'ps' scriptLocation: 'inlineScript' inlineScript: | - echo "##vso[task.setvariable variable=ARM_CLIENT_ID]$env:servicePrincipalId" - echo "##vso[task.setvariable variable=ARM_ID_TOKEN]$env:idToken" - echo "##vso[task.setvariable variable=ARM_TENANT_ID]$env:tenantId" - - - script: | - echo "Client ID: $(ARM_CLIENT_ID)" - echo "ID Token: $(ARM_ID_TOKEN)" - echo "Tenant ID: $(ARM_TENANT_ID)" - az login --service-principal -u $(ARM_CLIENT_ID) --tenant $(ARM_TENANT_ID) --allow-no-subscriptions --federated-token $(ARM_ID_TOKEN) - displayName: "Login to Azure" - - - script: $(Agent.TempDirectory)/.source-index/tools/UploadIndexStage1 -i .source-index/stage1output -n $(Build.Repository.Name) -s netsourceindexstage1 -b stage1 - displayName: Upload stage1 artifacts to source index + $(Agent.TempDirectory)/.source-index/tools/UploadIndexStage1 -i .source-index/stage1output -n $(Build.Repository.Name) -s netsourceindexstage1 -b stage1 diff --git a/eng/common/core-templates/post-build/common-variables.yml b/eng/common/core-templates/post-build/common-variables.yml index b9ede10bf0..d5627a994a 100644 --- a/eng/common/core-templates/post-build/common-variables.yml +++ b/eng/common/core-templates/post-build/common-variables.yml @@ -8,8 +8,6 @@ variables: # Default Maestro++ API Endpoint and API Version - name: MaestroApiEndPoint value: "https://maestro.dot.net" - - name: MaestroApiAccessToken - value: $(MaestroAccessToken) - name: MaestroApiVersion value: "2020-02-20" diff --git a/eng/common/core-templates/post-build/post-build.yml b/eng/common/core-templates/post-build/post-build.yml index fb15c40c03..454fd75c7a 100644 --- a/eng/common/core-templates/post-build/post-build.yml +++ b/eng/common/core-templates/post-build/post-build.yml @@ -300,14 +300,17 @@ stages: - task: NuGetAuthenticate@1 - - task: PowerShell@2 + - task: AzureCLI@2 displayName: Publish Using Darc inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 - arguments: -BuildId $(BARBuildId) + azureSubscription: "Darc: Maestro Production" + scriptType: ps + scriptLocation: scriptPath + scriptPath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 + arguments: > + -BuildId $(BARBuildId) -PublishingInfraVersion ${{ parameters.publishingInfraVersion }} - -AzdoToken '$(publishing-dnceng-devdiv-code-r-build-re)' - -MaestroToken '$(MaestroApiAccessToken)' + -AzdoToken '$(System.AccessToken)' -WaitPublishingFinish true -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' diff --git a/eng/common/core-templates/post-build/setup-maestro-vars.yml b/eng/common/core-templates/post-build/setup-maestro-vars.yml index 8d56b57267..f7602980db 100644 --- a/eng/common/core-templates/post-build/setup-maestro-vars.yml +++ b/eng/common/core-templates/post-build/setup-maestro-vars.yml @@ -15,19 +15,20 @@ steps: artifactName: ReleaseConfigs checkDownloadedFiles: true - - task: PowerShell@2 + - task: AzureCLI@2 name: setReleaseVars displayName: Set Release Configs Vars inputs: - targetType: inline - pwsh: true - script: | + azureSubscription: "Darc: Maestro Production" + scriptType: pscore + scriptLocation: inlineScript + inlineScript: | try { if (!$Env:PromoteToMaestroChannels -or $Env:PromoteToMaestroChannels.Trim() -eq '') { $Content = Get-Content $(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt $BarId = $Content | Select -Index 0 - $Channels = $Content | Select -Index 1 + $Channels = $Content | Select -Index 1 $IsStableBuild = $Content | Select -Index 2 $AzureDevOpsProject = $Env:System_TeamProject @@ -35,15 +36,16 @@ steps: $AzureDevOpsBuildId = $Env:Build_BuildId } else { - $buildApiEndpoint = "${Env:MaestroApiEndPoint}/api/builds/${Env:BARBuildId}?api-version=${Env:MaestroApiVersion}" + . $(Build.SourcesDirectory)\eng\common\tools.ps1 + $darc = Get-Darc + $buildInfo = & $darc get-build ` + --id ${{ parameters.BARBuildId }} ` + --extended ` + --output-format json ` + --ci ` + | convertFrom-Json - $apiHeaders = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' - $apiHeaders.Add('Accept', 'application/json') - $apiHeaders.Add('Authorization',"Bearer ${Env:MAESTRO_API_TOKEN}") - - $buildInfo = try { Invoke-WebRequest -Method Get -Uri $buildApiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } - - $BarId = $Env:BARBuildId + $BarId = ${{ parameters.BARBuildId }} $Channels = $Env:PromoteToMaestroChannels -split "," $Channels = $Channels -join "][" $Channels = "[$Channels]" @@ -69,6 +71,4 @@ steps: exit 1 } env: - MAESTRO_API_TOKEN: $(MaestroApiAccessToken) - BARBuildId: ${{ parameters.BARBuildId }} PromoteToMaestroChannels: ${{ parameters.PromoteToChannelIds }} diff --git a/eng/common/core-templates/steps/component-governance.yml b/eng/common/core-templates/steps/component-governance.yml index df449a34c1..cf0649aa95 100644 --- a/eng/common/core-templates/steps/component-governance.yml +++ b/eng/common/core-templates/steps/component-governance.yml @@ -2,7 +2,8 @@ parameters: disableComponentGovernance: false componentGovernanceIgnoreDirectories: '' is1ESPipeline: false - + displayName: 'Component Detection' + steps: - ${{ if eq(parameters.disableComponentGovernance, 'true') }}: - script: echo "##vso[task.setvariable variable=skipComponentGovernanceDetection]true" @@ -10,5 +11,6 @@ steps: - ${{ if ne(parameters.disableComponentGovernance, 'true') }}: - task: ComponentGovernanceComponentDetection@0 continueOnError: true + displayName: ${{ parameters.displayName }} inputs: - ignoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} \ No newline at end of file + ignoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} diff --git a/eng/common/core-templates/steps/enable-internal-sources.yml b/eng/common/core-templates/steps/enable-internal-sources.yml index 80deddafb1..64f881bffc 100644 --- a/eng/common/core-templates/steps/enable-internal-sources.yml +++ b/eng/common/core-templates/steps/enable-internal-sources.yml @@ -6,30 +6,42 @@ parameters: - name: is1ESPipeline type: boolean default: false +# Legacy parameters to allow for PAT usage +- name: legacyCredential + type: string + default: '' steps: - ${{ if ne(variables['System.TeamProject'], 'public') }}: - # If running on dnceng (internal project), just use the default behavior for NuGetAuthenticate. - # If running on DevDiv, NuGetAuthenticate is not really an option. It's scoped to a single feed, and we have many feeds that - # may be added. Instead, we'll use the traditional approach (add cred to nuget.config), but use an account token. - - ${{ if eq(variables['System.TeamProject'], 'internal') }}: + - ${{ if ne(parameters.legacyCredential, '') }}: - task: PowerShell@2 displayName: Setup Internal Feeds inputs: filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 - arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config - - task: NuGetAuthenticate@1 + arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -Password $Env:Token + env: + Token: ${{ parameters.legacyCredential }} + # If running on dnceng (internal project), just use the default behavior for NuGetAuthenticate. + # If running on DevDiv, NuGetAuthenticate is not really an option. It's scoped to a single feed, and we have many feeds that + # may be added. Instead, we'll use the traditional approach (add cred to nuget.config), but use an account token. - ${{ else }}: - - template: /eng/common/templates/steps/get-federated-access-token.yml - parameters: - federatedServiceConnection: ${{ parameters.nugetFederatedServiceConnection }} - outputVariableName: 'dnceng-artifacts-feeds-read-access-token' - - task: PowerShell@2 - displayName: Setup Internal Feeds - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 - arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -Password $(dnceng-artifacts-feeds-read-access-token) - # This is required in certain scenarios to install the ADO credential provider. - # It installed by default in some msbuild invocations (e.g. VS msbuild), but needs to be installed for others - # (e.g. dotnet msbuild). - - task: NuGetAuthenticate@1 + - ${{ if eq(variables['System.TeamProject'], 'internal') }}: + - task: PowerShell@2 + displayName: Setup Internal Feeds + inputs: + filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 + arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config + - ${{ else }}: + - template: /eng/common/templates/steps/get-federated-access-token.yml + parameters: + federatedServiceConnection: ${{ parameters.nugetFederatedServiceConnection }} + outputVariableName: 'dnceng-artifacts-feeds-read-access-token' + - task: PowerShell@2 + displayName: Setup Internal Feeds + inputs: + filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 + arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -Password $(dnceng-artifacts-feeds-read-access-token) + # This is required in certain scenarios to install the ADO credential provider. + # It installed by default in some msbuild invocations (e.g. VS msbuild), but needs to be installed for others + # (e.g. dotnet msbuild). + - task: NuGetAuthenticate@1 diff --git a/eng/common/core-templates/steps/get-federated-access-token.yml b/eng/common/core-templates/steps/get-federated-access-token.yml index c8c49cc0e8..3a4d4410c4 100644 --- a/eng/common/core-templates/steps/get-federated-access-token.yml +++ b/eng/common/core-templates/steps/get-federated-access-token.yml @@ -3,6 +3,14 @@ parameters: type: string - name: outputVariableName type: string +- name: is1ESPipeline + type: boolean +- name: stepName + type: string + default: 'getFederatedAccessToken' +- name: condition + type: string + default: '' # Resource to get a token for. Common values include: # - '499b84ac-1321-427f-aa17-267ca6975798' for Azure DevOps # - 'https://storage.azure.com/' for storage @@ -10,10 +18,16 @@ parameters: - name: resource type: string default: '499b84ac-1321-427f-aa17-267ca6975798' +- name: isStepOutputVariable + type: boolean + default: false steps: - task: AzureCLI@2 displayName: 'Getting federated access token for feeds' + name: ${{ parameters.stepName }} + ${{ if ne(parameters.condition, '') }}: + condition: ${{ parameters.condition }} inputs: azureSubscription: ${{ parameters.federatedServiceConnection }} scriptType: 'pscore' @@ -25,4 +39,4 @@ steps: exit 1 } Write-Host "Setting '${{ parameters.outputVariableName }}' with the access token value" - Write-Host "##vso[task.setvariable variable=${{ parameters.outputVariableName }};issecret=true]$accessToken" \ No newline at end of file + Write-Host "##vso[task.setvariable variable=${{ parameters.outputVariableName }};issecret=true;isOutput=${{ parameters.isStepOutputVariable }}]$accessToken" \ No newline at end of file diff --git a/eng/common/core-templates/steps/publish-logs.yml b/eng/common/core-templates/steps/publish-logs.yml index 8c5ea77b58..80788c5231 100644 --- a/eng/common/core-templates/steps/publish-logs.yml +++ b/eng/common/core-templates/steps/publish-logs.yml @@ -32,7 +32,6 @@ steps: '$(MaestroAccessToken)' '$(dn-bot-all-orgs-artifact-feeds-rw)' '$(akams-client-id)' - '$(akams-client-secret)' '$(microsoft-symbol-server-pat)' '$(symweb-symbol-server-pat)' '$(dn-bot-all-orgs-build-rw-code-rw)' diff --git a/eng/common/core-templates/steps/source-build.yml b/eng/common/core-templates/steps/source-build.yml index 16c778d92c..2915d29bb7 100644 --- a/eng/common/core-templates/steps/source-build.yml +++ b/eng/common/core-templates/steps/source-build.yml @@ -121,7 +121,9 @@ steps: # a nupkg cache of input packages (a local feed). # This path must match the upstream cache path in property 'CurrentRepoSourceBuiltNupkgCacheDir' # in src\Microsoft.DotNet.Arcade.Sdk\tools\SourceBuild\SourceBuildArcade.targets -- task: ComponentGovernanceComponentDetection@0 - displayName: Component Detection (Exclude upstream cache) - inputs: - ignoreDirectories: '$(Build.SourcesDirectory)/artifacts/sb/src/artifacts/obj/source-built-upstream-cache' +- template: /eng/common/core-templates/steps/component-governance.yml + parameters: + displayName: Component Detection (Exclude upstream cache) + is1ESPipeline: ${{ parameters.is1ESPipeline }} + componentGovernanceIgnoreDirectories: '$(Build.SourcesDirectory)/artifacts/sb/src/artifacts/obj/source-built-upstream-cache' + disableComponentGovernance: ${{ eq(variables['System.TeamProject'], 'public') }} diff --git a/eng/common/cross/arm/sources.list.bionic b/eng/common/cross/arm/sources.list.bionic deleted file mode 100644 index 2109557409..0000000000 --- a/eng/common/cross/arm/sources.list.bionic +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse diff --git a/eng/common/cross/arm/sources.list.focal b/eng/common/cross/arm/sources.list.focal deleted file mode 100644 index 4de2600c17..0000000000 --- a/eng/common/cross/arm/sources.list.focal +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse diff --git a/eng/common/cross/arm/sources.list.jammy b/eng/common/cross/arm/sources.list.jammy deleted file mode 100644 index 6bb0453029..0000000000 --- a/eng/common/cross/arm/sources.list.jammy +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse diff --git a/eng/common/cross/arm/sources.list.jessie b/eng/common/cross/arm/sources.list.jessie deleted file mode 100644 index 4d142ac9b1..0000000000 --- a/eng/common/cross/arm/sources.list.jessie +++ /dev/null @@ -1,3 +0,0 @@ -# Debian (sid) # UNSTABLE -deb http://ftp.debian.org/debian/ sid main contrib non-free -deb-src http://ftp.debian.org/debian/ sid main contrib non-free diff --git a/eng/common/cross/arm/sources.list.xenial b/eng/common/cross/arm/sources.list.xenial deleted file mode 100644 index 56fbb36a59..0000000000 --- a/eng/common/cross/arm/sources.list.xenial +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ xenial main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-security main restricted universe multiverse diff --git a/eng/common/cross/arm/sources.list.zesty b/eng/common/cross/arm/sources.list.zesty deleted file mode 100644 index ea2c14a787..0000000000 --- a/eng/common/cross/arm/sources.list.zesty +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ zesty main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.bionic b/eng/common/cross/arm64/sources.list.bionic deleted file mode 100644 index 2109557409..0000000000 --- a/eng/common/cross/arm64/sources.list.bionic +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.buster b/eng/common/cross/arm64/sources.list.buster deleted file mode 100644 index 7194ac64a9..0000000000 --- a/eng/common/cross/arm64/sources.list.buster +++ /dev/null @@ -1,11 +0,0 @@ -deb http://deb.debian.org/debian buster main -deb-src http://deb.debian.org/debian buster main - -deb http://deb.debian.org/debian-security/ buster/updates main -deb-src http://deb.debian.org/debian-security/ buster/updates main - -deb http://deb.debian.org/debian buster-updates main -deb-src http://deb.debian.org/debian buster-updates main - -deb http://deb.debian.org/debian buster-backports main contrib non-free -deb-src http://deb.debian.org/debian buster-backports main contrib non-free diff --git a/eng/common/cross/arm64/sources.list.focal b/eng/common/cross/arm64/sources.list.focal deleted file mode 100644 index 4de2600c17..0000000000 --- a/eng/common/cross/arm64/sources.list.focal +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.jammy b/eng/common/cross/arm64/sources.list.jammy deleted file mode 100644 index 6bb0453029..0000000000 --- a/eng/common/cross/arm64/sources.list.jammy +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.stretch b/eng/common/cross/arm64/sources.list.stretch deleted file mode 100644 index 0e12157743..0000000000 --- a/eng/common/cross/arm64/sources.list.stretch +++ /dev/null @@ -1,12 +0,0 @@ -deb http://deb.debian.org/debian stretch main -deb-src http://deb.debian.org/debian stretch main - -deb http://deb.debian.org/debian-security/ stretch/updates main -deb-src http://deb.debian.org/debian-security/ stretch/updates main - -deb http://deb.debian.org/debian stretch-updates main -deb-src http://deb.debian.org/debian stretch-updates main - -deb http://deb.debian.org/debian stretch-backports main contrib non-free -deb-src http://deb.debian.org/debian stretch-backports main contrib non-free - diff --git a/eng/common/cross/arm64/sources.list.xenial b/eng/common/cross/arm64/sources.list.xenial deleted file mode 100644 index 56fbb36a59..0000000000 --- a/eng/common/cross/arm64/sources.list.xenial +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ xenial main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.zesty b/eng/common/cross/arm64/sources.list.zesty deleted file mode 100644 index ea2c14a787..0000000000 --- a/eng/common/cross/arm64/sources.list.zesty +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ zesty main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-security main restricted universe multiverse diff --git a/eng/common/cross/armel/sources.list.jessie b/eng/common/cross/armel/sources.list.jessie deleted file mode 100644 index 3d9c3059d8..0000000000 --- a/eng/common/cross/armel/sources.list.jessie +++ /dev/null @@ -1,3 +0,0 @@ -# Debian (jessie) # Stable -deb http://ftp.debian.org/debian/ jessie main contrib non-free -deb-src http://ftp.debian.org/debian/ jessie main contrib non-free diff --git a/eng/common/cross/armv6/sources.list.bookworm b/eng/common/cross/armv6/sources.list.bookworm deleted file mode 100644 index 1016113526..0000000000 --- a/eng/common/cross/armv6/sources.list.bookworm +++ /dev/null @@ -1,2 +0,0 @@ -deb http://raspbian.raspberrypi.org/raspbian/ bookworm main contrib non-free rpi -deb-src http://raspbian.raspberrypi.org/raspbian/ bookworm main contrib non-free rpi diff --git a/eng/common/cross/armv6/sources.list.buster b/eng/common/cross/armv6/sources.list.buster deleted file mode 100644 index f27fc4fb34..0000000000 --- a/eng/common/cross/armv6/sources.list.buster +++ /dev/null @@ -1,2 +0,0 @@ -deb http://raspbian.raspberrypi.org/raspbian/ buster main contrib non-free rpi -deb-src http://raspbian.raspberrypi.org/raspbian/ buster main contrib non-free rpi diff --git a/eng/common/cross/build-rootfs.sh b/eng/common/cross/build-rootfs.sh index 7455dcb6af..4b5e8d7166 100644 --- a/eng/common/cross/build-rootfs.sh +++ b/eng/common/cross/build-rootfs.sh @@ -30,7 +30,8 @@ __IllumosArch=arm7 __HaikuArch=arm __QEMUArch=arm __UbuntuArch=armhf -__UbuntuRepo="http://ports.ubuntu.com/" +__UbuntuRepo= +__UbuntuSuites="updates security backports" __LLDB_Package="liblldb-3.9-dev" __SkipUnmount=0 @@ -71,7 +72,7 @@ __AlpinePackages+=" krb5-dev" __AlpinePackages+=" openssl-dev" __AlpinePackages+=" zlib-dev" -__FreeBSDBase="13.2-RELEASE" +__FreeBSDBase="13.3-RELEASE" __FreeBSDPkg="1.17.0" __FreeBSDABI="13" __FreeBSDPackages="libunwind" @@ -129,6 +130,7 @@ __AlpineKeys=' 616db30d:MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAnpUpyWDWjlUk3smlWeA0\nlIMW+oJ38t92CRLHH3IqRhyECBRW0d0aRGtq7TY8PmxjjvBZrxTNDpJT6KUk4LRm\na6A6IuAI7QnNK8SJqM0DLzlpygd7GJf8ZL9SoHSH+gFsYF67Cpooz/YDqWrlN7Vw\ntO00s0B+eXy+PCXYU7VSfuWFGK8TGEv6HfGMALLjhqMManyvfp8hz3ubN1rK3c8C\nUS/ilRh1qckdbtPvoDPhSbTDmfU1g/EfRSIEXBrIMLg9ka/XB9PvWRrekrppnQzP\nhP9YE3x/wbFc5QqQWiRCYyQl/rgIMOXvIxhkfe8H5n1Et4VAorkpEAXdsfN8KSVv\nLSMazVlLp9GYq5SUpqYX3KnxdWBgN7BJoZ4sltsTpHQ/34SXWfu3UmyUveWj7wp0\nx9hwsPirVI00EEea9AbP7NM2rAyu6ukcm4m6ATd2DZJIViq2es6m60AE6SMCmrQF\nwmk4H/kdQgeAELVfGOm2VyJ3z69fQuywz7xu27S6zTKi05Qlnohxol4wVb6OB7qG\nLPRtK9ObgzRo/OPumyXqlzAi/Yvyd1ZQk8labZps3e16bQp8+pVPiumWioMFJDWV\nGZjCmyMSU8V6MB6njbgLHoyg2LCukCAeSjbPGGGYhnKLm1AKSoJh3IpZuqcKCk5C\n8CM1S15HxV78s9dFntEqIokCAwEAAQ== ' __Keyring= +__KeyringFile="/usr/share/keyrings/ubuntu-archive-keyring.gpg" __SkipSigCheck=0 __UseMirror=0 @@ -162,6 +164,7 @@ while :; do __UbuntuArch=armel __UbuntuRepo="http://ftp.debian.org/debian/" __CodeName=jessie + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" ;; armv6) __BuildArch=armv6 @@ -169,10 +172,12 @@ while :; do __QEMUArch=arm __UbuntuRepo="http://raspbian.raspberrypi.org/raspbian/" __CodeName=buster + __KeyringFile="/usr/share/keyrings/raspbian-archive-keyring.gpg" __LLDB_Package="liblldb-6.0-dev" + __UbuntuSuites= - if [[ -e "/usr/share/keyrings/raspbian-archive-keyring.gpg" ]]; then - __Keyring="--keyring /usr/share/keyrings/raspbian-archive-keyring.gpg" + if [[ -e "$__KeyringFile" ]]; then + __Keyring="--keyring $__KeyringFile" fi ;; riscv64) @@ -181,13 +186,8 @@ while :; do __AlpinePackages="${__AlpinePackages// lldb-dev/}" __QEMUArch=riscv64 __UbuntuArch=riscv64 - __UbuntuRepo="http://deb.debian.org/debian" __UbuntuPackages="${__UbuntuPackages// libunwind8-dev/}" unset __LLDB_Package - - if [[ -e "/usr/share/keyrings/debian-archive-keyring.gpg" ]]; then - __Keyring="--keyring /usr/share/keyrings/debian-archive-keyring.gpg --include=debian-archive-keyring" - fi ;; ppc64le) __BuildArch=ppc64le @@ -288,8 +288,17 @@ while :; do __CodeName=jammy fi ;; + noble) # Ubuntu 24.04 + if [[ "$__CodeName" != "jessie" ]]; then + __CodeName=noble + fi + if [[ -n "$__LLDB_Package" ]]; then + __LLDB_Package="liblldb-18-dev" + fi + ;; jessie) # Debian 8 __CodeName=jessie + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then __UbuntuRepo="http://ftp.debian.org/debian/" @@ -298,6 +307,7 @@ while :; do stretch) # Debian 9 __CodeName=stretch __LLDB_Package="liblldb-6.0-dev" + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then __UbuntuRepo="http://ftp.debian.org/debian/" @@ -306,6 +316,7 @@ while :; do buster) # Debian 10 __CodeName=buster __LLDB_Package="liblldb-6.0-dev" + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then __UbuntuRepo="http://ftp.debian.org/debian/" @@ -313,6 +324,7 @@ while :; do ;; bullseye) # Debian 11 __CodeName=bullseye + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then __UbuntuRepo="http://ftp.debian.org/debian/" @@ -320,6 +332,7 @@ while :; do ;; bookworm) # Debian 12 __CodeName=bookworm + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then __UbuntuRepo="http://ftp.debian.org/debian/" @@ -327,6 +340,7 @@ while :; do ;; sid) # Debian sid __CodeName=sid + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then __UbuntuRepo="http://ftp.debian.org/debian/" @@ -436,6 +450,10 @@ fi __UbuntuPackages+=" ${__LLDB_Package:-}" +if [[ -z "$__UbuntuRepo" ]]; then + __UbuntuRepo="http://ports.ubuntu.com/" +fi + if [[ -n "$__LLVM_MajorVersion" ]]; then __UbuntuPackages+=" libclang-common-${__LLVM_MajorVersion}${__LLVM_MinorVersion:+.$__LLVM_MinorVersion}-dev" fi @@ -587,18 +605,18 @@ elif [[ "$__CodeName" == "illumos" ]]; then fi echo "Building binutils. Please wait.." if [[ "$__hasWget" == 1 ]]; then - wget -O- https://ftp.gnu.org/gnu/binutils/binutils-2.33.1.tar.bz2 | tar -xjf - + wget -O- https://ftp.gnu.org/gnu/binutils/binutils-2.42.tar.xz | tar -xJf - else - curl -SL https://ftp.gnu.org/gnu/binutils/binutils-2.33.1.tar.bz2 | tar -xjf - + curl -SL https://ftp.gnu.org/gnu/binutils/binutils-2.42.tar.xz | tar -xJf - fi mkdir build-binutils && cd build-binutils - ../binutils-2.33.1/configure --prefix="$__RootfsDir" --target="${__illumosArch}-sun-solaris2.10" --program-prefix="${__illumosArch}-illumos-" --with-sysroot="$__RootfsDir" + ../binutils-2.42/configure --prefix="$__RootfsDir" --target="${__illumosArch}-sun-solaris2.11" --program-prefix="${__illumosArch}-illumos-" --with-sysroot="$__RootfsDir" make -j "$JOBS" && make install && cd .. echo "Building gcc. Please wait.." if [[ "$__hasWget" == 1 ]]; then - wget -O- https://ftp.gnu.org/gnu/gcc/gcc-8.4.0/gcc-8.4.0.tar.xz | tar -xJf - + wget -O- https://ftp.gnu.org/gnu/gcc/gcc-13.3.0/gcc-13.3.0.tar.xz | tar -xJf - else - curl -SL https://ftp.gnu.org/gnu/gcc/gcc-8.4.0/gcc-8.4.0.tar.xz | tar -xJf - + curl -SL https://ftp.gnu.org/gnu/gcc/gcc-13.3.0/gcc-13.3.0.tar.xz | tar -xJf - fi CFLAGS="-fPIC" CXXFLAGS="-fPIC" @@ -606,7 +624,7 @@ elif [[ "$__CodeName" == "illumos" ]]; then CFLAGS_FOR_TARGET="-fPIC" export CFLAGS CXXFLAGS CXXFLAGS_FOR_TARGET CFLAGS_FOR_TARGET mkdir build-gcc && cd build-gcc - ../gcc-8.4.0/configure --prefix="$__RootfsDir" --target="${__illumosArch}-sun-solaris2.10" --program-prefix="${__illumosArch}-illumos-" --with-sysroot="$__RootfsDir" --with-gnu-as \ + ../gcc-13.3.0/configure --prefix="$__RootfsDir" --target="${__illumosArch}-sun-solaris2.11" --program-prefix="${__illumosArch}-illumos-" --with-sysroot="$__RootfsDir" --with-gnu-as \ --with-gnu-ld --disable-nls --disable-libgomp --disable-libquadmath --disable-libssp --disable-libvtv --disable-libcilkrts --disable-libada --disable-libsanitizer \ --disable-libquadmath-support --disable-shared --enable-tls make -j "$JOBS" && make install && cd .. @@ -614,7 +632,7 @@ elif [[ "$__CodeName" == "illumos" ]]; then if [[ "$__UseMirror" == 1 ]]; then BaseUrl=https://pkgsrc.smartos.skylime.net fi - BaseUrl="$BaseUrl/packages/SmartOS/trunk/${__illumosArch}/All" + BaseUrl="$BaseUrl/packages/SmartOS/2019Q4/${__illumosArch}/All" echo "Downloading manifest" if [[ "$__hasWget" == 1 ]]; then wget "$BaseUrl" @@ -732,8 +750,18 @@ elif [[ -n "$__CodeName" ]]; then fi # shellcheck disable=SC2086 + echo running debootstrap "--variant=minbase" $__Keyring --arch "$__UbuntuArch" "$__CodeName" "$__RootfsDir" "$__UbuntuRepo" debootstrap "--variant=minbase" $__Keyring --arch "$__UbuntuArch" "$__CodeName" "$__RootfsDir" "$__UbuntuRepo" - cp "$__CrossDir/$__BuildArch/sources.list.$__CodeName" "$__RootfsDir/etc/apt/sources.list" + + mkdir -p "$__RootfsDir/etc/apt/sources.list.d/" + cat > "$__RootfsDir/etc/apt/sources.list.d/$__CodeName.sources" < 0 ]]; do diff --git a/eng/common/dotnet-install.sh b/eng/common/dotnet-install.sh index a2fba47038..7b9d97e3bd 100755 --- a/eng/common/dotnet-install.sh +++ b/eng/common/dotnet-install.sh @@ -71,6 +71,9 @@ case $cpuname in i[3-6]86) buildarch=x86 ;; + riscv64) + buildarch=riscv64 + ;; *) echo "Unknown CPU $cpuname detected, treating it as x64" buildarch=x64 diff --git a/eng/common/native/CommonLibrary.psm1 b/eng/common/native/CommonLibrary.psm1 index ca38268c44..f71f6af6cd 100644 --- a/eng/common/native/CommonLibrary.psm1 +++ b/eng/common/native/CommonLibrary.psm1 @@ -277,7 +277,8 @@ function Get-MachineArchitecture { if (($ProcessorArchitecture -Eq "AMD64") -Or ($ProcessorArchitecture -Eq "IA64") -Or ($ProcessorArchitecture -Eq "ARM64") -Or - ($ProcessorArchitecture -Eq "LOONGARCH64")) { + ($ProcessorArchitecture -Eq "LOONGARCH64") -Or + ($ProcessorArchitecture -Eq "RISCV64")) { return "x64" } return "x86" diff --git a/eng/common/native/init-compiler.sh b/eng/common/native/init-compiler.sh index 62900e12b2..9a0e1f2b45 100644 --- a/eng/common/native/init-compiler.sh +++ b/eng/common/native/init-compiler.sh @@ -19,11 +19,9 @@ case "$compiler" in # clangx.y or clang-x.y version="$(echo "$compiler" | tr -d '[:alpha:]-=')" majorVersion="${version%%.*}" - [ -z "${version##*.*}" ] && minorVersion="${version#*.}" - if [ -z "$minorVersion" ] && [ -n "$majorVersion" ] && [ "$majorVersion" -le 6 ]; then - minorVersion=0; - fi + # LLVM based on v18 released in early 2024, with two releases per year + maxVersion="$((18 + ((($(date +%Y) - 2024) * 12 + $(date +%-m) - 3) / 6)))" compiler=clang ;; @@ -31,7 +29,9 @@ case "$compiler" in # gccx.y or gcc-x.y version="$(echo "$compiler" | tr -d '[:alpha:]-=')" majorVersion="${version%%.*}" - [ -z "${version##*.*}" ] && minorVersion="${version#*.}" + + # GCC based on v14 released in early 2024, with one release per year + maxVersion="$((14 + ((($(date +%Y) - 2024) * 12 + $(date +%-m) - 3) / 12)))" compiler=gcc ;; esac @@ -49,12 +49,10 @@ check_version_exists() { desired_version=-1 # Set up the environment to be used for building with the desired compiler. - if command -v "$compiler-$1.$2" > /dev/null; then - desired_version="-$1.$2" - elif command -v "$compiler$1$2" > /dev/null; then - desired_version="$1$2" - elif command -v "$compiler-$1$2" > /dev/null; then - desired_version="-$1$2" + if command -v "$compiler-$1" > /dev/null; then + desired_version="-$1" + elif command -v "$compiler$1" > /dev/null; then + desired_version="$1" fi echo "$desired_version" @@ -75,7 +73,7 @@ set_compiler_version_from_CC() { fi # gcc and clang often display 3 part versions. However, gcc can show only 1 part in some environments. - IFS=. read -r majorVersion minorVersion _ < /dev/null; then - echo "Error: No usable version of $compiler found." + echo "Error: No compatible version of $compiler was found within the range of $minVersion to $maxVersion. Please upgrade your toolchain or specify the compiler explicitly using CLR_CC and CLR_CXX environment variables." exit 1 fi CC="$(command -v "$compiler" 2> /dev/null)" CXX="$(command -v "$cxxCompiler" 2> /dev/null)" set_compiler_version_from_CC - else - if [ "$compiler" = "clang" ] && [ "$majorVersion" -lt 5 ] && { [ "$build_arch" = "arm" ] || [ "$build_arch" = "armel" ]; }; then - # If a major version was provided explicitly, and it was too old, find a newer compiler instead - if ! command -v "$compiler" > /dev/null; then - echo "Error: Found clang version $majorVersion which is not supported on arm/armel architectures, and there is no clang in PATH." - exit 1 - fi - - CC="$(command -v "$compiler" 2> /dev/null)" - CXX="$(command -v "$cxxCompiler" 2> /dev/null)" - set_compiler_version_from_CC - fi fi else - desired_version="$(check_version_exists "$majorVersion" "$minorVersion")" + desired_version="$(check_version_exists "$majorVersion")" if [ "$desired_version" = "-1" ]; then - echo "Error: Could not find specific version of $compiler: $majorVersion $minorVersion." + echo "Error: Could not find specific version of $compiler: $majorVersion." exit 1 fi fi diff --git a/eng/common/post-build/nuget-validation.ps1 b/eng/common/post-build/nuget-validation.ps1 index 9c81aa4391..e5de00c898 100644 --- a/eng/common/post-build/nuget-validation.ps1 +++ b/eng/common/post-build/nuget-validation.ps1 @@ -5,6 +5,13 @@ param( [Parameter(Mandatory=$true)][string] $PackagesPath # Path to where the packages to be validated are ) +# `tools.ps1` checks $ci to perform some actions. Since the post-build +# scripts don't necessarily execute in the same agent that run the +# build.ps1/sh script this variable isn't automatically set. +$ci = $true +$disableConfigureToolsetImport = $true +. $PSScriptRoot\..\tools.ps1 + try { & $PSScriptRoot\nuget-verification.ps1 ${PackagesPath}\*.nupkg } diff --git a/eng/common/post-build/publish-using-darc.ps1 b/eng/common/post-build/publish-using-darc.ps1 index e831d5c1d2..90b58e32a8 100644 --- a/eng/common/post-build/publish-using-darc.ps1 +++ b/eng/common/post-build/publish-using-darc.ps1 @@ -2,7 +2,6 @@ param( [Parameter(Mandatory=$true)][int] $BuildId, [Parameter(Mandatory=$true)][int] $PublishingInfraVersion, [Parameter(Mandatory=$true)][string] $AzdoToken, - [Parameter(Mandatory=$true)][string] $MaestroToken, [Parameter(Mandatory=$false)][string] $MaestroApiEndPoint = 'https://maestro.dot.net', [Parameter(Mandatory=$true)][string] $WaitPublishingFinish, [Parameter(Mandatory=$false)][string] $ArtifactsPublishingAdditionalParameters, @@ -36,13 +35,14 @@ try { } & $darc add-build-to-channel ` - --id $buildId ` - --publishing-infra-version $PublishingInfraVersion ` - --default-channels ` - --source-branch main ` - --azdev-pat $AzdoToken ` - --bar-uri $MaestroApiEndPoint ` - --password $MaestroToken ` + --id $buildId ` + --publishing-infra-version $PublishingInfraVersion ` + --default-channels ` + --source-branch main ` + --azdev-pat "$AzdoToken" ` + --bar-uri "$MaestroApiEndPoint" ` + --ci ` + --verbose ` @optionalParams if ($LastExitCode -ne 0) { diff --git a/eng/common/templates/job/job.yml b/eng/common/templates/job/job.yml index 5920952c5b..8da477dd69 100644 --- a/eng/common/templates/job/job.yml +++ b/eng/common/templates/job/job.yml @@ -1,5 +1,11 @@ parameters: enablePublishBuildArtifacts: false + disableComponentGovernance: '' + componentGovernanceIgnoreDirectories: '' +# Sbom related params + enableSbom: true + PackageVersion: 9.0.0 + BuildDropPath: '$(Build.SourcesDirectory)/artifacts' jobs: - template: /eng/common/core-templates/job/job.yml @@ -13,6 +19,26 @@ jobs: steps: - ${{ each step in parameters.steps }}: - ${{ step }} + + componentGovernanceSteps: + - template: /eng/common/templates/steps/component-governance.yml + parameters: + ${{ if eq(parameters.disableComponentGovernance, '') }}: + ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.runAsPublic, 'false'), or(startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'), startsWith(variables['Build.SourceBranch'], 'refs/heads/dotnet/'), startsWith(variables['Build.SourceBranch'], 'refs/heads/microsoft/'), eq(variables['Build.SourceBranch'], 'refs/heads/main'))) }}: + disableComponentGovernance: false + ${{ else }}: + disableComponentGovernance: true + ${{ else }}: + disableComponentGovernance: ${{ parameters.disableComponentGovernance }} + componentGovernanceIgnoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} + + - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.enableSbom, 'true')) }}: + - template: /eng/common/templates/steps/generate-sbom.yml + parameters: + PackageVersion: ${{ parameters.packageVersion }} + BuildDropPath: ${{ parameters.buildDropPath }} + publishArtifacts: false + artifactPublishSteps: - ${{ if ne(parameters.artifacts.publish, '') }}: diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 0febe696db..9574f4eb9d 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -653,7 +653,7 @@ function GetNuGetPackageCachePath() { $env:NUGET_PACKAGES = Join-Path $env:UserProfile '.nuget\packages\' } else { $env:NUGET_PACKAGES = Join-Path $RepoRoot '.packages\' - $env:RESTORENOCACHE = $true + $env:RESTORENOHTTPCACHE = $true } } diff --git a/eng/common/tools.sh b/eng/common/tools.sh index a4f5d1b776..00473c9f91 100644 --- a/eng/common/tools.sh +++ b/eng/common/tools.sh @@ -347,14 +347,14 @@ function InitializeBuildTool { fi } -# Set RestoreNoCache as a workaround for https://github.com/NuGet/Home/issues/3116 +# Set RestoreNoHttpCache as a workaround for https://github.com/NuGet/Home/issues/3116 function GetNuGetPackageCachePath { if [[ -z ${NUGET_PACKAGES:-} ]]; then if [[ "$use_global_nuget_cache" == true ]]; then - export NUGET_PACKAGES="$HOME/.nuget/packages" + export NUGET_PACKAGES="$HOME/.nuget/packages/" else - export NUGET_PACKAGES="$repo_root/.packages" - export RESTORENOCACHE=true + export NUGET_PACKAGES="$repo_root/.packages/" + export RESTORENOHTTPCACHE=true fi fi diff --git a/eng/verify-nupkgs-exe-version.ps1 b/eng/verify-nupkgs-exe-version.ps1 deleted file mode 100644 index 7535b9aef3..0000000000 --- a/eng/verify-nupkgs-exe-version.ps1 +++ /dev/null @@ -1,8 +0,0 @@ -Get-ChildItem S:\p\vstest3\artifacts\packages\Debug\Shipping -Filter vstest.console.exe -Recurse -Force | ForEach-Object { - if ($_.VersionInfo.ProductVersion.Contains("+")) { - throw "Some files contain '+' in the ProductVersion, this breaks DTAAgent in AzDO." - } - else { - "$_ version $($_.VersionInfo.ProductVersion) is ok." - } -} \ No newline at end of file diff --git a/eng/verify-nupkgs-exe.ps1 b/eng/verify-nupkgs-exe.ps1 deleted file mode 100644 index 459a4dcb43..0000000000 --- a/eng/verify-nupkgs-exe.ps1 +++ /dev/null @@ -1,90 +0,0 @@ -$exclusions = @{ - "CodeCoverage\CodeCoverage.exe" = "x86" - "Dynamic Code Coverage Tools\CodeCoverage.exe" = "x86" - "amd64\CodeCoverage.exe" = "x64" - - "IntelliTrace.exe" = "x86" - "ProcessSnapshotCleanup.exe" = "x86-64" - "TDEnvCleanup.exe" = "x86" - - "TestPlatform\SettingsMigrator.exe" = "x86" - - "dump\DumpMinitool.exe" = "x86-64" - - "QTAgent32.exe" = "x86" - "QTAgent32_35.exe" = "x86" - "QTAgent32_40.exe" = "x86" - "QTDCAgent32.exe" = "x86" - - "V1\VSTestVideoRecorder.exe" = "x86" - "VideoRecorder\VSTestVideoRecorder.exe" = "x86" -} - -$errs = @() -Get-ChildItem S:\p\vstest3\artifacts\packages\Debug\Shipping -Filter *.exe -Recurse -Force | ForEach-Object { - $m = & "C:\Program Files\Microsoft Visual Studio\2022\IntPreview\VC\Tools\MSVC\14.38.32919\bin\HostX86\x86\dumpbin.exe" /headers $_.FullName | Select-String "machine \((.*)\)" - if (-not $m.Matches.Success) { - $err = "Did not find the platform of the exe $fullName)." - } - - $platform = $m.Matches.Groups[1].Value - $fullName = $_.FullName - $name = $_.Name - - if ("x86" -eq $platform) { - $corFlags = "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\CorFlags.exe" - $corFlagsOutput = & $corFlags $fullName - # this is an native x86 exe or a .net x86 that requires of prefers 32bit - $platform = if ($corFlagsOutput -like "*does not have a valid managed header*" -or $corFlagsOutput -like "*32BITREQ : 1*" -or $corFlagsOutput -like "*32BITPREF : 1*") { - # this is an native x86 exe or a .net x86 that requires of prefers 32bit - "x86" } else { - # this is a x86 executable that is built as AnyCpu and does not prefer 32-bit so it will run as x64 on 64-bit system. - "x86-64" } - } - - if (($pair = $exclusions.GetEnumerator() | Where-Object { $fullName -like "*$($_.Name)" })) { - if (1 -lt $($pair).Count) { - $err = "Too many paths matched the query, only one match is allowed. Matches: $($pair.Name)" - $errs += $err - Write-Host -ForegroundColor Red Error: $err - } - - if ($platform -ne $pair.Value) { - $err = "$fullName must have architecture $($pair.Value), but it was $platform." - $errs += $err - Write-Host -ForegroundColor Red Error: $err - } - } - elseif ("x86" -eq $platform) { - if ($name -notlike "*x86*") { - $err = "$fullName has architecture $platform, and must contain x86 in the name of the executable." - $errs += $err - Write-Host -ForegroundColor Red Error: $err - } - } - elseif ($platform -in "x64", "x86-64") { - if ($name -like "*x86*" -or $name -like "*arm64*") { - $err = "$fullName has architecture $platform, and must NOT contain x86 or arm64 in the name of the executable." - $errs += $err - Write-Host -ForegroundColor Red Error: $err - } - } - elseif ("arm64" -eq $platform) { - if ($name -notlike "*arm64*") { - $err = "$fullName has architecture $platform, and must contain arm64 in the name of the executable." - $errs += $err - Write-Host -ForegroundColor Red Error: $err - } - } - else { - $err = "$fullName has unknown architecture $platform." - $errs += $err - Write-Host -ForegroundColor Red $err - } - - "Success: $name is $platform - $fullName" -} - -if ($errs) { - throw "Fail!:`n$($errs -join "`n")" -} \ No newline at end of file diff --git a/eng/verify-nupkgs.ps1 b/eng/verify-nupkgs.ps1 index c87d4ceaab..b3698ce7cc 100644 --- a/eng/verify-nupkgs.ps1 +++ b/eng/verify-nupkgs.ps1 @@ -19,9 +19,9 @@ function Verify-Nuget-Packages { $expectedNumOfFiles = @{ "Microsoft.CodeCoverage" = 59; "Microsoft.NET.Test.Sdk" = 15; - "Microsoft.TestPlatform" = 607; + "Microsoft.TestPlatform" = 608; "Microsoft.TestPlatform.Build" = 20; - "Microsoft.TestPlatform.CLI" = 470; + "Microsoft.TestPlatform.CLI" = 471; "Microsoft.TestPlatform.Extensions.TrxLogger" = 34; "Microsoft.TestPlatform.ObjectModel" = 92; "Microsoft.TestPlatform.AdapterUtilities" = 75; @@ -98,9 +98,9 @@ function Verify-Nuget-Packages { } } finally { - if ($null -ne $unzipNugetPackageDir -and (Test-Path $unzipNugetPackageDir)) { - Remove-Item -Force -Recurse $unzipNugetPackageDir | Out-Null - } + # if ($null -ne $unzipNugetPackageDir -and (Test-Path $unzipNugetPackageDir)) { + # Remove-Item -Force -Recurse $unzipNugetPackageDir | Out-Null + # } } } @@ -109,6 +109,7 @@ function Verify-Nuget-Packages { } Write-Host "Completed Verify-Nuget-Packages." + $unzipNugetPackageDirs } function Unzip { @@ -156,4 +157,150 @@ function Verify-Version { Match-VersionAgainstBranch -vsTestVersion $vsTestProductVersion -branchName $currentBranch -errors $errors } -Verify-Nuget-Packages +function Verify-NugetPackageExe { + param( + [Parameter(Mandatory)] + [ValidateSet("Debug", "Release")] + [string] $configuration, + $UnzipNugetPackages + ) + + + $exclusions = @{ + "CodeCoverage\CodeCoverage.exe" = "x86" + "Dynamic Code Coverage Tools\CodeCoverage.exe" = "x86" + "amd64\CodeCoverage.exe" = "x64" + + "IntelliTrace.exe" = "x86" + "ProcessSnapshotCleanup.exe" = "x86-64" + "TDEnvCleanup.exe" = "x86" + + "TestPlatform\SettingsMigrator.exe" = "x86" + + "dump\DumpMinitool.exe" = "x86-64" + + "QTAgent32.exe" = "x86" + "QTAgent32_35.exe" = "x86" + "QTAgent32_40.exe" = "x86" + "QTDCAgent32.exe" = "x86" + + "V1\VSTestVideoRecorder.exe" = "x86" + "VideoRecorder\VSTestVideoRecorder.exe" = "x86" + } + + $errs = @() + $exes = $UnzipNugetPackages | Get-ChildItem -Filter *.exe -Recurse -Force + if (0 -eq @($exes).Length) { + throw "No exe files were found." + } + + # use wow programfiles because they always point to x64 programfiles where VS is installed + $dumpBin = Get-ChildItem -Recurse -Force -Filter dumpbin.exe -path "$env:ProgramW6432\Microsoft Visual Studio\2022\Enterprise" | Select-Object -First 1 + if (-not $dumpBin) { + throw "Did not find dumpbin.exe in '$env:ProgramW6432\Microsoft Visual Studio\2022\Enterprise'." + } + + $corFlags = Get-ChildItem -Recurse -Force -Filter CorFlags.exe -path "${env:ProgramFiles(x86)}\Microsoft SDKs\Windows" | Select-Object -First 1 + if (-not $corFlags) { + throw "Did not find CorFlags.exe in '${env:ProgramFiles(x86)}\Microsoft SDKs\Windows'." + } + + $exes | ForEach-Object { + $m = & $dumpBin /headers $_.FullName | Select-String "machine \((.*)\)" + if (-not $m.Matches.Success) { + $err = "Did not find the platform of the exe $fullName)." + } + + $platform = $m.Matches.Groups[1].Value + $fullName = $_.FullName + $name = $_.Name + + if ("x86" -eq $platform) { + $corFlagsOutput = & $corFlags $fullName + # this is an native x86 exe or a .net x86 that requires of prefers 32bit + $platform = if ($corFlagsOutput -like "*does not have a valid managed header*" -or $corFlagsOutput -like "*32BITREQ : 1*" -or $corFlagsOutput -like "*32BITPREF : 1*") { + # this is an native x86 exe or a .net x86 that requires of prefers 32bit + "x86" } else { + # this is a x86 executable that is built as AnyCpu and does not prefer 32-bit so it will run as x64 on 64-bit system. + "x86-64" } + } + + if (($pair = $exclusions.GetEnumerator() | Where-Object { $fullName -like "*$($_.Name)" })) { + if (1 -lt $($pair).Count) { + $err = "Too many paths matched the query, only one match is allowed. Matches: $($pair.Name)" + $errs += $err + Write-Host -ForegroundColor Red Error: $err + } + + if ($platform -ne $pair.Value) { + $err = "$fullName must have architecture $($pair.Value), but it was $platform." + $errs += $err + Write-Host -ForegroundColor Red Error: $err + } + } + elseif ("x86" -eq $platform) { + if ($name -notlike "*x86*") { + $err = "$fullName has architecture $platform, and must contain x86 in the name of the executable." + $errs += $err + Write-Host -ForegroundColor Red Error: $err + } + } + elseif ($platform -in "x64", "x86-64") { + if ($name -like "*x86*" -or $name -like "*arm64*") { + $err = "$fullName has architecture $platform, and must NOT contain x86 or arm64 in the name of the executable." + $errs += $err + Write-Host -ForegroundColor Red Error: $err + } + } + elseif ("arm64" -eq $platform) { + if ($name -notlike "*arm64*") { + $err = "$fullName has architecture $platform, and must contain arm64 in the name of the executable." + $errs += $err + Write-Host -ForegroundColor Red Error: $err + } + } + else { + $err = "$fullName has unknown architecture $platform." + $errs += $err + Write-Host -ForegroundColor Red $err + } + + "Success: $name is $platform - $fullName" + } + + if ($errs) { + throw "Fail!:`n$($errs -join "`n")" + } +} + +function Verify-NugetPackageVersion { + param( + [Parameter(Mandatory)] + [ValidateSet("Debug", "Release")] + [string] $configuration, + $UnzipNugetPackages + ) + + # look for vstest.console.dll because unified build for .NET does not produce vstest.console.exe + $exes = $UnzipNugetPackages | Get-ChildItem -Filter vstest.console.dll -Recurse -Force + if (0 -eq @($exes).Length) { + throw "No vstest.console.dll files were found." + } + + $exes | ForEach-Object { + if ($_.VersionInfo.ProductVersion.Contains("+")) { + throw "$_ contains '+' in the ProductVersion $($_.VersionInfo.ProductVersion), this breaks DTAAgent in AzDO." + } + else { + "$_ version $($_.VersionInfo.ProductVersion) is ok." + } + } + +} + + +$unzipNugetPackages = Verify-Nuget-Packages +Start-sleep -Seconds 10 +# skipped, it is hard to find the right dumpbin.exe and corflags tools on server +# Verify-NugetPackageExe -configuration $configuration -UnzipNugetPackages $unzipNugetPackages +Verify-NugetPackageVersion -configuration $configuration -UnzipNugetPackages $unzipNugetPackages diff --git a/global.json b/global.json index 5d25f929eb..7ef6d61a2c 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "9.0.100-preview.4.24267.66", + "version": "9.0.100-preview.5.24307.3", "rollForward": "minor", "allowPrerelease": false, "architecture": "x64" @@ -11,17 +11,17 @@ "2.1.30", "3.1.32", "5.0.17", - "6.0.29", - "7.0.18", - "8.0.4" + "6.0.32", + "7.0.20", + "8.0.7" ], "dotnet/x86": [ "2.1.30", "3.1.32", "5.0.17", - "6.0.29", - "7.0.18", - "8.0.4" + "6.0.32", + "7.0.20", + "8.0.7" ] }, "vs": { @@ -29,9 +29,9 @@ }, "xcopy-msbuild": "17.8.5", "vswhere": "2.2.7", - "dotnet": "9.0.100-preview.4.24267.66" + "dotnet": "9.0.100-preview.5.24307.3" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.24306.4" + "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.24408.2" } } diff --git a/playground/Directory.Build.props b/playground/Directory.Build.props index 60fd349d0a..6f5b8d7bf3 100644 --- a/playground/Directory.Build.props +++ b/playground/Directory.Build.props @@ -2,6 +2,6 @@ - true + true diff --git a/playground/TestPlatform.Playground/Program.cs b/playground/TestPlatform.Playground/Program.cs index 142b324cb3..0cebf6d996 100644 --- a/playground/TestPlatform.Playground/Program.cs +++ b/playground/TestPlatform.Playground/Program.cs @@ -105,7 +105,7 @@ static void Main() // var processStartInfo = new ProcessStartInfo // { // FileName = console, - // Arguments = $"{string.Join(" ", sources)} --settings:{settingsFile} --listtests", + // Arguments = $"{string.Join(" ", sources)} --settings:{settingsFile} --logger:trx;LogFileName=my.trx;WarnOnFileOverwrite=false", // UseShellExecute = false, // }; // EnvironmentVariables.Variables.ToList().ForEach(processStartInfo.Environment.Add); diff --git a/playground/TestPlatform.Playground/TestPlatform.Playground.csproj b/playground/TestPlatform.Playground/TestPlatform.Playground.csproj index f20a1bd4d8..9a5dcbffbe 100644 --- a/playground/TestPlatform.Playground/TestPlatform.Playground.csproj +++ b/playground/TestPlatform.Playground/TestPlatform.Playground.csproj @@ -32,6 +32,7 @@ + @@ -74,6 +75,7 @@ + diff --git a/samples/Directory.Build.props b/samples/Directory.Build.props index 60fd349d0a..6f5b8d7bf3 100644 --- a/samples/Directory.Build.props +++ b/samples/Directory.Build.props @@ -2,6 +2,6 @@ - true + true diff --git a/shared/NullableAttributes.cs b/shared/NullableAttributes.cs index ded53a2c9f..845ee9bdfa 100644 --- a/shared/NullableAttributes.cs +++ b/shared/NullableAttributes.cs @@ -96,7 +96,7 @@ internal sealed class MemberNotNullAttribute : Attribute /// /// The field or property member that is promised to be not-null. /// - public MemberNotNullAttribute(string member) => Members = new[] { member }; + public MemberNotNullAttribute(string member) => Members = [member]; /// Initializes the attribute with the list of field and property members. /// @@ -122,7 +122,7 @@ internal sealed class MemberNotNullWhenAttribute : Attribute public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; - Members = new[] { member }; + Members = [member]; } /// Initializes the attribute with the specified return value condition and list of field and property members. diff --git a/src/AttachVS/AttachVS.csproj b/src/AttachVS/AttachVS.csproj index 621a7d9654..480945c0e3 100644 --- a/src/AttachVS/AttachVS.csproj +++ b/src/AttachVS/AttachVS.csproj @@ -4,7 +4,7 @@ Exe net7;net472 AttachVS - true + true diff --git a/src/DataCollectors/DumpMinitool.arm64/DumpMinitool.arm64.csproj b/src/DataCollectors/DumpMinitool.arm64/DumpMinitool.arm64.csproj index 1efec3f46e..1163b54034 100644 --- a/src/DataCollectors/DumpMinitool.arm64/DumpMinitool.arm64.csproj +++ b/src/DataCollectors/DumpMinitool.arm64/DumpMinitool.arm64.csproj @@ -11,7 +11,7 @@ so order here matters. --> AnyCPU false - true + true - + + - + + - + Microsoft.TestPlatform.CLI.sourcebuild.product.nuspec true - false + false $(OutputPath) Microsoft.TestPlatform.CLI vstest visual-studio unittest testplatform mstest microsoft test testing diff --git a/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.nuspec b/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.nuspec index 7af61c0a59..e5d37dcb48 100644 --- a/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.nuspec +++ b/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.nuspec @@ -45,6 +45,7 @@ + diff --git a/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.sourcebuild.nuspec b/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.sourcebuild.nuspec index 3f1469375e..163cd961fd 100644 --- a/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.sourcebuild.nuspec +++ b/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.sourcebuild.nuspec @@ -71,6 +71,8 @@ + + diff --git a/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.sourcebuild.product.nuspec b/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.sourcebuild.product.nuspec index 5541bce3eb..e53eaba922 100644 --- a/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.sourcebuild.product.nuspec +++ b/src/package/Microsoft.TestPlatform.CLI/Microsoft.TestPlatform.CLI.sourcebuild.product.nuspec @@ -44,6 +44,7 @@ + diff --git a/src/package/Microsoft.TestPlatform/Microsoft.TestPlatform.nuspec b/src/package/Microsoft.TestPlatform/Microsoft.TestPlatform.nuspec index 0903b475db..921d46e25c 100644 --- a/src/package/Microsoft.TestPlatform/Microsoft.TestPlatform.nuspec +++ b/src/package/Microsoft.TestPlatform/Microsoft.TestPlatform.nuspec @@ -448,16 +448,16 @@ - + - + - + @@ -541,6 +541,7 @@ + diff --git a/src/package/Microsoft.VisualStudio.TestTools.TestPlatform.V2.CLI/Microsoft.VisualStudio.TestTools.TestPlatform.V2.CLI.csproj b/src/package/Microsoft.VisualStudio.TestTools.TestPlatform.V2.CLI/Microsoft.VisualStudio.TestTools.TestPlatform.V2.CLI.csproj index f711b8068a..c2fb1120e9 100644 --- a/src/package/Microsoft.VisualStudio.TestTools.TestPlatform.V2.CLI/Microsoft.VisualStudio.TestTools.TestPlatform.V2.CLI.csproj +++ b/src/package/Microsoft.VisualStudio.TestTools.TestPlatform.V2.CLI/Microsoft.VisualStudio.TestTools.TestPlatform.V2.CLI.csproj @@ -11,7 +11,7 @@ - true + true false false false diff --git a/src/testhost.x86/AppDomainEngineInvoker.cs b/src/testhost.x86/AppDomainEngineInvoker.cs index 0401e6bc32..f26ac8557b 100644 --- a/src/testhost.x86/AppDomainEngineInvoker.cs +++ b/src/testhost.x86/AppDomainEngineInvoker.cs @@ -93,8 +93,7 @@ private AppDomain CreateNewAppDomain(string testSourcePath) /// /// Create the Engine Invoker in new AppDomain based on test source path /// - /// Test Source to run/discover tests for - /// Merged config file if there is any merging of test config and test host config + /// The appdomain in which the invoker should be created. /// private static IEngineInvoker CreateInvokerInAppDomain(AppDomain appDomain) { @@ -106,7 +105,7 @@ private static IEngineInvoker CreateInvokerInAppDomain(AppDomain appDomain) false, BindingFlags.Default, null, - new object?[] { CultureInfo.DefaultThreadCurrentUICulture?.Name, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) }, + [CultureInfo.DefaultThreadCurrentUICulture?.Name, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)], null, null); @@ -247,7 +246,7 @@ public CustomAssemblySetup(string uiCulture, string testPlatformPath) CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture(uiCulture); } - _resolverPaths = new string[] { testPlatformPath, Path.Combine(testPlatformPath, "Extensions") }; + _resolverPaths = [testPlatformPath, Path.Combine(testPlatformPath, "Extensions")]; _resolvedAssemblies = new Dictionary(); AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } diff --git a/src/testhost.x86/UnitTestClient.cs b/src/testhost.x86/UnitTestClient.cs index b28b0f4ce8..de0f39cfa6 100644 --- a/src/testhost.x86/UnitTestClient.cs +++ b/src/testhost.x86/UnitTestClient.cs @@ -55,6 +55,6 @@ internal static string[] SplitArguments(string commandLine) parmChars[index] = '\n'; } - return (new string(parmChars)).Split(new[] { '\n' }); + return (new string(parmChars)).Split(['\n']); } } diff --git a/src/vstest.console/CommandLine/Executor.cs b/src/vstest.console/CommandLine/Executor.cs index beb8185b71..951a4166e1 100644 --- a/src/vstest.console/CommandLine/Executor.cs +++ b/src/vstest.console/CommandLine/Executor.cs @@ -141,7 +141,7 @@ internal int Execute(params string[]? args) if (args == null || args.Length == 0 || args.Any(StringUtils.IsNullOrWhiteSpace)) { Output.Error(true, CommandLineResources.NoArgumentsProvided); - args = new string[] { HelpArgumentProcessor.CommandName }; + args = [HelpArgumentProcessor.CommandName]; exitCode = 1; } diff --git a/src/vstest.console/InProcessVsTestConsoleWrapper.cs b/src/vstest.console/InProcessVsTestConsoleWrapper.cs index 8ba865f64c..5dbdd0ea61 100644 --- a/src/vstest.console/InProcessVsTestConsoleWrapper.cs +++ b/src/vstest.console/InProcessVsTestConsoleWrapper.cs @@ -126,7 +126,8 @@ internal InProcessVsTestConsoleWrapper( ProcessHelper.ExternalEnvironmentVariables = environmentVariableBaseline; string someExistingFile = typeof(InProcessVsTestConsoleWrapper).Assembly.Location; - var args = new VsTestConsoleProcessManager(someExistingFile).BuildArguments(consoleParameters); + using var manager = new VsTestConsoleProcessManager(someExistingFile); + var args = manager.BuildArguments(consoleParameters); // Skip vstest.console path, we are already running in process, so it would just end up // being understood as test dll to run. (it is present even though we don't provide // dotnet path, because it is a .dll file). diff --git a/src/vstest.console/Internal/ConsoleLogger.cs b/src/vstest.console/Internal/ConsoleLogger.cs index 5df4885ebc..7d6ef0278f 100644 --- a/src/vstest.console/Internal/ConsoleLogger.cs +++ b/src/vstest.console/Internal/ConsoleLogger.cs @@ -909,6 +909,20 @@ public MinimalTestResult(TestResult testResult) Outcome = testResult.Outcome; StartTime = testResult.StartTime; EndTime = testResult.EndTime; + + // When the test framework (e.g. xUnit 2.x.x) does not report start or end time + // we assign it to UTC now when constructing the test result. But that does not + // work for our logger, because we take the earliest StartTime and oldest EndTime + // to calculate the duration and this makes the first test to be "missing" from the + // duration. + // + // Instead we subtract the duration to get a more accurate result. We also + // don't compare the times for equality because the times in the TestResult are assigned + // on two different lines so they don't have to be the same. + if (EndTime - StartTime < testResult.Duration) + { + StartTime = EndTime - testResult.Duration; + } } public TestCase TestCase { get; } diff --git a/src/vstest.console/Internal/FilePatternParser.cs b/src/vstest.console/Internal/FilePatternParser.cs index 918d7a3805..804739ca7e 100644 --- a/src/vstest.console/Internal/FilePatternParser.cs +++ b/src/vstest.console/Internal/FilePatternParser.cs @@ -27,7 +27,7 @@ public class FilePatternParser { private readonly Matcher _matcher; private readonly IFileHelper _fileHelper; - private readonly char[] _wildCardCharacters = { '*' }; + private readonly char[] _wildCardCharacters = ['*']; public FilePatternParser() : this(new Matcher(), new FileHelper()) diff --git a/src/vstest.console/Internal/MSBuildLogger.cs b/src/vstest.console/Internal/MSBuildLogger.cs index 7a087592eb..691236db32 100644 --- a/src/vstest.console/Internal/MSBuildLogger.cs +++ b/src/vstest.console/Internal/MSBuildLogger.cs @@ -78,7 +78,15 @@ private void TestMessageHandler(object? sender, TestRunMessageEventArgs e) SendMessage($"output-info", e.Message); break; case TestMessageLevel.Warning: - SendMessage($"output-warning", e.Message); + // Downgrade xUnit skip warning to info, otherwise any skipped test will report warning, which is often upgraded to error. + if (e.Message.EndsWith("[SKIP]")) + { + SendMessage($"output-info", e.Message); + } + else + { + SendMessage($"output-warning", e.Message); + } break; case TestMessageLevel.Error: SendMessage($"output-error", e.Message); diff --git a/src/vstest.console/Processors/CollectArgumentProcessor.cs b/src/vstest.console/Processors/CollectArgumentProcessor.cs index 2a6ea0761f..c050e85f22 100644 --- a/src/vstest.console/Processors/CollectArgumentProcessor.cs +++ b/src/vstest.console/Processors/CollectArgumentProcessor.cs @@ -241,7 +241,7 @@ private static bool DoesDataCollectorSettingsExist(string friendlyName, internal static void AddDataCollectorToRunSettings(string arguments, IRunSettingsProvider runSettingsManager, IFileHelper fileHelper) { - AddDataCollectorToRunSettings(new string[] { arguments }, runSettingsManager, fileHelper, string.Empty); + AddDataCollectorToRunSettings([arguments], runSettingsManager, fileHelper, string.Empty); } internal static void AddDataCollectorToRunSettings(string[] arguments, IRunSettingsProvider runSettingsManager, IFileHelper fileHelper, string exceptionMessage) diff --git a/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs b/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs index 139eb92e86..6afdcd808e 100644 --- a/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs +++ b/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs @@ -176,8 +176,6 @@ public void Initialize(string? argument) /// /// Initialize blame. /// - /// Enable dump. - /// Blame parameters. private void InitializeBlame(bool enableCrashDump, bool enableHangDump, bool monitorPostMortemDebugger, Dictionary? collectDumpParameters) { // Add Blame Logger @@ -333,9 +331,6 @@ private static void AddMonitorPostMortemDebuggerNode(Dictionary /// /// Adds node in outer node. /// - /// Parameters. - /// Xml document. - /// Outer node. private static void AddNode(Dictionary? parameters, XmlDocument xmlDocument, XmlElement outernode, string nodeName) { var dumpNode = xmlDocument.CreateElement(nodeName); diff --git a/src/vstest.console/Processors/EnableCodeCoverageArgumentProcessor.cs b/src/vstest.console/Processors/EnableCodeCoverageArgumentProcessor.cs index 783e2d967c..db2ce05372 100644 --- a/src/vstest.console/Processors/EnableCodeCoverageArgumentProcessor.cs +++ b/src/vstest.console/Processors/EnableCodeCoverageArgumentProcessor.cs @@ -77,7 +77,8 @@ internal class EnableCodeCoverageArgumentExecutor : IArgumentExecutor internal const string FriendlyName = "Code Coverage"; private static readonly string XPathSeperator = "/"; - private static readonly string[] NodeNames = new string[] { Constants.RunSettingsName, Constants.DataCollectionRunSettingsName, Constants.DataCollectorsSettingName, Constants.DataCollectorSettingName }; + private static readonly string[] NodeNames = [Constants.RunSettingsName, Constants.DataCollectionRunSettingsName, Constants.DataCollectorsSettingName, Constants.DataCollectorSettingName + ]; #region Default CodeCoverage Settings String @@ -191,7 +192,6 @@ public ArgumentProcessorResult Execute() /// /// Updates with code coverage settings if not configured. /// - /// The run settings document. private void UpdateWithCodeCoverageSettingsIfNotConfigured() { var runsettingsXml = _runSettingsManager.ActiveRunSettings?.SettingsXml; @@ -258,7 +258,7 @@ private static string GetMissingNodesTextIfAny(string existingPath, string fullp { var xmlText = "{0}"; var nonExistingPath = fullpath.Substring(existingPath.Length); - var requiredNodeNames = nonExistingPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); + var requiredNodeNames = nonExistingPath.Split(['/'], StringSplitOptions.RemoveEmptyEntries); var format = "<{0}>{1}"; foreach (var nodeName in requiredNodeNames) diff --git a/src/vstest.console/Processors/EnableDiagArgumentProcessor.cs b/src/vstest.console/Processors/EnableDiagArgumentProcessor.cs index c5cee215fe..d3bc5e6a6b 100644 --- a/src/vstest.console/Processors/EnableDiagArgumentProcessor.cs +++ b/src/vstest.console/Processors/EnableDiagArgumentProcessor.cs @@ -101,6 +101,7 @@ internal class EnableDiagArgumentExecutor : IArgumentExecutor /// Default constructor. /// /// The file helper. + /// Process helper public EnableDiagArgumentExecutor(IFileHelper fileHelper, IProcessHelper processHelper) { _fileHelper = fileHelper; diff --git a/src/vstest.console/Processors/ListFullyQualifiedTestsArgumentProcessor.cs b/src/vstest.console/Processors/ListFullyQualifiedTestsArgumentProcessor.cs index f6580388e6..8bd9581d09 100644 --- a/src/vstest.console/Processors/ListFullyQualifiedTestsArgumentProcessor.cs +++ b/src/vstest.console/Processors/ListFullyQualifiedTestsArgumentProcessor.cs @@ -107,6 +107,8 @@ internal class ListFullyQualifiedTestsArgumentExecutor : IArgumentExecutor /// /// The options. /// + /// Runsettings provider. + /// Test request manager. public ListFullyQualifiedTestsArgumentExecutor( CommandLineOptions options, IRunSettingsProvider runSettingsProvider, @@ -121,6 +123,9 @@ public ListFullyQualifiedTestsArgumentExecutor( /// /// The options. /// + /// Runsettings provider. + /// Test request manager. + /// Output such as console. internal ListFullyQualifiedTestsArgumentExecutor( CommandLineOptions options, IRunSettingsProvider runSettingsProvider, diff --git a/src/vstest.console/Processors/ListTestsArgumentProcessor.cs b/src/vstest.console/Processors/ListTestsArgumentProcessor.cs index a8e3a84d7c..18dcba4914 100644 --- a/src/vstest.console/Processors/ListTestsArgumentProcessor.cs +++ b/src/vstest.console/Processors/ListTestsArgumentProcessor.cs @@ -111,6 +111,8 @@ internal class ListTestsArgumentExecutor : IArgumentExecutor /// /// The options. /// + /// Runsettings provider. + /// Test request manager. public ListTestsArgumentExecutor( CommandLineOptions options, IRunSettingsProvider runSettingsProvider, @@ -125,6 +127,9 @@ public ListTestsArgumentExecutor( /// /// The options. /// + /// Run setting provider. + /// Output such as console. + /// Test request manager internal ListTestsArgumentExecutor( CommandLineOptions options, IRunSettingsProvider runSettingsProvider, diff --git a/src/vstest.console/Processors/ResultsDirectoryArgumentProcessor.cs b/src/vstest.console/Processors/ResultsDirectoryArgumentProcessor.cs index 3855941ce0..b7e03835fd 100644 --- a/src/vstest.console/Processors/ResultsDirectoryArgumentProcessor.cs +++ b/src/vstest.console/Processors/ResultsDirectoryArgumentProcessor.cs @@ -83,7 +83,7 @@ internal class ResultsDirectoryArgumentExecutor : IArgumentExecutor /// Default constructor. /// /// The options. - /// The test platform + /// Runsettings manager. public ResultsDirectoryArgumentExecutor(CommandLineOptions options, IRunSettingsProvider runSettingsManager) { ValidateArg.NotNull(options, nameof(options)); diff --git a/src/vstest.console/Processors/TestAdapterLoadingStrategyArgumentProcessor.cs b/src/vstest.console/Processors/TestAdapterLoadingStrategyArgumentProcessor.cs index 92b4a73e74..91ee48d550 100644 --- a/src/vstest.console/Processors/TestAdapterLoadingStrategyArgumentProcessor.cs +++ b/src/vstest.console/Processors/TestAdapterLoadingStrategyArgumentProcessor.cs @@ -100,7 +100,9 @@ internal class TestAdapterLoadingStrategyArgumentExecutor : IArgumentExecutor /// Default constructor. /// /// The options. - /// The test platform + /// Run setting manager. + /// Output such as console. + /// File helper public TestAdapterLoadingStrategyArgumentExecutor(CommandLineOptions options, IRunSettingsProvider runSettingsManager, IOutput output, IFileHelper fileHelper) { _commandLineOptions = options ?? throw new ArgumentNullException(nameof(options)); @@ -195,7 +197,7 @@ private void ForceIsolation() private void ValidateTestAdapterPaths(TestAdapterLoadingStrategy strategy) { - var testAdapterPaths = _commandLineOptions.TestAdapterPath ?? new string[0]; + var testAdapterPaths = _commandLineOptions.TestAdapterPath ?? []; if (!_commandLineOptions.TestAdapterPathsSet) { testAdapterPaths = TestAdapterPathArgumentExecutor.SplitPaths(_runSettingsManager.QueryRunSettingsNode(TestAdapterPathArgumentExecutor.RunSettingsPath)).Union(testAdapterPaths).Distinct().ToArray(); diff --git a/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs b/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs index 2c1ab3f7b0..8ae3214634 100644 --- a/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs +++ b/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs @@ -96,7 +96,7 @@ internal class TestAdapterPathArgumentExecutor : IArgumentExecutor /// /// Separators for multiple paths in argument. /// - internal readonly static char[] ArgumentSeparators = new[] { ';' }; + internal readonly static char[] ArgumentSeparators = [';']; public const string RunSettingsPath = "RunConfiguration.TestAdaptersPaths"; @@ -104,7 +104,9 @@ internal class TestAdapterPathArgumentExecutor : IArgumentExecutor /// Default constructor. /// /// The options. - /// The test platform + /// Run setting manager. + /// Output such as console. + /// File helper public TestAdapterPathArgumentExecutor(CommandLineOptions options, IRunSettingsProvider runSettingsManager, IOutput output, IFileHelper fileHelper) { _commandLineOptions = options ?? throw new ArgumentNullException(nameof(options)); @@ -132,7 +134,7 @@ public void Initialize(string? argument) // VSTS task add double quotes around TestAdapterpath. For example if user has given TestAdapter path C:\temp, // Then VSTS task will add TestAdapterPath as "/TestAdapterPath:\"C:\Temp\"". // Remove leading and trailing ' " ' chars... - argument = argument.Trim().Trim(new char[] { '\"' }); + argument = argument.Trim().Trim(['\"']); // Get test adapter paths from RunSettings. var testAdapterPathsInRunSettings = _runSettingsManager.QueryRunSettingsNode(RunSettingsPath); @@ -167,6 +169,6 @@ public ArgumentProcessorResult Execute() /// Paths. internal static string[] SplitPaths(string? paths) { - return paths.IsNullOrWhiteSpace() ? new string[0] : paths.Split(ArgumentSeparators, StringSplitOptions.RemoveEmptyEntries); + return paths.IsNullOrWhiteSpace() ? [] : paths.Split(ArgumentSeparators, StringSplitOptions.RemoveEmptyEntries); } } diff --git a/src/vstest.console/Processors/Utilities/ArgumentProcessorFactory.cs b/src/vstest.console/Processors/Utilities/ArgumentProcessorFactory.cs index 321df61125..81f6123af8 100644 --- a/src/vstest.console/Processors/Utilities/ArgumentProcessorFactory.cs +++ b/src/vstest.console/Processors/Utilities/ArgumentProcessorFactory.cs @@ -23,14 +23,12 @@ internal class ArgumentProcessorFactory private Dictionary? _commandToProcessorMap; private Dictionary? _specialCommandToProcessorMap; + /// /// Initializes the argument processor factory. /// /// /// The argument Processors. /// - /// - /// The feature flag support. - /// /// /// This is not public because the static Create method should be used to access the instance. /// @@ -298,7 +296,7 @@ public static IArgumentProcessor WrapLazyProcessorToInitializeOnInstantiation(IA /// Decorates a lazy argument processor so that the real processor is initialized when the lazy value is obtained. /// /// The lazy processor. - /// The argument with which the real processor should be initialized. + /// The argument with which the real processor should be initialized. /// The decorated lazy processor. private static IArgumentProcessor WrapLazyProcessorToInitializeOnInstantiation( IArgumentProcessor processor, diff --git a/src/vstest.console/Processors/Utilities/ArgumentProcessorUtilities.cs b/src/vstest.console/Processors/Utilities/ArgumentProcessorUtilities.cs index a5744648cd..99f9130d39 100644 --- a/src/vstest.console/Processors/Utilities/ArgumentProcessorUtilities.cs +++ b/src/vstest.console/Processors/Utilities/ArgumentProcessorUtilities.cs @@ -8,8 +8,8 @@ namespace Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.Utilities; internal class ArgumentProcessorUtilities { - public static readonly char[] SemiColonArgumentSeparator = { ';' }; - public static readonly char[] EqualNameValueSeparator = { '=' }; + public static readonly char[] SemiColonArgumentSeparator = [';']; + public static readonly char[] EqualNameValueSeparator = ['=']; /// /// Get argument list from raw argument using argument separator. diff --git a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs index 4a8134cd03..f93857b671 100644 --- a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs +++ b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs @@ -78,6 +78,13 @@ internal class TestRequestManager : ITestRequestManager /// Assumption: There can only be one active discovery request. /// private IDiscoveryRequest? _currentDiscoveryRequest; + /// + /// Guards cancellation of the current discovery request, by resetting when the request is received, + /// because the request needs time to setup and populate the _currentTestRunRequest. This might take a relatively + /// long time when the machine is slow, because the setup is called as an async task, so it needs to be processed by thread pool + /// and there might be a queue of existing tasks. + /// + private readonly ManualResetEvent _discoveryStarting = new(true); /// /// Maintains the current active test run attachments processing cancellation token source. @@ -163,106 +170,119 @@ public void DiscoverTests( ITestDiscoveryEventsRegistrar discoveryEventsRegistrar, ProtocolConfig protocolConfig) { - EqtTrace.Info("TestRequestManager.DiscoverTests: Discovery tests started."); - - // TODO: Normalize rest of the data on the request as well - discoveryPayload.Sources = KnownPlatformSourceFilter.FilterKnownPlatformSources(discoveryPayload.Sources?.Distinct().ToList()); - discoveryPayload.RunSettings ??= ""; - - var runsettings = discoveryPayload.RunSettings; - - if (discoveryPayload.TestPlatformOptions != null) + try { - _telemetryOptedIn = discoveryPayload.TestPlatformOptions.CollectMetrics; - } + // Flag that that discovery is being initialized, so all requests to cancel discovery will wait till we set the discovery up. + _discoveryStarting.Reset(); - var requestData = GetRequestData(protocolConfig); - if (UpdateRunSettingsIfRequired( - runsettings, - discoveryPayload.Sources.ToList(), - discoveryEventsRegistrar, - isDiscovery: true, - out string updatedRunsettings, - out IDictionary sourceToArchitectureMap, - out IDictionary sourceToFrameworkMap)) - { - runsettings = updatedRunsettings; - } + // Make sure to run the run request inside a lock as the below section is not thread-safe. + // There can be only one discovery or execution request at a given point in time. + lock (_syncObject) + { + EqtTrace.Info("TestRequestManager.DiscoverTests: Discovery tests started."); - var sourceToSourceDetailMap = discoveryPayload.Sources.Select(source => new SourceDetail - { - Source = source, - Architecture = sourceToArchitectureMap[source], - Framework = sourceToFrameworkMap[source], - }).ToDictionary(k => k.Source!); + // TODO: Normalize rest of the data on the request as well + discoveryPayload.Sources = KnownPlatformSourceFilter.FilterKnownPlatformSources(discoveryPayload.Sources?.Distinct().ToList()); + discoveryPayload.RunSettings ??= ""; - var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettings); - var batchSize = runConfiguration.BatchSize; - var testCaseFilterFromRunsettings = runConfiguration.TestCaseFilter; + var runsettings = discoveryPayload.RunSettings; - if (requestData.IsTelemetryOptedIn) - { - // Collect metrics. - CollectMetrics(requestData, runConfiguration); + if (discoveryPayload.TestPlatformOptions != null) + { + _telemetryOptedIn = discoveryPayload.TestPlatformOptions.CollectMetrics; + } - // Collect commands. - LogCommandsTelemetryPoints(requestData); - } + var requestData = GetRequestData(protocolConfig); + if (UpdateRunSettingsIfRequired( + runsettings, + discoveryPayload.Sources.ToList(), + discoveryEventsRegistrar, + isDiscovery: true, + out string updatedRunsettings, + out IDictionary sourceToArchitectureMap, + out IDictionary sourceToFrameworkMap)) + { + runsettings = updatedRunsettings; + } - // Create discovery request. - var criteria = new DiscoveryCriteria( - discoveryPayload.Sources, - batchSize, - _commandLineOptions.TestStatsEventTimeout, - runsettings, - discoveryPayload.TestSessionInfo) - { - TestCaseFilter = _commandLineOptions.TestCaseFilterValue - ?? testCaseFilterFromRunsettings - }; + var sourceToSourceDetailMap = discoveryPayload.Sources.Select(source => new SourceDetail + { + Source = source, + Architecture = sourceToArchitectureMap[source], + Framework = sourceToFrameworkMap[source], + }).ToDictionary(k => k.Source!); - // Make sure to run the run request inside a lock as the below section is not thread-safe. - // There can be only one discovery or execution request at a given point in time. - lock (_syncObject) - { - try - { - EqtTrace.Info("TestRequestManager.DiscoverTests: Synchronization context taken"); + var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettings); + var batchSize = runConfiguration.BatchSize; + var testCaseFilterFromRunsettings = runConfiguration.TestCaseFilter; - _currentDiscoveryRequest = _testPlatform.CreateDiscoveryRequest( - requestData, - criteria, - discoveryPayload.TestPlatformOptions, - sourceToSourceDetailMap, - new EventRegistrarToWarningLoggerAdapter(discoveryEventsRegistrar)); - discoveryEventsRegistrar?.RegisterDiscoveryEvents(_currentDiscoveryRequest); + if (requestData.IsTelemetryOptedIn) + { + // Collect metrics. + CollectMetrics(requestData, runConfiguration); - // Notify start of discovery start. - _testPlatformEventSource.DiscoveryRequestStart(); + // Collect commands. + LogCommandsTelemetryPoints(requestData); + } - // Start the discovery of tests and wait for completion. - _currentDiscoveryRequest.DiscoverAsync(); - _currentDiscoveryRequest.WaitForCompletion(); - } - finally - { - if (_currentDiscoveryRequest != null) + // Create discovery request. + var criteria = new DiscoveryCriteria( + discoveryPayload.Sources, + batchSize, + _commandLineOptions.TestStatsEventTimeout, + runsettings, + discoveryPayload.TestSessionInfo) { - // Dispose the discovery request and unregister for events. - discoveryEventsRegistrar?.UnregisterDiscoveryEvents(_currentDiscoveryRequest); - _currentDiscoveryRequest.Dispose(); - _currentDiscoveryRequest = null; - } + TestCaseFilter = _commandLineOptions.TestCaseFilterValue + ?? testCaseFilterFromRunsettings + }; - EqtTrace.Info("TestRequestManager.DiscoverTests: Discovery tests completed."); - _testPlatformEventSource.DiscoveryRequestStop(); - // Posts the discovery complete event. - _metricsPublisher.Result.PublishMetrics( - TelemetryDataConstants.TestDiscoveryCompleteEvent, - requestData.MetricsCollection.Metrics!); + try + { + EqtTrace.Info("TestRequestManager.DiscoverTests: Synchronization context taken"); + + _currentDiscoveryRequest = _testPlatform.CreateDiscoveryRequest( + requestData, + criteria, + discoveryPayload.TestPlatformOptions, + sourceToSourceDetailMap, + new EventRegistrarToWarningLoggerAdapter(discoveryEventsRegistrar)); + // Discovery started, allow cancellations to proceed. + _currentDiscoveryRequest.OnDiscoveryStart += (s, e) => _discoveryStarting.Set(); + discoveryEventsRegistrar?.RegisterDiscoveryEvents(_currentDiscoveryRequest); + + // Notify start of discovery start. + _testPlatformEventSource.DiscoveryRequestStart(); + + // Start the discovery of tests and wait for completion. + _currentDiscoveryRequest.DiscoverAsync(); + _currentDiscoveryRequest.WaitForCompletion(); + } + finally + { + if (_currentDiscoveryRequest != null) + { + // Dispose the discovery request and unregister for events. + discoveryEventsRegistrar?.UnregisterDiscoveryEvents(_currentDiscoveryRequest); + _currentDiscoveryRequest.Dispose(); + _currentDiscoveryRequest = null; + } + + EqtTrace.Info("TestRequestManager.DiscoverTests: Discovery tests completed."); + _testPlatformEventSource.DiscoveryRequestStop(); + + // Posts the discovery complete event. + _metricsPublisher.Result.PublishMetrics( + TelemetryDataConstants.TestDiscoveryCompleteEvent, + requestData.MetricsCollection.Metrics!); + } } } + finally + { + _discoveryStarting.Set(); + } } /// @@ -624,6 +644,12 @@ public void CancelTestRun() public void CancelDiscovery() { EqtTrace.Info("TestRequestManager.CancelDiscovery: Sending cancel request."); + + // Wait for discovery request to initialize, before cancelling it, otherwise the + // _currentDiscoveryRequest might be null, because discovery did not have enough time to + // initialize and did not manage to populate _currentDiscoveryRequest yet, leading to hanging run + // that "ignores" the cancellation. + _discoveryStarting.WaitOne(3000); _currentDiscoveryRequest?.Abort(); } @@ -1278,7 +1304,6 @@ private void RunTests( /// This method either looks at runsettings directly when running as a server (DesignMode / IDE / via VSTestConsoleWrapper, or how you wanna call it) /// or uses the pre-parsed runsettings when in console mode. /// - /// /// private bool IsFrameworkSetByRunSettings( XPathNavigator navigator, @@ -1314,7 +1339,6 @@ private bool IsFrameworkSetByRunSettings( /// This method either looks at runsettings directly when running as a server (DesignMode / IDE / via VSTestConsoleWrapper, or how you wanna call it) /// or uses the pre-parsed runsettings when in console mode. /// - /// /// private bool IsPlatformSetByRunSettings( XPathNavigator navigator, out Architecture chosenPlatform) diff --git a/temp/testhost/testhost-9.0.runtimeconfig.json b/temp/testhost/testhost-9.0.runtimeconfig.json new file mode 100644 index 0000000000..146e13202e --- /dev/null +++ b/temp/testhost/testhost-9.0.runtimeconfig.json @@ -0,0 +1,9 @@ +{ + "runtimeOptions": { + "tfm": "net9.0", + "framework": { + "name": "Microsoft.NETCore.App", + "version": "9.0.0-preview.0" + } + } +} diff --git a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs index abf09de509..43923342e1 100644 --- a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs +++ b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs @@ -95,11 +95,11 @@ public void InitializeShouldThrowExceptionIfLoggerIsNull() [TestMethod] public void InitializeShouldInitializeDefaultEventLogNames() { - List eventLogNames = new() - { + List eventLogNames = + [ "System", "Application" - }; + ]; _eventLogDataCollector.Initialize(null, _mockDataCollectionEvents.Object, _mockDataCollectionSink, _mockDataCollectionLogger.Object, _dataCollectionEnvironmentContext); @@ -113,11 +113,11 @@ public void InitializeShouldInitializeCustomEventLogNamesIfSpecifiedInConfigurat string configurationString = @""; - List eventLogNames = new() - { + List eventLogNames = + [ "MyEventName", "MyEventName2" - }; + ]; XmlDocument expectedXmlDoc = new(); expectedXmlDoc.LoadXml(configurationString); @@ -131,12 +131,12 @@ public void InitializeShouldInitializeCustomEventLogNamesIfSpecifiedInConfigurat [TestMethod] public void InitializeShouldInitializeDefaultLogEntryTypes() { - List entryTypes = new() - { + List entryTypes = + [ EventLogEntryType.Error, EventLogEntryType.Warning, EventLogEntryType.FailureAudit - }; + ]; _eventLogDataCollector.Initialize(null, _mockDataCollectionEvents.Object, _mockDataCollectionSink, _mockDataCollectionLogger.Object, _dataCollectionEnvironmentContext); @@ -150,10 +150,7 @@ public void InitializeShouldInitializeEntryTypesIfSpecifiedInConfiguration() string configurationString = @""; - List entryTypes = new() - { - EventLogEntryType.Error - }; + List entryTypes = [EventLogEntryType.Error]; XmlDocument expectedXmlDoc = new(); expectedXmlDoc.LoadXml(configurationString); @@ -169,10 +166,7 @@ public void InitializeShouldInitializeEventSourcesIfSpecifiedInConfiguration() string configurationString = @""; - List eventSources = new() - { - "MyEventSource" - }; + List eventSources = ["MyEventSource"]; XmlDocument expectedXmlDoc = new(); expectedXmlDoc.LoadXml(configurationString); diff --git a/test/Directory.Build.props b/test/Directory.Build.props index 60fd349d0a..6f5b8d7bf3 100644 --- a/test/Directory.Build.props +++ b/test/Directory.Build.props @@ -2,6 +2,6 @@ - true + true diff --git a/test/Intent/Runner.cs b/test/Intent/Runner.cs index 6edf62eb0f..cbe7706cba 100644 --- a/test/Intent/Runner.cs +++ b/test/Intent/Runner.cs @@ -62,7 +62,7 @@ public static void Run(IEnumerable paths, IRunLogger logger) // Declaring type cannot be really null for types you define in C# // without doing any reflection magic. var instance = Activator.CreateInstance(method.DeclaringType!); - var testResult = method.Invoke(instance, Array.Empty()); + var testResult = method.Invoke(instance, []); if (testResult is Task task) { // When the result is a task we need to await it. diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs index 02d4bd56f9..b36ace80bc 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs @@ -305,7 +305,7 @@ private static bool IsAdministrator() private void ValidateDump(int expectedDumpCount = 1) { - var attachments = StdOutWithWhiteSpace.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) + var attachments = StdOutWithWhiteSpace.Split([Environment.NewLine], StringSplitOptions.RemoveEmptyEntries) .SkipWhile(l => !l.Contains("Attachments:")).Skip(1) .Where(l => !string.IsNullOrWhiteSpace(l)) .ToList(); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs index a48cedbd97..9698a81144 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs @@ -106,7 +106,7 @@ public void DataCollectorAttachmentProcessor(RunnerInfo runnerInfo) string runSettings = GetRunsettingsFilePath(TempDirectory.Path); string diagFileName = Path.Combine(TempDirectory.Path, "diaglog.txt"); var extensionsPath = Path.GetDirectoryName(GetTestDllForFramework("AttachmentProcessorDataCollector.dll", "netstandard2.0")); - var arguments = PrepareArguments(new string[] { assemblyPath, secondAssemblyPath }, null, runSettings, FrameworkArgValue, runnerInfo.InIsolationValue, resultsDirectory: TempDirectory.Path); + var arguments = PrepareArguments([assemblyPath, secondAssemblyPath], null, runSettings, FrameworkArgValue, runnerInfo.InIsolationValue, resultsDirectory: TempDirectory.Path); arguments = string.Concat(arguments, $" /Diag:{diagFileName}", $" /TestAdapterPath:{extensionsPath}"); XElement runSettingsXml = XElement.Load(runSettings); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs index 4bf3b42e52..5a7284c7cf 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs @@ -42,12 +42,12 @@ public void Cleanup() public void Create_ShouldReturnListOfAttachmentProcessors() { // arrange - List invokedDataCollectors = new() - { + List invokedDataCollectors = + [ new InvokedDataCollector(new Uri("datacollector://Sample"), "Sample", typeof(SampleDataCollector).AssemblyQualifiedName!, typeof(SampleDataCollector).Assembly.Location, true), new InvokedDataCollector(new Uri("datacollector://SampleData2"), "SampleData2", typeof(SampleData2Collector).AssemblyQualifiedName!, typeof(SampleData2Collector).Assembly.Location, true), new InvokedDataCollector(new Uri("datacollector://SampleData3"), "SampleData3", typeof(SampleData3Collector).AssemblyQualifiedName!, typeof(SampleData3Collector).Assembly.Location, true) - }; + ]; // act var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); @@ -69,7 +69,7 @@ public void Create_ShouldReturnListOfAttachmentProcessors() public void Create_EmptyOrNullInvokedDataCollector_ShouldReturnCodeCoverageDataAttachmentsHandler(bool empty) { // act - var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(empty ? Array.Empty() : null, null); + var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(empty ? [] : null, null); //assert Assert.AreEqual(1, dataCollectorAttachmentsProcessors.Length); @@ -80,10 +80,12 @@ public void Create_EmptyOrNullInvokedDataCollector_ShouldReturnCodeCoverageDataA public void Create_ShouldNotFailIfWrongDataCollectorAttachmentProcessor() { // arrange - List invokedDataCollectors = new() - { - new InvokedDataCollector(new Uri("datacollector://SampleData4"), "SampleData4", typeof(SampleData4Collector).AssemblyQualifiedName!, typeof(SampleData4Collector).Assembly.Location, true) - }; + List invokedDataCollectors = + [ + new InvokedDataCollector(new Uri("datacollector://SampleData4"), "SampleData4", + typeof(SampleData4Collector).AssemblyQualifiedName!, typeof(SampleData4Collector).Assembly.Location, + true) + ]; // act var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); @@ -97,10 +99,10 @@ public void Create_ShouldNotFailIfWrongDataCollectorAttachmentProcessor() public void Create_ShouldAddTwoTimeCodeCoverageDataAttachmentsHandler() { // arrange - List invokedDataCollectors = new() - { + List invokedDataCollectors = + [ new InvokedDataCollector(new Uri("datacollector://microsoft/CodeCoverage/2.0"), "SampleData5", typeof(SampleData5Collector).AssemblyQualifiedName!, typeof(SampleData5Collector).Assembly.Location, true) - }; + ]; // act var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); @@ -129,11 +131,11 @@ public void Create_ShouldLoadOrderingByFilePath() Directory.CreateDirectory(version2); File.Copy(dataCollectorFilePath, Path.Combine(version2, Path.GetFileName(dataCollectorFilePath)), true); - List invokedDataCollectors = new() - { + List invokedDataCollectors = + [ new InvokedDataCollector(new Uri("my://sample/datacollector"), "sample", "AttachmentProcessorDataCollector.SampleDataCollectorV2", Path.Combine(version1, Path.GetFileName(dataCollectorFilePath)), true), new InvokedDataCollector(new Uri("my://sample/datacollector"), "sample", "AttachmentProcessorDataCollector.SampleDataCollectorV2", Path.Combine(version2, Path.GetFileName(dataCollectorFilePath)), true) - }; + ]; // act var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DiscoveryTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DiscoveryTests.cs index 12658fd877..5fc1cd39a3 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DiscoveryTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DiscoveryTests.cs @@ -97,11 +97,12 @@ public void TypesToLoadAttributeTests() var extensionsDirectory = IntegrationTestEnvironment.ExtensionsDirectory; var extensionsToVerify = new Dictionary { - {"Microsoft.TestPlatform.Extensions.EventLogCollector.dll", new[] { "Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector"} }, - {"Microsoft.TestPlatform.Extensions.BlameDataCollector.dll", new[] { "Microsoft.TestPlatform.Extensions.BlameDataCollector.BlameLogger", "Microsoft.TestPlatform.Extensions.BlameDataCollector.BlameCollector" } }, - {"Microsoft.VisualStudio.TestPlatform.Extensions.Html.TestLogger.dll", new[] { "Microsoft.VisualStudio.TestPlatform.Extensions.HtmlLogger.HtmlLogger" } }, - {"Microsoft.VisualStudio.TestPlatform.Extensions.Trx.TestLogger.dll", new[] { "Microsoft.VisualStudio.TestPlatform.Extensions.TrxLogger.TrxLogger" } }, - {"Microsoft.TestPlatform.TestHostRuntimeProvider.dll", new[] { "Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DefaultTestHostManager", "Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DotnetTestHostManager" } } + {"Microsoft.TestPlatform.Extensions.EventLogCollector.dll", ["Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector"] }, + {"Microsoft.TestPlatform.Extensions.BlameDataCollector.dll", ["Microsoft.TestPlatform.Extensions.BlameDataCollector.BlameLogger", "Microsoft.TestPlatform.Extensions.BlameDataCollector.BlameCollector"] }, + {"Microsoft.VisualStudio.TestPlatform.Extensions.Html.TestLogger.dll", ["Microsoft.VisualStudio.TestPlatform.Extensions.HtmlLogger.HtmlLogger"] }, + {"Microsoft.VisualStudio.TestPlatform.Extensions.Trx.TestLogger.dll", ["Microsoft.VisualStudio.TestPlatform.Extensions.TrxLogger.TrxLogger"] }, + {"Microsoft.TestPlatform.TestHostRuntimeProvider.dll", ["Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DefaultTestHostManager", "Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DotnetTestHostManager"] + } }; foreach (var extension in extensionsToVerify.Keys) diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DotnetTestMSBuildOutputTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DotnetTestMSBuildOutputTests.cs index 089bdc74a8..db4cd5f13e 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DotnetTestMSBuildOutputTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DotnetTestMSBuildOutputTests.cs @@ -23,7 +23,12 @@ public void MSBuildLoggerCanBeEnabledByBuildPropertyAndDoesNotEatSpecialChars(Ru SetTestEnvironment(_testEnvironment, runnerInfo); var projectPath = GetIsolatedTestAsset("TerminalLoggerTestProject.csproj"); - InvokeDotnetTest($@"{projectPath} -nodereuse:false /p:VsTestUseMSBuildOutput=true /p:PackageVersion={IntegrationTestEnvironment.LatestLocallyBuiltNugetVersion}"); + InvokeDotnetTest($@"{projectPath} -nodereuse:false /p:PackageVersion={IntegrationTestEnvironment.LatestLocallyBuiltNugetVersion}", new Dictionary + { + // Setting this temporarily, until we upgrade to final net9, which has this option set automatically in the MSBUILD sdk. + // Without this option we don't produce any output to the terminal logger. + ["_MSBUILDTLENABLED"] = "1" + }); // The output: // Determining projects to restore... @@ -33,7 +38,7 @@ public void MSBuildLoggerCanBeEnabledByBuildPropertyAndDoesNotEatSpecialChars(Ru // C:\Users\nohwnd\AppData\Local\Temp\vstest\xvoVt\UnitTest1.cs(41): error VSTEST1: (FailingTest) SampleUnitTestProject.UnitTest1.FailingTest() Assert.AreEqual failed. Expected:<2>. Actual:<3>. [C:\Users\nohwnd\AppData\Local\Temp\vstest\xvoVt\SimpleTestProject.csproj::TargetFramework=net462] // C:\Users\nohwnd\AppData\Local\Temp\vstest\xvoVt\UnitTest1.cs(41): error VSTEST1: (FailingTest) SampleUnitTestProject.UnitTest1.FailingTest() Assert.AreEqual failed. Expected:<2>. Actual:<3>. [C:\Users\nohwnd\AppData\Local\Temp\vstest\xvoVt\SimpleTestProject.csproj::TargetFramework=netcoreapp3.1] - StdOutputContains("error VSTEST1: FailingTest ("); + StdOutputContains("error TESTERROR: FailingTest ("); StdOutputContains("): Error Message: Assert.AreEqual failed. Expected:<ğğğ𦮙我們剛才從𓋴𓅓𓏏𓇏𓇌𓀀>. Actual:."); StdOutputContains("at TerminalLoggerUnitTests.UnitTest1.FailingTest() in"); // We are sending those as low prio messages, they won't show up on screen but will be in binlog. diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs index cc0979cd53..abadb1e3e5 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs @@ -102,9 +102,9 @@ private void VaildateDataCollectorOutput(TempDirectory tempDirectory) var eventIdsDics = new Dictionary { - { new[] { "110", "111", "112" }, false }, - { new[] { "220", "221", "222", "223" }, false }, - { new[] { "330", "331", "332" }, false } + { ["110", "111", "112"], false }, + { ["220", "221", "222", "223"], false }, + { ["330", "331", "332"], false } }; // Since there is no guaranty that test will run in a particular order, we will check file for all available list of ids @@ -112,7 +112,7 @@ private void VaildateDataCollectorOutput(TempDirectory tempDirectory) Assert.IsTrue(VerifyOrder2(fileContent2, eventIdsDics), $"Event log file content: {fileContent2}"); Assert.IsTrue(VerifyOrder2(fileContent3, eventIdsDics), $"Event log file content: {fileContent3}"); - Assert.IsTrue(VerifyOrder(fileContent4, new[] { "110", "111", "112", "220", "221", "222", "223", "330", "331", "332" }), $"Event log file content: {fileContent4}"); + Assert.IsTrue(VerifyOrder(fileContent4, ["110", "111", "112", "220", "221", "222", "223", "330", "331", "332"]), $"Event log file content: {fileContent4}"); } private static bool VerifyOrder2(string content, Dictionary eventIdsDics) diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/CompatibilityRowsBuilder.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/CompatibilityRowsBuilder.cs index c34315c42f..d798463ae2 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/CompatibilityRowsBuilder.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/CompatibilityRowsBuilder.cs @@ -155,7 +155,7 @@ public List CreateData() allRows[i].Index = i; } - return JustRow == null ? allRows : new List { allRows[JustRow.Value] }; + return JustRow == null ? allRows : [allRows[JustRow.Value]]; } private static SemanticVersion ParseAndPatchSemanticVersion(string? version) @@ -244,7 +244,7 @@ private void AddEveryVersionOfHost(List dataRows) // .NET Framework testhost ships with the runner, and the version from the // runner directory is always the same as the runner. There are no variations // so we just need to add host versions for .NET testhosts. - var hostVersions = isNetFramework ? Array.Empty() : _hostVersions.ToArray(); + var hostVersions = isNetFramework ? [] : _hostVersions.ToArray(); foreach (var hostVersion in hostVersions) { foreach (var _ in _adapters) diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreRunnerAttribute.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreRunnerAttribute.cs index 478c595d3d..a1362f1c56 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreRunnerAttribute.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreRunnerAttribute.cs @@ -25,7 +25,7 @@ public class NetCoreRunnerAttribute : Attribute, ITestDataSource private readonly string _targetFrameworks; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// To run tests with desktop runner(vstest.console.exe), use AcceptanceTestBase.Net462TargetFramework or alike values. public NetCoreRunnerAttribute(string targetFrameworks = AcceptanceTestBase.NETFX462_NET50) @@ -59,7 +59,7 @@ public IEnumerable GetData(MethodInfo methodInfo) DebugDataCollector = DebugDataCollector, DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } return dataRows; @@ -67,6 +67,6 @@ public IEnumerable GetData(MethodInfo methodInfo) public string GetDisplayName(MethodInfo methodInfo, object?[]? data) { - return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? Array.Empty())); + return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? [])); } } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreTargetFrameworkDataSourceAttribute.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreTargetFrameworkDataSourceAttribute.cs index 5cc808dd7f..a227c37af1 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreTargetFrameworkDataSourceAttribute.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreTargetFrameworkDataSourceAttribute.cs @@ -57,7 +57,7 @@ private void AddRunnerDataRow(List dataRows, string runnerFramework, s DebugVSTestConsole = DebugVSTestConsole, DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } public IEnumerable GetData(MethodInfo methodInfo) @@ -83,6 +83,6 @@ public IEnumerable GetData(MethodInfo methodInfo) public string GetDisplayName(MethodInfo methodInfo, object?[]? data) { - return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? Array.Empty())); + return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? [])); } } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFrameworkRunnerAttribute.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFrameworkRunnerAttribute.cs index 3ade381b25..037bb03a1a 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFrameworkRunnerAttribute.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFrameworkRunnerAttribute.cs @@ -62,7 +62,7 @@ public IEnumerable GetData(MethodInfo methodInfo) DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } return dataRows; @@ -70,6 +70,6 @@ public IEnumerable GetData(MethodInfo methodInfo) public string GetDisplayName(MethodInfo methodInfo, object?[]? data) { - return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? Array.Empty())); + return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? [])); } } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFullTargetFrameworkDataSourceAttribute.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFullTargetFrameworkDataSourceAttribute.cs index c38cdde9cf..eeec157d7e 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFullTargetFrameworkDataSourceAttribute.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFullTargetFrameworkDataSourceAttribute.cs @@ -65,7 +65,7 @@ public IEnumerable GetData(MethodInfo methodInfo) DebugDataCollector = DebugDataCollector, DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } if (_useDesktopRunner && isWindows) @@ -85,7 +85,7 @@ public IEnumerable GetData(MethodInfo methodInfo) DebugDataCollector = DebugDataCollector, DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } if (_inProcess) @@ -103,7 +103,7 @@ public IEnumerable GetData(MethodInfo methodInfo) DebugDataCollector = DebugDataCollector, DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } } @@ -112,6 +112,6 @@ public IEnumerable GetData(MethodInfo methodInfo) public string GetDisplayName(MethodInfo methodInfo, object?[]? data) { - return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? Array.Empty())); + return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? [])); } } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/RunnnerInfo.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/RunnnerInfo.cs index b052591c78..c25929c04b 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/RunnnerInfo.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/RunnnerInfo.cs @@ -9,12 +9,6 @@ namespace Microsoft.TestPlatform.AcceptanceTests; -/// -/// -/// -/// -/// -/// Supported value = /InIsolation. [Serializable] // Type should be serializable to allow the tree-view behavior of test discovery in Test Explorer public class RunnerInfo { diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/TestDataSourceAttribute.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/TestDataSourceAttribute.cs index 8b334fcb4f..d67d02f975 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/TestDataSourceAttribute.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/TestDataSourceAttribute.cs @@ -18,7 +18,7 @@ public abstract class TestDataSourceAttribute : Attribute, ITestDataSource w public void AddData(T1 value1) { - _data.Add(new object[] { value1 }); + _data.Add([value1]); } public virtual string GetDisplayName(MethodInfo methodInfo, T1 value1) @@ -49,7 +49,7 @@ public abstract class TestDataSourceAttribute : Attribute, ITestDataSour public void AddData(T1 value1, T2 value2) { - _data.Add(new object[] { value1, value2 }); + _data.Add([value1, value2]); } public virtual string GetDisplayName(MethodInfo methodInfo, T1 value1, T2 value2) @@ -81,7 +81,7 @@ public abstract class TestDataSourceAttribute : Attribute, ITestData public void AddData(T1 value1, T2 value2, T3 value3) { - _data.Add(new object[] { value1, value2, value3 }); + _data.Add([value1, value2, value3]); } public virtual string GetDisplayName(MethodInfo methodInfo, T1 value1, T2 value2, T3 value3) @@ -108,13 +108,13 @@ public abstract class TestDataSourceAttribute : Attribute, ITest where T3 : notnull where T4 : notnull { - private readonly List _data = new(); + private readonly List _data = []; public abstract void CreateData(MethodInfo methodInfo); public void AddData(T1 value1, T2 value2, T3 value3, T4 value4) { - _data.Add(new object[] { value1, value2, value3, value4 }); + _data.Add([value1, value2, value3, value4]); } public virtual string GetDisplayName(MethodInfo methodInfo, T1 value1, T2 value2, T3 value3, T4 value4) diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/FilePatternParserTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/FilePatternParserTests.cs index 04ba1df6eb..a7f30c2ad9 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/FilePatternParserTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/FilePatternParserTests.cs @@ -67,7 +67,7 @@ public void WildCardPatternShouldCorrectlyWorkForRelativeAssemblyPath(RunnerInfo var testAssembly = GetSampleTestAssembly(); testAssembly = testAssembly.Replace("SimpleTestProject.dll", "*TestProj*.dll"); - var wildCardIndex = testAssembly.IndexOfAny(new char[] { '*' }); + var wildCardIndex = testAssembly.IndexOfAny(['*']); var testAssemblyDirectory = testAssembly.Substring(0, wildCardIndex); testAssembly = testAssembly.Substring(wildCardIndex); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs index a3092eb8d5..4bf30e4da6 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs @@ -233,7 +233,7 @@ private static void IsFileAndContentEqual(string filePath) } string filePathContent = sb.ToString(); - string[] divs = { "Total tests", "Passed", "Failed", "Skipped", "Run duration", "Pass percentage", "PassingTest" }; + string[] divs = ["Total tests", "Passed", "Failed", "Skipped", "Run duration", "Pass percentage", "PassingTest"]; foreach (string str in divs) { StringAssert.Contains(filePathContent, str); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Performance/PerfInstrumentation/PerfAnalyzer.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Performance/PerfInstrumentation/PerfAnalyzer.cs index ff51365afb..3e89d97d85 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Performance/PerfInstrumentation/PerfAnalyzer.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Performance/PerfInstrumentation/PerfAnalyzer.cs @@ -148,7 +148,7 @@ public double GetElapsedTimeByTaskName(string taskName) /// The task name. /// /// - /// The . + /// The . /// public IDictionary GetEventDataByTaskName(string taskName) { diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Performance/TranslationLayer/TelemetryPerfTestBase.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Performance/TranslationLayer/TelemetryPerfTestBase.cs index d1a72e3716..cb4a59b220 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Performance/TranslationLayer/TelemetryPerfTestBase.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Performance/TranslationLayer/TelemetryPerfTestBase.cs @@ -34,8 +34,6 @@ public TelemetryPerfTestBase() /// /// Used for posting the telemetry to AppInsights /// - /// - /// public void PostTelemetry(IDictionary handlerMetrics, PerfAnalyzer perfAnalyzer, string projectName, [CallerMemberName] string? scenario = null) { var properties = new Dictionary @@ -114,8 +112,6 @@ private static string GetAdapterName(string projectName) /// /// Returns the full path to the test asset dll /// - /// Name of the directory of the test dll - /// Name of the test project without extension /// public string[] GetPerfAssetFullPath(string name, string framework = "net48") { diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/RunsettingsTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/RunsettingsTests.cs index 7a22fea29d..3546759ab5 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/RunsettingsTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/RunsettingsTests.cs @@ -47,13 +47,12 @@ public void CommandLineRunSettingsShouldWinAmongAllOptions(RunnerInfo runnerInfo var runSettingsArgs = string.Join( " ", - new string[] - { + [ "RunConfiguration.MaxCpuCount=1", string.Concat("RunConfiguration.TargetPlatform=",targetPlatform), string.Concat("RunConfiguration.TargetFrameworkVersion=" , GetTargetFrameworkForRunsettings()), string.Concat("RunConfiguration.TestAdaptersPaths=" , GetTestAdapterPath()) - }); + ]); RunTestWithRunSettings(runConfigurationDictionary, runSettingsArgs, additionalArgs, testhostProcessName, expectedNumOfProcessCreated); } @@ -82,13 +81,12 @@ public void CLIRunsettingsShouldWinBetweenCLISwitchesAndCLIRunsettings(RunnerInf // Pass non parallel var runSettingsArgs = string.Join( " ", - new string[] - { + [ "RunConfiguration.MaxCpuCount=1", string.Concat("RunConfiguration.TargetPlatform=",targetPlatform), string.Concat("RunConfiguration.TargetFrameworkVersion=" , GetTargetFrameworkForRunsettings()), string.Concat("RunConfiguration.TestAdaptersPaths=" , GetTestAdapterPath()) - }); + ]); RunTestWithRunSettings(null, runSettingsArgs, additionalArgs, testhostProcessName, expectedNumOfProcessCreated); } @@ -96,9 +94,6 @@ public void CLIRunsettingsShouldWinBetweenCLISwitchesAndCLIRunsettings(RunnerInf /// /// Command line switches should have high precedence if runsetting file and command line switch specified /// - /// - /// - /// [TestMethod] [NetFullTargetFrameworkDataSource] [NetCoreTargetFrameworkDataSource] @@ -170,13 +165,12 @@ public void RunSettingsParamsAsArguments(RunnerInfo runnerInfo) var runSettingsArgs = string.Join( " ", - new string[] - { + [ "RunConfiguration.MaxCpuCount=1", string.Concat("RunConfiguration.TargetPlatform=",targetPlatform), string.Concat("RunConfiguration.TargetFrameworkVersion=" , GetTargetFrameworkForRunsettings()), string.Concat("RunConfiguration.TestAdaptersPaths=" , GetTestAdapterPath()) - }); + ]); RunTestWithRunSettings(null, runSettingsArgs, null, testhostProcessName, expectedNumOfProcessCreated); } @@ -206,13 +200,12 @@ public void RunSettingsAndRunSettingsParamsAsArguments(RunnerInfo runnerInfo) var runSettingsArgs = string.Join( " ", - new string[] - { + [ "RunConfiguration.MaxCpuCount=1", string.Concat("RunConfiguration.TargetPlatform=",targetPlatform), string.Concat("RunConfiguration.TargetFrameworkVersion=" , GetTargetFrameworkForRunsettings()), string.Concat("RunConfiguration.TestAdaptersPaths=" , GetTestAdapterPath()) - }); + ]); RunTestWithRunSettings(runConfigurationDictionary, runSettingsArgs, null, testhostProcessName, expectedNumOfProcessCreated); } diff --git a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/ManagedNameParserTests.cs b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/ManagedNameParserTests.cs index 9587f844c0..826de8e0d1 100644 --- a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/ManagedNameParserTests.cs +++ b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/ManagedNameParserTests.cs @@ -45,11 +45,11 @@ void AssertParse(string expectedMethod, int expectedArity, string[] expectedPara Assert.AreEqual(("Method", 0, null), Parse("Method")); Assert.AreEqual(("Method", 0, null), Parse("Method()")); Assert.AreEqual(("Method", 2, null), Parse("Method`2()")); - AssertParse("Method", 0, new string[] { "System.Int32" }, "Method(System.Int32)"); - AssertParse("Method", 0, new string[] { "TypeA", "List" }, "Method(TypeA,List)"); - AssertParse("Method", 1, new string[] { "B", "List" }, "Method`1(B,List)"); - AssertParse("Method", 0, new string[] { "B[]" }, "Method(B[])"); - AssertParse("Method", 0, new string[] { "A[,]", "B[,,][]" }, "Method(A[,],B[,,][])"); + AssertParse("Method", 0, ["System.Int32"], "Method(System.Int32)"); + AssertParse("Method", 0, ["TypeA", "List"], "Method(TypeA,List)"); + AssertParse("Method", 1, ["B", "List"], "Method`1(B,List)"); + AssertParse("Method", 0, ["B[]"], "Method(B[])"); + AssertParse("Method", 0, ["A[,]", "B[,,][]"], "Method(A[,],B[,,][])"); // An F# method that would look like this in code: member _.``method that does not pass`` () = // And like this in CIL: instance void 'method that does not pass' () cil managed diff --git a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/CompatibilityTests.cs b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/CompatibilityTests.cs index 18232380ee..175ea9bcb2 100644 --- a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/CompatibilityTests.cs +++ b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/CompatibilityTests.cs @@ -12,16 +12,16 @@ namespace Microsoft.TestPlatform.AdapterUtilities.UnitTests.TestIdProvider; public class CompatibilityTests { [TestMethod] - [DataRow(new[] { "eea339da-6b5e-0d4b-3255-bfef95601890", "" })] - [DataRow(new[] { "740b9afc-3350-4257-ca01-5bd47799147d", "adapter://", "name1" })] // less than one block - [DataRow(new[] { "119c5b31-c0fb-1c12-6d1a-d617bb2bd996", "adapter://namesamplenam.testname" })] // 1 full block - [DataRow(new[] { "2a4c33ec-6115-4bd7-2e94-71f2fd3a5ee3", "adapter://namesamplenamespace.testname" })] // 1 full block and extra - [DataRow(new[] { "119c5b31-c0fb-1c12-6d1a-d617bb2bd996", "adapter://", "name", "samplenam", ".", "testname" })] // 1 full block - [DataRow(new[] { "2a4c33ec-6115-4bd7-2e94-71f2fd3a5ee3", "adapter://", "name", "samplenamespace", ".", "testname" })] // 1 full block and extra - [DataRow(new[] { "1fc07043-3d2d-1401-c732-3b507feec548", "adapter://namesamplenam.testnameaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" })] // 2 full blocks - [DataRow(new[] { "24e8a50b-2766-6a12-f461-9f8e4fa1cbb5", "adapter://namesamplenamespace.testnameaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" })] // 2 full blocks and extra - [DataRow(new[] { "1fc07043-3d2d-1401-c732-3b507feec548", "adapter://", "name", "samplenam", ".", "testname", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" })] // 2 full blocks - [DataRow(new[] { "24e8a50b-2766-6a12-f461-9f8e4fa1cbb5", "adapter://", "name", "samplenamespace", ".", "testname", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" })] // 2 full blocks and extra + [DataRow(["eea339da-6b5e-0d4b-3255-bfef95601890", ""])] + [DataRow(["740b9afc-3350-4257-ca01-5bd47799147d", "adapter://", "name1"])] // less than one block + [DataRow(["119c5b31-c0fb-1c12-6d1a-d617bb2bd996", "adapter://namesamplenam.testname"])] // 1 full block + [DataRow(["2a4c33ec-6115-4bd7-2e94-71f2fd3a5ee3", "adapter://namesamplenamespace.testname"])] // 1 full block and extra + [DataRow(["119c5b31-c0fb-1c12-6d1a-d617bb2bd996", "adapter://", "name", "samplenam", ".", "testname"])] // 1 full block + [DataRow(["2a4c33ec-6115-4bd7-2e94-71f2fd3a5ee3", "adapter://", "name", "samplenamespace", ".", "testname"])] // 1 full block and extra + [DataRow(["1fc07043-3d2d-1401-c732-3b507feec548", "adapter://namesamplenam.testnameaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"])] // 2 full blocks + [DataRow(["24e8a50b-2766-6a12-f461-9f8e4fa1cbb5", "adapter://namesamplenamespace.testnameaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"])] // 2 full blocks and extra + [DataRow(["1fc07043-3d2d-1401-c732-3b507feec548", "adapter://", "name", "samplenam", ".", "testname", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"])] // 2 full blocks + [DataRow(["24e8a50b-2766-6a12-f461-9f8e4fa1cbb5", "adapter://", "name", "samplenamespace", ".", "testname", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"])] // 2 full blocks and extra public void IdCompatibilityTests(string[] data) { // Arrange diff --git a/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs b/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs index 7c464bb381..a8ed80b8f1 100644 --- a/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs +++ b/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs @@ -3,7 +3,6 @@ using System.Text.RegularExpressions; -using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.TestPlatform.Build.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -47,7 +46,7 @@ public void CreateArgumentShouldAddCLIRunSettingsArgAtEnd() { const string codeCoverageOption = "Code Coverage"; - _vsTestTask.VSTestCollect = new string[] { codeCoverageOption }; + _vsTestTask.VSTestCollect = [codeCoverageOption]; _vsTestTask.VSTestBlame = true; const string arg1 = "RunConfiguration.ResultsDirectory=Path having Space"; @@ -79,7 +78,7 @@ public void CreateArgumentShouldPassResultsDirectoryCorrectly() public void CreateArgumentShouldNotSetConsoleLoggerVerbosityIfConsoleLoggerIsGivenInArgs() { _vsTestTask.VSTestVerbosity = "diag"; - _vsTestTask.VSTestLogger = new string[] { "Console;Verbosity=quiet" }; + _vsTestTask.VSTestLogger = ["Console;Verbosity=quiet"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); @@ -210,7 +209,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToQuietIfConsoleLoggerI [TestMethod] public void CreateArgumentShouldPreserveWhiteSpaceInLogger() { - _vsTestTask.VSTestLogger = new string[] { "trx;LogFileName=foo bar.trx" }; + _vsTestTask.VSTestLogger = ["trx;LogFileName=foo bar.trx"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); @@ -234,7 +233,7 @@ public void CreateArgumentShouldAddOneCollectArgumentForEachCollect() [TestMethod] public void CreateArgumentShouldAddMultipleTestAdapterPaths() { - _vsTestTask.VSTestTestAdapterPath = new ITaskItem[] { new TaskItem("path1"), new TaskItem("path2") }; + _vsTestTask.VSTestTestAdapterPath = [new TaskItem("path1"), new TaskItem("path2")]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); @@ -245,7 +244,7 @@ public void CreateArgumentShouldAddMultipleTestAdapterPaths() [TestMethod] public void CreateArgumentShouldAddMultipleLoggers() { - _vsTestTask.VSTestLogger = new string[] { "trx;LogFileName=foo bar.trx", "console" }; + _vsTestTask.VSTestLogger = ["trx;LogFileName=foo bar.trx", "console"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); StringAssert.Contains(commandline, "--logger:\"trx;LogFileName=foo bar.trx\""); @@ -257,7 +256,7 @@ public void CreateArgumentShouldAddTraceCollectorDirectoryPathAsTestAdapterForCo { const string traceDataCollectorDirectoryPath = @"c:\path\to\tracedata collector"; _vsTestTask.VSTestTraceDataCollectorDirectoryPath = new TaskItem(traceDataCollectorDirectoryPath); - _vsTestTask.VSTestCollect = new string[] { "code coverage" }; + _vsTestTask.VSTestCollect = ["code coverage"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); @@ -270,7 +269,7 @@ public void CreateArgumentShouldNotAddTraceCollectorDirectoryPathAsTestAdapterFo { const string traceDataCollectorDirectoryPath = @"c:\path\to\tracedata collector"; _vsTestTask.VSTestTraceDataCollectorDirectoryPath = new TaskItem(traceDataCollectorDirectoryPath); - _vsTestTask.VSTestCollect = new string[] { "not code coverage" }; + _vsTestTask.VSTestCollect = ["not code coverage"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); @@ -296,7 +295,7 @@ public void CreateArgumentShouldNotAddTestAdapterPathIfVSTestTraceDataCollectorD { _vsTestTask.VSTestTraceDataCollectorDirectoryPath = null; _vsTestTask.VSTestSetting = @"c:\path\to\sample.runsettings"; - _vsTestTask.VSTestCollect = new string[] { "code coverage" }; + _vsTestTask.VSTestCollect = ["code coverage"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs index 7ffc09294b..1a64538b9a 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs @@ -136,7 +136,7 @@ public void HandleDiscoveryCompleteShouldCloseDiscoveryManager() { var eventsHandler = _discoveryRequest as ITestDiscoveryEventsHandler2; - eventsHandler.HandleDiscoveryComplete(new DiscoveryCompleteEventArgs(1, false), Enumerable.Empty()); + eventsHandler.HandleDiscoveryComplete(new DiscoveryCompleteEventArgs(1, false), []); _discoveryManager.Verify(dm => dm.Close(), Times.Once); } @@ -148,7 +148,7 @@ public void HandleDiscoveryCompleteShouldCloseDiscoveryManagerBeforeRaiseDiscove _discoveryRequest.OnDiscoveryComplete += (s, e) => events.Add("complete"); var eventsHandler = _discoveryRequest as ITestDiscoveryEventsHandler2; - eventsHandler.HandleDiscoveryComplete(new DiscoveryCompleteEventArgs(1, false), Enumerable.Empty()); + eventsHandler.HandleDiscoveryComplete(new DiscoveryCompleteEventArgs(1, false), []); Assert.AreEqual(2, events.Count); Assert.AreEqual("close", events[0]); @@ -198,7 +198,7 @@ public void HandleDiscoveryCompleteShouldCollectMetrics() discoveryCompleteEventArgs.Metrics = dict; // Act - eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, Enumerable.Empty()); + eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, []); // Verify. mockMetricsCollector.Verify(rd => rd.Add(TelemetryDataConstants.TimeTakenInSecForDiscovery, It.IsAny()), Times.Once); @@ -247,7 +247,7 @@ public void HandleRawMessageShouldInvokeHandleDiscoveryCompleteOfLoggerManager() { TotalTests = 1, IsAborted = false, - LastDiscoveredTests = Enumerable.Empty() + LastDiscoveredTests = [] }); _discoveryRequest.HandleRawMessage(string.Empty); @@ -260,7 +260,7 @@ public void HandleDiscoveryCompleteShouldInvokeHandleDiscoveryCompleteOfLoggerMa { var discoveryCompleteEventArgs = new DiscoveryCompleteEventArgs(1, false); var eventsHandler = _discoveryRequest as ITestDiscoveryEventsHandler2; - eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, Enumerable.Empty()); + eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, []); _loggerManager.Verify(lm => lm.HandleDiscoveryComplete(discoveryCompleteEventArgs), Times.Once); } @@ -270,7 +270,7 @@ public void HandleDiscoveryCompleteShouldNotInvokeHandleDiscoveredTestsIfLastChu { var discoveryCompleteEventArgs = new DiscoveryCompleteEventArgs(1, false); var eventsHandler = _discoveryRequest as ITestDiscoveryEventsHandler2; - eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, Enumerable.Empty()); + eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, []); _loggerManager.Verify(lm => lm.HandleDiscoveredTests(It.IsAny()), Times.Never); } diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs index e07fbe9de9..d77e39fda6 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs @@ -508,7 +508,7 @@ public void HandleTestRunCompleteShouldHandleListAttachments() bool attachmentsFound = false; _testRunRequest.OnRunCompletion += (s, e) => attachmentsFound = e.AttachmentSets != null && e.AttachmentSets.Count == 1; - List attachmentSets = new() { new AttachmentSet(new Uri("datacollector://attachment"), "datacollectorAttachment") }; + List attachmentSets = [new AttachmentSet(new Uri("datacollector://attachment"), "datacollectorAttachment")]; _testRunRequest.ExecuteAsync(); var testRunCompleteEventsArgs = new TestRunCompleteEventArgs( diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs index 2bb19a3ca6..a44997fd80 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs @@ -121,7 +121,7 @@ public void SerialTestRunDecorator_Disabled(string falseValue, bool nullRunSetti testCases.Add(new TestCase() { Id = Guid.NewGuid() }); } - string[] sourcesName = new string[] { "testSource.dll" }; + string[] sourcesName = ["testSource.dll"]; _settingsMock.Setup(x => x.SettingsXml).Returns(nullRunSettings ? null : runsettings); _contextMock.Setup(x => x.RunSettings).Returns(_settingsMock.Object); diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs index ff82d8f17b..30612dfc6e 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs @@ -30,7 +30,7 @@ public TestPluginCacheTests() // Reset the singleton. TestPluginCache.Instance = null; _mockFileHelper = new Mock(); - _testablePluginCache = new TestableTestPluginCache(new List { typeof(TestPluginCacheTests).Assembly.Location }); + _testablePluginCache = new TestableTestPluginCache([typeof(TestPluginCacheTests).Assembly.Location]); _mockFileHelper.Setup(fh => fh.DirectoryExists(It.IsAny())).Returns(true); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs index a26d10ac56..aed57338cf 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs @@ -287,28 +287,28 @@ public void MergedDictionaryShouldBeEquivalentToTheExpectedDictionary() var first = new Dictionary> { // Merged with "key1" from the next set. - { "key1", new HashSet(new List() { "ext1", "ext2", "ext3" }) }, + { "key1", ["ext1", "ext2", "ext3"] }, // Empty hashset, will be removed from the result. - { "key2", new HashSet() }, + { "key2", [] }, // Added as is. - { "key5", new HashSet(new List() { "ext1", "ext2" }) } + { "key5", ["ext1", "ext2"] } }; var second = new Dictionary> { // Merged with "key1" from the previous set. - { "key1", new HashSet(new List() { "ext2", "ext3", "ext3", "ext4", "ext5" }) }, + { "key1", ["ext2", "ext3", "ext3", "ext4", "ext5"] }, // Empty hashset, will be removed from the result. - { "key2", new HashSet() }, + { "key2", [] }, // Empty hashset, will be removed from the result. - { "key3", new HashSet() }, + { "key3", [] }, // Added as is. - { "key4", new HashSet(new List() { "ext1" }) } + { "key4", ["ext1"] } }; var expected = new Dictionary> { - { "key1", new HashSet(new List() { "ext1", "ext2", "ext3", "ext4", "ext5" }) }, - { "key4", new HashSet(new List() { "ext1" }) }, - { "key5", new HashSet(new List() { "ext1", "ext2" }) } + { "key1", ["ext1", "ext2", "ext3", "ext4", "ext5"] }, + { "key4", ["ext1"] }, + { "key5", ["ext1", "ext2"] } }; // Merge the two dictionaries. @@ -329,9 +329,9 @@ public void AddExtensionTelemetryShouldAddJsonFormattedDiscoveredExtensionsTelem var telemetryData = new Dictionary(); var extensions = new Dictionary> { - { "key1", new HashSet(new List() { "ext1", "ext2", "ext3", "ext4", "ext5" }) }, - { "key4", new HashSet(new List() { "ext1" }) }, - { "key5", new HashSet(new List() { "ext1", "ext2" }) } + { "key1", ["ext1", "ext2", "ext3", "ext4", "ext5"] }, + { "key4", ["ext1"] }, + { "key5", ["ext1", "ext2"] } }; var expectedTelemetry = diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs index 849484134a..5077e68760 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs @@ -250,7 +250,7 @@ public void RaiseDiscoveredTestsShouldThrowExceptionIfNullDiscoveredTestsEventAr public void RaiseDiscoveredTestsShouldThrowExceptionIfAlreadyDisposed() { var loggerEvents = GetDisposedLoggerEvents(); - List testCases = new() { new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName") }; + List testCases = [new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName")]; DiscoveredTestsEventArgs discoveredTestsEventArgs = new(testCases); Assert.ThrowsException(() => loggerEvents.RaiseDiscoveredTests(discoveredTestsEventArgs)); @@ -266,7 +266,7 @@ public void RaiseDiscoveredTestsShouldInvokeRegisteredEventHandler() DiscoveredTestsEventArgs? receivedEventArgs = null; EventWaitHandle waitHandle = new AutoResetEvent(false); - List testCases = new() { new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName") }; + List testCases = [new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName")]; DiscoveredTestsEventArgs discoveredTestsEventArgs = new(testCases); // Register for the discovered tests event. diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs index 1b1b598cdc..a26dbdcdc1 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs @@ -25,14 +25,14 @@ public void FakesSettingsShouldThrowExceptionIfSourcesArePassedAsNull() [TestMethod] public void FakesSettingsShouldThrowExceptionIfRunSettingsIsPassedAsNull() { - Assert.ThrowsException(() => FakesUtilities.GenerateFakesSettingsForRunConfiguration(Array.Empty(), null!)); + Assert.ThrowsException(() => FakesUtilities.GenerateFakesSettingsForRunConfiguration([], null!)); } [TestMethod] public void FakesSettingsShouldBeNotGeneratedIfFakeConfiguratorAssemblyIsNotPresent() { string runSettingsXml = @""; - var generatedRunSettings = FakesUtilities.GenerateFakesSettingsForRunConfiguration(new string[] { @"C:\temp\UT.dll" }, runSettingsXml); + var generatedRunSettings = FakesUtilities.GenerateFakesSettingsForRunConfiguration([@"C:\temp\UT.dll"], runSettingsXml); Assert.AreEqual(generatedRunSettings, runSettingsXml); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/RunSettingsUtilitiesTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/RunSettingsUtilitiesTests.cs index 767417c4a8..f0b1133c56 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/RunSettingsUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/RunSettingsUtilitiesTests.cs @@ -95,7 +95,7 @@ public void GetMaxCpuCountWithInvalidCpuCountShouldReturnDefaultCpuCount() public void GetTestAdaptersPaths() { string settingXml = @"C:\testadapterpath;D:\secondtestadapterpath"; - string[] expectedResult = new string[] { @"C:\testadapterpath", @"D:\secondtestadapterpath" }; + string[] expectedResult = [@"C:\testadapterpath", @"D:\secondtestadapterpath"]; string[] result = (string[])RunSettingsUtilities.GetTestAdaptersPaths(settingXml); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs index db25959ca0..7d352a6327 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs @@ -358,7 +358,7 @@ private static void WriteOnSocket(Socket socket) { for (int i = 0; i < 10; i++) { - socket.Send(new byte[2] { 0x1, 0x0 }); + socket.Send([0x1, 0x0]); } } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs index 81245148c2..311230f716 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs @@ -44,7 +44,7 @@ public void SendAfterTestRunEndAndGetResultShouldReturnAttachments() attachment.Attachments.Add(new UriDataAttachment(attachmentUri, "filename.txt")); var invokedDataCollector = new InvokedDataCollector(datacollectorUri, displayName, typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false); _mockDataSerializer.Setup(x => x.DeserializePayload(It.IsAny())).Returns( - new AfterTestRunEndResult(new Collection() { attachment }, new Collection() { invokedDataCollector }, new Dictionary())); + new AfterTestRunEndResult([attachment], new Collection() { invokedDataCollector }, new Dictionary())); _mockCommunicationManager.SetupSequence(x => x.ReceiveRawMessage()).Returns(rawMessage1).Returns(rawMessage2); _mockDataSerializer.Setup(x => x.DeserializeMessage(rawMessage1)).Returns(new Message() { MessageType = MessageType.TelemetryEventMessage, Payload = null }); _mockDataSerializer.Setup(x => x.DeserializeMessage(rawMessage2)).Returns(new Message() { MessageType = MessageType.AfterTestRunEndResult, Payload = null }); @@ -80,7 +80,7 @@ public void SendAfterTestRunEndAndGetResultShouldReturnAttachmentsAndPropagateTe attachment.Attachments.Add(new UriDataAttachment(attachmentUri, "filename.txt")); var invokedDataCollector = new InvokedDataCollector(datacollectorUri, displayName, typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false); _mockDataSerializer.Setup(x => x.DeserializePayload(It.IsAny())).Returns( - new AfterTestRunEndResult(new Collection() { attachment }, new Collection() { invokedDataCollector }, new Dictionary())); + new AfterTestRunEndResult([attachment], new Collection() { invokedDataCollector }, new Dictionary())); _mockCommunicationManager.SetupSequence(x => x.ReceiveRawMessage()).Returns(rawMessage1).Returns(rawMessage2); _mockDataSerializer.Setup(x => x.DeserializeMessage(rawMessage1)).Returns(new Message() { MessageType = MessageType.TelemetryEventMessage, Payload = null }); _mockDataSerializer.Setup(x => x.DeserializeMessage(rawMessage2)).Returns(new Message() { MessageType = MessageType.AfterTestRunEndResult, Payload = null }); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/JsonDataSerializerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/JsonDataSerializerTests.cs index 05a8c8650f..fed8fb3d84 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/JsonDataSerializerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/JsonDataSerializerTests.cs @@ -49,16 +49,16 @@ public void SerializePayloadShouldNotPickDefaultSettings(int version) var classWithSelfReferencingLoop = new ClassWithSelfReferencingLoop(null); classWithSelfReferencingLoop = new ClassWithSelfReferencingLoop(classWithSelfReferencingLoop); - classWithSelfReferencingLoop.InfiniteRefernce!.InfiniteRefernce = classWithSelfReferencingLoop; + classWithSelfReferencingLoop.InfiniteReference!.InfiniteReference = classWithSelfReferencingLoop; string serializedPayload = _jsonDataSerializer.SerializePayload("dummy", classWithSelfReferencingLoop, version); if (version <= 1) { - Assert.AreEqual("{\"MessageType\":\"dummy\",\"Payload\":{\"InfiniteRefernce\":{}}}", serializedPayload); + Assert.AreEqual("{\"MessageType\":\"dummy\",\"Payload\":{\"InfiniteReference\":{}}}", serializedPayload); } else { - Assert.AreEqual($"{{\"Version\":{version},\"MessageType\":\"dummy\",\"Payload\":{{\"InfiniteRefernce\":{{}}}}}}", serializedPayload); + Assert.AreEqual($"{{\"Version\":{version},\"MessageType\":\"dummy\",\"Payload\":{{\"InfiniteReference\":{{}}}}}}", serializedPayload); } JsonConvert.DefaultSettings = null; @@ -76,7 +76,7 @@ public void DeserializeMessageShouldNotPickDefaultSettings() PreserveReferencesHandling = PreserveReferencesHandling.All, }; - Message message = _jsonDataSerializer.DeserializeMessage("{\"MessageType\":\"dummy\",\"Payload\":{\"InfiniteRefernce\":{}}}"); + Message message = _jsonDataSerializer.DeserializeMessage("{\"MessageType\":\"dummy\",\"Payload\":{\"InfiniteReference\":{}}}"); Assert.AreEqual("dummy", message?.MessageType); JsonConvert.DefaultSettings = null; } @@ -137,7 +137,7 @@ public void DeserializePayloadIsUnaffectedByJsonConverterDefaultSettings(int ver }; // This line should deserialize properly - Message message = _jsonDataSerializer.DeserializeMessage($"{{\"Version\":\"{version}\",\"MessageType\":\"dummy\",\"Payload\":{{\"InfiniteRefernce\":{{}}}}}}"); + Message message = _jsonDataSerializer.DeserializeMessage($"{{\"Version\":\"{version}\",\"MessageType\":\"dummy\",\"Payload\":{{\"InfiniteReference\":{{}}}}}}"); //restore the default settings to null @@ -150,7 +150,7 @@ public void SerializePayloadShouldSerializeAnObjectWithSelfReferencingLoop() { var classWithSelfReferencingLoop = new ClassWithSelfReferencingLoop(null); classWithSelfReferencingLoop = new ClassWithSelfReferencingLoop(classWithSelfReferencingLoop); - classWithSelfReferencingLoop.InfiniteRefernce!.InfiniteRefernce = classWithSelfReferencingLoop; + classWithSelfReferencingLoop.InfiniteReference!.InfiniteReference = classWithSelfReferencingLoop; // This line should not throw exception _jsonDataSerializer.SerializePayload("dummy", classWithSelfReferencingLoop); @@ -161,7 +161,7 @@ public void DeserializeShouldDeserializeAnObjectWhichHadSelfReferencingLoopBefor { var classWithSelfReferencingLoop = new ClassWithSelfReferencingLoop(null); classWithSelfReferencingLoop = new ClassWithSelfReferencingLoop(classWithSelfReferencingLoop); - classWithSelfReferencingLoop.InfiniteRefernce!.InfiniteRefernce = classWithSelfReferencingLoop; + classWithSelfReferencingLoop.InfiniteReference!.InfiniteReference = classWithSelfReferencingLoop; var json = _jsonDataSerializer.SerializePayload("dummy", classWithSelfReferencingLoop); @@ -169,7 +169,7 @@ public void DeserializeShouldDeserializeAnObjectWhichHadSelfReferencingLoopBefor var result = _jsonDataSerializer.Deserialize(json, 1)!; Assert.AreEqual(typeof(ClassWithSelfReferencingLoop), result.GetType()); - Assert.IsNull(result.InfiniteRefernce); + Assert.IsNull(result.InfiniteReference); } [TestMethod] @@ -255,9 +255,9 @@ public class ClassWithSelfReferencingLoop { public ClassWithSelfReferencingLoop(ClassWithSelfReferencingLoop? ir) { - InfiniteRefernce = ir; + InfiniteReference = ir; } - public ClassWithSelfReferencingLoop? InfiniteRefernce { get; set; } + public ClassWithSelfReferencingLoop? InfiniteReference { get; set; } } } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs index 3fa3d0c968..8cdeb06831 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs @@ -35,7 +35,7 @@ public class TestRequestSenderTests private readonly Mock _mockDataSerializer; private readonly Mock _mockChannel; - private readonly List _pathToAdditionalExtensions = new() { "Hello", "World" }; + private readonly List _pathToAdditionalExtensions = ["Hello", "World"]; private readonly Mock _mockDiscoveryEventsHandler; private readonly Mock _mockExecutionEventsHandler; private readonly TestRunCriteriaWithSources _testRunCriteriaWithSources; diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs index 7f9b7cf5f0..1b7ec113d6 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs @@ -33,7 +33,7 @@ public void GetArgumentsDictionaryShouldIgnoreValuesWithoutPreceedingHypen() Assert.AreEqual("2312", argsDictionary["--parentprocessid"]); Assert.AreEqual(@"C:\temp\1.dll", argsDictionary["--testsourcepath"]); - args = new List() { "--port", "12312", "--parentprocessid", "2312", "testsourcepath", @"C:\temp\1.dll" }; + args = ["--port", "12312", "--parentprocessid", "2312", "testsourcepath", @"C:\temp\1.dll"]; argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(args.ToArray()); Assert.IsTrue(argsDictionary.Count == 2); @@ -81,7 +81,7 @@ public void GetArgumentsDictionaryShouldReturnEmptyDictionaryIfEmptyArgIsPassed( var argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(null); Assert.IsTrue(argsDictionary.Count == 0); - argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(System.Array.Empty()); + argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary([]); Assert.IsTrue(argsDictionary.Count == 0); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs index 24da177a5d..54bb5e48e6 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs @@ -56,11 +56,10 @@ public TestRunAttachmentsProcessingManagerTests() _mockAttachmentHandler1.Setup(h => h.GetExtensionUris()).Returns(new[] { new Uri(Uri1) }); _mockAttachmentHandler2.Setup(h => h.GetExtensionUris()).Returns(new[] { new Uri(Uri2) }); _mockDataCollectorAttachmentsProcessorsFactory.Setup(p => p.Create(It.IsAny(), It.IsAny())) - .Returns(new DataCollectorAttachmentProcessor[] - { + .Returns([ new( "friendlyNameA", _mockAttachmentHandler1.Object ), new( "friendlyNameB" ,_mockAttachmentHandler2.Object ) - }); + ]); _manager = new TestRunAttachmentsProcessingManager(_mockEventSource.Object, _mockDataCollectorAttachmentsProcessorsFactory.Object); @@ -114,10 +113,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnNoAttachments_IfNoA public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1NotProcessedAttachmentThroughEventsHandler_If1NotRelatedAttachmentOnInput() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri3), "uri3_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri3), "uri3_input")]; // act await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _mockEventsHandler.Object, _cancellationTokenSource.Token); @@ -138,10 +134,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1NotProcessedAttach public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1NotProcessedAttachment_If1NotRelatedAttachmentOnInput() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri3), "uri3_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri3), "uri3_input")]; // act var result = await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _cancellationTokenSource.Token); @@ -161,15 +154,9 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1NotProcessedAttach public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1ProcessedAttachmentThroughEventsHandler_IfRelatedAttachmentOnInput() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; - List outputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_output") - }; + List outputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_output")]; _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachments); @@ -192,15 +179,9 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1ProcessedAttachmen public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1ProcessedAttachment_IfRelatedAttachmentOnInput() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; - List outputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_output") - }; + List outputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_output")]; _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachments); @@ -224,10 +205,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1ProcessedAttachmen public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachmentsThroughEventsHandler_IfRelatedAttachmentOnInputButHandlerThrowsException() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; var exceptionToThrow = new Exception("exception message"); _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).Throws(exceptionToThrow); @@ -251,10 +229,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachmentsT public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_IfRelatedAttachmentOnInputButHandlerThrowsException() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).Throws(new Exception("exception message")); @@ -277,10 +252,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachmentsT { // arrange _cancellationTokenSource.Cancel(); - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; // act await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _mockEventsHandler.Object, _cancellationTokenSource.Token); @@ -301,10 +273,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_ { // arrange _cancellationTokenSource.Cancel(); - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; // act var result = await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _cancellationTokenSource.Token); @@ -324,24 +293,18 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProcessedAttachmentsThroughEventsHandler_IfRelatedAttachmentsOnInput() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input1"), new AttachmentSet(new Uri(Uri1), "uri1_input2"), new AttachmentSet(new Uri(Uri2), "uri2_input1"), new AttachmentSet(new Uri(Uri2), "uri2_input2"), - new AttachmentSet(new Uri(Uri3), "uri3_input1"), - }; + new AttachmentSet(new Uri(Uri3), "uri3_input1") + ]; - List outputAttachmentsForHandler1 = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_output") - }; + List outputAttachmentsForHandler1 = [new AttachmentSet(new Uri(Uri1), "uri1_output")]; - List outputAttachmentsForHandler2 = new() - { - new AttachmentSet(new Uri(Uri2), "uri2_output") - }; + List outputAttachmentsForHandler2 = [new AttachmentSet(new Uri(Uri2), "uri2_output")]; _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(null!, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler1); _mockAttachmentHandler2.Setup(h => h.ProcessAttachmentSetsAsync(null!, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler2); @@ -365,24 +328,18 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProcessedAttachment public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProcessedAttachments_IfRelatedAttachmentsOnInput() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input1"), new AttachmentSet(new Uri(Uri1), "uri1_input2"), new AttachmentSet(new Uri(Uri2), "uri2_input1"), new AttachmentSet(new Uri(Uri2), "uri2_input2"), - new AttachmentSet(new Uri(Uri3), "uri3_input1"), - }; + new AttachmentSet(new Uri(Uri3), "uri3_input1") + ]; - List outputAttachmentsForHandler1 = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_output") - }; + List outputAttachmentsForHandler1 = [new AttachmentSet(new Uri(Uri1), "uri1_output")]; - List outputAttachmentsForHandler2 = new() - { - new AttachmentSet(new Uri(Uri2), "uri2_output") - }; + List outputAttachmentsForHandler2 = [new AttachmentSet(new Uri(Uri2), "uri2_output")]; _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler1); _mockAttachmentHandler2.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler2); @@ -407,10 +364,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProcessedAttachment public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachmentsThroughEventsHandler_IfOperationCancelled() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; ICollection outputAttachments = new List { @@ -491,10 +445,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachmentsT public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_IfOperationCancelled() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; ICollection outputAttachments = new List { @@ -552,11 +503,11 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProperlySendProgressEvents_IfHandlersPropagesEvents() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input"), new AttachmentSet(new Uri(Uri2), "uri2_input") - }; + ]; ICollection outputAttachments1 = new List { @@ -628,11 +579,11 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProperlySendProgres public async Task ProcessTestRunAttachmentsAsync_ShouldNotFailIfRunsettingsIsNull() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input"), new AttachmentSet(new Uri(Uri2), "uri2_input") - }; + ]; ICollection outputAttachments = new List { new(new Uri(Uri2), "uri2_output") @@ -658,16 +609,16 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldNotFailIfRunsettingsIsNul public async Task ProcessTestRunAttachmentsAsync_ShouldFlowCorrectDataCollectorConfiguration(bool withConfig) { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input"), new AttachmentSet(new Uri(Uri2), "uri2_input") - }; + ]; - List invokedDataCollectors = new() - { + List invokedDataCollectors = + [ new InvokedDataCollector(new Uri(Uri1), withConfig ? "friendlyNameA" : "friendlyNameB", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false) - }; + ]; string runSettingsXml = $@" @@ -716,10 +667,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldFlowCorrectDataCollectorC public async Task ProcessTestRunAttachmentsAsync_ShouldNotConsumeAttachmentsIfProcessorFails() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input_1") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input_1")]; inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file1", "Sample1")); inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file2", "Sample2")); inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file3", "Sample3")); @@ -778,10 +726,10 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldNotConsumeAttachmentsIfPr public async Task ProcessTestRunAttachmentsAsync_ShouldNotConsumeAttachmentsIfAllProcessorsFail() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input_1"), - }; + List inputAttachments = + [ + new AttachmentSet(new Uri(Uri1), "uri1_input_1") + ]; inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file1", "Sample1")); inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file2", "Sample2")); inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file3", "Sample3")); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyDiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyDiscoveryManagerTests.cs index 879ef89150..4e0c03058d 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyDiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyDiscoveryManagerTests.cs @@ -40,7 +40,7 @@ public InProcessProxyDiscoveryManagerTests() public void DiscoverTestsShouldCallInitialize() { var manualResetEvent = new ManualResetEvent(false); - _mockDiscoveryManager.Setup(o => o.Initialize(Enumerable.Empty(), null)).Callback( + _mockDiscoveryManager.Setup(o => o.Initialize(Array.Empty(), null)).Callback( () => manualResetEvent.Set()); var discoveryCriteria = new DiscoveryCriteria(new[] { "test.dll" }, 1, string.Empty); @@ -53,7 +53,7 @@ public void DiscoverTestsShouldCallInitialize() public void DiscoverTestsShouldUpdateTestPluginCacheWithExtensionsReturnByTestHost() { var manualResetEvent = new ManualResetEvent(false); - _mockDiscoveryManager.Setup(o => o.Initialize(Enumerable.Empty(), null)).Callback( + _mockDiscoveryManager.Setup(o => o.Initialize(Array.Empty(), null)).Callback( () => manualResetEvent.Set()); var path = Path.Combine(Path.GetTempPath(), "DiscoveryDummy.dll"); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs index 6ef4ea3f74..4122e2cbdc 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs @@ -44,7 +44,7 @@ public void StartTestRunShouldCallInitialize() var mockTestMessageEventHandler = new Mock(); _inProcessProxyExecutionManager.StartTestRun(testRunCriteria, null!); - _mockExecutionManager.Verify(o => o.Initialize(Enumerable.Empty(), It.IsAny()), Times.Once, "StartTestRun should call Initialize if not already initialized"); + _mockExecutionManager.Verify(o => o.Initialize(Array.Empty(), It.IsAny()), Times.Once, "StartTestRun should call Initialize if not already initialized"); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs index 066afb05cb..37cfb2764d 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs @@ -30,7 +30,7 @@ public class ParallelProxyDiscoveryManagerTests private readonly List> _usedMockManagers; private readonly Func _createMockManager; private readonly Mock _mockEventHandler; - private readonly List _sources = new() { "1.dll", "2.dll" }; + private readonly List _sources = ["1.dll", "2.dll"]; private readonly DiscoveryCriteria _discoveryCriteriaWith2Sources; private readonly List _runtimeProviders; private int _createMockManagerCalled; @@ -70,11 +70,10 @@ public ParallelProxyDiscoveryManagerTests() _mockEventHandler = new Mock(); _discoveryCriteriaWith2Sources = new DiscoveryCriteria(_sources, 100, null); _runtimeProviders = new List { - new(typeof(ITestRuntimeProvider), false, "", new List - { + new(typeof(ITestRuntimeProvider), false, "", [ new() { Source = _sources[0], Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, new() { Source = _sources[1], Architecture = Architecture.X86, Framework = Framework.DefaultFramework } - }) + ]) }; // This event is Set by callback from _mockEventHandler in SetupDiscoveryManager diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs index 061e6c00a2..2ac3486f2f 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs @@ -73,13 +73,12 @@ public ParallelProxyExecutionManagerTests() _processedSources = new List(); _testRunCriteriaWith2Sources = new TestRunCriteria(_sources, 100, false, string.Empty, TimeSpan.MaxValue, null, "Name~Test", new FilterOptions() { FilterRegEx = @"^[^\s\(]+" }); _runtimeProviders = new List { - new(typeof(ITestRuntimeProvider), false, "", new List - { + new(typeof(ITestRuntimeProvider), false, "", [ new() { Source = "1.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, new() { Source = "2.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, // For testcases on the bottom. - new() { Source = "3.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, - }) + new() { Source = "3.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework } + ]) }; // Configure testcases diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs index a9774c1367..b78ab647f8 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs @@ -222,7 +222,7 @@ public void DiscoverTestsShouldQueryTestHostManagerForExtensions() TestPluginCache.Instance = null; try { - TestPluginCacheHelper.SetupMockAdditionalPathExtensions(new[] { "c:\\e1.dll" }); + TestPluginCacheHelper.SetupMockAdditionalPathExtensions(["c:\\e1.dll"]); _mockFileHelper.Setup(fh => fh.Exists(It.IsAny())).Returns(true); _mockRequestSender.Setup(s => s.WaitForRequestHandlerConnection(It.IsAny(), It.IsAny())).Returns(true); _mockTestHostManager.Setup(th => th.GetTestPlatformExtensions(It.IsAny>(), It.IsAny>())).Returns(new[] { "he1.dll", "c:\\e1.dll" }); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs index 416a12ca8c..286c193f53 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs @@ -320,7 +320,7 @@ public void SetupChannelShouldThrowExceptionWithAllSourcesIfTestHostExitedBefore _mockRequestSender.Setup(s => s.WaitForRequestHandlerConnection(It.IsAny(), It.IsAny())).Returns(false); _mockTestHostManager.Setup(tmh => tmh.LaunchTestHostAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(true)).Callback(() => _mockTestHostManager.Raise(t => t.HostExited += null, new HostProviderEventArgs("I crashed!"))); - Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.Resources.TestHostExitedWithError, string.Join("', '", new[] { "source1.dll", "source2.dll" }), "I crashed!"), Assert.ThrowsException(() => _testExecutionManager.SetupChannel(new List { "source1.dll", "source2.dll" }, runsettings)).Message); + Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.Resources.TestHostExitedWithError, string.Join("', '", ["source1.dll", "source2.dll"]), "I crashed!"), Assert.ThrowsException(() => _testExecutionManager.SetupChannel(new List { "source1.dll", "source2.dll" }, runsettings)).Message); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs index 6e1dc96b61..a38583a79e 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs @@ -6,7 +6,6 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; @@ -72,10 +71,10 @@ public void SetupChannelShouldLaunchTestHost() var expectedStartInfo = new TestProcessStartInfo(); _mockRequestSender.Setup(rs => rs.InitializeCommunication()).Returns(123); _mockTestHostManager.Setup( - th => th.GetTestHostProcessStartInfo(Enumerable.Empty(), It.IsAny>(), It.IsAny())) + th => th.GetTestHostProcessStartInfo(Array.Empty(), It.IsAny>(), It.IsAny())) .Returns(expectedStartInfo); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockTestHostManager.Verify(thl => thl.LaunchTestHostAsync(It.Is(si => si == expectedStartInfo), It.IsAny()), Times.Once); } @@ -86,7 +85,7 @@ public void SetupChannelShouldCreateTimestampedLogFileForHost() _mockRequestSender.Setup(rs => rs.InitializeCommunication()).Returns(123); EqtTrace.InitializeTrace("log.txt", PlatformTraceLevel.Verbose); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockTestHostManager.Verify( th => @@ -125,7 +124,7 @@ public void SetupChannelOutcomeShouldTakeTesthostSessionSupportIntoAccount( }; Assert.IsTrue(testOperationManager.IsTesthostCompatibleWithTestSessions() == expectedCompatibilityCheckResult); - Assert.IsTrue(testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings) == expectedSetupResult); + Assert.IsTrue(testOperationManager.SetupChannel([], DefaultRunSettings) == expectedSetupResult); } [TestMethod] @@ -133,7 +132,7 @@ public void SetupChannelShouldAddRunnerProcessIdForTestHost() { _mockRequestSender.Setup(rs => rs.InitializeCommunication()).Returns(123); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); #if NET5_0_OR_GREATER var pid = Environment.ProcessId; @@ -161,7 +160,7 @@ public void SetupChannelShouldAddCorrectTraceLevelForTestHost() #endif _mockRequestSender.Setup(rs => rs.InitializeCommunication()).Returns(123); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockTestHostManager.Verify( th => @@ -174,7 +173,7 @@ public void SetupChannelShouldAddCorrectTraceLevelForTestHost() [TestMethod] public void SetupChannelShouldSetupServerForCommunication() { - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(s => s.InitializeCommunication(), Times.Once); } @@ -201,7 +200,7 @@ public void SetupChannelShouldCallHostServerIfRunnerIsServer() var localTestOperationManager = new TestableProxyOperationManager(_mockRequestData.Object, testRequestSender, _mockTestHostManager.Object); - localTestOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + localTestOperationManager.SetupChannel([], DefaultRunSettings); mockCommunicationServer.Verify(s => s.Start(IPAddress.Loopback.ToString() + ":0"), Times.Once); } @@ -229,7 +228,7 @@ public void SetupChannelShouldCallSetupClientIfRunnerIsClient() var localTestOperationManager = new TestableProxyOperationManager(_mockRequestData.Object, testRequestSender, _mockTestHostManager.Object); - localTestOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + localTestOperationManager.SetupChannel([], DefaultRunSettings); mockCommunicationEndpoint.Verify(s => s.Start(It.IsAny()), Times.Once); } @@ -237,8 +236,8 @@ public void SetupChannelShouldCallSetupClientIfRunnerIsClient() [TestMethod] public void SetupChannelShouldNotInitializeIfConnectionIsAlreadyInitialized() { - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(s => s.InitializeCommunication(), Times.Once); } @@ -246,7 +245,7 @@ public void SetupChannelShouldNotInitializeIfConnectionIsAlreadyInitialized() [TestMethod] public void SetupChannelShouldWaitForTestHostConnection() { - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.WaitForRequestHandlerConnection(ConnectionTimeout, It.IsAny()), Times.Once); } @@ -254,8 +253,8 @@ public void SetupChannelShouldWaitForTestHostConnection() [TestMethod] public void SetupChannelShouldNotWaitForTestHostConnectionIfConnectionIsInitialized() { - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.WaitForRequestHandlerConnection(ConnectionTimeout, It.IsAny()), Times.Exactly(1)); } @@ -266,7 +265,7 @@ public void SetupChannelShouldHonorTimeOutSetByUser() Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, "100"); _mockRequestSender.Setup(rs => rs.WaitForRequestHandlerConnection(100000, It.IsAny())).Returns(true); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.WaitForRequestHandlerConnection(100000, It.IsAny()), Times.Exactly(1)); } @@ -279,7 +278,7 @@ public void SetupChannelShouldThrowIfWaitForTestHostConnectionTimesOut() var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object); - var message = Assert.ThrowsException(() => operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)).Message; + var message = Assert.ThrowsException(() => operationManager.SetupChannel([], DefaultRunSettings)).Message; Assert.AreEqual(message, TimoutErrorMessage); } @@ -293,7 +292,7 @@ public void SetupChannelShouldThrowTestPlatformExceptionIfRequestCancelled() var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object, cancellationTokenSource); cancellationTokenSource.Cancel(); - var message = Assert.ThrowsException(() => operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)).Message; + var message = Assert.ThrowsException(() => operationManager.SetupChannel([], DefaultRunSettings)).Message; Equals("Canceling the operation as requested.", message); } @@ -308,7 +307,7 @@ public void SetupChannelShouldThrowTestPlatformExceptionIfRequestCancelledDuring var cancellationTokenSource = new CancellationTokenSource(); var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object, cancellationTokenSource); - var message = Assert.ThrowsException(() => operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)).Message; + var message = Assert.ThrowsException(() => operationManager.SetupChannel([], DefaultRunSettings)).Message; Equals("Canceling the operation as requested.", message); } @@ -322,7 +321,7 @@ public void SetupChannelShouldThrowTestPlatformExceptionIfRequestCancelledPostHo _mockTestHostManager.Setup(rs => rs.LaunchTestHostAsync(It.IsAny(), It.IsAny())).Callback(() => cancellationTokenSource.Cancel()); var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object, cancellationTokenSource); - var message = Assert.ThrowsException(() => operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)).Message; + var message = Assert.ThrowsException(() => operationManager.SetupChannel([], DefaultRunSettings)).Message; Equals("Canceling the operation as requested.", message); } @@ -334,14 +333,14 @@ public void SetupChannelShouldThrowIfLaunchTestHostFails() var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object); - var message = Assert.ThrowsException(() => operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)).Message; + var message = Assert.ThrowsException(() => operationManager.SetupChannel([], DefaultRunSettings)).Message; Assert.AreEqual(message, Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Resources.Resources.InitializationFailed); } [TestMethod] public void SetupChannelShouldCheckVersionWithTestHost() { - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.CheckVersionWithTestHost(), Times.Once); } @@ -350,7 +349,7 @@ public void SetupChannelShouldThrowExceptionIfVersionCheckFails() { // Make the version check fail _mockRequestSender.Setup(rs => rs.CheckVersionWithTestHost()).Throws(new TestPlatformException("Version check failed")); - Assert.ThrowsException(() => _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)); + Assert.ThrowsException(() => _testOperationManager.SetupChannel([], DefaultRunSettings)); } [TestMethod] @@ -362,7 +361,7 @@ public void SetupChannelForDotnetHostManagerWithIsVersionCheckRequiredFalseShoul var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, testHostManager); - operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + operationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.CheckVersionWithTestHost(), Times.Never); } @@ -375,7 +374,7 @@ public void SetupChannelForDotnetHostManagerWithIsVersionCheckRequiredTrueShould testHostManager.Initialize(new NullMessageLogger(), DefaultRunSettings); var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, testHostManager); - operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + operationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.CheckVersionWithTestHost(), Times.Once); } @@ -384,7 +383,7 @@ public void SetupChannelForDotnetHostManagerWithIsVersionCheckRequiredTrueShould public void CloseShouldEndSessionIfHostWasLaunched() { _mockRequestSender.Setup(rs => rs.WaitForRequestHandlerConnection(ConnectionTimeout, It.IsAny())).Returns(true); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _testOperationManager.Close(); @@ -412,11 +411,11 @@ public void CloseShouldResetChannelInitialization() { SetupWaitForTestHostExit(); _mockRequestSender.Setup(rs => rs.WaitForRequestHandlerConnection(ConnectionTimeout, It.IsAny())).Returns(true); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _testOperationManager.Close(); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockTestHostManager.Verify(th => th.LaunchTestHostAsync(It.IsAny(), It.IsAny()), Times.Exactly(2)); } @@ -425,7 +424,7 @@ public void CloseShouldTerminateTesthostProcessIfWaitTimesout() { // Ensure testhost start returns a dummy process id _mockRequestSender.Setup(rs => rs.WaitForRequestHandlerConnection(ConnectionTimeout, It.IsAny())).Returns(true); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _testOperationManager.Close(); @@ -472,7 +471,7 @@ public void UpdateTestProcessStartInfoShouldUpdateTelemetryOptedInArgTrueIfTelem .Returns(Task.FromResult(true)); // Act. - testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + testOperationManager.SetupChannel([], DefaultRunSettings); // Verify. Assert.IsTrue(receivedTestProcessInfo.Arguments!.Contains("--telemetryoptedin true")); @@ -495,7 +494,7 @@ public void UpdateTestProcessStartInfoShouldUpdateTelemetryOptedInArgFalseIfTele .Returns(Task.FromResult(true)); // Act. - testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + testOperationManager.SetupChannel([], DefaultRunSettings); // Verify. Assert.IsTrue(receivedTestProcessInfo.Arguments!.Contains("--telemetryoptedin false")); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs index 615c62c2bd..853bfa8486 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs @@ -108,14 +108,14 @@ public ProxyTestSessionManagerTests() _fakeTestSourcesToRuntimeProviderMap = new Dictionary { - [_fakeTestSources[0]] = new TestRuntimeProviderInfo(typeof(ITestRuntimeProvider), false, _fakeRunSettings, new List - { - new() { + [_fakeTestSources[0]] = new TestRuntimeProviderInfo(typeof(ITestRuntimeProvider), false, _fakeRunSettings, [ + new() + { Source = _fakeTestSources[0], Architecture = Architecture.X86, Framework = Framework.DefaultFramework } - }) + ]) }; } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs index 681ac0e675..bb923e63bb 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs @@ -54,17 +54,14 @@ public ParallelDataCollectionEventsHandlerTests() public void HandleTestRunComplete_ShouldCallProcessTestRunAttachmentsAsyncWithAttachmentsAndUseResults() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input1"), new AttachmentSet(new Uri(Uri2), "uri2_input1"), new AttachmentSet(new Uri(Uri3), "uri3_input1") - }; + ]; - Collection outputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input1") - }; + Collection outputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input1")]; _mockTestRunAttachmentsProcessingManager.Setup(f => f.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, It.IsAny>(), It.IsAny>(), It.IsAny())).Returns(Task.FromResult(outputAttachments)); @@ -80,12 +77,12 @@ public void HandleTestRunComplete_ShouldCallProcessTestRunAttachmentsAsyncWithAt public void HandleTestRunComplete_ShouldCallProcessTestRunAttachmentsAsyncWithAttachmentsAndNotUserResults_IfManagerReturnsNull() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input1"), new AttachmentSet(new Uri(Uri2), "uri2_input1"), new AttachmentSet(new Uri(Uri3), "uri3_input1") - }; + ]; _mockTestRunAttachmentsProcessingManager.Setup(f => f.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, It.IsAny>(), It.IsAny>(), It.IsAny())).Returns(Task.FromResult((Collection)null!)); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs index ec44ce64b4..3215c024a3 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs @@ -49,7 +49,8 @@ public DiscovererEnumeratorTests() _discovererEnumerator = new DiscovererEnumerator(_mockRequestData.Object, _discoveryResultCache, _mockTestPlatformEventSource.Object, _mockAssemblyProperties.Object, _cancellationTokenSource.Token); _runSettingsMock = new Mock(); _messageLoggerMock = new Mock(); - TestPluginCacheHelper.SetupMockExtensions(new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + TestPluginCacheHelper.SetupMockExtensions( + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); TestDiscoveryExtensionManager.Destroy(); } @@ -70,7 +71,7 @@ public void Cleanup() public void LoadTestsShouldReportWarningOnNoDiscoverers() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(TestPluginCache).Assembly.Location }, + [typeof(TestPluginCache).Assembly.Location], () => { }); var sources = new List { typeof(DiscoveryResultCacheTests).Assembly.Location }; @@ -90,7 +91,7 @@ public void LoadTestsShouldReportWarningOnNoDiscoverers() public void LoadTestsShouldNotCallIntoDiscoverersIfNoneMatchesSources() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List { "temp.jpeg" }; @@ -115,7 +116,7 @@ public void LoadTestsShouldNotCallIntoDiscoverersIfNoneMatchesSources() public void LoadTestsShouldCallOnlyNativeDiscovererIfNativeAssembliesPassed() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); _mockAssemblyProperties.Setup(pe => pe.GetAssemblyType("native.dll")).Returns(AssemblyType.Native); @@ -150,7 +151,7 @@ public void LoadTestsShouldCallOnlyNativeDiscovererIfNativeAssembliesPassed() public void LoadTestsShouldCallOnlyManagedDiscovererIfManagedAssembliesPassed() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); _mockAssemblyProperties.Setup(pe => pe.GetAssemblyType("managed.dll")).Returns(AssemblyType.Managed); @@ -185,7 +186,7 @@ public void LoadTestsShouldCallOnlyManagedDiscovererIfManagedAssembliesPassed() public void LoadTestsShouldCallBothNativeAndManagedDiscoverersWithCorrectSources() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); _mockAssemblyProperties.Setup(pe => pe.GetAssemblyType("native.dll")).Returns(AssemblyType.Native); @@ -228,7 +229,7 @@ public void LoadTestsShouldCallBothNativeAndManagedDiscoverersWithCorrectSources public void LoadTestsShouldCallIntoADiscovererThatMatchesTheSources() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -269,7 +270,7 @@ public void LoadTestsShouldCallIntoADiscovererThatMatchesTheSources() public void LoadTestsShouldCallIntoMultipleDiscoverersThatMatchesTheSources() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var dllsources = new List @@ -350,7 +351,7 @@ public void LoadTestsShouldCallIntoMultipleDiscoverersThatMatchesTheSources() public void LoadTestsShouldCallIntoOtherDiscoverersWhenCreatingOneFails() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -394,7 +395,7 @@ public void LoadTestsShouldCallIntoOtherDiscoverersWhenCreatingOneFails() public void LoadTestsShouldCallIntoOtherDiscoverersEvenIfDiscoveryInOneFails() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -449,7 +450,7 @@ public void LoadTestsShouldCollectMetrics() }; TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -484,7 +485,7 @@ public void LoadTestsShouldCollectMetrics() public void LoadTestsShouldNotCallIntoDiscoverersWhenCancelled() { // Setup - string[] extensions = new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }; + string[] extensions = [typeof(DiscovererEnumeratorTests).Assembly.Location]; TestPluginCacheHelper.SetupMockExtensions(extensions, () => { }); var dllsources = new List @@ -572,7 +573,7 @@ public void LoadTestShouldInstrumentAdapterDiscoveryStop() public void LoadTestsShouldIterateOverAllExtensionsInTheMapAndDiscoverTests() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var dllsources = new List @@ -696,7 +697,7 @@ private static void SetupForNoTestsAvailableInGivenAssemblies( private void InvokeLoadTestWithMockSetup() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs index dca3280bf7..86fee2b8d9 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs @@ -160,7 +160,7 @@ public void DiscoverTestsShouldLogIfThereAreNoValidSources() public void DiscoverTestsShouldLogIfTheSameSourceIsSpecifiedTwice() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -187,7 +187,7 @@ public void DiscoverTestsShouldLogIfTheSameSourceIsSpecifiedTwice() public void DiscoverTestsShouldDiscoverTestsInTheSpecifiedSource() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -215,7 +215,7 @@ public void DiscoverTestsShouldSendMetricsOnDiscoveryComplete() DiscoveryCompleteEventArgs? receivedDiscoveryCompleteEventArgs = null; TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -253,7 +253,7 @@ public void DiscoverTestsShouldCollectMetrics() _mockRequestData.Setup(rd => rd.MetricsCollection).Returns(mockMetricsCollector.Object); TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -278,7 +278,7 @@ public void DiscoveryInitializeShouldVerifyWarningMessageIfAdapterFailedToLoad() var assemblyLocation = typeof(DiscoveryManagerTests).Assembly.Location; var mockLogger = new Mock(); TestPluginCacheHelper.SetupMockExtensions( - new string[] { assemblyLocation }, + [assemblyLocation], () => { }); //Act diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs index 89b6b64aa6..f57cf09db5 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs @@ -200,7 +200,7 @@ public void ProcessRequestsDiscoveryStartShouldStartDiscoveryWithGivenCriteria() [TestMethod] public void DiscoveryCompleteShouldSendDiscoveryCompletePayloadOnChannel() { - var discoveryComplete = new DiscoveryCompletePayload { TotalTests = 1, LastDiscoveredTests = Enumerable.Empty(), IsAborted = false }; + var discoveryComplete = new DiscoveryCompletePayload { TotalTests = 1, LastDiscoveredTests = [], IsAborted = false }; var message = _dataSerializer.SerializePayload(MessageType.DiscoveryComplete, discoveryComplete); ProcessRequestsAsync(_mockTestHostManagerFactory.Object); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs index b1aeeffeaa..4f7194fd83 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs @@ -91,7 +91,7 @@ public BaseRunTestsTests() new PlatformThread(), _mockDataSerializer.Object); - TestPluginCacheHelper.SetupMockExtensions(new string[] { typeof(BaseRunTestsTests).Assembly.Location }, () => { }); + TestPluginCacheHelper.SetupMockExtensions([typeof(BaseRunTestsTests).Assembly.Location], () => { }); } [TestCleanup] @@ -809,7 +809,7 @@ private void SetupForExecutionThreadApartmentStateTests(PlatformApartmentState a _mockThread.Object, _mockDataSerializer.Object); - TestPluginCacheHelper.SetupMockExtensions(new string[] { typeof(BaseRunTestsTests).Assembly.Location }, () => { }); + TestPluginCacheHelper.SetupMockExtensions([typeof(BaseRunTestsTests).Assembly.Location], () => { }); var assemblyLocation = typeof(BaseRunTestsTests).Assembly.Location; var executorUriExtensionMap = new List> { diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs index 72da52e034..bea628a470 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs @@ -78,7 +78,7 @@ public void InitializeShouldLoadAndInitializeAllExtensions() var commonAssemblyLocation = typeof(ExecutionManagerTests).Assembly.Location; var mockTestMessageEventHandler = new Mock(); TestPluginCacheHelper.SetupMockExtensions( - new string[] { commonAssemblyLocation }, + [commonAssemblyLocation], () => { }); @@ -142,7 +142,7 @@ public void StartTestRunShouldRunTestsInTheProvidedSources() { var assemblyLocation = typeof(ExecutionManagerTests).Assembly.Location; TestPluginCacheHelper.SetupMockExtensions( - new string[] { assemblyLocation }, + [assemblyLocation], () => { }); TestPluginCache.Instance.DiscoverTestExtensions(TestPlatformConstants.TestAdapterEndsWithPattern); TestPluginCache.Instance.DiscoverTestExtensions(TestPlatformConstants.TestAdapterEndsWithPattern); @@ -205,7 +205,7 @@ public void StartTestRunShouldRunTestsForTheProvidedTests() "A.dll")); fh!.RecordResult(tr); }; - TestPluginCacheHelper.SetupMockExtensions(new string[] { assemblyLocation }, () => { }); + TestPluginCacheHelper.SetupMockExtensions([assemblyLocation], () => { }); _executionManager.StartTestRun(tests, null, null, _testExecutionContext, null, mockTestRunEventsHandler.Object); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs index d0b676eb03..ba5b3dd728 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs @@ -56,7 +56,7 @@ public RunTestsWithSourcesTests() _mockRequestData.Setup(rd => rd.MetricsCollection).Returns(_mockMetricsCollection.Object); TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(RunTestsWithSourcesTests).Assembly.Location }, + [typeof(RunTestsWithSourcesTests).Assembly.Location], () => { }); TestPluginCache.Instance.DiscoverTestExtensions(TestPlatformConstants.TestAdapterEndsWithPattern); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/PostProcessing/ArtifactProcessingTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/PostProcessing/ArtifactProcessingTests.cs index f38dfc2eee..909ac63b15 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/PostProcessing/ArtifactProcessingTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/PostProcessing/ArtifactProcessingTests.cs @@ -140,7 +140,7 @@ public async Task PostProcessArtifactsAsync_ShouldRunPostProcessing() // arrange _fileHelperMock.Setup(x => x.DirectoryExists(It.IsAny())).Returns(true); _fileHelperMock.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((string path, string pattern, SearchOption so) => new string[2] { "/tmp/sessionId/runsettings.xml", "/tmp/sessionId/executionComplete.json" }); + .Returns((string path, string pattern, SearchOption so) => ["/tmp/sessionId/runsettings.xml", "/tmp/sessionId/executionComplete.json"]); _fileHelperMock.Setup(x => x.GetStream(It.IsAny(), It.IsAny(), It.IsAny())) .Returns((string path, FileMode mode, FileAccess access) => { @@ -188,7 +188,7 @@ public async Task PostProcessArtifactsAsync_NullRunSettings_ShouldRunPostProcess // arrange _fileHelperMock.Setup(x => x.DirectoryExists(It.IsAny())).Returns(true); _fileHelperMock.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((string path, string pattern, SearchOption so) => new string[1] { "/tmp/sessionId/executionComplete.json" }); + .Returns((string path, string pattern, SearchOption so) => ["/tmp/sessionId/executionComplete.json"]); _fileHelperMock.Setup(x => x.GetStream(It.IsAny(), It.IsAny(), It.IsAny())) .Returns((string path, FileMode mode, FileAccess access) => { @@ -231,7 +231,7 @@ public async Task PostProcessArtifactsAsync_EmptyInvokedDataCollectors_ShouldRun // arrange _fileHelperMock.Setup(x => x.DirectoryExists(It.IsAny())).Returns(true); _fileHelperMock.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((string path, string pattern, SearchOption so) => new string[1] { "/tmp/sessionId/runsettings.xml" }); + .Returns((string path, string pattern, SearchOption so) => ["/tmp/sessionId/runsettings.xml"]); _fileHelperMock.Setup(x => x.GetStream(It.IsAny(), It.IsAny(), It.IsAny())) .Returns((string path, FileMode mode, FileAccess access) => { @@ -266,7 +266,7 @@ public async Task PostProcessArtifactsAsync_DeserializationException_ShouldStopP // arrange _fileHelperMock.Setup(x => x.DirectoryExists(It.IsAny())).Returns(true); _fileHelperMock.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((string path, string pattern, SearchOption so) => new string[1] { "/tmp/sessionId/executionComplete.json" }); + .Returns((string path, string pattern, SearchOption so) => ["/tmp/sessionId/executionComplete.json"]); _fileHelperMock.Setup(x => x.GetStream(It.IsAny(), It.IsAny(), It.IsAny())) .Returns((string path, FileMode mode, FileAccess access) => { diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs index 7608bee072..420f2ab44c 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs @@ -31,7 +31,7 @@ public class TestEngineTests public TestEngineTests() { - TestPluginCacheHelper.SetupMockExtensions(new[] { typeof(TestEngineTests).Assembly.Location }, () => { }); + TestPluginCacheHelper.SetupMockExtensions([typeof(TestEngineTests).Assembly.Location], () => { }); _mockProcessHelper = new Mock(); _mockRequestData = new Mock(); _mockMetricsCollection = new Mock(); @@ -1042,7 +1042,7 @@ public void CreatingNonParallelExecutionManagerShouldReturnExecutionManagerWithD var testRunCriteria = new TestRunCriteria(new List { "1.dll" }, 100, false, settingXml); var runtimeProviderInfo = new TestRuntimeProviderInfo(typeof(ITestRuntimeProvider), false, settingXml, - new List { new() { Source = "1.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework } }); + [new() { Source = "1.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }]); var nonParallelExecutionManager = _testEngine.CreateNonParallelExecutionManager(_mockRequestData.Object, testRunCriteria, true, runtimeProviderInfo); Assert.IsNotNull(nonParallelExecutionManager); @@ -1068,10 +1068,10 @@ public void CreatedNonParallelExecutionManagerShouldBeInitialzedWithCorrectTestS "; var runtimeProviderInfo = new TestRuntimeProviderInfo(typeof(ITestRuntimeProvider), false, settingXml, - new List { - new() { Source = "1.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, - new() { Source = "2.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework } - }); + [ + new() { Source = "1.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, + new() { Source = "2.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework } + ]); var nonParallelExecutionManager = _testEngine.CreateNonParallelExecutionManager(_mockRequestData.Object, testRunCriteria, true, runtimeProviderInfo); Assert.IsInstanceOfType(nonParallelExecutionManager, typeof(ProxyExecutionManagerWithDataCollection)); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs index e72987971c..7510928451 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs @@ -36,7 +36,7 @@ public class TestLoggerManagerTests public void Initialize() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(TestLoggerManagerTests).Assembly.Location }, + [typeof(TestLoggerManagerTests).Assembly.Location], () => { }); } @@ -409,7 +409,7 @@ public void HandleDiscoveredTestsShouldInvokeDiscoveredTestsHandlerOfLoggers() s_counter = 0; WaitHandle.Reset(); - List testCases = new() { new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName") }; + List testCases = [new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName")]; DiscoveredTestsEventArgs discoveredTestsEventArgs = new(testCases); // setup TestLogger @@ -430,7 +430,7 @@ public void HandleDiscoveredTestsShouldNotInvokeDiscoveredTestsHandlerOfLoggersI s_counter = 0; WaitHandle.Reset(); - List testCases = new() { new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName") }; + List testCases = [new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName")]; DiscoveredTestsEventArgs discoveredTestsEventArgs = new(testCases); // setup TestLogger diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs index e1f1970f0c..e2d3e41e48 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs @@ -761,6 +761,7 @@ internal class TestableBlameCollector : BlameCollector /// /// MockFileHelper instance. /// + /// Mockd process helper internal TestableBlameCollector(IBlameReaderWriter blameReaderWriter, IProcessDumpUtility processDumpUtility, IInactivityTimer? inactivityTimer, IFileHelper mockFileHelper, IProcessHelper mockProcessHelper) : base(blameReaderWriter, processDumpUtility, inactivityTimer, mockFileHelper, mockProcessHelper) diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs index 629b94f369..03e9c234ac 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs @@ -44,7 +44,7 @@ public void GetDumpFileWillThrowExceptionIfNoDumpfile() var testResultsDirectory = "D:\\TestResults"; _mockFileHelper.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(System.Array.Empty()); + .Returns([]); _mockProcessHelper.Setup(x => x.GetProcessName(processId)) .Returns(process); diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs index 91a2b72fa6..9c1cc94e27 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs @@ -739,11 +739,11 @@ public void GetCustomPropertyValueFromTestCaseShouldReadCategoryAttributesFromTe List listCategoriesActual = Converter.GetCustomPropertyValueFromTestCase(testCase1, "MSTestDiscoverer.TestCategory"); - List listCategoriesExpected = new() - { + List listCategoriesExpected = + [ "ClassLevel", "AsmLevel" - }; + ]; CollectionAssert.AreEqual(listCategoriesExpected, listCategoriesActual); } @@ -758,11 +758,11 @@ public void GetCustomPropertyValueFromTestCaseShouldReadWorkItemAttributesFromTe List listWorkItemsActual = Converter.GetCustomPropertyValueFromTestCase(testCase1, "WorkItemIds"); - List listWorkItemsExpected = new() - { + List listWorkItemsExpected = + [ "99999", "0" - }; + ]; CollectionAssert.AreEqual(listWorkItemsExpected, listWorkItemsActual); } diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs index f5eb8b75bd..a459932bfc 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs @@ -96,7 +96,7 @@ public void ToTestElementShouldAssignTestCategoryOfUnitTestElement() var unitTestElement = Converter.ToTestElement(testCase.Id, Guid.Empty, Guid.Empty, testCase.DisplayName, TrxLoggerConstants.UnitTestType, testCase); - object[] expected = new[] { "MethodLevel", "ClassLevel", "AsmLevel" }; + object[] expected = ["MethodLevel", "ClassLevel", "AsmLevel"]; CollectionAssert.AreEqual(expected, unitTestElement.TestCategories.ToArray().OrderByDescending(x => x).ToArray()); } @@ -112,7 +112,7 @@ public void ToTestElementShouldAssignWorkItemOfUnitTestElement() var unitTestElement = Converter.ToTestElement(testCase.Id, Guid.Empty, Guid.Empty, testCase.DisplayName, TrxLoggerConstants.UnitTestType, testCase); - int[] expected = new[] { 0, 3, 99999 }; + int[] expected = [0, 3, 99999]; CollectionAssert.AreEquivalent(expected, unitTestElement.WorkItems.ToArray()); } @@ -227,10 +227,7 @@ private static void SetupForToCollectionEntries(out string tempDir, out List - { - new(new Uri("datacollector://microsoft/CodeCoverage/2.0"), "Code Coverage") - }; + attachmentSets = [new(new Uri("datacollector://microsoft/CodeCoverage/2.0"), "Code Coverage")]; testRun = new TestRun(Guid.NewGuid()); testRun.RunConfiguration = new TestRunConfiguration("Testrun 1", new TrxFileHelper()); diff --git a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs index 9b36182524..0055035827 100644 --- a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs +++ b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs @@ -60,7 +60,7 @@ public DefaultTestHostManagerTests() _testHostManager = new DefaultTestHostManager(_mockProcessHelper.Object, _mockFileHelper.Object, _mockDotnetHostHelper.Object, _mockEnvironment.Object, _mockEnvironmentVariable.Object); _testHostManager.Initialize(_mockMessageLogger.Object, $" {Architecture.X64} {Framework.DefaultFramework} {false} "); - _startInfo = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + _startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); } [TestMethod] @@ -68,7 +68,7 @@ public void ConstructorShouldSetX86ProcessForX86Architecture() { _testHostManager.Initialize(_mockMessageLogger.Object, $" {Architecture.X86} {Framework.DefaultFramework} {false} "); - var info = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + var info = _testHostManager.GetTestHostProcessStartInfo([], null, default); StringAssert.EndsWith(info.FileName, "testhost.x86.exe"); } @@ -84,7 +84,7 @@ public void GetTestHostProcessStartInfoShouldIncludeFileNameFromSubFolderTestHos { _mockProcessHelper.Setup(ph => ph.GetCurrentProcessFileName()).Returns("dotnet.exe"); _mockFileHelper.Setup(x => x.Exists(It.IsAny())).Returns(false); - var startInfo = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + var startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); Assert.IsTrue(startInfo.FileName!.EndsWith(Path.Combine("TestHostNetFramework", "testhost.exe"))); } @@ -94,7 +94,7 @@ public void GetTestHostProcessStartInfoShouldNotIncludeFileNameFromSubFolderTest { _mockProcessHelper.Setup(ph => ph.GetCurrentProcessFileName()).Returns("dotnet.exe"); _mockFileHelper.Setup(x => x.Exists(It.IsAny())).Returns(true); - var startInfo = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + var startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); Assert.IsFalse(startInfo.FileName!.EndsWith(Path.Combine("TestHost", "testhost.exe"))); Assert.IsTrue(startInfo.FileName!.EndsWith("testhost.exe")); @@ -104,7 +104,7 @@ public void GetTestHostProcessStartInfoShouldNotIncludeFileNameFromSubFolderTest public void GetTestHostProcessStartInfoShouldNotIncludeFileNameFromSubFolderTestHostWhenCurrentProcessIsIde() { _mockProcessHelper.Setup(ph => ph.GetCurrentProcessFileName()).Returns("devenv.exe"); - var startInfo = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + var startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); Assert.IsFalse(startInfo.FileName!.EndsWith(Path.Combine("TestHost", "testhost.exe"))); Assert.IsTrue(startInfo.FileName!.EndsWith("testhost.exe")); @@ -115,7 +115,7 @@ public void GetTestHostProcessStartInfoShouldIncludeConnectionInfo() { var connectionInfo = new TestRunnerConnectionInfo { Port = 123, ConnectionInfo = new TestHostConnectionInfo { Endpoint = "127.0.0.0:123", Role = ConnectionRole.Client, Transport = Transport.Sockets }, RunnerProcessId = 101 }; var info = _testHostManager.GetTestHostProcessStartInfo( - Enumerable.Empty(), + [], null, connectionInfo); @@ -148,7 +148,7 @@ public void GetTestHostProcessStartInfoShouldIncludeEnvironmentVariables() { var environmentVariables = new Dictionary { { "k1", "v1" } }; - var info = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), environmentVariables, default); + var info = _testHostManager.GetTestHostProcessStartInfo([], environmentVariables, default); Assert.AreEqual(environmentVariables, info.EnvironmentVariables); } @@ -213,7 +213,7 @@ public void GetTestHostProcessStartInfoShouldNotUseMonoAsHostOnNonWindowsIfStart public void GetTestPlatformExtensionsShouldReturnExtensionsListAsIsIfSourcesListIsEmpty() { _testHostManager.Initialize(_mockMessageLogger.Object, $" "); - List currentList = new() { @"FooExtension.dll" }; + List currentList = [@"FooExtension.dll"]; // Act var resultExtensions = _testHostManager.GetTestPlatformExtensions(new List(), currentList).ToList(); @@ -226,7 +226,7 @@ public void GetTestPlatformExtensionsShouldReturnExtensionsListAsIsIfSourcesList public void GetTestPlatformExtensionsShouldReturnExtensionsListAsIsIfSourcesListIsNull() { _testHostManager.Initialize(_mockMessageLogger.Object, $" "); - List currentList = new() { @"FooExtension.dll" }; + List currentList = [@"FooExtension.dll"]; // Act var resultExtensions = _testHostManager.GetTestPlatformExtensions(null, currentList).ToList(); @@ -238,17 +238,17 @@ public void GetTestPlatformExtensionsShouldReturnExtensionsListAsIsIfSourcesList [TestMethod] public void GetTestPlatformExtensionsShouldNotExcludeOutputDirectoryExtensionsIfTestAdapterPathIsSet() { - List sourcesDir = new() { @"C:\Source1" }; - List sources = new() { @"C:\Source1\source1.dll" }; + List sourcesDir = [@"C:\Source1"]; + List sources = [@"C:\Source1\source1.dll"]; - List extensionsList1 = new() { @"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll" }; + List extensionsList1 = [@"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll"]; _mockFileHelper.Setup(fh => fh.EnumerateFiles(sourcesDir[0], SearchOption.TopDirectoryOnly, "TestAdapter.dll")).Returns(extensionsList1); _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[0])).Returns(new Version(2, 0)); _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[1])).Returns(new Version(5, 5)); _testHostManager.Initialize(_mockMessageLogger.Object, $" C:\\Foo "); - List currentList = new() { @"FooExtension.dll", @"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll" }; + List currentList = [@"FooExtension.dll", @"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll"]; // Act var resultExtensions = _testHostManager.GetTestPlatformExtensions(sources, currentList).ToList(); @@ -261,11 +261,11 @@ public void GetTestPlatformExtensionsShouldNotExcludeOutputDirectoryExtensionsIf [TestCategory("Windows")] public void GetTestPlatformExtensionsShouldIncludeOutputDirectoryExtensionsIfTestAdapterPathIsNotSet() { - List sourcesDir = new() { "C:\\Source1", "C:\\Source2" }; - List sources = new() { @"C:\Source1\source1.dll", @"C:\Source2\source2.dll" }; + List sourcesDir = ["C:\\Source1", "C:\\Source2"]; + List sources = [@"C:\Source1\source1.dll", @"C:\Source2\source2.dll"]; - List extensionsList1 = new() { @"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll" }; - List extensionsList2 = new() { @"C:\Source2\ext1.TestAdapter.dll", @"C:\Source2\ext2.TestAdapter.dll" }; + List extensionsList1 = [@"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll"]; + List extensionsList2 = [@"C:\Source2\ext1.TestAdapter.dll", @"C:\Source2\ext2.TestAdapter.dll"]; _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[0])).Returns(new Version(2, 0)); _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[1])).Returns(new Version(5, 5)); @@ -281,7 +281,7 @@ public void GetTestPlatformExtensionsShouldIncludeOutputDirectoryExtensionsIfTes var resultExtensions = _testHostManager.GetTestPlatformExtensions(sources, new List()).ToList(); // Verify - List expectedList = new() { @"C:\Source2\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll" }; + List expectedList = [@"C:\Source2\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll"]; CollectionAssert.AreEqual(expectedList, resultExtensions); _mockMessageLogger.Verify(ml => ml.SendMessage(TestMessageLevel.Warning, "Multiple versions of same extension found. Selecting the highest version." + Environment.NewLine + " ext1.TestAdapter : 2.2\n ext2.TestAdapter : 5.5"), Times.Once); } @@ -290,11 +290,11 @@ public void GetTestPlatformExtensionsShouldIncludeOutputDirectoryExtensionsIfTes [TestCategory("Windows")] public void GetTestPlatformExtensionsShouldReturnPathTheHigherVersionedFileExtensions() { - List sourcesDir = new() { "C:\\Source1", "C:\\Source2" }; - List sources = new() { @"C:\Source1\source1.dll", @"C:\Source2\source2.dll" }; + List sourcesDir = ["C:\\Source1", "C:\\Source2"]; + List sources = [@"C:\Source1\source1.dll", @"C:\Source2\source2.dll"]; - List extensionsList1 = new() { @"C:\Source1\ext1.TestAdapter.dll" }; - List extensionsList2 = new() { @"C:\Source2\ext1.TestAdapter.dll" }; + List extensionsList1 = [@"C:\Source1\ext1.TestAdapter.dll"]; + List extensionsList2 = [@"C:\Source2\ext1.TestAdapter.dll"]; _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[0])).Returns(new Version(2, 0)); _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList2[0])).Returns(new Version(2, 2)); @@ -316,11 +316,11 @@ public void GetTestPlatformExtensionsShouldReturnPathTheHigherVersionedFileExten [TestCategory("Windows")] public void GetTestPlatformExtensionsShouldReturnPathToSingleFileExtensionOfATypeIfVersionsAreSame() { - List sourcesDir = new() { "C:\\Source1", "C:\\Source2" }; - List sources = new() { @"C:\Source1\source1.dll", @"C:\Source2\source2.dll" }; + List sourcesDir = ["C:\\Source1", "C:\\Source2"]; + List sources = [@"C:\Source1\source1.dll", @"C:\Source2\source2.dll"]; - List extensionsList1 = new() { @"C:\Source1\ext1.TestAdapter.dll" }; - List extensionsList2 = new() { @"C:\Source2\ext1.TestAdapter.dll" }; + List extensionsList1 = [@"C:\Source1\ext1.TestAdapter.dll"]; + List extensionsList2 = [@"C:\Source2\ext1.TestAdapter.dll"]; _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[0])).Returns(new Version(2, 0)); _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList2[0])).Returns(new Version(2, 0)); @@ -353,7 +353,7 @@ public void LaunchTestHostShouldReturnTestHostProcessId() It.IsAny>())).Returns(Process.GetCurrentProcess()); _testHostManager.Initialize(_mockMessageLogger.Object, $" {Architecture.X64} {Framework.DefaultFramework} {false} "); - var startInfo = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + var startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); _testHostManager.HostLaunched += TestHostManagerHostLaunched; diff --git a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs index 130e3b4b6c..7d643fcae4 100644 --- a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs +++ b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs @@ -42,7 +42,7 @@ public class DotnetTestHostManagerTests private readonly Mock _mockEnvironment; private readonly Mock _mockRunsettingHelper; private readonly TestRunnerConnectionInfo _defaultConnectionInfo; - private readonly string[] _testSource = { "test.dll" }; + private readonly string[] _testSource = ["test.dll"]; private readonly string _defaultTestHostPath; private readonly TestProcessStartInfo _defaultTestProcessStartInfo; private readonly TestableDotnetTestHostManager _dotnetHostManager; @@ -548,7 +548,7 @@ public void GetTestHostProcessStartInfoShouldIncludeSourceDirectoryAsWorkingDire public void GetTestPlatformExtensionsShouldReturnEmptySetIfSourceDirectoryDoesNotExist() { _mockFileHelper.Setup(fh => fh.DirectoryExists(It.IsAny())).Returns(false); - var extensions = _dotnetHostManager.GetTestPlatformExtensions(new[] { $".{Path.DirectorySeparatorChar}foo.dll" }, Enumerable.Empty()); + var extensions = _dotnetHostManager.GetTestPlatformExtensions(new[] { $".{Path.DirectorySeparatorChar}foo.dll" }, []); Assert.AreEqual(0, extensions.Count()); } @@ -558,7 +558,7 @@ public void GetTestPlatformExtensionsShouldReturnLibrariesFromSourceDirectory() { _mockFileHelper.Setup(fh => fh.DirectoryExists(It.IsAny())).Returns(true); _mockFileHelper.Setup(fh => fh.EnumerateFiles(It.IsAny(), SearchOption.TopDirectoryOnly, It.IsAny())).Returns(new[] { "foo.TestAdapter.dll" }); - var extensions = _dotnetHostManager.GetTestPlatformExtensions(new[] { $".{Path.DirectorySeparatorChar}foo.dll" }, Enumerable.Empty()); + var extensions = _dotnetHostManager.GetTestPlatformExtensions(new[] { $".{Path.DirectorySeparatorChar}foo.dll" }, []); CollectionAssert.AreEqual(new[] { "foo.TestAdapter.dll" }, extensions.ToArray()); } @@ -569,7 +569,7 @@ public void GetTestPlatformExtensionsShouldReturnEmptySetIfSourceDirectoryIsEmpt // Parent directory is empty since the input source is file "test.dll" _mockFileHelper.Setup(fh => fh.DirectoryExists(It.IsAny())).Returns(true); _mockFileHelper.Setup(fh => fh.EnumerateFiles(It.IsAny(), SearchOption.TopDirectoryOnly, It.IsAny())).Returns(new[] { "foo.dll" }); - var extensions = _dotnetHostManager.GetTestPlatformExtensions(_testSource, Enumerable.Empty()); + var extensions = _dotnetHostManager.GetTestPlatformExtensions(_testSource, []); Assert.AreEqual(0, extensions.Count()); } @@ -579,7 +579,7 @@ public void GetTestPlatformExtensionsShouldNotAddNonCoverletDataCollectorsExtens { _mockFileHelper.Setup(fh => fh.DirectoryExists(It.IsAny())).Returns(true); _mockFileHelper.Setup(fh => fh.EnumerateFiles(It.IsAny(), SearchOption.TopDirectoryOnly, It.IsAny())).Returns(new[] { "foo.dll" }); - var extensions = _dotnetHostManager.GetTestPlatformExtensions(_testSource, new List { "abc.dataollector.dll" }); + var extensions = _dotnetHostManager.GetTestPlatformExtensions(_testSource, ["abc.dataollector.dll"]); Assert.AreEqual(0, extensions.Count()); } @@ -669,14 +669,15 @@ public void GetTestHostProcessStartInfoShouldIncludeTestHostPathNextToTestRunner // we can't put in a "default" value, and we don't have other way to determine if this provided value is the // runtime default or the actual value that user provided, so right now the default will use the latest, instead // or the more correct 1.0, it should be okay, as that version is not supported anymore anyway - [DataRow("netcoreapp3.1", "3.1")] - [DataRow("net5.0", "5.0")] + [DataRow("netcoreapp3.1", "3.1", true)] + [DataRow("net5.0", "5.0", true)] // net6.0 is currently the latest released version, but it still has it's own runtime config, it is not the same as // "latest" which means the latest you have on system. So if you have only 5.0 SDK then net6.0 will fail because it can't find net6.0, // but latest would use net5.0 because that is the latest one on your system. - [DataRow("net6.0", "6.0")] - public void GetTestHostProcessStartInfoShouldIncludeTestHostPathNextToTestRunnerIfTesthostDllIsNoFoundAndDepsFileNotFoundWithTheCorrectTfm(string tfm, string suffix) + [DataRow("net6.0", "6.0", true)] + [DataRow("net6.0", "latest", false)] + public void GetTestHostProcessStartInfoShouldIncludeTestHostPathNextToTestRunnerIfTesthostDllIsNoFoundAndDepsFileNotFoundWithTheCorrectTfm(string tfm, string suffix, bool runtimeConfigExists) { // Absolute path to the source directory var sourcePath = Path.Combine(_temp, "test.dll"); @@ -687,6 +688,8 @@ public void GetTestHostProcessStartInfoShouldIncludeTestHostPathNextToTestRunner var testhostNextToRunner = Path.Combine(here, "testhost.dll"); _mockFileHelper.Setup(ph => ph.Exists(testhostNextToRunner)).Returns(true); + _mockFileHelper.Setup(ph => ph.Exists(It.Is(s => s.Contains($"{suffix}.runtimeconfig.json")))).Returns(runtimeConfigExists); + _dotnetHostManager.Initialize(_mockMessageLogger.Object, $"{tfm}"); var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); diff --git a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs index 0fe2212be4..cdbe0a44d1 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs @@ -100,8 +100,9 @@ public void TempDirectoryCleanup() /// List of test assemblies. /// Path to test adapter. /// Text of run settings. - /// - /// + /// Framework to use. + /// If we should run in a separate process. + /// The directory where results are stored. /// Command line arguments string. public static string PrepareArguments(string[] testAssemblies, string? testAdapterPath, string? runSettings, string framework, string? inIsolation = "", string? resultsDirectory = null) @@ -169,18 +170,20 @@ public static string PrepareArguments(string[] testAssemblies, string? testAdapt /// Name of the test assembly. /// Path to test adapter. /// Text of run settings. - /// - /// + /// The framework to use. + /// If we should run in separate process. + /// The directory in which results will be stored. /// Command line arguments string. public static string PrepareArguments(string testAssembly, string? testAdapterPath, string? runSettings, string framework, string? inIsolation = "", string? resultsDirectory = null) - => PrepareArguments(new string[] { testAssembly }, testAdapterPath, runSettings, framework, inIsolation, resultsDirectory); + => PrepareArguments([testAssembly], testAdapterPath, runSettings, framework, inIsolation, resultsDirectory); /// /// Invokes vstest.console with specified arguments. /// /// Arguments provided to vstest.console.exe + /// Environment variables to set to the started process. public void InvokeVsTest(string? arguments, Dictionary? environmentVariables = null) { var debugEnvironmentVariables = AddDebugEnvironmentVariables(environmentVariables); @@ -192,6 +195,7 @@ public void InvokeVsTest(string? arguments, Dictionary? environ /// Invokes our local copy of dotnet that is patched with artifacts from the build with specified arguments. /// /// Arguments provided to vstest.console.exe + /// Environment variables to set to the started process. public void InvokeDotnetTest(string arguments, Dictionary? environmentVariables = null) { var debugEnvironmentVariables = AddDebugEnvironmentVariables(environmentVariables); @@ -229,6 +233,7 @@ public void InvokeDotnetTest(string arguments, Dictionary? envi /// Path to test adapters. /// Dotnet Framework of test assembly. /// Run settings for execution. + /// Environment variables to set to the started process. public void InvokeVsTestForExecution(string testAssembly, string? testAdapterPath, string framework, @@ -275,6 +280,8 @@ public void InvokeVsTestForExecution(string testAssembly, /// A test assembly. /// Path to test adapters. /// Run settings for execution. + /// The target framework to use. + /// Environment variables to set to the started process. public void InvokeVsTestForDiscovery(string testAssembly, string testAdapterPath, string runSettings = "", string targetFramework = "", Dictionary? environmentVariables = null) { @@ -782,6 +789,7 @@ protected void ExecuteVsTestConsole(string? args, out string stdOut, out string /// /// /// + /// Environment variables to set to the started process. private static void ExecutePatchedDotnet(string command, string args, out string stdOut, out string stdError, out int exitCode, Dictionary? environmentVariables = null) { diff --git a/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs b/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs index a36eee6046..e9c401a7b6 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs @@ -17,7 +17,7 @@ public static class TestPluginCacheHelper public static TestableTestPluginCache SetupMockAdditionalPathExtensions(Type callingTest) { return SetupMockAdditionalPathExtensions( - new string[] { callingTest.Assembly.Location }); + [callingTest.Assembly.Location]); } public static TestableTestPluginCache SetupMockAdditionalPathExtensions(string[] extensions) @@ -42,7 +42,7 @@ public static void SetupMockExtensions(Type callingTest, Mock? mock public static void SetupMockExtensions(Type callingTest, Action callback, Mock? mockFileHelper = null) { - SetupMockExtensions(new[] { callingTest.Assembly.Location }, callback, mockFileHelper); + SetupMockExtensions([callingTest.Assembly.Location], callback, mockFileHelper); } public static void SetupMockExtensions(string[] extensions, Action callback, Mock? mockFileHelper = null) diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs index 0761e61d69..0dfa24dd46 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs @@ -86,7 +86,7 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIfOnly1Atta var attachmentSet = new AttachmentSet(new Uri("datacollector://microsoft/CodeCoverage/2.0"), string.Empty); attachmentSet.Attachments.Add(new UriDataAttachment(new Uri("C:\\temp\\aa.coverage"), "coverage")); - Collection attachment = new() { attachmentSet }; + Collection attachment = [attachmentSet]; ICollection resultAttachmentSets = await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); @@ -106,7 +106,7 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIf2Differen attachmentSet.Attachments.Add(new UriDataAttachment(new Uri(file1Path), "coverage")); attachmentSet.Attachments.Add(new UriDataAttachment(new Uri(file2Path), "coverage")); - Collection attachment = new() { attachmentSet }; + Collection attachment = [attachmentSet]; ICollection resultAttachmentSets = await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); @@ -127,7 +127,7 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIf2SameForm attachmentSet.Attachments.Add(new UriDataAttachment(new Uri(file1Path), "coverage")); attachmentSet.Attachments.Add(new UriDataAttachment(new Uri(file1Path), "coverage")); - Collection attachment = new() { attachmentSet }; + Collection attachment = [attachmentSet]; ICollection resultAttachmentSets = await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); @@ -144,7 +144,7 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIfOnly1Logs var attachmentSet = new AttachmentSet(new Uri("datacollector://microsoft/CodeCoverage/2.0"), string.Empty); attachmentSet.Attachments.Add(new UriDataAttachment(new Uri("C:\\temp\\aa.logs"), "coverage")); - Collection attachment = new() { attachmentSet }; + Collection attachment = [attachmentSet]; ICollection resultAttachmentSets = await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); @@ -165,7 +165,7 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIfOnlySever attachmentSet1.Attachments.Add(new UriDataAttachment(new Uri("C:\\temp\\aa.logs"), "coverage")); attachmentSet1.Attachments.Add(new UriDataAttachment(new Uri("C:\\temp\\bb.logs"), "coverage")); - Collection attachment = new() { attachmentSet, attachmentSet1 }; + Collection attachment = [attachmentSet, attachmentSet1]; ICollection resultAttachmentSets = await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); @@ -183,11 +183,11 @@ public async Task HandleDataCollectionAttachmentSetsShouldThrowIfCancellationReq CancellationTokenSource cts = new(); cts.Cancel(); - Collection attachment = new() - { + Collection attachment = + [ attachmentSet, attachmentSet - }; + ]; await Assert.ThrowsExceptionAsync(async () => await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, cts.Token)); diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs index 30789efec3..c1106695a7 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs @@ -24,9 +24,9 @@ private static void VerifyCommandLineSplitter(string commandLine, string[] expec [TestMethod] public void TestCommandLineSplitter() { - VerifyCommandLineSplitter("", System.Array.Empty()); - VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\"", new[] { @"/testadapterpath:c:\Path" }); - VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\" /logger:\"trx\"", new[] { @"/testadapterpath:c:\Path", "/logger:trx" }); - VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\" /logger:\"trx\" /diag:\"log.txt\"", new[] { @"/testadapterpath:c:\Path", "/logger:trx", "/diag:log.txt" }); + VerifyCommandLineSplitter("", []); + VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\"", [@"/testadapterpath:c:\Path"]); + VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\" /logger:\"trx\"", [@"/testadapterpath:c:\Path", "/logger:trx"]); + VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\" /logger:\"trx\" /diag:\"log.txt\"", [@"/testadapterpath:c:\Path", "/logger:trx", "/diag:log.txt"]); } } diff --git a/test/SettingsMigrator.UnitTests/PathResolverTests.cs b/test/SettingsMigrator.UnitTests/PathResolverTests.cs index 7df59759f3..678865ddd4 100644 --- a/test/SettingsMigrator.UnitTests/PathResolverTests.cs +++ b/test/SettingsMigrator.UnitTests/PathResolverTests.cs @@ -22,49 +22,49 @@ public PathResolverTests() [TestMethod] public void PathResolverShouldReturnNullForEmptyArguments() { - var newFilePath = _pathResolver.GetTargetPath(Array.Empty()); + var newFilePath = _pathResolver.GetTargetPath([]); Assert.IsNull(newFilePath, "Empty arguments should return null"); } [TestMethod] public void PathResolverShouldReturnNullForInvalidArguments() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "asd", "asd", "asd" }); + var newFilePath = _pathResolver.GetTargetPath(["asd", "asd", "asd"]); Assert.IsNull(newFilePath, "Invalid arguments should return null"); } [TestMethod] public void PathResolverShouldReturnNullForRelativePaths() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "asd.testsettings" }); + var newFilePath = _pathResolver.GetTargetPath(["asd.testsettings"]); Assert.IsNull(newFilePath, "Relative paths should return null"); } [TestMethod] public void PathResolverShouldReturnNullForRelativePathsWithTwoArguments() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "asd.Testsettings", "C:\\asd.runsettings" }); + var newFilePath = _pathResolver.GetTargetPath(["asd.Testsettings", "C:\\asd.runsettings"]); Assert.IsNull(newFilePath, "Relative paths should return null"); } [TestMethod] public void PathResolverShouldNotReturnNullForPathsWithExtensionInCapitals() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "C:\\asd.TestSEettings", "C:\\asd.RuNSettings" }); + var newFilePath = _pathResolver.GetTargetPath(["C:\\asd.TestSEettings", "C:\\asd.RuNSettings"]); Assert.IsNotNull(newFilePath, "Relative paths should not return null"); } [TestMethod] public void PathResolverShouldReturnNullForRelativePathsForRunsettings() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "C:\\asd.testsettings", "asd.runsettings" }); + var newFilePath = _pathResolver.GetTargetPath(["C:\\asd.testsettings", "asd.runsettings"]); Assert.IsNull(newFilePath, "Relative paths should return null"); } [TestMethod] public void PathResolverShouldReturnRunsettingsPathOfSameLocationAsTestSettings() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "C:\\asd.testsettings" }); + var newFilePath = _pathResolver.GetTargetPath(["C:\\asd.testsettings"]); Assert.IsNotNull(newFilePath, "File path should not be null."); Assert.IsTrue(string.Equals(Path.GetExtension(newFilePath), ".runsettings"), "File path should be .runsettings"); Assert.IsTrue(newFilePath!.Contains("C:\\asd_"), "File should be of same name as testsettings"); diff --git a/test/SettingsMigrator.UnitTests/ProgramTests.cs b/test/SettingsMigrator.UnitTests/ProgramTests.cs index 5025e97963..9e4ef90675 100644 --- a/test/SettingsMigrator.UnitTests/ProgramTests.cs +++ b/test/SettingsMigrator.UnitTests/ProgramTests.cs @@ -11,14 +11,14 @@ public class ProgramTests [TestMethod] public void MoreThanTwoArgumentsShouldNotBeAccepted() { - int returnCode = Program.Main(new string[] { "asd", "asd", "asd" }); + int returnCode = Program.Main(["asd", "asd", "asd"]); Assert.AreEqual(1, returnCode, "More than 2 arguments should not be accepted."); } [TestMethod] public void NoArgumentsShouldNotBeAccepted() { - int returnCode = Program.Main(System.Array.Empty()); + int returnCode = Program.Main([]); Assert.AreEqual(1, returnCode, "No arguments should not be accepted."); } } diff --git a/test/TranslationLayer.UnitTests/TestSessionTests.cs b/test/TranslationLayer.UnitTests/TestSessionTests.cs index f6eb5fac6a..5b2220d1bc 100644 --- a/test/TranslationLayer.UnitTests/TestSessionTests.cs +++ b/test/TranslationLayer.UnitTests/TestSessionTests.cs @@ -22,12 +22,12 @@ namespace Microsoft.TestPlatform.VsTestConsole.TranslationLayer.UnitTests; public class TestSessionTests { private readonly string _testSettings = "TestSettings"; - private readonly List _testSources = new() { "Hello", "World" }; - private readonly List _testCases = new() - { + private readonly List _testSources = ["Hello", "World"]; + private readonly List _testCases = + [ new TestCase("a.b.c", new Uri("d://uri"), "a.dll"), new TestCase("d.e.f", new Uri("g://uri"), "d.dll") - }; + ]; private readonly TestSessionInfo _testSessionInfo; private readonly ITestSession _testSession; diff --git a/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs b/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs index 71d0689dcb..b2d496d208 100644 --- a/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs +++ b/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs @@ -436,13 +436,13 @@ public void DiscoverTestsShouldCompleteWithSingleFullyDiscoveredSource() var mockHandler = new Mock(); - List sources = new() { "1.dll" }; + List sources = ["1.dll"]; var testCase = new TestCase("hello", new Uri("world://how"), source: sources[0]); var testsFound = new Message() { MessageType = MessageType.TestCasesFound, - Payload = JToken.FromObject(new List() { testCase }) + Payload = JToken.FromObject(new List { testCase }) }; var payload = new DiscoveryCompletePayload() { TotalTests = 1, LastDiscoveredTests = null, IsAborted = false, FullyDiscoveredSources = sources }; @@ -476,7 +476,7 @@ public void DiscoverTestsShouldCompleteWithCorrectAbortedValuesIfAbortingWasRequ var mockHandler = new Mock(); - List sources = new() { "1.dll" }; + List sources = ["1.dll"]; var testCase = new TestCase("hello", new Uri("world://how"), source: sources[0]); var testsFound = new Message() diff --git a/test/TranslationLayer.UnitTests/VsTestConsoleWrapperTests.cs b/test/TranslationLayer.UnitTests/VsTestConsoleWrapperTests.cs index 5b7ad29759..e3ba446662 100644 --- a/test/TranslationLayer.UnitTests/VsTestConsoleWrapperTests.cs +++ b/test/TranslationLayer.UnitTests/VsTestConsoleWrapperTests.cs @@ -28,12 +28,12 @@ public class VsTestConsoleWrapperTests private readonly Mock _mockProcessManager; private readonly Mock _mockProcessHelper; private readonly Mock _mockRequestSender; - private readonly List _testSources = new() { "Hello", "World" }; - private readonly List _testCases = new() - { + private readonly List _testSources = ["Hello", "World"]; + private readonly List _testCases = + [ new TestCase("a.b.c", new Uri("d://uri"), "a.dll"), new TestCase("d.e.f", new Uri("g://uri"), "d.dll") - }; + ]; private readonly ConsoleParameters _consoleParameters; private readonly Mock _telemetryEventsHandler; diff --git a/test/datacollector.UnitTests/DataCollectionManagerTests.cs b/test/datacollector.UnitTests/DataCollectionManagerTests.cs index e13553f3d0..7cf8a2a93a 100644 --- a/test/datacollector.UnitTests/DataCollectionManagerTests.cs +++ b/test/datacollector.UnitTests/DataCollectionManagerTests.cs @@ -359,7 +359,7 @@ public void SessionEndedShouldReturnAttachments() var attachment = new AttachmentSet(new Uri("my://custom/datacollector"), "CustomDataCollector"); attachment.Attachments.Add(new UriDataAttachment(new Uri("my://filename.txt"), "filename.txt")); - _mockDataCollectionAttachmentManager.Setup(x => x.GetAttachments(It.IsAny())).Returns(new List() { attachment }); + _mockDataCollectionAttachmentManager.Setup(x => x.GetAttachments(It.IsAny())).Returns([attachment]); _dataCollectionManager.InitializeDataCollectors(_dataCollectorSettings); var sessionStartEventArgs = new SessionStartEventArgs(); @@ -387,7 +387,7 @@ public void SessionEndedShouldContinueDataCollectionIfExceptionIsThrownWhileSend var attachment = new AttachmentSet(new Uri("my://custom/datacollector"), "CustomDataCollector"); attachment.Attachments.Add(new UriDataAttachment(new Uri("my://filename.txt"), "filename.txt")); - _mockDataCollectionAttachmentManager.Setup(x => x.GetAttachments(It.IsAny())).Returns(new List() { attachment }); + _mockDataCollectionAttachmentManager.Setup(x => x.GetAttachments(It.IsAny())).Returns([attachment]); SetupMockDataCollector((XmlElement a, DataCollectionEvents b, DataCollectionSink c, DataCollectionLogger d, DataCollectionEnvironmentContext e) => b.SessionEnd += (sender, ev) => diff --git a/test/datacollector.UnitTests/DataCollectorMainTests.cs b/test/datacollector.UnitTests/DataCollectorMainTests.cs index 8c83ca950b..59103a2949 100644 --- a/test/datacollector.UnitTests/DataCollectorMainTests.cs +++ b/test/datacollector.UnitTests/DataCollectorMainTests.cs @@ -20,9 +20,9 @@ namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector.UnitTests; [TestClass] public class DataCollectorMainTests { - private readonly string[] _args = { "--port", "1025", "--parentprocessid", "100", "--diag", "abc.txt", "--tracelevel", "3" }; - private readonly string[] _argsWithEmptyDiagArg = { "--port", "1025", "--parentprocessid", "100", "--diag", "", "--tracelevel", "3" }; - private readonly string[] _argsWithInvalidTraceLevel = { "--port", "1025", "--parentprocessid", "100", "--diag", "abc.txt", "--tracelevel", "5" }; + private readonly string[] _args = ["--port", "1025", "--parentprocessid", "100", "--diag", "abc.txt", "--tracelevel", "3"]; + private readonly string[] _argsWithEmptyDiagArg = ["--port", "1025", "--parentprocessid", "100", "--diag", "", "--tracelevel", "3"]; + private readonly string[] _argsWithInvalidTraceLevel = ["--port", "1025", "--parentprocessid", "100", "--diag", "abc.txt", "--tracelevel", "5"]; private static readonly string TimeoutErrorMessage = "datacollector process failed to connect to vstest.console process after 90 seconds. This may occur due to machine slowness, please set environment variable VSTEST_CONNECTION_TIMEOUT to increase timeout."; diff --git a/test/vstest.ProgrammerTests/Fakes/FakeTestBatchBuilder.cs b/test/vstest.ProgrammerTests/Fakes/FakeTestBatchBuilder.cs index 03b1a781d6..e3c40d179a 100644 --- a/test/vstest.ProgrammerTests/Fakes/FakeTestBatchBuilder.cs +++ b/test/vstest.ProgrammerTests/Fakes/FakeTestBatchBuilder.cs @@ -49,7 +49,7 @@ internal FakeTestBatchBuilder WithBatchSize(int batchSize) /// /// Sets the dll path (source) to be the provided value. /// - /// + /// /// internal FakeTestBatchBuilder WithDllPath(string path) { diff --git a/test/vstest.ProgrammerTests/Fakes/FakeTestDllBuilder.cs b/test/vstest.ProgrammerTests/Fakes/FakeTestDllBuilder.cs index 7b05974c8a..a8703938ec 100644 --- a/test/vstest.ProgrammerTests/Fakes/FakeTestDllBuilder.cs +++ b/test/vstest.ProgrammerTests/Fakes/FakeTestDllBuilder.cs @@ -46,7 +46,6 @@ internal FakeTestDllBuilder WithTestBatches(List> testBatches) /// /// Use this to get basic test batch, or use WithTestBatches together with TestBatchBuilder, to get a custom batch. /// - /// /// internal FakeTestDllBuilder WithTestCount(int totalCount, int? batchSize = null) { diff --git a/test/vstest.ProgrammerTests/Fakes/FakeTestHostResponsesBuilder.cs b/test/vstest.ProgrammerTests/Fakes/FakeTestHostResponsesBuilder.cs index a0f53bd5e9..bfb459fc84 100644 --- a/test/vstest.ProgrammerTests/Fakes/FakeTestHostResponsesBuilder.cs +++ b/test/vstest.ProgrammerTests/Fakes/FakeTestHostResponsesBuilder.cs @@ -41,7 +41,6 @@ internal FakeTestHostResponsesBuilder VersionCheck(FakeMessage message) /// For VersionCheck message it does the given before action and responds with the given FakeMessage and then does the given after action. /// Use FakeMessage.NoResponse to not respond. /// - /// /// internal FakeTestHostResponsesBuilder VersionCheck(FakeMessage message, Action? beforeAction = null, Action? afterAction = null) { diff --git a/test/vstest.ProgrammerTests/Fakes/StringExtensions.cs b/test/vstest.ProgrammerTests/Fakes/StringExtensions.cs index f5df113f53..8d33f23acb 100644 --- a/test/vstest.ProgrammerTests/Fakes/StringExtensions.cs +++ b/test/vstest.ProgrammerTests/Fakes/StringExtensions.cs @@ -17,6 +17,6 @@ public static string JoinBy(this IEnumerable value, string delimiter) public static List AsList(this T value) { - return new List { value }; + return [value]; } } diff --git a/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs b/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs index 9ff6c075f7..36c9822d57 100644 --- a/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs +++ b/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs @@ -668,7 +668,7 @@ internal static string GetRawMessage(this Message request) s_messageProperty = request.GetType().GetProperty("RawMessage")!.GetGetMethod(); } - return (string)s_messageProperty!.Invoke(request, Array.Empty())!; + return (string)s_messageProperty!.Invoke(request, [])!; } } diff --git a/test/vstest.ProgrammerTests/Program.cs b/test/vstest.ProgrammerTests/Program.cs index 22f4c0e949..f6d0f025be 100644 --- a/test/vstest.ProgrammerTests/Program.cs +++ b/test/vstest.ProgrammerTests/Program.cs @@ -9,6 +9,6 @@ internal class Program { static void Main() { - Intent.Console.Program.Main(new[] { Assembly.GetExecutingAssembly().Location }); + Intent.Console.Program.Main([Assembly.GetExecutingAssembly().Location]); } } diff --git a/test/vstest.console.UnitTests/CommandLine/GenerateFakesUtilitiesTests.cs b/test/vstest.console.UnitTests/CommandLine/GenerateFakesUtilitiesTests.cs index 65f5013af7..201ee8312c 100644 --- a/test/vstest.console.UnitTests/CommandLine/GenerateFakesUtilitiesTests.cs +++ b/test/vstest.console.UnitTests/CommandLine/GenerateFakesUtilitiesTests.cs @@ -37,7 +37,7 @@ public void FakesShouldNotBeGeneratedIfDisableAutoFakesSetToTrue() CommandLineOptions.Instance.DisableAutoFakes = true; string runSettingsXml = @".netstandard,Version=5.0"; - runSettingsXml = GenerateFakesUtilities.GenerateFakesSettings(CommandLineOptions.Instance, System.Array.Empty(), runSettingsXml); + runSettingsXml = GenerateFakesUtilities.GenerateFakesSettings(CommandLineOptions.Instance, [], runSettingsXml); Assert.AreEqual(runSettingsXml, _runSettings); } diff --git a/test/vstest.console.UnitTests/ExecutorUnitTests.cs b/test/vstest.console.UnitTests/ExecutorUnitTests.cs index e8102f24da..313ec26a25 100644 --- a/test/vstest.console.UnitTests/ExecutorUnitTests.cs +++ b/test/vstest.console.UnitTests/ExecutorUnitTests.cs @@ -171,7 +171,7 @@ public void ExecuteShouldInstrumentVsTestConsoleStop() [TestMethod] public void ExecuteShouldExitWithErrorOnResponseFileException() { - string[] args = { "@FileDoesNotExist.rsp" }; + string[] args = ["@FileDoesNotExist.rsp"]; var mockOutput = new MockOutput(); var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(args); @@ -226,7 +226,7 @@ public void ExecuteShouldNotThrowSettingsExceptionButLogOutput() File.WriteAllText(runSettingsFile, fileContents); var testSourceDllPath = Path.GetTempFileName(); - string[] args = { testSourceDllPath, "/settings:" + runSettingsFile }; + string[] args = [testSourceDllPath, "/settings:" + runSettingsFile]; var mockOutput = new MockOutput(); var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(args); @@ -264,7 +264,7 @@ public void ExecuteShouldReturnNonZeroExitCodeIfSettingsException() File.WriteAllText(runSettingsFile, fileContents); - string[] args = { "/settings:" + runSettingsFile }; + string[] args = ["/settings:" + runSettingsFile]; var mockOutput = new MockOutput(); var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(args); @@ -299,7 +299,7 @@ public void ExecutorShouldShowRightErrorMessage() File.WriteAllText(runSettingsFile, fileContents); - string[] args = { "/settings:" + runSettingsFile }; + string[] args = ["/settings:" + runSettingsFile]; var mockOutput = new MockOutput(); var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(args); diff --git a/test/vstest.console.UnitTests/Processors/ArtifactProcessingPostProcessModeProcessorTest.cs b/test/vstest.console.UnitTests/Processors/ArtifactProcessingPostProcessModeProcessorTest.cs index 3556acb841..78fea1b91f 100644 --- a/test/vstest.console.UnitTests/Processors/ArtifactProcessingPostProcessModeProcessorTest.cs +++ b/test/vstest.console.UnitTests/Processors/ArtifactProcessingPostProcessModeProcessorTest.cs @@ -64,10 +64,10 @@ public void ProcessorExecutorInitialize_ExceptionShouldNotBubbleUp() public void ArtifactProcessingPostProcessMode_ContainsPostProcessCommand() { _featureFlagMock.Setup(x => x.IsSet(It.IsAny())).Returns(false); - Assert.IsTrue(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(new string[] { "--artifactsProcessingMode-postprocess" }, _featureFlagMock.Object)); - Assert.IsTrue(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(new string[] { "--ARTIfactsProcessingMode-postprocess" }, _featureFlagMock.Object)); - Assert.IsFalse(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(new string[] { "-ARTIfactsProcessingMode-postprocess" }, _featureFlagMock.Object)); - Assert.IsFalse(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(new string[] { "--ARTIfactsProcessingMode-postproces" }, _featureFlagMock.Object)); + Assert.IsTrue(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(["--artifactsProcessingMode-postprocess"], _featureFlagMock.Object)); + Assert.IsTrue(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(["--ARTIfactsProcessingMode-postprocess"], _featureFlagMock.Object)); + Assert.IsFalse(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(["-ARTIfactsProcessingMode-postprocess"], _featureFlagMock.Object)); + Assert.IsFalse(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(["--ARTIfactsProcessingMode-postproces"], _featureFlagMock.Object)); Assert.IsFalse(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(null, _featureFlagMock.Object)); } } diff --git a/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs index a27be02e89..3a40e52bfb 100644 --- a/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs @@ -114,7 +114,7 @@ public void InitializeShouldNotThrowExceptionIfArgumentIsNull() [TestMethod] public void InitializeShouldNotThrowExceptionIfArgumentIsEmpty() { - _executor.Initialize(Array.Empty()); + _executor.Initialize([]); Assert.IsNull(_settingsProvider.ActiveRunSettings); } @@ -122,7 +122,7 @@ public void InitializeShouldNotThrowExceptionIfArgumentIsEmpty() [TestMethod] public void InitializeShouldCreateEmptyRunSettingsIfArgumentsHasOnlyWhiteSpace() { - _executor.Initialize(new string[] { " " }); + _executor.Initialize([" "]); Assert.IsNull(_settingsProvider.ActiveRunSettings); } @@ -344,42 +344,43 @@ public static IEnumerable TestRunParameterArgInvalidTestCases() return InvalidTestCases; } - private static readonly List InvalidTestCases = new() - { - new object[] { "TestRunParameters.Parameter(name=asf,value=rgq)" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=\"rgq\" )" }, - new object[] { "TestRunParameters.Parameter( name=\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParametersParameter(name=\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Paramete(name=\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parametername=\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(ame=\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\" value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",alue=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=\"rgq\"" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=\"rgq\")wfds" }, - new object[] { "TestRunParameters.Parameter(name=\"\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=\"\")" }, - new object[] { "TestRunParameters.Parameter(name=asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf,value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=\"rgq)" }, - new object[] { "TestRunParameters.Parameter(name=\"asf@#!\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"\",value=\"fgf\")" }, - new object[] { "TestRunParameters.Parameter(name=\"gag\",value=\"\")" }, - new object[] { "TestRunParameters.Parameter(name=\"gag\")" } - }; + private static readonly List InvalidTestCases = + [ + ["TestRunParameters.Parameter(name=asf,value=rgq)"], + ["TestRunParameters.Parameter(name=\"asf\",value=\"rgq\" )"], + ["TestRunParameters.Parameter( name=\"asf\",value=\"rgq\")"], + ["TestRunParametersParameter(name=\"asf\",value=\"rgq\")"], + ["TestRunParameters.Paramete(name=\"asf\",value=\"rgq\")"], + ["TestRunParameters.Parametername=\"asf\",value=\"rgq\")"], + ["TestRunParameters.Parameter(ame=\"asf\",value=\"rgq\")"], + ["TestRunParameters.Parameter(name\"asf\",value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\" value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",alue=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",value\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",value=\"rgq\""], + ["TestRunParameters.Parameter(name=\"asf\",value=\"rgq\")wfds"], + ["TestRunParameters.Parameter(name=\"\",value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",value=\"\")"], + ["TestRunParameters.Parameter(name=asf\",value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf,value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",value=rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",value=\"rgq)"], + ["TestRunParameters.Parameter(name=\"asf@#!\",value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"\",value=\"fgf\")"], + ["TestRunParameters.Parameter(name=\"gag\",value=\"\")"], + ["TestRunParameters.Parameter(name=\"gag\")"] + ]; public static IEnumerable TestRunParameterArgValidTestCases() { return ValidTestCases; } - private static readonly List ValidTestCases = new() - { - new object[] { "TestRunParameters.Parameter(name=\"weburl\",value=\"&><\")" , - string.Join(Environment.NewLine, "", + private static readonly List ValidTestCases = + [ + [ + "TestRunParameters.Parameter(name=\"weburl\",value=\"&><\")", string.Join(Environment.NewLine, + "", "", " ", " ", @@ -388,9 +389,10 @@ public static IEnumerable TestRunParameterArgValidTestCases() " ", " ", "") - }, - new object[] { "TestRunParameters.Parameter(name=\"weburl\",value=\"http://localhost//abc\")" , - string.Join(Environment.NewLine, "", + ], + [ + "TestRunParameters.Parameter(name=\"weburl\",value=\"http://localhost//abc\")", string.Join( + Environment.NewLine, "", "", " ", " ", @@ -399,8 +401,9 @@ public static IEnumerable TestRunParameterArgValidTestCases() " ", " ", "") - }, - new object[] { "TestRunParameters.Parameter(name= \"a_sf123_12\",value= \"2324346a!@#$%^*()_+-=':;.,/?{}[]|\")" , + ], + [ + "TestRunParameters.Parameter(name= \"a_sf123_12\",value= \"2324346a!@#$%^*()_+-=':;.,/?{}[]|\")", string.Join(Environment.NewLine, "", "", " ", @@ -410,9 +413,10 @@ public static IEnumerable TestRunParameterArgValidTestCases() " ", " ", "") - }, - new object[] { "TestRunParameters.Parameter(name = \"weburl\" , value = \"http://localhost//abc\")" , - string.Join(Environment.NewLine, "", + ], + [ + "TestRunParameters.Parameter(name = \"weburl\" , value = \"http://localhost//abc\")", string.Join( + Environment.NewLine, "", "", " ", " ", @@ -421,8 +425,8 @@ public static IEnumerable TestRunParameterArgValidTestCases() " ", " ", "") - }, - }; + ] + ]; #endregion [TestMethod] @@ -459,7 +463,7 @@ public void InitializeShouldMergeTestRunParametersWithSpaces() "value=\"myValue 2\")", }; - var runsettings = string.Join(Environment.NewLine, new[]{ + var runsettings = string.Join(Environment.NewLine, [ "", "", " ", @@ -469,7 +473,8 @@ public void InitializeShouldMergeTestRunParametersWithSpaces() " ", " ", " ", - ""}); + "" + ]); _executor.Initialize(args); diff --git a/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs index 418be5202e..eaffa017fc 100644 --- a/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs @@ -191,11 +191,11 @@ public void ExecutorExecuteForValidSourceWithTestCaseFilterShouldRunTests() ResetAndAddSourceToCommandLineOptions(); - List list = new() - { + List list = + [ new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1") - }; + ]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -275,11 +275,11 @@ public void ExecutorExecuteShouldThrowTestPlatformExceptionThrownDuringExecution var mockTestRunRequest = new Mock(); var mockDiscoveryRequest = new Mock(); - List list = new() - { + List list = + [ new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") - }; + ]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestRunRequest.Setup(dr => dr.ExecuteAsync()).Throws(new TestPlatformException("DummyTestPlatformException")); @@ -302,11 +302,11 @@ public void ExecutorExecuteShouldThrowSettingsExceptionThrownDuringExecution() var mockTestRunRequest = new Mock(); var mockDiscoveryRequest = new Mock(); - List list = new() - { + List list = + [ new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") - }; + ]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestRunRequest.Setup(dr => dr.ExecuteAsync()).Throws(new SettingsException("DummySettingsException")); @@ -329,11 +329,11 @@ public void ExecutorExecuteShouldThrowInvalidOperationExceptionThrownDuringExecu var mockTestRunRequest = new Mock(); var mockDiscoveryRequest = new Mock(); - List list = new() - { + List list = + [ new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") - }; + ]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestRunRequest.Setup(dr => dr.ExecuteAsync()).Throws(new InvalidOperationException("DummySettingsException")); @@ -359,7 +359,7 @@ public void ExecutorExecuteShouldForValidSourcesAndNoTestsDiscoveredShouldLogWar ResetAndAddSourceToCommandLineOptions(); // Setting some test adapter path - CommandLineOptions.Instance.TestAdapterPath = new[] { @"C:\Foo" }; + CommandLineOptions.Instance.TestAdapterPath = [@"C:\Foo"]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(new List())); mockTestPlatform.Setup(tp => tp.CreateDiscoveryRequest(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny())).Returns(mockDiscoveryRequest.Object); @@ -404,10 +404,7 @@ public void ExecutorExecuteShouldForValidSourcesAndValidSelectedTestsRunsTestsAn ResetAndAddSourceToCommandLineOptions(); - List list = new() - { - new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1") - }; + List list = [new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -431,11 +428,11 @@ public void ExecutorShouldRunTestsWhenTestsAreCommaSeparated() ResetAndAddSourceToCommandLineOptions(); - List list = new() - { + List list = + [ new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1") - }; + ]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -460,11 +457,11 @@ public void ExecutorShouldRunTestsWhenTestsAreFiltered() ResetAndAddSourceToCommandLineOptions(); - List list = new() - { + List list = + [ new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1") - }; + ]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -489,10 +486,7 @@ public void ExecutorShouldWarnWhenTestsAreNotAvailable() ResetAndAddSourceToCommandLineOptions(); - List list = new() - { - new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1") - }; + List list = [new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1")]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -517,11 +511,11 @@ public void ExecutorShouldRunTestsWhenTestsAreCommaSeparatedWithEscape() ResetAndAddSourceToCommandLineOptions(); - List list = new() - { + List list = + [ new TestCase("Test1(a,b)", new Uri("http://FooTestUri1"), "Source1"), new TestCase("Test2(c,d)", new Uri("http://FooTestUri1"), "Source1") - }; + ]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -545,11 +539,11 @@ public void ExecutorShouldDisplayWarningIfNoTestsAreExecuted() var mockDiscoveryRequest = new Mock(); var mockTestRunStats = new Mock(); - List list = new() - { + List list = + [ new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") - }; + ]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestRunRequest.Setup(tr => tr.ExecuteAsync()).Returns(1).Raises(tr => tr.OnRunCompletion += null, @@ -576,11 +570,11 @@ public void ExecutorShouldNotDisplayWarningIfTestsAreExecuted() var mockDiscoveryRequest = new Mock(); var testRunStats = new TestRunStatistics(1, new Dictionary { { TestOutcome.Passed, 1 } }); - List list = new() - { + List list = + [ new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") - }; + ]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestRunRequest.Setup(tr => tr.ExecuteAsync()).Returns(1).Raises(tr => tr.OnRunCompletion += null, diff --git a/test/vstest.console.UnitTests/Processors/RunTestsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/RunTestsArgumentProcessorTests.cs index 2ed759112b..0c31c47d9d 100644 --- a/test/vstest.console.UnitTests/Processors/RunTestsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/RunTestsArgumentProcessorTests.cs @@ -252,11 +252,11 @@ private ArgumentProcessorResult RunRunArgumentProcessorExecuteWithMockSetup(ITes var mockTestPlatform = new Mock(); var mockConsoleOutput = new Mock(); - List list = new() - { + List list = + [ new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") - }; + ]; var mockTestRunStats = new Mock(); var args = new TestRunCompleteEventArgs(mockTestRunStats.Object, false, false, null, null, null, new TimeSpan()); diff --git a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs index 4859fe631a..01f9acf5f0 100644 --- a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs +++ b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs @@ -84,7 +84,7 @@ public void CreateArgumentProcessorShouldReturnNullIfInvalidCommandIsPassed() ArgumentProcessorFactory factory = ArgumentProcessorFactory.Create(); - IArgumentProcessor result = factory.CreateArgumentProcessor(command, new string[] { "" })!; + IArgumentProcessor result = factory.CreateArgumentProcessor(command, [""])!; Assert.IsNull(result); } @@ -96,7 +96,7 @@ public void CreateArgumentProcessorShouldReturnCliRunSettingsArgumentProcessorIf ArgumentProcessorFactory factory = ArgumentProcessorFactory.Create(); - IArgumentProcessor result = factory.CreateArgumentProcessor(command, new string[] { "" })!; + IArgumentProcessor result = factory.CreateArgumentProcessor(command, [""])!; Assert.AreEqual(typeof(CliRunSettingsArgumentProcessor), result.GetType()); } diff --git a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs index c7cb234b47..a597af523d 100644 --- a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs +++ b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs @@ -40,7 +40,7 @@ public void GetArgumentListShouldReturnCorrectArgumentList(string argument) } [TestMethod] - [DataRow(new string[] { "key1=value1", "invalidPair", "key2=value2" })] + [DataRow(["key1=value1", "invalidPair", "key2=value2"])] public void GetArgumentParametersShouldThrowErrorOnInvalidParameters(string[] parameterArgs) { try