From 00aacfca4b6f0aeedcc94740e09461238bf7dcb6 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 1 Feb 2024 17:11:01 -0800 Subject: [PATCH 01/57] Enable testing against ACR --- .ci/test.yml | 27 ++++++++++++++++++- .../FindPSResourceACRServer.Tests.ps1 | 10 +++---- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/.ci/test.yml b/.ci/test.yml index 541d72542..d22673e80 100644 --- a/.ci/test.yml +++ b/.ci/test.yml @@ -11,6 +11,14 @@ jobs: vmImage: ${{ parameters.imageName }} displayName: ${{ parameters.displayName }} steps: + - ${{ parameters.powershellExecutable }}: | + Install-Module -Name 'Microsoft.PowerShell.SecretManagement' -force -SkipPublisherCheck -AllowClobber + Install-Module -Name 'Microsoft.PowerShell.SecretStore' -force -SkipPublisherCheck -AllowClobber + $vaultPassword = ConvertTo-SecureString $("a!!"+ (Get-Random -Maximum ([int]::MaxValue))) -AsPlainText -Force + Set-SecretStoreConfiguration -Authentication None -Interaction None -Confirm:$false -Password $vaultPassword + Register-SecretVault -Name SecretStore -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault + displayName: Install Secret store + - task: DownloadBuildArtifacts@0 displayName: 'Download artifacts' inputs: @@ -53,6 +61,24 @@ jobs: displayName: Install module for test from downloaded artifact workingDirectory: ${{ parameters.buildDirectory }} + - task: AzurePowerShell@5 + inputs: + azureSubscription: PSResourceGetACR + azurePowerShellVersion: LatestVersion + ScriptType: InlineScript + pwsh: true + inline: | + Write-Verbose -Verbose "Getting Azure Container Registry" + Get-AzContainerRegistry -ResourceGroupName 'PSResourceGet' -Name 'psresourcegettest' | Select-Object -Property * + Write-Verbose -Verbose "Setting up secret for Azure Container Registry" + $azt = Get-AzAccessToken + $tenantId = $azt.TenantID + Set-Secret -Name $tenantId -Secret $azt.Token -Verbose + $vstsCommandString = "vso[task.setvariable variable=TenantId]$tenantId" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + displayName: 'Setup Azure Container Registry secret' + - ${{ parameters.powershellExecutable }}: | $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath @@ -68,4 +94,3 @@ jobs: workingDirectory: ${{ parameters.buildDirectory }} errorActionPreference: continue condition: succeededOrFailed() - diff --git a/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 index ed7e4bfc8..1b9c36d7e 100644 --- a/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 @@ -1,9 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -<# -# These tests are working with manual validation but there is currently no automated testing for ACR repositories. - $modPath = "$psscriptroot/../PSGetTestUtils.psm1" Import-Module $modPath -Force -Verbose @@ -12,9 +9,10 @@ Describe 'Test HTTP Find-PSResource for ACR Server Protocol' -tags 'CI' { BeforeAll{ $testModuleName = "hello-world" $ACRRepoName = "ACRRepo" - $ACRRepoUri = "https://psgetregistry.azurecr.io" + $ACRRepoUri = "https://psresourcegettest.azurecr.io" Get-NewPSResourceRepositoryFile - Register-PSResourceRepository -Name $ACRRepoName -Uri $ACRepoUri -ApiVersion "ACR" + $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") + Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'acr' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose } AfterAll { @@ -138,5 +136,3 @@ Describe 'Test HTTP Find-PSResource for ACR Server Protocol' -tags 'CI' { $err[0].FullyQualifiedErrorId | Should -BeExactly "FindAllFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" } } - -#> \ No newline at end of file From 9929dfd1c935d2d846c144a7e0a2c3958cd0c5fd Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 1 Feb 2024 17:17:18 -0800 Subject: [PATCH 02/57] Fix yaml --- .ci/test.yml | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/.ci/test.yml b/.ci/test.yml index d22673e80..13be97783 100644 --- a/.ci/test.yml +++ b/.ci/test.yml @@ -62,22 +62,22 @@ jobs: workingDirectory: ${{ parameters.buildDirectory }} - task: AzurePowerShell@5 - inputs: - azureSubscription: PSResourceGetACR - azurePowerShellVersion: LatestVersion - ScriptType: InlineScript - pwsh: true - inline: | - Write-Verbose -Verbose "Getting Azure Container Registry" - Get-AzContainerRegistry -ResourceGroupName 'PSResourceGet' -Name 'psresourcegettest' | Select-Object -Property * - Write-Verbose -Verbose "Setting up secret for Azure Container Registry" - $azt = Get-AzAccessToken - $tenantId = $azt.TenantID - Set-Secret -Name $tenantId -Secret $azt.Token -Verbose - $vstsCommandString = "vso[task.setvariable variable=TenantId]$tenantId" - Write-Host "sending " + $vstsCommandString - Write-Host "##$vstsCommandString" - displayName: 'Setup Azure Container Registry secret' + inputs: + azureSubscription: PSResourceGetACR + azurePowerShellVersion: LatestVersion + ScriptType: InlineScript + pwsh: true + inline: | + Write-Verbose -Verbose "Getting Azure Container Registry" + Get-AzContainerRegistry -ResourceGroupName 'PSResourceGet' -Name 'psresourcegettest' | Select-Object -Property * + Write-Verbose -Verbose "Setting up secret for Azure Container Registry" + $azt = Get-AzAccessToken + $tenantId = $azt.TenantID + Set-Secret -Name $tenantId -Secret $azt.Token -Verbose + $vstsCommandString = "vso[task.setvariable variable=TenantId]$tenantId" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + displayName: 'Setup Azure Container Registry secret' - ${{ parameters.powershellExecutable }}: | $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' From b490e24bc5d88da988a1acbf0dfc11b4fcfec8ee Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 9 Feb 2024 16:43:44 -0800 Subject: [PATCH 03/57] Add ACR install tests --- .../InstallPSResourceACRServer.Tests.ps1 | 267 ++++++++++++++++++ 1 file changed, 267 insertions(+) create mode 100644 test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 diff --git a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 new file mode 100644 index 000000000..ba8d13d7b --- /dev/null +++ b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 @@ -0,0 +1,267 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +$ProgressPreference = "SilentlyContinue" +$modPath = "$psscriptroot/../PSGetTestUtils.psm1" +Import-Module $modPath -Force -Verbose + +Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { + + BeforeAll { + $testModuleName = "test_local_mod" + $testModuleName2 = "test_local_mod2" + $testScriptName = "test_ado_script" + $ACRRepoName = "ACRRepo" + $ACRRepoUri = "https://psresourcegettest.azurecr.io" + Get-NewPSResourceRepositoryFile + $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") + Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'acr' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose + } + + AfterEach { + Uninstall-PSResource $testModuleName, $testModuleName2, $testScriptName -Version "*" -SkipDependencyCheck -ErrorAction SilentlyContinue + } + + AfterAll { + Get-RevertPSResourceRepositoryFile + } + + $testCases = @{Name="*"; ErrorId="NameContainsWildcard"}, + @{Name="Test_local_m*"; ErrorId="NameContainsWildcard"}, + @{Name="Test?local","Test[local"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} + + It "Should not install resource with wildcard in name" -TestCases $testCases { + param($Name, $ErrorId) + Install-PSResource -Name $Name -Repository $ADORepoName -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + $res = Get-InstalledPSResource $testModuleName + $res | Should -BeNullOrEmpty + } + + It "Install specific module resource by name" { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + <# currently failing + It "Install specific script resource by name" { + Install-PSResource -Name $testScriptName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testScriptName + $pkg.Name | Should -Be $testScriptName + $pkg.Version | Should -Be "1.0.0" + } + #> + + It "Install multiple resources by name" { + $pkgNames = @($testModuleName, $testModuleName2) + Install-PSResource -Name $pkgNames -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $pkgNames + $pkg.Name | Should -Be $pkgNames + } + + It "Should not install resource given nonexistant name" { + Install-PSResource -Name "NonExistantModule" -Repository $ADORepoName -TrustRepository -ErrorVariable err -ErrorAction SilentlyContinue + $pkg = Get-InstalledPSResource "NonExistantModule" + $pkg | Should -BeNullOrEmpty + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "InstallPackageFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + } + + # Do some version testing, but Find-PSResource should be doing thorough testing + It "Should install resource given name and exact version" { + Install-PSResource -Name $testModuleName -Version "1.0.0" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "1.0.0" + } + + It "Should install resource given name and exact version with bracket syntax" { + Install-PSResource -Name $testModuleName -Version "[1.0.0]" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "1.0.0" + } + + It "Should install resource given name and exact range inclusive [1.0.0, 5.0.0]" { + Install-PSResource -Name $testModuleName -Version "[1.0.0, 5.0.0]" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + It "Should install resource given name and exact range exclusive (1.0.0, 5.0.0)" { + Install-PSResource -Name $testModuleName -Version "(1.0.0, 5.0.0)" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "3.0.0" + } + + # TODO: Update this test and others like it that use try/catch blocks instead of Should -Throw + It "Should not install resource with incorrectly formatted version such as exclusive version (1.0.0.0)" { + $Version = "(1.0.0.0)" + try { + Install-PSResource -Name $testModuleName -Version $Version -Repository $ADORepoName -TrustRepository -ErrorAction SilentlyContinue + } + catch + {} + $Error[0].FullyQualifiedErrorId | Should -be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + + $res = Get-InstalledPSResource $testModuleName + $res | Should -BeNullOrEmpty + } + + It "Install resource when given Name, Version '*', should install the latest version" { + Install-PSResource -Name $testModuleName -Version "*" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + It "Install resource with latest (including prerelease) version given Prerelease parameter" { + Install-PSResource -Name $testModuleName -Prerelease -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.2.5" + $pkg.Prerelease | Should -Be "alpha001" + } + + It "Install resource via InputObject by piping from Find-PSresource" { + Find-PSResource -Name $testModuleName -Repository $ADORepoName | Install-PSResource -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + It "Install resource with companyname and repository source location and validate properties" { + Install-PSResource -Name $testModuleName -Version "5.2.5-alpha001" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Version | Should -Be "5.2.5" + $pkg.Prerelease | Should -Be "alpha001" + + $pkg.CompanyName | Should -Be "None" + $pkg.RepositorySourceLocation | Should -Be $ADORepoUri + } + + # Windows only + It "Install resource under CurrentUser scope - Windows only" -Skip:(!(Get-IsWindows)) { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -Scope CurrentUser + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("Documents") | Should -Be $true + } + + # Windows only + It "Install resource under AllUsers scope - Windows only" -Skip:(!((Get-IsWindows) -and (Test-IsAdmin))) { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -Scope AllUsers -Verbose + $pkg = Get-InstalledPSResource $testModuleName -Scope AllUsers + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("Program Files") | Should -Be $true + } + + # Windows only + It "Install resource under no specified scope - Windows only" -Skip:(!(Get-IsWindows)) { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("Documents") | Should -Be $true + } + + # Unix only + # Expected path should be similar to: '/home/janelane/.local/share/powershell/Modules' + It "Install resource under CurrentUser scope - Unix only" -Skip:(Get-IsWindows) { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -Scope CurrentUser + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("$env:HOME/.local") | Should -Be $true + } + + # Unix only + # Expected path should be similar to: '/home/janelane/.local/share/powershell/Modules' + It "Install resource under no specified scope - Unix only" -Skip:(Get-IsWindows) { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("$env:HOME/.local") | Should -Be $true + } + + It "Should not install resource that is already installed" { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -WarningVariable WarningVar -warningaction SilentlyContinue + $WarningVar | Should -Not -BeNullOrEmpty + } + + It "Reinstall resource that is already installed with -Reinstall parameter" { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + Install-PSResource -Name $testModuleName -Repository $ADORepoName -Reinstall -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + It "Install PSResourceInfo object piped in" { + Find-PSResource -Name $testModuleName -Version "1.0.0.0" -Repository $ADORepoName | Install-PSResource -TrustRepository + $res = Get-InstalledPSResource -Name $testModuleName + $res.Name | Should -Be $testModuleName + $res.Version | Should -Be "1.0.0" + } + + It "Install module using -PassThru" { + $res = Install-PSResource -Name $testModuleName -Repository $ADORepoName -PassThru -TrustRepository + $res.Name | Should -Contain $testModuleName + } +} + +Describe 'Test Install-PSResource for V3Server scenarios' -tags 'ManualValidationOnly' { + + BeforeAll { + $testModuleName = "TestModule" + $testModuleName2 = "testModuleWithlicense" + Get-NewPSResourceRepositoryFile + Register-LocalRepos + } + + AfterEach { + Uninstall-PSResource $testModuleName, $testModuleName2 -SkipDependencyCheck -ErrorAction SilentlyContinue + } + + AfterAll { + Get-RevertPSResourceRepositoryFile + } + + # Unix only manual test + # Expected path should be similar to: '/usr/local/share/powershell/Modules' + It "Install resource under AllUsers scope - Unix only" -Skip:(Get-IsWindows) { + Install-PSResource -Name $testModuleName -Repository $TestGalleryName -Scope AllUsers + $pkg = Get-Module $testModuleName -ListAvailable + $pkg.Name | Should -Be $testModuleName + $pkg.Path.Contains("/usr/") | Should -Be $true + } + + # This needs to be manually tested due to prompt + It "Install resource that requires accept license without -AcceptLicense flag" { + Install-PSResource -Name $testModuleName2 -Repository $TestGalleryName + $pkg = Get-InstalledPSResource $testModuleName2 + $pkg.Name | Should -Be $testModuleName2 + $pkg.Version | Should -Be "0.0.1.0" + } + + # This needs to be manually tested due to prompt + It "Install resource should prompt 'trust repository' if repository is not trusted" { + Set-PSResourceRepository PoshTestGallery -Trusted:$false + + Install-PSResource -Name $testModuleName -Repository $TestGalleryName -confirm:$false + + $pkg = Get-Module $testModuleName -ListAvailable + $pkg.Name | Should -Be $testModuleName + + Set-PSResourceRepository PoshTestGallery -Trusted + } +} From 525eb808159e08c1537a24120745bf5038e8a1b1 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Sat, 10 Feb 2024 12:34:38 -0800 Subject: [PATCH 04/57] Add publish tests --- .../PublishPSResourceACRServer.Tests.ps1 | 444 ++++++++++++++++++ 1 file changed, 444 insertions(+) create mode 100644 test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 new file mode 100644 index 000000000..750bf51ff --- /dev/null +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -0,0 +1,444 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +$modPath = "$psscriptroot/../PSGetTestUtils.psm1" +Import-Module $modPath -Force -Verbose + +$testDir = (get-item $psscriptroot).parent.FullName + +function CreateTestModule +{ + param ( + [string] $Path = "$TestDrive", + [string] $ModuleName = 'TEMP-PSResourceGetTempTestModule' + ) + + $modulePath = Join-Path -Path $Path -ChildPath $ModuleName + $moduleMan = Join-Path $modulePath -ChildPath ($ModuleName + '.psd1') + $moduleSrc = Join-Path $modulePath -ChildPath ($ModuleName + '.psm1') + + if ( Test-Path -Path $modulePath) { + Remove-Item -Path $modulePath -Recurse -Force + } + + $null = New-Item -Path $modulePath -ItemType Directory -Force + + @' + @{{ + RootModule = "{0}.psm1" + ModuleVersion = '1.0.0' + Author = 'None' + Description = 'None' + GUID = '0c2829fc-b165-4d72-9038-ae3a71a755c1' + FunctionsToExport = @('Test1') + RequiredModules = @('NonExistentModule') + }} +'@ -f $ModuleName | Out-File -FilePath $moduleMan + + @' + function Test1 { + Write-Output 'Hello from Test1' + } +'@ | Out-File -FilePath $moduleSrc +} + +Describe "Test Publish-PSResource" -tags 'CI' { + BeforeAll { + Get-NewPSResourceRepositoryFile + + # Register repositories + $ACRRepoName = "ACRRepo" + $ACRRepoUri = "https://psresourcegettest.azurecr.io" + $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") + Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'acr' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose + + # Create module + $script:tmpModulesPath = Join-Path -Path $TestDrive -ChildPath "tmpModulesPath" + $script:PublishModuleName = "TEMP-PSResourceGetTempTestModule" + $script:PublishModuleBase = Join-Path $script:tmpModulesPath -ChildPath $script:PublishModuleName + if(!(Test-Path $script:PublishModuleBase)) + { + New-Item -Path $script:PublishModuleBase -ItemType Directory -Force + } + $script:PublishModuleBaseUNC = $script:PublishModuleBase -Replace '^(.):', '\\localhost\$1$' + + #Create dependency module + $script:DependencyModuleName = "TEMP-PackageManagement" + $script:DependencyModuleBase = Join-Path $script:tmpModulesPath -ChildPath $script:DependencyModuleName + if(!(Test-Path $script:DependencyModuleBase)) + { + New-Item -Path $script:DependencyModuleBase -ItemType Directory -Force + } + + # Create temp destination path + $script:destinationPath = [IO.Path]::GetFullPath((Join-Path -Path $TestDrive -ChildPath "tmpDestinationPath")) + New-Item $script:destinationPath -ItemType directory -Force + + #Create folder where we shall place all script files to be published for these tests + $script:tmpScriptsFolderPath = Join-Path -Path $TestDrive -ChildPath "tmpScriptsPath" + if(!(Test-Path $script:tmpScriptsFolderPath)) + { + New-Item -Path $script:tmpScriptsFolderPath -ItemType Directory -Force + } + + # Path to folder, within our test folder, where we store invalid module and script files used for testing + $script:testFilesFolderPath = Join-Path $testDir -ChildPath "testFiles" + + # Path to specifically to that invalid test modules folder + $script:testModulesFolderPath = Join-Path $script:testFilesFolderPath -ChildPath "testModules" + + # Path to specifically to that invalid test scripts folder + $script:testScriptsFolderPath = Join-Path $script:testFilesFolderPath -ChildPath "testScripts" + } + AfterAll { + Get-RevertPSResourceRepositoryFile + } + + It "Publish module with required module not installed on the local machine using -SkipModuleManifestValidate" { + $ModuleName = "TEMP-ModuleWithMissingRequiredModule" + CreateTestModule -Path $TestDrive -ModuleName $ModuleName + + # Skip the module manifest validation test, which fails from the missing manifest required module. + $testModulePath = Join-Path -Path $TestDrive -ChildPath ModuleWithMissingRequiredModule + Publish-PSResource -Path $testModulePath -Repository $ACRRepoName -Confirm:$false -SkipDependenciesCheck -SkipModuleManifestValidate + + $results = Find-PSResource -Name ModuleWithMissingRequiredModule -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $ModuleName + $results[0].Version | Should -Be "1.0.0" + } + + It "Publish a module with -Path pointing to a module directory (parent directory has same name)" { + $version = "1.0.0" + New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $script:PublishModuleBase -Repository $testRepository2 + + $results = Find-PSResource -Name ModuleWithMissingRequiredModule -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $script:PublishModuleName + $results[0].Version | Should -Be $version + } + + It "Publish a module with -Path pointing to a module directory (parent directory has different name)" { + $version = "2.0.0" + $newModuleRoot = Join-Path -Path $script:PublishModuleBase -ChildPath "NewTestParentDirectory" + New-Item -Path $newModuleRoot -ItemType Directory + New-ModuleManifest -Path (Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $newModuleRoot -Repository $testRepository2 + + $results = Find-PSResource -Name ModuleWithMissingRequiredModule -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $script:PublishModuleName + $results[0].Version | Should -Be $version + } + + It "Publish a module with -Path pointing to a .psd1 (parent directory has same name)" { + $version = "3.0.0" + $manifestPath = Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1" + New-ModuleManifest -Path $manifestPath -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $manifestPath -Repository $testRepository2 + + $results = Find-PSResource -Name ModuleWithMissingRequiredModule -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $script:PublishModuleName + $results[0].Version | Should -Be $version + } + + It "Publish a module with -Path pointing to a .psd1 (parent directory has different name)" { + $version = "4.0.0" + $newModuleRoot = Join-Path -Path $script:PublishModuleBase -ChildPath "NewTestParentDirectory" + New-Item -Path $newModuleRoot -ItemType Directory + $manifestPath = Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1" + New-ModuleManifest -Path $manifestPath -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $manifestPath -Repository $testRepository2 + + $results = Find-PSResource -Name ModuleWithMissingRequiredModule -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $script:PublishModuleName + $results[0].Version | Should -Be $version + } + + It "Publish a module with -Path pointing to a module directory (parent directory has same name) on a network share" { + $version = "5.0.0" + New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBaseUNC -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $script:PublishModuleBaseUNC -Repository $ACRRepoName + + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $script:PublishModuleName + $results[0].Version | Should -Be $version + } + + It "Publish a module with -Path pointing to a module directory (parent directory has different name) on a network share" { + $version = "6.0.0" + $newModuleRoot = Join-Path -Path $script:PublishModuleBaseUNC -ChildPath "NewTestParentDirectory" + New-Item -Path $newModuleRoot -ItemType Directory + New-ModuleManifest -Path (Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $newModuleRoot -Repository $ACRRepoName + + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $script:PublishModuleName + $results[0].Version | Should -Be $version + } + + It "Publish a module with -Path pointing to a .psd1 (parent directory has same name) on a network share" { + $version = "7.0.0" + $manifestPath = Join-Path -Path $script:PublishModuleBaseUNC -ChildPath "$script:PublishModuleName.psd1" + New-ModuleManifest -Path $manifestPath -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $manifestPath -Repository $ACRRepoName + + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $script:PublishModuleName + $results[0].Version | Should -Be $version + } + + It "Publish a module with -Path pointing to a .psd1 (parent directory has different name) on a network share" { + $version = "8.0.0" + $newModuleRoot = Join-Path -Path $script:PublishModuleBaseUNC -ChildPath "NewTestParentDirectory" + New-Item -Path $newModuleRoot -ItemType Directory + $manifestPath = Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1" + New-ModuleManifest -Path $manifestPath -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $manifestPath -Repository $ACRRepoName + + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $script:PublishModuleName + $results[0].Version | Should -Be $version + } + + It "Publish a module and preserve file structure" { + $version = "9.0.0" + $testFile = Join-Path -Path "TestSubDirectory" -ChildPath "TestSubDirFile.ps1" + New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" + New-Item -Path (Join-Path -Path $script:PublishModuleBase -ChildPath $testFile) -Force + + Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName + + Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -Force -AsNupkg -Path $TestDrive + # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell + $nupkgPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName.$version.nupkg" + $zipPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName.$version.zip" + Rename-Item -Path $nupkgPath -NewName $zipPath + $unzippedPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName" + New-Item $unzippedPath -Itemtype directory -Force + Expand-Archive -Path $zipPath -DestinationPath $unzippedPath + + Test-Path -Path (Join-Path -Path $unzippedPath -ChildPath $testFile) | Should -Be $True + } + + It "Publish a module with -Path -Repository and -DestinationPath" { + $version = "10.0.0" + New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName -DestinationPath $script:destinationPath + + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $script:PublishModuleName + $results[0].Version | Should -Be $version + + $expectedPath = Join-Path -Path $script:destinationPath -ChildPath "$script:PublishModuleName.$version.nupkg" + Test-Path $expectedPath | Should -Be $true + } + + It "Publish a module and clean up properly when file in module is readonly" { + $version = "11.0.0" + New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" + + # Create a readonly file that will throw access denied error if deletion is attempted + $file = Join-Path -Path $script:PublishModuleBase -ChildPath "inaccessiblefile.txt" + New-Item $file -Itemtype file -Force + Set-ItemProperty -Path $file -Name IsReadOnly -Value $true + + Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName + + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $script:PublishModuleName + $results[0].Version | Should -Be $version + } + + It "Publish a module when the .psd1 version and the path version are different" { + $incorrectVersion = "15.2.4" + $correctVersion = "12.0.0" + $versionBase = (Join-Path -Path $script:PublishModuleBase -ChildPath $incorrectVersion) + New-Item -Path $versionBase -ItemType Directory + $modManifestPath = (Join-Path -Path $versionBase -ChildPath "$script:PublishModuleName.psd1") + New-ModuleManifest -Path $modManifestPath -ModuleVersion $correctVersion -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $modManifestPath -Repository $ACRRepoName + + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $script:PublishModuleName + $results[0].Version | Should -Be $correctVersion + } + + It "Publish a script"{ + $scriptName = "TEMP-PSGetTestScript" + $scriptVersion = "1.0.0" + + $params = @{ + Version = $scriptVersion + GUID = [guid]::NewGuid() + Author = 'Jane' + CompanyName = 'Microsoft Corporation' + Copyright = '(c) 2020 Microsoft Corporation. All rights reserved.' + Description = "Description for the $scriptName script" + LicenseUri = "https://$scriptName.com/license" + IconUri = "https://$scriptName.com/icon" + ProjectUri = "https://$scriptName.com" + Tags = @('Tag1','Tag2', "Tag-$scriptName-$scriptVersion") + ReleaseNotes = "$scriptName release notes" + } + + $scriptPath = (Join-Path -Path $script:tmpScriptsFolderPath -ChildPath "$scriptName.ps1") + New-PSScriptFileInfo @params -Path $scriptPath + + Publish-PSResource -Path $scriptPath -Repository $ACRRepoName + + $results = Find-PSResource -Name $scriptName -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $scriptName + $results[0].Version | Should -Be $scriptVersion + } + + It "Should publish a script without lines in between comment blocks locally" { + $scriptName = "ScriptWithoutEmptyLinesBetweenCommentBlocks" + $scriptVersion = "1.0.0" + $scriptPath = (Join-Path -Path $script:testScriptsFolderPath -ChildPath "$scriptName.ps1") + + Publish-PSResource -Path $scriptPath -Repository $ACRRepoName + + $results = Find-PSResource -Name $scriptName -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $scriptName + $results[0].Version | Should -Be $scriptVersion + } + + It "Should publish a script without lines in help block locally" { + $scriptName = "ScriptWithoutEmptyLinesInMetadata" + $scriptVersion = "1.0.0" + $scriptPath = (Join-Path -Path $script:testScriptsFolderPath -ChildPath "$scriptName.ps1") + + Publish-PSResource -Path $scriptPath -Repository $ACRRepoName + + $results = Find-PSResource -Name $scriptName -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $scriptName + $results[0].Version | Should -Be $scriptVersion + } + + It "Should publish a script with ExternalModuleDependencies that are not published" { + $scriptName = "testscript" + $scriptVersion = "1.0.0" + $scriptPath = Join-Path -Path $script:testScriptsFolderPath -ChildPath "$scriptName.ps1" + New-PSScriptFileInfo -Description 'test' -Version $scriptVersion -RequiredModules @{ModuleName='testModule'} -ExternalModuleDependencies 'testModule' -Path $scriptPath -Force + + Publish-PSResource -Path $scriptPath -Repository $ACRRepoName + + $results = Find-PSResource -Name $scriptName -Repository $ACRRepoName + $results | Should -Not -BeNullOrEmpty + $results[0].Name | Should -Be $scriptName + $results[0].Version | Should -Be $scriptVersion + } + + It "Should write error and not publish script when Author property is missing" { + $scriptName = "InvalidScriptMissingAuthor.ps1" + + $scriptFilePath = Join-Path $script:testScriptsFolderPath -ChildPath $scriptName + Publish-PSResource -Path $scriptFilePath -Repository $ACRRepoName -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "psScriptMissingAuthor,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + + Find-PSResource -Name $scriptName -Repository $ACRRepoName -ErrorVariable findErr -ErrorAction SilentlyContinue + $findErr.Count | Should -BeGreaterThan 0 + $findErr[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + } + + It "Should write error and not publish script when Version property is missing" { + $scriptName = "InvalidScriptMissingVersion.ps1" + + $scriptFilePath = Join-Path $script:testScriptsFolderPath -ChildPath $scriptName + Publish-PSResource -Path $scriptFilePath -Repository $ACRRepoName -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "psScriptMissingVersion,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + + Find-PSResource -Name $scriptName -Repository $ACRRepoName -ErrorVariable findErr -ErrorAction SilentlyContinue + $findErr.Count | Should -BeGreaterThan 0 + $findErr[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + } + + It "Should write error and not publish script when Guid property is missing" { + $scriptName = "InvalidScriptMissingGuid.ps1" + + $scriptFilePath = Join-Path $script:testScriptsFolderPath -ChildPath $scriptName + Publish-PSResource -Path $scriptFilePath -Repository $ACRRepoName -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "psScriptMissingGuid,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + + Find-PSResource -Name $scriptName -Repository $ACRRepoName -ErrorVariable findErr -ErrorAction SilentlyContinue + $findErr.Count | Should -BeGreaterThan 0 + $findErr[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + } + + It "Should write error and not publish script when Description property is missing" { + $scriptName = "InvalidScriptMissingDescription.ps1" + + $scriptFilePath = Join-Path $script:testScriptsFolderPath -ChildPath $scriptName + Publish-PSResource -Path $scriptFilePath -Repository $ACRRepoName -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "PSScriptInfoMissingDescription,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + + Find-PSResource -Name $scriptName -Repository $ACRRepoName -ErrorVariable findErr -ErrorAction SilentlyContinue + $findErr.Count | Should -BeGreaterThan 0 + $findErr[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + } + + It "Should write error and not publish script when Description block altogether is missing" { + # we expect .ps1 files to have a separate comment block for .DESCRIPTION property, not to be included in the PSScriptInfo commment block + $scriptName = "InvalidScriptMissingDescriptionCommentBlock.ps1" + + $scriptFilePath = Join-Path $script:testScriptsFolderPath -ChildPath $scriptName + Publish-PSResource -Path $scriptFilePath -Repository $ACRRepoName -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "missingHelpInfoCommentError,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + + Find-PSResource -Name $scriptName -Repository $ACRRepoName -ErrorVariable findErr -ErrorAction SilentlyContinue + $findErr.Count | Should -BeGreaterThan 0 + $findErr[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + } + + It "Publish a module with that has an invalid version format, should throw" { + $moduleName = "TEMP-incorrectmoduleversion" + $incorrectmoduleversion = Join-Path -Path $script:testModulesFolderPath -ChildPath $moduleName + + {Publish-PSResource -Path $incorrectmoduleversion -Repository $ACRRepoName -ErrorAction Stop} | Should -Throw -ErrorId "InvalidModuleManifest,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + } + + + It "Publish a module with a dependency that has an invalid version format, should throw" { + $moduleName = "TEMP-incorrectdepmoduleversion" + $incorrectdepmoduleversion = Join-Path -Path $script:testModulesFolderPath -ChildPath $moduleName + + {Publish-PSResource -Path $incorrectdepmoduleversion -Repository $ACRRepoName -ErrorAction Stop} | Should -Throw -ErrorId "InvalidModuleManifest,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + } + + It "Publish a module with using an invalid file path (path to .psm1), should throw" { + $fileName = "$script:PublishModuleName.psm1" + $psm1Path = Join-Path -Path $script:PublishModuleBase -ChildPath $fileName + $null = New-Item -Path $psm1Path -ItemType File -Force + + {Publish-PSResource -Path $psm1Path -Repository $ACRRepoName -ErrorAction Stop} | Should -Throw -ErrorId "InvalidPublishPath,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + } +} From 179d0967586357ddb56536c0f43bf89e5139b7f4 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Sat, 10 Feb 2024 12:55:38 -0800 Subject: [PATCH 05/57] Update test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 Co-authored-by: alerickson <25858831+alerickson@users.noreply.github.com> --- test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 index 1b9c36d7e..624b56c1e 100644 --- a/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 @@ -7,7 +7,7 @@ Import-Module $modPath -Force -Verbose Describe 'Test HTTP Find-PSResource for ACR Server Protocol' -tags 'CI' { BeforeAll{ - $testModuleName = "hello-world" + $testModuleName = "test_local_mod" $ACRRepoName = "ACRRepo" $ACRRepoUri = "https://psresourcegettest.azurecr.io" Get-NewPSResourceRepositoryFile From 2c81e023a8359ecad60f1f89d41edcff51e4c728 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 1 Feb 2024 17:11:01 -0800 Subject: [PATCH 06/57] Enable testing against ACR --- .ci/test.yml | 27 ++++++++++++++++++- .../FindPSResourceACRServer.Tests.ps1 | 10 +++---- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/.ci/test.yml b/.ci/test.yml index 541d72542..d22673e80 100644 --- a/.ci/test.yml +++ b/.ci/test.yml @@ -11,6 +11,14 @@ jobs: vmImage: ${{ parameters.imageName }} displayName: ${{ parameters.displayName }} steps: + - ${{ parameters.powershellExecutable }}: | + Install-Module -Name 'Microsoft.PowerShell.SecretManagement' -force -SkipPublisherCheck -AllowClobber + Install-Module -Name 'Microsoft.PowerShell.SecretStore' -force -SkipPublisherCheck -AllowClobber + $vaultPassword = ConvertTo-SecureString $("a!!"+ (Get-Random -Maximum ([int]::MaxValue))) -AsPlainText -Force + Set-SecretStoreConfiguration -Authentication None -Interaction None -Confirm:$false -Password $vaultPassword + Register-SecretVault -Name SecretStore -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault + displayName: Install Secret store + - task: DownloadBuildArtifacts@0 displayName: 'Download artifacts' inputs: @@ -53,6 +61,24 @@ jobs: displayName: Install module for test from downloaded artifact workingDirectory: ${{ parameters.buildDirectory }} + - task: AzurePowerShell@5 + inputs: + azureSubscription: PSResourceGetACR + azurePowerShellVersion: LatestVersion + ScriptType: InlineScript + pwsh: true + inline: | + Write-Verbose -Verbose "Getting Azure Container Registry" + Get-AzContainerRegistry -ResourceGroupName 'PSResourceGet' -Name 'psresourcegettest' | Select-Object -Property * + Write-Verbose -Verbose "Setting up secret for Azure Container Registry" + $azt = Get-AzAccessToken + $tenantId = $azt.TenantID + Set-Secret -Name $tenantId -Secret $azt.Token -Verbose + $vstsCommandString = "vso[task.setvariable variable=TenantId]$tenantId" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + displayName: 'Setup Azure Container Registry secret' + - ${{ parameters.powershellExecutable }}: | $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath @@ -68,4 +94,3 @@ jobs: workingDirectory: ${{ parameters.buildDirectory }} errorActionPreference: continue condition: succeededOrFailed() - diff --git a/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 index ed7e4bfc8..1b9c36d7e 100644 --- a/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 @@ -1,9 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -<# -# These tests are working with manual validation but there is currently no automated testing for ACR repositories. - $modPath = "$psscriptroot/../PSGetTestUtils.psm1" Import-Module $modPath -Force -Verbose @@ -12,9 +9,10 @@ Describe 'Test HTTP Find-PSResource for ACR Server Protocol' -tags 'CI' { BeforeAll{ $testModuleName = "hello-world" $ACRRepoName = "ACRRepo" - $ACRRepoUri = "https://psgetregistry.azurecr.io" + $ACRRepoUri = "https://psresourcegettest.azurecr.io" Get-NewPSResourceRepositoryFile - Register-PSResourceRepository -Name $ACRRepoName -Uri $ACRepoUri -ApiVersion "ACR" + $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") + Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'acr' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose } AfterAll { @@ -138,5 +136,3 @@ Describe 'Test HTTP Find-PSResource for ACR Server Protocol' -tags 'CI' { $err[0].FullyQualifiedErrorId | Should -BeExactly "FindAllFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" } } - -#> \ No newline at end of file From f0a3f1c7f43121a39914f4b7c72f5af4e110280c Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 1 Feb 2024 17:17:18 -0800 Subject: [PATCH 07/57] Fix yaml --- .ci/test.yml | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/.ci/test.yml b/.ci/test.yml index d22673e80..13be97783 100644 --- a/.ci/test.yml +++ b/.ci/test.yml @@ -62,22 +62,22 @@ jobs: workingDirectory: ${{ parameters.buildDirectory }} - task: AzurePowerShell@5 - inputs: - azureSubscription: PSResourceGetACR - azurePowerShellVersion: LatestVersion - ScriptType: InlineScript - pwsh: true - inline: | - Write-Verbose -Verbose "Getting Azure Container Registry" - Get-AzContainerRegistry -ResourceGroupName 'PSResourceGet' -Name 'psresourcegettest' | Select-Object -Property * - Write-Verbose -Verbose "Setting up secret for Azure Container Registry" - $azt = Get-AzAccessToken - $tenantId = $azt.TenantID - Set-Secret -Name $tenantId -Secret $azt.Token -Verbose - $vstsCommandString = "vso[task.setvariable variable=TenantId]$tenantId" - Write-Host "sending " + $vstsCommandString - Write-Host "##$vstsCommandString" - displayName: 'Setup Azure Container Registry secret' + inputs: + azureSubscription: PSResourceGetACR + azurePowerShellVersion: LatestVersion + ScriptType: InlineScript + pwsh: true + inline: | + Write-Verbose -Verbose "Getting Azure Container Registry" + Get-AzContainerRegistry -ResourceGroupName 'PSResourceGet' -Name 'psresourcegettest' | Select-Object -Property * + Write-Verbose -Verbose "Setting up secret for Azure Container Registry" + $azt = Get-AzAccessToken + $tenantId = $azt.TenantID + Set-Secret -Name $tenantId -Secret $azt.Token -Verbose + $vstsCommandString = "vso[task.setvariable variable=TenantId]$tenantId" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + displayName: 'Setup Azure Container Registry secret' - ${{ parameters.powershellExecutable }}: | $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' From 5e97ee433787ab11f8afec55ff790f7d53cefe2a Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Sat, 10 Feb 2024 12:55:38 -0800 Subject: [PATCH 08/57] Update test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 Co-authored-by: alerickson <25858831+alerickson@users.noreply.github.com> --- test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 index 1b9c36d7e..624b56c1e 100644 --- a/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceACRServer.Tests.ps1 @@ -7,7 +7,7 @@ Import-Module $modPath -Force -Verbose Describe 'Test HTTP Find-PSResource for ACR Server Protocol' -tags 'CI' { BeforeAll{ - $testModuleName = "hello-world" + $testModuleName = "test_local_mod" $ACRRepoName = "ACRRepo" $ACRRepoUri = "https://psresourcegettest.azurecr.io" Get-NewPSResourceRepositoryFile From cf7b3851070ef68c6193ea6c9f7cc88095747437 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 9 Feb 2024 16:43:44 -0800 Subject: [PATCH 09/57] Add ACR install tests --- .../InstallPSResourceACRServer.Tests.ps1 | 267 ++++++++++++++++++ 1 file changed, 267 insertions(+) create mode 100644 test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 diff --git a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 new file mode 100644 index 000000000..ba8d13d7b --- /dev/null +++ b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 @@ -0,0 +1,267 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +$ProgressPreference = "SilentlyContinue" +$modPath = "$psscriptroot/../PSGetTestUtils.psm1" +Import-Module $modPath -Force -Verbose + +Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { + + BeforeAll { + $testModuleName = "test_local_mod" + $testModuleName2 = "test_local_mod2" + $testScriptName = "test_ado_script" + $ACRRepoName = "ACRRepo" + $ACRRepoUri = "https://psresourcegettest.azurecr.io" + Get-NewPSResourceRepositoryFile + $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") + Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'acr' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose + } + + AfterEach { + Uninstall-PSResource $testModuleName, $testModuleName2, $testScriptName -Version "*" -SkipDependencyCheck -ErrorAction SilentlyContinue + } + + AfterAll { + Get-RevertPSResourceRepositoryFile + } + + $testCases = @{Name="*"; ErrorId="NameContainsWildcard"}, + @{Name="Test_local_m*"; ErrorId="NameContainsWildcard"}, + @{Name="Test?local","Test[local"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} + + It "Should not install resource with wildcard in name" -TestCases $testCases { + param($Name, $ErrorId) + Install-PSResource -Name $Name -Repository $ADORepoName -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + $res = Get-InstalledPSResource $testModuleName + $res | Should -BeNullOrEmpty + } + + It "Install specific module resource by name" { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + <# currently failing + It "Install specific script resource by name" { + Install-PSResource -Name $testScriptName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testScriptName + $pkg.Name | Should -Be $testScriptName + $pkg.Version | Should -Be "1.0.0" + } + #> + + It "Install multiple resources by name" { + $pkgNames = @($testModuleName, $testModuleName2) + Install-PSResource -Name $pkgNames -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $pkgNames + $pkg.Name | Should -Be $pkgNames + } + + It "Should not install resource given nonexistant name" { + Install-PSResource -Name "NonExistantModule" -Repository $ADORepoName -TrustRepository -ErrorVariable err -ErrorAction SilentlyContinue + $pkg = Get-InstalledPSResource "NonExistantModule" + $pkg | Should -BeNullOrEmpty + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "InstallPackageFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + } + + # Do some version testing, but Find-PSResource should be doing thorough testing + It "Should install resource given name and exact version" { + Install-PSResource -Name $testModuleName -Version "1.0.0" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "1.0.0" + } + + It "Should install resource given name and exact version with bracket syntax" { + Install-PSResource -Name $testModuleName -Version "[1.0.0]" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "1.0.0" + } + + It "Should install resource given name and exact range inclusive [1.0.0, 5.0.0]" { + Install-PSResource -Name $testModuleName -Version "[1.0.0, 5.0.0]" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + It "Should install resource given name and exact range exclusive (1.0.0, 5.0.0)" { + Install-PSResource -Name $testModuleName -Version "(1.0.0, 5.0.0)" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "3.0.0" + } + + # TODO: Update this test and others like it that use try/catch blocks instead of Should -Throw + It "Should not install resource with incorrectly formatted version such as exclusive version (1.0.0.0)" { + $Version = "(1.0.0.0)" + try { + Install-PSResource -Name $testModuleName -Version $Version -Repository $ADORepoName -TrustRepository -ErrorAction SilentlyContinue + } + catch + {} + $Error[0].FullyQualifiedErrorId | Should -be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + + $res = Get-InstalledPSResource $testModuleName + $res | Should -BeNullOrEmpty + } + + It "Install resource when given Name, Version '*', should install the latest version" { + Install-PSResource -Name $testModuleName -Version "*" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + It "Install resource with latest (including prerelease) version given Prerelease parameter" { + Install-PSResource -Name $testModuleName -Prerelease -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.2.5" + $pkg.Prerelease | Should -Be "alpha001" + } + + It "Install resource via InputObject by piping from Find-PSresource" { + Find-PSResource -Name $testModuleName -Repository $ADORepoName | Install-PSResource -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + It "Install resource with companyname and repository source location and validate properties" { + Install-PSResource -Name $testModuleName -Version "5.2.5-alpha001" -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Version | Should -Be "5.2.5" + $pkg.Prerelease | Should -Be "alpha001" + + $pkg.CompanyName | Should -Be "None" + $pkg.RepositorySourceLocation | Should -Be $ADORepoUri + } + + # Windows only + It "Install resource under CurrentUser scope - Windows only" -Skip:(!(Get-IsWindows)) { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -Scope CurrentUser + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("Documents") | Should -Be $true + } + + # Windows only + It "Install resource under AllUsers scope - Windows only" -Skip:(!((Get-IsWindows) -and (Test-IsAdmin))) { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -Scope AllUsers -Verbose + $pkg = Get-InstalledPSResource $testModuleName -Scope AllUsers + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("Program Files") | Should -Be $true + } + + # Windows only + It "Install resource under no specified scope - Windows only" -Skip:(!(Get-IsWindows)) { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("Documents") | Should -Be $true + } + + # Unix only + # Expected path should be similar to: '/home/janelane/.local/share/powershell/Modules' + It "Install resource under CurrentUser scope - Unix only" -Skip:(Get-IsWindows) { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -Scope CurrentUser + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("$env:HOME/.local") | Should -Be $true + } + + # Unix only + # Expected path should be similar to: '/home/janelane/.local/share/powershell/Modules' + It "Install resource under no specified scope - Unix only" -Skip:(Get-IsWindows) { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("$env:HOME/.local") | Should -Be $true + } + + It "Should not install resource that is already installed" { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -WarningVariable WarningVar -warningaction SilentlyContinue + $WarningVar | Should -Not -BeNullOrEmpty + } + + It "Reinstall resource that is already installed with -Reinstall parameter" { + Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + Install-PSResource -Name $testModuleName -Repository $ADORepoName -Reinstall -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + It "Install PSResourceInfo object piped in" { + Find-PSResource -Name $testModuleName -Version "1.0.0.0" -Repository $ADORepoName | Install-PSResource -TrustRepository + $res = Get-InstalledPSResource -Name $testModuleName + $res.Name | Should -Be $testModuleName + $res.Version | Should -Be "1.0.0" + } + + It "Install module using -PassThru" { + $res = Install-PSResource -Name $testModuleName -Repository $ADORepoName -PassThru -TrustRepository + $res.Name | Should -Contain $testModuleName + } +} + +Describe 'Test Install-PSResource for V3Server scenarios' -tags 'ManualValidationOnly' { + + BeforeAll { + $testModuleName = "TestModule" + $testModuleName2 = "testModuleWithlicense" + Get-NewPSResourceRepositoryFile + Register-LocalRepos + } + + AfterEach { + Uninstall-PSResource $testModuleName, $testModuleName2 -SkipDependencyCheck -ErrorAction SilentlyContinue + } + + AfterAll { + Get-RevertPSResourceRepositoryFile + } + + # Unix only manual test + # Expected path should be similar to: '/usr/local/share/powershell/Modules' + It "Install resource under AllUsers scope - Unix only" -Skip:(Get-IsWindows) { + Install-PSResource -Name $testModuleName -Repository $TestGalleryName -Scope AllUsers + $pkg = Get-Module $testModuleName -ListAvailable + $pkg.Name | Should -Be $testModuleName + $pkg.Path.Contains("/usr/") | Should -Be $true + } + + # This needs to be manually tested due to prompt + It "Install resource that requires accept license without -AcceptLicense flag" { + Install-PSResource -Name $testModuleName2 -Repository $TestGalleryName + $pkg = Get-InstalledPSResource $testModuleName2 + $pkg.Name | Should -Be $testModuleName2 + $pkg.Version | Should -Be "0.0.1.0" + } + + # This needs to be manually tested due to prompt + It "Install resource should prompt 'trust repository' if repository is not trusted" { + Set-PSResourceRepository PoshTestGallery -Trusted:$false + + Install-PSResource -Name $testModuleName -Repository $TestGalleryName -confirm:$false + + $pkg = Get-Module $testModuleName -ListAvailable + $pkg.Name | Should -Be $testModuleName + + Set-PSResourceRepository PoshTestGallery -Trusted + } +} From 0fad988be4df6bbe5c19cf92a584bcffa12464a1 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 13 Feb 2024 20:42:02 -0800 Subject: [PATCH 10/57] Update Install tests --- .../InstallPSResourceACRServer.Tests.ps1 | 52 +++++++++---------- 1 file changed, 25 insertions(+), 27 deletions(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 index ba8d13d7b..24f2b9f1b 100644 --- a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 @@ -32,7 +32,7 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { It "Should not install resource with wildcard in name" -TestCases $testCases { param($Name, $ErrorId) - Install-PSResource -Name $Name -Repository $ADORepoName -ErrorVariable err -ErrorAction SilentlyContinue + Install-PSResource -Name $Name -Repository $ACRRepoName -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -BeGreaterThan 0 $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" $res = Get-InstalledPSResource $testModuleName @@ -40,30 +40,28 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { } It "Install specific module resource by name" { - Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "5.0.0" } - <# currently failing It "Install specific script resource by name" { - Install-PSResource -Name $testScriptName -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testScriptName -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testScriptName $pkg.Name | Should -Be $testScriptName $pkg.Version | Should -Be "1.0.0" } - #> It "Install multiple resources by name" { $pkgNames = @($testModuleName, $testModuleName2) - Install-PSResource -Name $pkgNames -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $pkgNames -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $pkgNames $pkg.Name | Should -Be $pkgNames } It "Should not install resource given nonexistant name" { - Install-PSResource -Name "NonExistantModule" -Repository $ADORepoName -TrustRepository -ErrorVariable err -ErrorAction SilentlyContinue + Install-PSResource -Name "NonExistantModule" -Repository $ACRRepoName -TrustRepository -ErrorVariable err -ErrorAction SilentlyContinue $pkg = Get-InstalledPSResource "NonExistantModule" $pkg | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 @@ -72,28 +70,28 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { # Do some version testing, but Find-PSResource should be doing thorough testing It "Should install resource given name and exact version" { - Install-PSResource -Name $testModuleName -Version "1.0.0" -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Version "1.0.0" -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "1.0.0" } It "Should install resource given name and exact version with bracket syntax" { - Install-PSResource -Name $testModuleName -Version "[1.0.0]" -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Version "[1.0.0]" -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "1.0.0" } It "Should install resource given name and exact range inclusive [1.0.0, 5.0.0]" { - Install-PSResource -Name $testModuleName -Version "[1.0.0, 5.0.0]" -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Version "[1.0.0, 5.0.0]" -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "5.0.0" } It "Should install resource given name and exact range exclusive (1.0.0, 5.0.0)" { - Install-PSResource -Name $testModuleName -Version "(1.0.0, 5.0.0)" -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Version "(1.0.0, 5.0.0)" -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "3.0.0" @@ -103,7 +101,7 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { It "Should not install resource with incorrectly formatted version such as exclusive version (1.0.0.0)" { $Version = "(1.0.0.0)" try { - Install-PSResource -Name $testModuleName -Version $Version -Repository $ADORepoName -TrustRepository -ErrorAction SilentlyContinue + Install-PSResource -Name $testModuleName -Version $Version -Repository $ACRRepoName -TrustRepository -ErrorAction SilentlyContinue } catch {} @@ -114,14 +112,14 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { } It "Install resource when given Name, Version '*', should install the latest version" { - Install-PSResource -Name $testModuleName -Version "*" -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Version "*" -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "5.0.0" } It "Install resource with latest (including prerelease) version given Prerelease parameter" { - Install-PSResource -Name $testModuleName -Prerelease -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Prerelease -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "5.2.5" @@ -129,14 +127,14 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { } It "Install resource via InputObject by piping from Find-PSresource" { - Find-PSResource -Name $testModuleName -Repository $ADORepoName | Install-PSResource -TrustRepository + Find-PSResource -Name $testModuleName -Repository $ACRRepoName | Install-PSResource -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "5.0.0" } It "Install resource with companyname and repository source location and validate properties" { - Install-PSResource -Name $testModuleName -Version "5.2.5-alpha001" -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Version "5.2.5-alpha001" -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Version | Should -Be "5.2.5" $pkg.Prerelease | Should -Be "alpha001" @@ -147,7 +145,7 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { # Windows only It "Install resource under CurrentUser scope - Windows only" -Skip:(!(Get-IsWindows)) { - Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -Scope CurrentUser + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository -Scope CurrentUser $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.InstalledLocation.ToString().Contains("Documents") | Should -Be $true @@ -155,7 +153,7 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { # Windows only It "Install resource under AllUsers scope - Windows only" -Skip:(!((Get-IsWindows) -and (Test-IsAdmin))) { - Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -Scope AllUsers -Verbose + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository -Scope AllUsers -Verbose $pkg = Get-InstalledPSResource $testModuleName -Scope AllUsers $pkg.Name | Should -Be $testModuleName $pkg.InstalledLocation.ToString().Contains("Program Files") | Should -Be $true @@ -163,7 +161,7 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { # Windows only It "Install resource under no specified scope - Windows only" -Skip:(!(Get-IsWindows)) { - Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.InstalledLocation.ToString().Contains("Documents") | Should -Be $true @@ -172,7 +170,7 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { # Unix only # Expected path should be similar to: '/home/janelane/.local/share/powershell/Modules' It "Install resource under CurrentUser scope - Unix only" -Skip:(Get-IsWindows) { - Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -Scope CurrentUser + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository -Scope CurrentUser $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.InstalledLocation.ToString().Contains("$env:HOME/.local") | Should -Be $true @@ -181,40 +179,40 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { # Unix only # Expected path should be similar to: '/home/janelane/.local/share/powershell/Modules' It "Install resource under no specified scope - Unix only" -Skip:(Get-IsWindows) { - Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.InstalledLocation.ToString().Contains("$env:HOME/.local") | Should -Be $true } It "Should not install resource that is already installed" { - Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository -WarningVariable WarningVar -warningaction SilentlyContinue + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository -WarningVariable WarningVar -warningaction SilentlyContinue $WarningVar | Should -Not -BeNullOrEmpty } It "Reinstall resource that is already installed with -Reinstall parameter" { - Install-PSResource -Name $testModuleName -Repository $ADORepoName -TrustRepository + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "5.0.0" - Install-PSResource -Name $testModuleName -Repository $ADORepoName -Reinstall -TrustRepository + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -Reinstall -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "5.0.0" } It "Install PSResourceInfo object piped in" { - Find-PSResource -Name $testModuleName -Version "1.0.0.0" -Repository $ADORepoName | Install-PSResource -TrustRepository + Find-PSResource -Name $testModuleName -Version "1.0.0.0" -Repository $ACRRepoName | Install-PSResource -TrustRepository $res = Get-InstalledPSResource -Name $testModuleName $res.Name | Should -Be $testModuleName $res.Version | Should -Be "1.0.0" } It "Install module using -PassThru" { - $res = Install-PSResource -Name $testModuleName -Repository $ADORepoName -PassThru -TrustRepository + $res = Install-PSResource -Name $testModuleName -Repository $ACRRepoName -PassThru -TrustRepository $res.Name | Should -Contain $testModuleName } } From 323e2cdaea59d3cf9126bfc265ff5ee29fe2404f Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 13 Feb 2024 21:01:52 -0800 Subject: [PATCH 11/57] Update tests --- .../InstallPSResourceACRServer.Tests.ps1 | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 index 24f2b9f1b..7328ce20c 100644 --- a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 @@ -46,13 +46,15 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { $pkg.Version | Should -Be "5.0.0" } + <# TODO: enable after implementing script functionality It "Install specific script resource by name" { Install-PSResource -Name $testScriptName -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testScriptName $pkg.Name | Should -Be $testScriptName $pkg.Version | Should -Be "1.0.0" } - + #> + It "Install multiple resources by name" { $pkgNames = @($testModuleName, $testModuleName2) Install-PSResource -Name $pkgNames -Repository $ACRRepoName -TrustRepository @@ -65,7 +67,7 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { $pkg = Get-InstalledPSResource "NonExistantModule" $pkg | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "InstallPackageFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly "ResourceNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" } # Do some version testing, but Find-PSResource should be doing thorough testing @@ -118,6 +120,7 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { $pkg.Version | Should -Be "5.0.0" } + <# TODO: enable when prerelease functionality is implemented It "Install resource with latest (including prerelease) version given Prerelease parameter" { Install-PSResource -Name $testModuleName -Prerelease -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName @@ -125,6 +128,7 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { $pkg.Version | Should -Be "5.2.5" $pkg.Prerelease | Should -Be "alpha001" } + #> It "Install resource via InputObject by piping from Find-PSresource" { Find-PSResource -Name $testModuleName -Repository $ACRRepoName | Install-PSResource -TrustRepository @@ -134,10 +138,9 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { } It "Install resource with companyname and repository source location and validate properties" { - Install-PSResource -Name $testModuleName -Version "5.2.5-alpha001" -Repository $ACRRepoName -TrustRepository + Install-PSResource -Name $testModuleName -Version "5.0.0" -Repository $ACRRepoName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName - $pkg.Version | Should -Be "5.2.5" - $pkg.Prerelease | Should -Be "alpha001" + $pkg.Version | Should -Be "5.0.0" $pkg.CompanyName | Should -Be "None" $pkg.RepositorySourceLocation | Should -Be $ADORepoUri From d841b253e5e58ba697e18b2e60201f45a400109d Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 13 Feb 2024 21:41:27 -0800 Subject: [PATCH 12/57] Update test --- .../InstallPSResourceACRServer.Tests.ps1 | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 index 7328ce20c..c8de0750a 100644 --- a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 @@ -137,12 +137,14 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { $pkg.Version | Should -Be "5.0.0" } - It "Install resource with companyname and repository source location and validate properties" { - Install-PSResource -Name $testModuleName -Version "5.0.0" -Repository $ACRRepoName -TrustRepository - $pkg = Get-InstalledPSResource $testModuleName - $pkg.Version | Should -Be "5.0.0" - - $pkg.CompanyName | Should -Be "None" + It "Install resource with copyright, description and repository source location and validate properties" { + $testModule = "test_module" + Install-PSResource -Name $testModule -Version "7.0.0" -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModule + $pkg.Name | Should -Be $testModule + $pkg.Version | Should -Be "7.0.0" + $pkg.Copyright | Should -Be "(c) Anam Navied. All rights reserved." + $pkg.Description | Should -Be "This is a test module, for PSGallery team internal testing. Do not take a dependency on this package. This version contains tags for the package." $pkg.RepositorySourceLocation | Should -Be $ADORepoUri } From 7e3831284c82f663ce37206d5243147881f387ac Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 13 Feb 2024 21:53:27 -0800 Subject: [PATCH 13/57] Update test --- .../InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 index c8de0750a..0d0952588 100644 --- a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 @@ -145,7 +145,7 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { $pkg.Version | Should -Be "7.0.0" $pkg.Copyright | Should -Be "(c) Anam Navied. All rights reserved." $pkg.Description | Should -Be "This is a test module, for PSGallery team internal testing. Do not take a dependency on this package. This version contains tags for the package." - $pkg.RepositorySourceLocation | Should -Be $ADORepoUri + $pkg.RepositorySourceLocation | Should -Be $ACRRepoUri } # Windows only From 2e1a9f46089fe3ceb41a42f7c5c327a0ab642ef1 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 13 Feb 2024 22:32:06 -0800 Subject: [PATCH 14/57] update test --- .../InstallPSResourceACRServer.Tests.ps1 | 270 ++++++++++++++++++ 1 file changed, 270 insertions(+) create mode 100644 test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 diff --git a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 new file mode 100644 index 000000000..655d06ce6 --- /dev/null +++ b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 @@ -0,0 +1,270 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +$ProgressPreference = "SilentlyContinue" +$modPath = "$psscriptroot/../PSGetTestUtils.psm1" +Import-Module $modPath -Force -Verbose + +Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { + + BeforeAll { + $testModuleName = "test_local_mod" + $testModuleName2 = "test_local_mod2" + $testScriptName = "test_ado_script" + $ACRRepoName = "ACRRepo" + $ACRRepoUri = "https://psresourcegettest.azurecr.io/" + Get-NewPSResourceRepositoryFile + $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") + Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'acr' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose + } + + AfterEach { + Uninstall-PSResource $testModuleName, $testModuleName2, $testScriptName -Version "*" -SkipDependencyCheck -ErrorAction SilentlyContinue + } + + AfterAll { + Get-RevertPSResourceRepositoryFile + } + + $testCases = @{Name="*"; ErrorId="NameContainsWildcard"}, + @{Name="Test_local_m*"; ErrorId="NameContainsWildcard"}, + @{Name="Test?local","Test[local"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} + + It "Should not install resource with wildcard in name" -TestCases $testCases { + param($Name, $ErrorId) + Install-PSResource -Name $Name -Repository $ACRRepoName -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + $res = Get-InstalledPSResource $testModuleName + $res | Should -BeNullOrEmpty + } + + It "Install specific module resource by name" { + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + <# TODO: enable after implementing script functionality + It "Install specific script resource by name" { + Install-PSResource -Name $testScriptName -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testScriptName + $pkg.Name | Should -Be $testScriptName + $pkg.Version | Should -Be "1.0.0" + } + #> + + It "Install multiple resources by name" { + $pkgNames = @($testModuleName, $testModuleName2) + Install-PSResource -Name $pkgNames -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $pkgNames + $pkg.Name | Should -Be $pkgNames + } + + It "Should not install resource given nonexistant name" { + Install-PSResource -Name "NonExistantModule" -Repository $ACRRepoName -TrustRepository -ErrorVariable err -ErrorAction SilentlyContinue + $pkg = Get-InstalledPSResource "NonExistantModule" + $pkg | Should -BeNullOrEmpty + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "ResourceNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + } + + # Do some version testing, but Find-PSResource should be doing thorough testing + It "Should install resource given name and exact version" { + Install-PSResource -Name $testModuleName -Version "1.0.0" -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "1.0.0" + } + + It "Should install resource given name and exact version with bracket syntax" { + Install-PSResource -Name $testModuleName -Version "[1.0.0]" -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "1.0.0" + } + + It "Should install resource given name and exact range inclusive [1.0.0, 5.0.0]" { + Install-PSResource -Name $testModuleName -Version "[1.0.0, 5.0.0]" -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + It "Should install resource given name and exact range exclusive (1.0.0, 5.0.0)" { + Install-PSResource -Name $testModuleName -Version "(1.0.0, 5.0.0)" -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "3.0.0" + } + + # TODO: Update this test and others like it that use try/catch blocks instead of Should -Throw + It "Should not install resource with incorrectly formatted version such as exclusive version (1.0.0.0)" { + $Version = "(1.0.0.0)" + try { + Install-PSResource -Name $testModuleName -Version $Version -Repository $ACRRepoName -TrustRepository -ErrorAction SilentlyContinue + } + catch + {} + $Error[0].FullyQualifiedErrorId | Should -be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + + $res = Get-InstalledPSResource $testModuleName + $res | Should -BeNullOrEmpty + } + + It "Install resource when given Name, Version '*', should install the latest version" { + Install-PSResource -Name $testModuleName -Version "*" -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + <# TODO: enable when prerelease functionality is implemented + It "Install resource with latest (including prerelease) version given Prerelease parameter" { + Install-PSResource -Name $testModuleName -Prerelease -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.2.5" + $pkg.Prerelease | Should -Be "alpha001" + } + #> + + It "Install resource via InputObject by piping from Find-PSresource" { + Find-PSResource -Name $testModuleName -Repository $ACRRepoName | Install-PSResource -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + It "Install resource with copyright, description and repository source location and validate properties" { + $testModule = "test_module" + Install-PSResource -Name $testModule -Version "7.0.0" -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModule + $pkg.Name | Should -Be $testModule + $pkg.Version | Should -Be "7.0.0" + $pkg.Copyright | Should -Be "(c) Anam Navied. All rights reserved." + $pkg.Description | Should -Be "This is a test module, for PSGallery team internal testing. Do not take a dependency on this package. This version contains tags for the package." + $pkg.RepositorySourceLocation | Should -Be $ACRRepoUri + } + + # Windows only + It "Install resource under CurrentUser scope - Windows only" -Skip:(!(Get-IsWindows)) { + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository -Scope CurrentUser + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("Documents") | Should -Be $true + } + + # Windows only + It "Install resource under AllUsers scope - Windows only" -Skip:(!((Get-IsWindows) -and (Test-IsAdmin))) { + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository -Scope AllUsers -Verbose + $pkg = Get-InstalledPSResource $testModuleName -Scope AllUsers + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("Program Files") | Should -Be $true + } + + # Windows only + It "Install resource under no specified scope - Windows only" -Skip:(!(Get-IsWindows)) { + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("Documents") | Should -Be $true + } + + # Unix only + # Expected path should be similar to: '/home/janelane/.local/share/powershell/Modules' + It "Install resource under CurrentUser scope - Unix only" -Skip:(Get-IsWindows) { + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository -Scope CurrentUser + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("$env:HOME/.local") | Should -Be $true + } + + # Unix only + # Expected path should be similar to: '/home/janelane/.local/share/powershell/Modules' + It "Install resource under no specified scope - Unix only" -Skip:(Get-IsWindows) { + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.InstalledLocation.ToString().Contains("$env:HOME/.local") | Should -Be $true + } + + It "Should not install resource that is already installed" { + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository -WarningVariable WarningVar -warningaction SilentlyContinue + $WarningVar | Should -Not -BeNullOrEmpty + } + + It "Reinstall resource that is already installed with -Reinstall parameter" { + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + Install-PSResource -Name $testModuleName -Repository $ACRRepoName -Reinstall -TrustRepository + $pkg = Get-InstalledPSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + $pkg.Version | Should -Be "5.0.0" + } + + It "Install PSResourceInfo object piped in" { + Find-PSResource -Name $testModuleName -Version "1.0.0.0" -Repository $ACRRepoName | Install-PSResource -TrustRepository + $res = Get-InstalledPSResource -Name $testModuleName + $res.Name | Should -Be $testModuleName + $res.Version | Should -Be "1.0.0" + } + + It "Install module using -PassThru" { + $res = Install-PSResource -Name $testModuleName -Repository $ACRRepoName -PassThru -TrustRepository + $res.Name | Should -Contain $testModuleName + } +} + +Describe 'Test Install-PSResource for V3Server scenarios' -tags 'ManualValidationOnly' { + + BeforeAll { + $testModuleName = "TestModule" + $testModuleName2 = "testModuleWithlicense" + Get-NewPSResourceRepositoryFile + Register-LocalRepos + } + + AfterEach { + Uninstall-PSResource $testModuleName, $testModuleName2 -SkipDependencyCheck -ErrorAction SilentlyContinue + } + + AfterAll { + Get-RevertPSResourceRepositoryFile + } + + # Unix only manual test + # Expected path should be similar to: '/usr/local/share/powershell/Modules' + It "Install resource under AllUsers scope - Unix only" -Skip:(Get-IsWindows) { + Install-PSResource -Name $testModuleName -Repository $TestGalleryName -Scope AllUsers + $pkg = Get-Module $testModuleName -ListAvailable + $pkg.Name | Should -Be $testModuleName + $pkg.Path.Contains("/usr/") | Should -Be $true + } + + # This needs to be manually tested due to prompt + It "Install resource that requires accept license without -AcceptLicense flag" { + Install-PSResource -Name $testModuleName2 -Repository $TestGalleryName + $pkg = Get-InstalledPSResource $testModuleName2 + $pkg.Name | Should -Be $testModuleName2 + $pkg.Version | Should -Be "0.0.1.0" + } + + # This needs to be manually tested due to prompt + It "Install resource should prompt 'trust repository' if repository is not trusted" { + Set-PSResourceRepository PoshTestGallery -Trusted:$false + + Install-PSResource -Name $testModuleName -Repository $TestGalleryName -confirm:$false + + $pkg = Get-Module $testModuleName -ListAvailable + $pkg.Name | Should -Be $testModuleName + + Set-PSResourceRepository PoshTestGallery -Trusted + } +} From e1ad8352634fa0e7c3df09175fef0420715f58a3 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 13 Feb 2024 22:35:08 -0800 Subject: [PATCH 15/57] Add / to repo uri --- .../InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 index 0d0952588..655d06ce6 100644 --- a/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceACRServer.Tests.ps1 @@ -12,7 +12,7 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { $testModuleName2 = "test_local_mod2" $testScriptName = "test_ado_script" $ACRRepoName = "ACRRepo" - $ACRRepoUri = "https://psresourcegettest.azurecr.io" + $ACRRepoUri = "https://psresourcegettest.azurecr.io/" Get-NewPSResourceRepositoryFile $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'acr' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose From b7f8f476f29cf5ea65b834eb81d73eeca126450e Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 13 Feb 2024 22:50:22 -0800 Subject: [PATCH 16/57] Add debugging --- .../InstallPSResourceGithubPackages.Tests.ps1 | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 index c8ed9cd96..44a3ff6e1 100644 --- a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 @@ -5,7 +5,7 @@ $ProgressPreference = "SilentlyContinue" $modPath = "$psscriptroot/../PSGetTestUtils.psm1" Import-Module $modPath -Force -Verbose -Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { +Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { BeforeAll { $testModuleName = "test_module" @@ -38,6 +38,9 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { $err.Count | Should -BeGreaterThan 0 $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" $res = Get-InstalledPSResource $testModuleName + Write-Output ($res.Name) + $res.Count | Should -Be 1 + $res.Name | Should -Be "Test_local_module" $res | Should -BeNullOrEmpty } From 5f46a60c4ee34b1af0f813f8d63f4466ca9221c0 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 13 Feb 2024 23:16:40 -0800 Subject: [PATCH 17/57] Add separate tests for install -Name '*' --- .../InstallPSResourceGithubPackages.Tests.ps1 | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 index 44a3ff6e1..5f4df50dc 100644 --- a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 @@ -28,8 +28,7 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { Get-RevertPSResourceRepositoryFile } - $testCases = @{Name="*"; ErrorId="NameContainsWildcard"}, - @{Name="Test_local_m*"; ErrorId="NameContainsWildcard"}, + $testCases = @{Name="Test_local_m*"; ErrorId="NameContainsWildcard"}, @{Name="Test?local","Test[local"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} It "Should not install resource with wildcard in name" -TestCases $testCases { @@ -38,9 +37,16 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { $err.Count | Should -BeGreaterThan 0 $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" $res = Get-InstalledPSResource $testModuleName - Write-Output ($res.Name) + $res | Should -BeNullOrEmpty + } + + It "Should install resource with -Name '*'" { + Install-PSResource -Name "*" -Repository $GithubPackagesRepoName -Credential $credential -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + $res = Get-InstalledPSResource $testModuleName $res.Count | Should -Be 1 - $res.Name | Should -Be "Test_local_module" + $res.Name | Should -Be "test_module" $res | Should -BeNullOrEmpty } From 429a864d6316e825500af595c570fe8a622fdfd7 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 13 Feb 2024 23:43:57 -0800 Subject: [PATCH 18/57] update github wildcard tests --- .../InstallPSResourceGithubPackages.Tests.ps1 | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 index 5f4df50dc..9b740d2e9 100644 --- a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 @@ -28,25 +28,29 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { Get-RevertPSResourceRepositoryFile } - $testCases = @{Name="Test_local_m*"; ErrorId="NameContainsWildcard"}, - @{Name="Test?local","Test[local"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} + It "Should not install resource with wildcard in name" { + Install-PSResource -Name "Test?module" -Repository $GithubPackagesRepoName -Credential $credential -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -BeGreaterThan 0 + $err[0].FullyQualifiedErrorId | Should -BeExactly "NameContainsWildcard,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + $res = Get-InstalledPSResource $testModuleName + $res | Should -BeNullOrEmpty + } - It "Should not install resource with wildcard in name" -TestCases $testCases { - param($Name, $ErrorId) - Install-PSResource -Name $Name -Repository $GithubPackagesRepoName -Credential $credential -ErrorVariable err -ErrorAction SilentlyContinue + It "Should install resource with wildcard at end of name" { + Install-PSResource -Name "Test_m*" -Repository $GithubPackagesRepoName -Credential $credential -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -BeGreaterThan 0 $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" $res = Get-InstalledPSResource $testModuleName + $res.Count | Should -Be 1 + $res.Name | Should -Be "test_module" $res | Should -BeNullOrEmpty } It "Should install resource with -Name '*'" { Install-PSResource -Name "*" -Repository $GithubPackagesRepoName -Credential $credential -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly "NameContainsWildcard,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" $res = Get-InstalledPSResource $testModuleName - $res.Count | Should -Be 1 - $res.Name | Should -Be "test_module" $res | Should -BeNullOrEmpty } From 83c68917fc9406c21ff0538eae2d8ac62662a8ae Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 13 Feb 2024 23:57:15 -0800 Subject: [PATCH 19/57] update github tests --- .../InstallPSResourceGithubPackages.Tests.ps1 | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 index 9b740d2e9..8d4f763f4 100644 --- a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 @@ -39,10 +39,8 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { It "Should install resource with wildcard at end of name" { Install-PSResource -Name "Test_m*" -Repository $GithubPackagesRepoName -Credential $credential -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorFilteringNamesForUnsupportedWildcards,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" $res = Get-InstalledPSResource $testModuleName - $res.Count | Should -Be 1 - $res.Name | Should -Be "test_module" $res | Should -BeNullOrEmpty } From 3e54e61a5306d85ac0db885b2a7330ff0aa311d0 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 00:00:58 -0800 Subject: [PATCH 20/57] update tests --- .../InstallPSResourceGithubPackages.Tests.ps1 | 24 ++++++------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 index 8d4f763f4..2a69a6fe4 100644 --- a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 @@ -28,29 +28,19 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { Get-RevertPSResourceRepositoryFile } - It "Should not install resource with wildcard in name" { - Install-PSResource -Name "Test?module" -Repository $GithubPackagesRepoName -Credential $credential -ErrorVariable err -ErrorAction SilentlyContinue - $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "NameContainsWildcard,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" - $res = Get-InstalledPSResource $testModuleName - $res | Should -BeNullOrEmpty - } + $testCases = @{Name="*"; ErrorId="NameContainsWildcard"}, + @{Name="Test_m*"; ErrorId="NameContainsWildcard"}, + @{Name="Test?module","Test[module"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} - It "Should install resource with wildcard at end of name" { - Install-PSResource -Name "Test_m*" -Repository $GithubPackagesRepoName -Credential $credential -ErrorVariable err -ErrorAction SilentlyContinue + It "Should not install resource with wildcard in name" -TestCases $testCases { + param($Name, $ErrorId) + Install-PSResource -Name $Name -Repository $GithubPackagesRepoName -Credential $credential -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorFilteringNamesForUnsupportedWildcards,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" $res = Get-InstalledPSResource $testModuleName $res | Should -BeNullOrEmpty } - It "Should install resource with -Name '*'" { - Install-PSResource -Name "*" -Repository $GithubPackagesRepoName -Credential $credential -ErrorVariable err -ErrorAction SilentlyContinue - $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "NameContainsWildcard,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" - $res = Get-InstalledPSResource $testModuleName - $res | Should -BeNullOrEmpty - } It "Install specific module resource by name" { Install-PSResource -Name $testModuleName -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository From a45cafc98cdf5ee2a3100fba3b8774f047a8d1ab Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 00:01:15 -0800 Subject: [PATCH 21/57] Remove whitespace --- .../InstallPSResourceGithubPackages.Tests.ps1 | 1 - 1 file changed, 1 deletion(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 index 2a69a6fe4..a45175290 100644 --- a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 @@ -41,7 +41,6 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { $res | Should -BeNullOrEmpty } - It "Install specific module resource by name" { Install-PSResource -Name $testModuleName -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository $pkg = Get-InstalledPSResource $testModuleName From b3d4bd5cecf99d7a7978367b798c046566f740da Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 00:54:56 -0800 Subject: [PATCH 22/57] uninstall all test resources before running tests --- .../InstallPSResourceGithubPackages.Tests.ps1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 index a45175290..79b520ac2 100644 --- a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 @@ -8,6 +8,8 @@ Import-Module $modPath -Force -Verbose Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { BeforeAll { + Uninstall-PSResource $testModuleName, $testScriptName -Version "*" -SkipDependencyCheck -ErrorAction SilentlyContinue + $testModuleName = "test_module" $testModuleName2 = "test_module2" $testScriptName = "test_script" From d1bfd3c65fd78e30769ae140ecc43fab4791c78e Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 09:43:26 -0800 Subject: [PATCH 23/57] Move uninstall to end of beforeall statement --- .../InstallPSResourceGithubPackages.Tests.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 index 79b520ac2..7c4e68d6a 100644 --- a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 @@ -8,8 +8,6 @@ Import-Module $modPath -Force -Verbose Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { BeforeAll { - Uninstall-PSResource $testModuleName, $testScriptName -Version "*" -SkipDependencyCheck -ErrorAction SilentlyContinue - $testModuleName = "test_module" $testModuleName2 = "test_module2" $testScriptName = "test_script" @@ -20,6 +18,8 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { $secureString = ConvertTo-SecureString $env:MAPPED_GITHUB_PAT -AsPlainText -Force $credential = New-Object pscredential ($env:GITHUB_USERNAME, $secureString) + + Uninstall-PSResource $testModuleName, $testScriptName -Version "*" -SkipDependencyCheck -ErrorAction SilentlyContinue } AfterEach { From ce048e6e99b7eed987c838a2b1d679b74262209c Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 15:54:38 -0800 Subject: [PATCH 24/57] Finish up modifying tests --- .../PublishPSResourceACRServer.Tests.ps1 | 58 ++++++++++--------- 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 750bf51ff..edba07bad 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -4,13 +4,12 @@ $modPath = "$psscriptroot/../PSGetTestUtils.psm1" Import-Module $modPath -Force -Verbose -$testDir = (get-item $psscriptroot).parent.FullName function CreateTestModule { param ( [string] $Path = "$TestDrive", - [string] $ModuleName = 'TEMP-PSResourceGetTempTestModule' + [string] $ModuleName = 'temp-psresourcegettemptestmodule' ) $modulePath = Join-Path -Path $Path -ChildPath $ModuleName @@ -44,6 +43,7 @@ function CreateTestModule Describe "Test Publish-PSResource" -tags 'CI' { BeforeAll { + $script:testDir = (get-item $psscriptroot).parent.FullName Get-NewPSResourceRepositoryFile # Register repositories @@ -54,7 +54,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { # Create module $script:tmpModulesPath = Join-Path -Path $TestDrive -ChildPath "tmpModulesPath" - $script:PublishModuleName = "TEMP-PSResourceGetTempTestModule" + $script:PublishModuleName = "temp-psresourcegettemptestmodule" $script:PublishModuleBase = Join-Path $script:tmpModulesPath -ChildPath $script:PublishModuleName if(!(Test-Path $script:PublishModuleBase)) { @@ -82,7 +82,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { } # Path to folder, within our test folder, where we store invalid module and script files used for testing - $script:testFilesFolderPath = Join-Path $testDir -ChildPath "testFiles" + $script:testFilesFolderPath = Join-Path $script:testDir -ChildPath "testFiles" # Path to specifically to that invalid test modules folder $script:testModulesFolderPath = Join-Path $script:testFilesFolderPath -ChildPath "testModules" @@ -95,7 +95,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { } It "Publish module with required module not installed on the local machine using -SkipModuleManifestValidate" { - $ModuleName = "TEMP-ModuleWithMissingRequiredModule" + $ModuleName = "ModuleWithMissingRequiredModule" CreateTestModule -Path $TestDrive -ModuleName $ModuleName # Skip the module manifest validation test, which fails from the missing manifest required module. @@ -111,10 +111,10 @@ Describe "Test Publish-PSResource" -tags 'CI' { It "Publish a module with -Path pointing to a module directory (parent directory has same name)" { $version = "1.0.0" New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName - Publish-PSResource -Path $script:PublishModuleBase -Repository $testRepository2 - - $results = Find-PSResource -Name ModuleWithMissingRequiredModule -Repository $ACRRepoName + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName $results | Should -Not -BeNullOrEmpty $results[0].Name | Should -Be $script:PublishModuleName $results[0].Version | Should -Be $version @@ -126,9 +126,9 @@ Describe "Test Publish-PSResource" -tags 'CI' { New-Item -Path $newModuleRoot -ItemType Directory New-ModuleManifest -Path (Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" - Publish-PSResource -Path $newModuleRoot -Repository $testRepository2 + Publish-PSResource -Path $newModuleRoot -Repository $ACRRepoName - $results = Find-PSResource -Name ModuleWithMissingRequiredModule -Repository $ACRRepoName + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName $results | Should -Not -BeNullOrEmpty $results[0].Name | Should -Be $script:PublishModuleName $results[0].Version | Should -Be $version @@ -139,9 +139,9 @@ Describe "Test Publish-PSResource" -tags 'CI' { $manifestPath = Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1" New-ModuleManifest -Path $manifestPath -ModuleVersion $version -Description "$script:PublishModuleName module" - Publish-PSResource -Path $manifestPath -Repository $testRepository2 + Publish-PSResource -Path $manifestPath -Repository $ACRRepoName - $results = Find-PSResource -Name ModuleWithMissingRequiredModule -Repository $ACRRepoName + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName $results | Should -Not -BeNullOrEmpty $results[0].Name | Should -Be $script:PublishModuleName $results[0].Version | Should -Be $version @@ -154,9 +154,9 @@ Describe "Test Publish-PSResource" -tags 'CI' { $manifestPath = Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1" New-ModuleManifest -Path $manifestPath -ModuleVersion $version -Description "$script:PublishModuleName module" - Publish-PSResource -Path $manifestPath -Repository $testRepository2 + Publish-PSResource -Path $manifestPath -Repository $ACRRepoName - $results = Find-PSResource -Name ModuleWithMissingRequiredModule -Repository $ACRRepoName + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName $results | Should -Not -BeNullOrEmpty $results[0].Name | Should -Be $script:PublishModuleName $results[0].Version | Should -Be $version @@ -224,7 +224,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName - Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -Force -AsNupkg -Path $TestDrive + Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell $nupkgPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName.$version.nupkg" $zipPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName.$version.zip" @@ -242,7 +242,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName -DestinationPath $script:destinationPath - $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -Version $version $results | Should -Not -BeNullOrEmpty $results[0].Name | Should -Be $script:PublishModuleName $results[0].Version | Should -Be $version @@ -262,7 +262,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName - $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -Version $version $results | Should -Not -BeNullOrEmpty $results[0].Name | Should -Be $script:PublishModuleName $results[0].Version | Should -Be $version @@ -278,12 +278,13 @@ Describe "Test Publish-PSResource" -tags 'CI' { Publish-PSResource -Path $modManifestPath -Repository $ACRRepoName - $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName + $results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -Version $correctVersion $results | Should -Not -BeNullOrEmpty $results[0].Name | Should -Be $script:PublishModuleName $results[0].Version | Should -Be $correctVersion } + <# TODO: enable with scripts are supported in ACR It "Publish a script"{ $scriptName = "TEMP-PSGetTestScript" $scriptVersion = "1.0.0" @@ -352,7 +353,8 @@ Describe "Test Publish-PSResource" -tags 'CI' { $results[0].Name | Should -Be $scriptName $results[0].Version | Should -Be $scriptVersion } - + #> + It "Should write error and not publish script when Author property is missing" { $scriptName = "InvalidScriptMissingAuthor.ps1" @@ -363,7 +365,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { Find-PSResource -Name $scriptName -Repository $ACRRepoName -ErrorVariable findErr -ErrorAction SilentlyContinue $findErr.Count | Should -BeGreaterThan 0 - $findErr[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $findErr[0].FullyQualifiedErrorId | Should -BeExactly "ResourceNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" } It "Should write error and not publish script when Version property is missing" { @@ -376,7 +378,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { Find-PSResource -Name $scriptName -Repository $ACRRepoName -ErrorVariable findErr -ErrorAction SilentlyContinue $findErr.Count | Should -BeGreaterThan 0 - $findErr[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $findErr[0].FullyQualifiedErrorId | Should -BeExactly "ResourceNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" } It "Should write error and not publish script when Guid property is missing" { @@ -389,7 +391,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { Find-PSResource -Name $scriptName -Repository $ACRRepoName -ErrorVariable findErr -ErrorAction SilentlyContinue $findErr.Count | Should -BeGreaterThan 0 - $findErr[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $findErr[0].FullyQualifiedErrorId | Should -BeExactly "ResourceNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" } It "Should write error and not publish script when Description property is missing" { @@ -402,7 +404,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { Find-PSResource -Name $scriptName -Repository $ACRRepoName -ErrorVariable findErr -ErrorAction SilentlyContinue $findErr.Count | Should -BeGreaterThan 0 - $findErr[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $findErr[0].FullyQualifiedErrorId | Should -BeExactly "ResourceNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" } It "Should write error and not publish script when Description block altogether is missing" { @@ -416,22 +418,22 @@ Describe "Test Publish-PSResource" -tags 'CI' { Find-PSResource -Name $scriptName -Repository $ACRRepoName -ErrorVariable findErr -ErrorAction SilentlyContinue $findErr.Count | Should -BeGreaterThan 0 - $findErr[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $findErr[0].FullyQualifiedErrorId | Should -BeExactly "ResourceNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" } It "Publish a module with that has an invalid version format, should throw" { - $moduleName = "TEMP-incorrectmoduleversion" + $moduleName = "incorrectmoduleversion" $incorrectmoduleversion = Join-Path -Path $script:testModulesFolderPath -ChildPath $moduleName - {Publish-PSResource -Path $incorrectmoduleversion -Repository $ACRRepoName -ErrorAction Stop} | Should -Throw -ErrorId "InvalidModuleManifest,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + { Publish-PSResource -Path $incorrectmoduleversion -Repository $ACRRepoName -ErrorAction Stop } | Should -Throw -ErrorId "InvalidModuleManifest,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" } It "Publish a module with a dependency that has an invalid version format, should throw" { - $moduleName = "TEMP-incorrectdepmoduleversion" + $moduleName = "incorrectdepmoduleversion" $incorrectdepmoduleversion = Join-Path -Path $script:testModulesFolderPath -ChildPath $moduleName - {Publish-PSResource -Path $incorrectdepmoduleversion -Repository $ACRRepoName -ErrorAction Stop} | Should -Throw -ErrorId "InvalidModuleManifest,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + { Publish-PSResource -Path $incorrectdepmoduleversion -Repository $ACRRepoName -ErrorAction Stop } | Should -Throw -ErrorId "InvalidModuleManifest,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" } It "Publish a module with using an invalid file path (path to .psm1), should throw" { From 63ed03c73cd3322b4a2a5d9e8f7e0bdad036bb14 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 16:13:25 -0800 Subject: [PATCH 25/57] Add GUID to test module name --- .../PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index edba07bad..c17ca7761 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -54,7 +54,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { # Create module $script:tmpModulesPath = Join-Path -Path $TestDrive -ChildPath "tmpModulesPath" - $script:PublishModuleName = "temp-psresourcegettemptestmodule" + $script:PublishModuleName = "temp-psresourcegettemptestmodule" + [System.Guid]::NewGuid(); $script:PublishModuleBase = Join-Path $script:tmpModulesPath -ChildPath $script:PublishModuleName if(!(Test-Path $script:PublishModuleBase)) { From 41571941b62e86fd8724e45b75d21de836a523cb Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 16:19:32 -0800 Subject: [PATCH 26/57] Add GUID to 'ModuleWithMissingRequiredModule' --- .../PublishPSResourceACRServer.Tests.ps1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index c17ca7761..3a89f8892 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -95,14 +95,14 @@ Describe "Test Publish-PSResource" -tags 'CI' { } It "Publish module with required module not installed on the local machine using -SkipModuleManifestValidate" { - $ModuleName = "ModuleWithMissingRequiredModule" + $ModuleName = "ModuleWithMissingRequiredModule-" + [System.Guid]::NewGuid() CreateTestModule -Path $TestDrive -ModuleName $ModuleName # Skip the module manifest validation test, which fails from the missing manifest required module. - $testModulePath = Join-Path -Path $TestDrive -ChildPath ModuleWithMissingRequiredModule + $testModulePath = Join-Path -Path $TestDrive -ChildPath $ModuleName Publish-PSResource -Path $testModulePath -Repository $ACRRepoName -Confirm:$false -SkipDependenciesCheck -SkipModuleManifestValidate - $results = Find-PSResource -Name ModuleWithMissingRequiredModule -Repository $ACRRepoName + $results = Find-PSResource -Name $ModuleName -Repository $ACRRepoName $results | Should -Not -BeNullOrEmpty $results[0].Name | Should -Be $ModuleName $results[0].Version | Should -Be "1.0.0" From 559244b206a6588b2943944d1f38026b5cf8fb2c Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 16:36:16 -0800 Subject: [PATCH 27/57] Add debugging messages --- .../PublishPSResourceACRServer.Tests.ps1 | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 3a89f8892..aacc896f2 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -98,6 +98,8 @@ Describe "Test Publish-PSResource" -tags 'CI' { $ModuleName = "ModuleWithMissingRequiredModule-" + [System.Guid]::NewGuid() CreateTestModule -Path $TestDrive -ModuleName $ModuleName + Write-Host "*************Module Name: $ModuleName*************" + Write-Verbose -Verbose "*************Module Name: $ModuleName*************" # Skip the module manifest validation test, which fails from the missing manifest required module. $testModulePath = Join-Path -Path $TestDrive -ChildPath $ModuleName Publish-PSResource -Path $testModulePath -Repository $ACRRepoName -Confirm:$false -SkipDependenciesCheck -SkipModuleManifestValidate @@ -222,7 +224,8 @@ Describe "Test Publish-PSResource" -tags 'CI' { New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" New-Item -Path (Join-Path -Path $script:PublishModuleBase -ChildPath $testFile) -Force - Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName + Write-Verbose -Verbose "***************** Module Name: $script:PublishModuleName ******** version 9.0.0 *********" + Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName -Verbose -Debug Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell From 807ed504c33edaf5d28135311697b2095775b856 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 16:37:44 -0800 Subject: [PATCH 28/57] Rerunning tests --- test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index aacc896f2..036bd98c1 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -218,6 +218,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $results[0].Version | Should -Be $version } + # It "Publish a module and preserve file structure" { $version = "9.0.0" $testFile = Join-Path -Path "TestSubDirectory" -ChildPath "TestSubDirFile.ps1" From 36cab7f6664422267264e5b39cdcd86502aca0f9 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 16:55:53 -0800 Subject: [PATCH 29/57] add more debugging message --- .../PublishPSResourceACRServer.Tests.ps1 | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 036bd98c1..7294d5597 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -95,11 +95,9 @@ Describe "Test Publish-PSResource" -tags 'CI' { } It "Publish module with required module not installed on the local machine using -SkipModuleManifestValidate" { - $ModuleName = "ModuleWithMissingRequiredModule-" + [System.Guid]::NewGuid() + $ModuleName = "modulewithmissingrequiredmodule-" + [System.Guid]::NewGuid() CreateTestModule -Path $TestDrive -ModuleName $ModuleName - Write-Host "*************Module Name: $ModuleName*************" - Write-Verbose -Verbose "*************Module Name: $ModuleName*************" # Skip the module manifest validation test, which fails from the missing manifest required module. $testModulePath = Join-Path -Path $TestDrive -ChildPath $ModuleName Publish-PSResource -Path $testModulePath -Repository $ACRRepoName -Confirm:$false -SkipDependenciesCheck -SkipModuleManifestValidate @@ -218,7 +216,6 @@ Describe "Test Publish-PSResource" -tags 'CI' { $results[0].Version | Should -Be $version } - # It "Publish a module and preserve file structure" { $version = "9.0.0" $testFile = Join-Path -Path "TestSubDirectory" -ChildPath "TestSubDirFile.ps1" @@ -226,6 +223,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { New-Item -Path (Join-Path -Path $script:PublishModuleBase -ChildPath $testFile) -Force Write-Verbose -Verbose "***************** Module Name: $script:PublishModuleName ******** version 9.0.0 *********" + Write-Verbose -Verbose "*************** Path contents: $(Get-ChildItem -Path $script:PublishModuleBase -Recurse) *********" Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName -Verbose -Debug Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive From 39c65c64e32040c78b6e965a8e00ce9dfea0393b Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 17:16:19 -0800 Subject: [PATCH 30/57] Comment out test --- .../PublishPSResourceACRServer.Tests.ps1 | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 7294d5597..02d5f73d4 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -44,13 +44,13 @@ function CreateTestModule Describe "Test Publish-PSResource" -tags 'CI' { BeforeAll { $script:testDir = (get-item $psscriptroot).parent.FullName - Get-NewPSResourceRepositoryFile + #Get-NewPSResourceRepositoryFile # Register repositories - $ACRRepoName = "ACRRepo" + $ACRRepoName = "ACRnew" $ACRRepoUri = "https://psresourcegettest.azurecr.io" - $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") - Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'acr' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose + #$psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") + #Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'acr' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose # Create module $script:tmpModulesPath = Join-Path -Path $TestDrive -ChildPath "tmpModulesPath" @@ -91,7 +91,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $script:testScriptsFolderPath = Join-Path $script:testFilesFolderPath -ChildPath "testScripts" } AfterAll { - Get-RevertPSResourceRepositoryFile + #Get-RevertPSResourceRepositoryFile } It "Publish module with required module not installed on the local machine using -SkipModuleManifestValidate" { @@ -216,14 +216,13 @@ Describe "Test Publish-PSResource" -tags 'CI' { $results[0].Version | Should -Be $version } + <# Test working locally but not in CI It "Publish a module and preserve file structure" { $version = "9.0.0" $testFile = Join-Path -Path "TestSubDirectory" -ChildPath "TestSubDirFile.ps1" New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" New-Item -Path (Join-Path -Path $script:PublishModuleBase -ChildPath $testFile) -Force - Write-Verbose -Verbose "***************** Module Name: $script:PublishModuleName ******** version 9.0.0 *********" - Write-Verbose -Verbose "*************** Path contents: $(Get-ChildItem -Path $script:PublishModuleBase -Recurse) *********" Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName -Verbose -Debug Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive @@ -237,7 +236,8 @@ Describe "Test Publish-PSResource" -tags 'CI' { Test-Path -Path (Join-Path -Path $unzippedPath -ChildPath $testFile) | Should -Be $True } - + #> + It "Publish a module with -Path -Repository and -DestinationPath" { $version = "10.0.0" New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" From 79a10cb63c31309758755e13785983b6b0e4aea7 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 14 Feb 2024 17:26:00 -0800 Subject: [PATCH 31/57] Revert changes made for testing locally --- .../PublishPSResourceACRServer.Tests.ps1 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 02d5f73d4..7e5389ad7 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -44,13 +44,13 @@ function CreateTestModule Describe "Test Publish-PSResource" -tags 'CI' { BeforeAll { $script:testDir = (get-item $psscriptroot).parent.FullName - #Get-NewPSResourceRepositoryFile + Get-NewPSResourceRepositoryFile # Register repositories - $ACRRepoName = "ACRnew" + $ACRRepoName = "ACRRepo" $ACRRepoUri = "https://psresourcegettest.azurecr.io" - #$psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") - #Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'acr' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose + $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") + Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'acr' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose # Create module $script:tmpModulesPath = Join-Path -Path $TestDrive -ChildPath "tmpModulesPath" @@ -91,7 +91,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $script:testScriptsFolderPath = Join-Path $script:testFilesFolderPath -ChildPath "testScripts" } AfterAll { - #Get-RevertPSResourceRepositoryFile + Get-RevertPSResourceRepositoryFile } It "Publish module with required module not installed on the local machine using -SkipModuleManifestValidate" { @@ -237,7 +237,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { Test-Path -Path (Join-Path -Path $unzippedPath -ChildPath $testFile) | Should -Be $True } #> - + It "Publish a module with -Path -Repository and -DestinationPath" { $version = "10.0.0" New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" From 23471ca0c0d814c079d4b330850165164b1eab69 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Thu, 15 Feb 2024 12:44:55 -0800 Subject: [PATCH 32/57] Uncomment failing test --- .../PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 7e5389ad7..15ab203f2 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -216,7 +216,6 @@ Describe "Test Publish-PSResource" -tags 'CI' { $results[0].Version | Should -Be $version } - <# Test working locally but not in CI It "Publish a module and preserve file structure" { $version = "9.0.0" $testFile = Join-Path -Path "TestSubDirectory" -ChildPath "TestSubDirFile.ps1" @@ -236,7 +235,6 @@ Describe "Test Publish-PSResource" -tags 'CI' { Test-Path -Path (Join-Path -Path $unzippedPath -ChildPath $testFile) | Should -Be $True } - #> It "Publish a module with -Path -Repository and -DestinationPath" { $version = "10.0.0" From 6b6252bf074c637307020ede15e0bbcbb54aa9f9 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Thu, 15 Feb 2024 13:13:38 -0800 Subject: [PATCH 33/57] Remove -Verbose -Debug --- .../PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 15ab203f2..36fdc2d17 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -222,7 +222,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" New-Item -Path (Join-Path -Path $script:PublishModuleBase -ChildPath $testFile) -Force - Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName -Verbose -Debug + Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell From 15eda3764c611d7b94019338d648975b94f07d96 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Thu, 15 Feb 2024 13:25:39 -0800 Subject: [PATCH 34/57] Add Should Not Throw --- .../PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 36fdc2d17..6edd5f85f 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -222,7 +222,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" New-Item -Path (Join-Path -Path $script:PublishModuleBase -ChildPath $testFile) -Force - Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName + { Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName -ErrorAction Stop } | Should -Not -Throw Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell From d7acba2851442380b3af2cc4328182ab2e24d0cf Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Thu, 15 Feb 2024 13:54:45 -0800 Subject: [PATCH 35/57] Add exception catch to PublishPSResource, and -Force param to New-Item in tests --- src/code/PublishPSResource.cs | 8 ++++++++ .../PublishPSResourceACRServer.Tests.ps1 | 16 +++++++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index afc012653..e4a13e19e 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -505,6 +505,14 @@ out string[] _ } } } + catch (Exception e) + { + WriteError(new ErrorRecord( + new MethodException($"Unexpected error publishing resource: '{e.Message}'"), + "ErrorPublishingPSResource", + ErrorCategory.NotSpecified, + this)); + } finally { WriteVerbose(string.Format("Deleting temporary directory '{0}'", outputDir)); diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 6edd5f85f..62950bb66 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -90,6 +90,12 @@ Describe "Test Publish-PSResource" -tags 'CI' { # Path to specifically to that invalid test scripts folder $script:testScriptsFolderPath = Join-Path $script:testFilesFolderPath -ChildPath "testScripts" } + AfterEach { + if(!(Test-Path $script:DependencyModuleBase)) + { + New-Item -Path $script:DependencyModuleBase -ItemType Directory -Force + } + } AfterAll { Get-RevertPSResourceRepositoryFile } @@ -123,7 +129,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { It "Publish a module with -Path pointing to a module directory (parent directory has different name)" { $version = "2.0.0" $newModuleRoot = Join-Path -Path $script:PublishModuleBase -ChildPath "NewTestParentDirectory" - New-Item -Path $newModuleRoot -ItemType Directory + New-Item -Path $newModuleRoot -ItemType Directory -Force New-ModuleManifest -Path (Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" Publish-PSResource -Path $newModuleRoot -Repository $ACRRepoName @@ -150,7 +156,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { It "Publish a module with -Path pointing to a .psd1 (parent directory has different name)" { $version = "4.0.0" $newModuleRoot = Join-Path -Path $script:PublishModuleBase -ChildPath "NewTestParentDirectory" - New-Item -Path $newModuleRoot -ItemType Directory + New-Item -Path $newModuleRoot -ItemType Directory -Force $manifestPath = Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1" New-ModuleManifest -Path $manifestPath -ModuleVersion $version -Description "$script:PublishModuleName module" @@ -177,7 +183,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { It "Publish a module with -Path pointing to a module directory (parent directory has different name) on a network share" { $version = "6.0.0" $newModuleRoot = Join-Path -Path $script:PublishModuleBaseUNC -ChildPath "NewTestParentDirectory" - New-Item -Path $newModuleRoot -ItemType Directory + New-Item -Path $newModuleRoot -ItemType Directory -Force New-ModuleManifest -Path (Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" Publish-PSResource -Path $newModuleRoot -Repository $ACRRepoName @@ -204,7 +210,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { It "Publish a module with -Path pointing to a .psd1 (parent directory has different name) on a network share" { $version = "8.0.0" $newModuleRoot = Join-Path -Path $script:PublishModuleBaseUNC -ChildPath "NewTestParentDirectory" - New-Item -Path $newModuleRoot -ItemType Directory + New-Item -Path $newModuleRoot -ItemType Directory -Force $manifestPath = Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1" New-ModuleManifest -Path $manifestPath -ModuleVersion $version -Description "$script:PublishModuleName module" @@ -272,7 +278,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $incorrectVersion = "15.2.4" $correctVersion = "12.0.0" $versionBase = (Join-Path -Path $script:PublishModuleBase -ChildPath $incorrectVersion) - New-Item -Path $versionBase -ItemType Directory + New-Item -Path $versionBase -ItemType Directory -Force $modManifestPath = (Join-Path -Path $versionBase -ChildPath "$script:PublishModuleName.psd1") New-ModuleManifest -Path $modManifestPath -ModuleVersion $correctVersion -Description "$script:PublishModuleName module" From 3caf02cb20b8bb6361796d402de7d85b7ea35494 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Thu, 15 Feb 2024 16:29:45 -0800 Subject: [PATCH 36/57] ThrowTerminatingError in PublishPSResource, delete ModuleBase dir after each unit test --- src/code/PublishPSResource.cs | 2 +- .../PublishPSResourceACRServer.Tests.ps1 | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index e4a13e19e..2c8d35075 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -507,7 +507,7 @@ out string[] _ } catch (Exception e) { - WriteError(new ErrorRecord( + ThrowTerminatingError(new ErrorRecord( new MethodException($"Unexpected error publishing resource: '{e.Message}'"), "ErrorPublishingPSResource", ErrorCategory.NotSpecified, diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 62950bb66..8f7bda99c 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -91,9 +91,9 @@ Describe "Test Publish-PSResource" -tags 'CI' { $script:testScriptsFolderPath = Join-Path $script:testFilesFolderPath -ChildPath "testScripts" } AfterEach { - if(!(Test-Path $script:DependencyModuleBase)) + if(!(Test-Path $script:PublishModuleBase)) { - New-Item -Path $script:DependencyModuleBase -ItemType Directory -Force + Remove-Item -Path $script:PublishModuleBase -Recurse -Force } } AfterAll { From b32c2c898283e41b6fa94d6dedba5439cf383d20 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Thu, 15 Feb 2024 18:18:48 -0800 Subject: [PATCH 37/57] Add 'throw e' to catch block --- src/code/PublishPSResource.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index 2c8d35075..0c9906a11 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -507,11 +507,7 @@ out string[] _ } catch (Exception e) { - ThrowTerminatingError(new ErrorRecord( - new MethodException($"Unexpected error publishing resource: '{e.Message}'"), - "ErrorPublishingPSResource", - ErrorCategory.NotSpecified, - this)); + throw e; } finally { From e3d5db5cf27635e34a7f7e9dc67af31b3cfd9455 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 15 Feb 2024 18:49:56 -0800 Subject: [PATCH 38/57] Ensure that exception is not swallowed by finally block --- src/code/InstallHelper.cs | 28 +++++++++---- src/code/PublishPSResource.cs | 20 +++++---- src/code/UpdateModuleManifest.cs | 39 ++++++++++++++---- src/code/Utils.cs | 70 +++++++++++++++++--------------- 4 files changed, 99 insertions(+), 58 deletions(-) diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index d7c3e9cd4..a2135ab76 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -95,7 +95,7 @@ public IEnumerable BeginInstallPackages( { _cmdletPassedIn.WriteDebug("In InstallHelper::BeginInstallPackages()"); _cmdletPassedIn.WriteDebug(string.Format("Parameters passed in >>> Name: '{0}'; VersionRange: '{1}'; NuGetVersion: '{2}'; VersionType: '{3}'; Version: '{4}'; Prerelease: '{5}'; Repository: '{6}'; " + - "AcceptLicense: '{7}'; Quiet: '{8}'; Reinstall: '{9}'; TrustRepository: '{10}'; NoClobber: '{11}'; AsNupkg: '{12}'; IncludeXml '{13}'; SavePackage '{14}'; TemporaryPath '{15}'; SkipDependencyCheck: '{16}'; " + + "AcceptLicense: '{7}'; Quiet: '{8}'; Reinstall: '{9}'; TrustRepository: '{10}'; NoClobber: '{11}'; AsNupkg: '{12}'; IncludeXml '{13}'; SavePackage '{14}'; TemporaryPath '{15}'; SkipDependencyCheck: '{16}'; " + "AuthenticodeCheck: '{17}'; PathsToInstallPkg: '{18}'; Scope '{19}'", string.Join(",", names), versionRange != null ? (versionRange.OriginalString != null ? versionRange.OriginalString : string.Empty) : string.Empty, @@ -265,7 +265,7 @@ private List ProcessRepositories( List repositoryNamesToSearch = new List(); bool sourceTrusted = false; - // Loop through all the repositories provided (in priority order) until there no more packages to install. + // Loop through all the repositories provided (in priority order) until there no more packages to install. for (int i = 0; i < listOfRepositories.Count && _pkgNamesToInstall.Count > 0; i++) { PSRepositoryInfo currentRepository = listOfRepositories[i]; @@ -614,7 +614,7 @@ private List InstallPackages( depFindFailed = true; continue; } - + if (String.Equals(depPkg.Name, parentPkgObj.Name, StringComparison.OrdinalIgnoreCase)) { continue; @@ -683,6 +683,16 @@ private List InstallPackages( } } } + catch (Exception e) + { + _cmdletPassedIn.WriteError(new ErrorRecord( + e, + "InstallPackageFailure", + ErrorCategory.InvalidOperation, + _cmdletPassedIn)); + + throw e; + } finally { DeleteInstallationTempPath(tempInstallPath); @@ -754,14 +764,14 @@ private Hashtable BeginPackageInstall( if (currentResult.exception != null && !currentResult.exception.Message.Equals(string.Empty)) { errRecord = new ErrorRecord( - currentResult.exception, - "FindConvertToPSResourceFailure", - ErrorCategory.ObjectNotFound, + currentResult.exception, + "FindConvertToPSResourceFailure", + ErrorCategory.ObjectNotFound, _cmdletPassedIn); } else if (searchVersionType == VersionType.VersionRange) { - // Check to see if version falls within version range + // Check to see if version falls within version range PSResourceInfo foundPkg = currentResult.returnedObject; string versionStr = $"{foundPkg.Version}"; if (foundPkg.IsPrerelease) @@ -800,7 +810,7 @@ private Hashtable BeginPackageInstall( if (_packagesOnMachine.Contains(currPkgNameVersion)) { _cmdletPassedIn.WriteWarning($"Resource '{pkgToInstall.Name}' with version '{pkgVersion}' is already installed. If you would like to reinstall, please run the cmdlet again with the -Reinstall parameter"); - + // Remove from tracking list of packages to install. _pkgNamesToInstall.RemoveAll(x => x.Equals(pkgToInstall.Name, StringComparison.InvariantCultureIgnoreCase)); @@ -1166,7 +1176,7 @@ private bool TrySaveNupkgToTempPath( /// /// Extracts files from .nupkg - /// Similar functionality as System.IO.Compression.ZipFile.ExtractToDirectory, + /// Similar functionality as System.IO.Compression.ZipFile.ExtractToDirectory, /// but while ExtractToDirectory cannot overwrite files, this method can. /// private bool TryExtractToDirectory(string zipPath, string extractPath, out ErrorRecord error) diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index 0c9906a11..573feb3a2 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -23,8 +23,8 @@ namespace Microsoft.PowerShell.PSResourceGet.Cmdlets /// /// Publishes a module, script, or nupkg to a designated repository. /// - [Cmdlet(VerbsData.Publish, - "PSResource", + [Cmdlet(VerbsData.Publish, + "PSResource", SupportsShouldProcess = true)] [Alias("pbres")] public sealed class PublishPSResource : PSCmdlet @@ -507,6 +507,12 @@ out string[] _ } catch (Exception e) { + WriteError(new ErrorRecord( + e, + "PublishPSResourceError", + ErrorCategory.NotSpecified, + this)); + throw e; } finally @@ -810,7 +816,7 @@ private Hashtable ParseRequiredModules(Hashtable parsedMetadataHash) if (!parsedMetadataHash.ContainsKey("requiredmodules")) { return null; - } + } LanguagePrimitives.TryConvertTo(parsedMetadataHash["requiredmodules"], out object[] requiredModules); // Required modules can be: @@ -843,7 +849,7 @@ private Hashtable ParseRequiredModules(Hashtable parsedMetadataHash) dependenciesHash.Add(moduleName, string.Empty); } } - var externalModuleDeps = parsedMetadataHash.ContainsKey("ExternalModuleDependencies") ? + var externalModuleDeps = parsedMetadataHash.ContainsKey("ExternalModuleDependencies") ? parsedMetadataHash["ExternalModuleDependencies"] : null; if (externalModuleDeps != null && LanguagePrimitives.TryConvertTo(externalModuleDeps, out string[] externalModuleNames)) @@ -1134,7 +1140,7 @@ private bool PushNupkg(string outputNupkgDir, string repoName, string repoUri, o WriteVerbose(string.Format("Successfully published the resource to '{0}'", repoUri)); error = null; success = true; - + return success; } @@ -1158,7 +1164,7 @@ private void InjectCredentialsToSettings(ISettings settings, IPackageSourceProvi var networkCred = Credential == null ? _networkCredential : Credential.GetNetworkCredential(); string key; - + if (packageSource == null) { @@ -1181,7 +1187,7 @@ private void InjectCredentialsToSettings(ISettings settings, IPackageSourceProvi isPasswordClearText: true, String.Empty)); } - + #endregion } } diff --git a/src/code/UpdateModuleManifest.cs b/src/code/UpdateModuleManifest.cs index 7778875b9..07334d6cd 100644 --- a/src/code/UpdateModuleManifest.cs +++ b/src/code/UpdateModuleManifest.cs @@ -668,6 +668,17 @@ private void CreateModuleManifestHelper(Hashtable parsedMetadata, string resolve WriteVerbose($"Moving '{tmpModuleManifestPath}' to '{resolvedManifestPath}'"); Utils.MoveFiles(tmpModuleManifestPath, resolvedManifestPath, overwrite: true); } + catch (Exception e) + { + errorRecord = new ErrorRecord( + e, + "CreateModuleManifestFailed", + ErrorCategory.InvalidOperation, + this); + + throw e; + } + finally { // Clean up temp file if move fails if (File.Exists(tmpModuleManifestPath)) @@ -970,7 +981,7 @@ private void CreateModuleManifestForWinPSHelper(Hashtable parsedMetadata, string "ErrorCreatingTempDir", ErrorCategory.InvalidData, this); - + return; } @@ -1007,7 +1018,7 @@ private void CreateModuleManifestForWinPSHelper(Hashtable parsedMetadata, string string privateDataString = GetPrivateDataString(tags, licenseUri, projectUri, iconUri, releaseNotes, prerelease, requireLicenseAcceptance, externalModuleDependencies); - // create new file in tmp path for updated module manifest (i.e updated with PrivateData entry) + // create new file in tmp path for updated module manifest (i.e updated with PrivateData entry) string newTmpModuleManifestPath = System.IO.Path.Combine(tmpParentPath, "Updated" + System.IO.Path.GetFileName(resolvedManifestPath)); if (!TryCreateNewPsd1WithUpdatedPrivateData(privateDataString, tmpModuleManifestPath, newTmpModuleManifestPath, out errorRecord)) { @@ -1020,6 +1031,16 @@ private void CreateModuleManifestForWinPSHelper(Hashtable parsedMetadata, string WriteVerbose($"Moving '{newTmpModuleManifestPath}' to '{resolvedManifestPath}'"); Utils.MoveFiles(newTmpModuleManifestPath, resolvedManifestPath, overwrite: true); } + catch (Exception e) + { + errorRecord = new ErrorRecord( + e, + "CreateModuleManifestForWinPSFailed", + ErrorCategory.InvalidOperation, + this); + + throw e; + } finally { // Clean up temp file if move fails if (File.Exists(tmpModuleManifestPath)) @@ -1043,7 +1064,7 @@ private string GetPrivateDataString(string[] tags, Uri licenseUri, Uri projectUr { /** Example PrivateData - + PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. @@ -1069,15 +1090,15 @@ Example PrivateData # External dependent modules of this module ExternalModuleDependencies = @('ModuleDep1, 'ModuleDep2') - + } # End of PSData hashtable - + } # End of PrivateData hashtable */ string tagsString = string.Join(", ", tags.Select(item => "'" + item + "'")); string tagLine = tags.Length != 0 ? $"Tags = @({tagsString})" : "# Tags = @()"; - + string licenseUriLine = licenseUri == null ? "# LicenseUri = ''" : $"LicenseUri = '{licenseUri.ToString()}'"; string projectUriLine = projectUri == null ? "# ProjectUri = ''" : $"ProjectUri = '{projectUri.ToString()}'"; string iconUriLine = iconUri == null ? "# IconUri = ''" : $"IconUri = '{iconUri.ToString()}'"; @@ -1089,7 +1110,7 @@ Example PrivateData string externalModuleDependenciesString = string.Join(", ", externalModuleDependencies.Select(item => "'" + item + "'")); string externalModuleDependenciesLine = externalModuleDependencies.Length == 0 ? "# ExternalModuleDependencies = @()" : $"ExternalModuleDependencies = @({externalModuleDependenciesString})"; - + string initialPrivateDataString = "PrivateData = @{" + System.Environment.NewLine + "PSData = @{" + System.Environment.NewLine; string privateDataString = $@" @@ -1157,7 +1178,7 @@ private bool TryCreateNewPsd1WithUpdatedPrivateData(string privateDataString, st { leftBracket--; } - + if (leftBracket == 0) { privateDataEndLine = i; @@ -1173,7 +1194,7 @@ private bool TryCreateNewPsd1WithUpdatedPrivateData(string privateDataString, st "PrivateDataEntryParsingError", ErrorCategory.InvalidOperation, this); - + return false; } diff --git a/src/code/Utils.cs b/src/code/Utils.cs index f09110423..d94aa1541 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -129,7 +129,7 @@ public static string[] GetStringArrayFromString(string[] delimeter, string strin return stringToConvertToArray.Split(delimeter, StringSplitOptions.RemoveEmptyEntries); } - + /// /// Converts an ArrayList of object types to a string array. /// @@ -169,7 +169,7 @@ public static string[] ProcessNameWildcards( { if (removeWildcardEntries) { - // Tag // CommandName // DSCResourceName + // Tag // CommandName // DSCResourceName errorMsgsList.Add($"{name} will be discarded from the provided entries."); continue; } @@ -260,17 +260,17 @@ public static bool TryGetVersionType( string[] versionSplit = version.Split(new string[] { "." }, StringSplitOptions.None); if (versionSplit.Length == 2 && versionSplit[1].Equals("*")) { - // eg: 2.* should translate to the version range "[2.0,2.99999]" + // eg: 2.* should translate to the version range "[2.0,2.99999]" modifiedVersion = $"[{versionSplit[0]}.0,{versionSplit[0]}.999999]"; } else if (versionSplit.Length == 3 && versionSplit[2].Equals("*")) { - // eg: 2.1.* should translate to the version range "[2.1.0,2.1.99999]" + // eg: 2.1.* should translate to the version range "[2.1.0,2.1.99999]" modifiedVersion = $"[{versionSplit[0]}.{versionSplit[1]}.0,{versionSplit[0]}.{versionSplit[1]}.999999]"; } else if (versionSplit.Length == 4 && versionSplit[3].Equals("*")) { - // eg: 2.8.8.* should translate to the version range "[2.1.3.0,2.1.3.99999]" + // eg: 2.8.8.* should translate to the version range "[2.1.3.0,2.1.3.99999]" modifiedVersion = $"[{versionSplit[0]}.{versionSplit[1]}.{versionSplit[2]}.0,{versionSplit[0]}.{versionSplit[1]}.{versionSplit[2]}.999999]"; } else { @@ -430,7 +430,7 @@ public static bool TryCreateValidUri( { // This is needed for a relative path Uri string. Does not throw error for an absolute path. var filePath = cmdletPassedIn.GetResolvedProviderPathFromPSPath(uriString, out ProviderInfo provider).First(); - + if (Uri.TryCreate(filePath, UriKind.Absolute, out uriResult)) { return true; @@ -633,7 +633,7 @@ public static PSCredential GetRepositoryCredentialFromSecretManagement( "RepositoryCredentialCannotGetSecretFromVault", ErrorCategory.InvalidOperation, cmdletPassedIn)); - + return null; } } @@ -920,7 +920,7 @@ public static NetworkCredential SetNetworkCredential( return networkCredential; } - + #endregion #region Path methods @@ -967,7 +967,7 @@ public static string GetInstalledPackageName(string pkgPath) return new DirectoryInfo(pkgPath).Parent.Name; } - // Find all potential resource paths + // Find all potential resource paths public static List GetPathsFromEnvVarAndScope( PSCmdlet psCmdlet, ScopeType? scope) @@ -998,7 +998,7 @@ public static List GetAllResourcePaths( ScopeType? scope = null) { List resourcePaths = GetPathsFromEnvVarAndScope(psCmdlet, scope); - + // resourcePaths should now contain, eg: // ./PowerShell/Scripts // ./PowerShell/Modules @@ -1048,7 +1048,7 @@ public static List GetAllInstallationPaths( ScopeType? scope) { List installationPaths = GetPathsFromEnvVarAndScope(psCmdlet, scope); - + installationPaths = installationPaths.Distinct(StringComparer.InvariantCultureIgnoreCase).ToList(); installationPaths.ForEach(dir => psCmdlet.WriteVerbose(string.Format("All paths to search: '{0}'", dir))); @@ -1216,7 +1216,7 @@ private static bool TryReadPSDataFile( allowedCommands: allowedCommands, allowedVariables: allowedVariables, allowEnvironmentVariables: allowEnvironmentVariables); - + // Convert contents into PSDataFile Hashtable by executing content as script. object result = scriptBlock.InvokeReturnAsIs(); if (result is PSObject psObject) @@ -1352,9 +1352,9 @@ public static bool TryCreateModuleSpecification( if (!moduleSpec.ContainsKey("ModuleName") || String.IsNullOrEmpty((string) moduleSpec["ModuleName"])) { errorList.Add(new ErrorRecord( - new ArgumentException($"RequiredModules Hashtable entry {moduleSpec.ToString()} is missing a key 'ModuleName' and associated value, which is required for each module specification entry"), - "NameMissingInModuleSpecification", - ErrorCategory.InvalidArgument, + new ArgumentException($"RequiredModules Hashtable entry {moduleSpec.ToString()} is missing a key 'ModuleName' and associated value, which is required for each module specification entry"), + "NameMissingInModuleSpecification", + ErrorCategory.InvalidArgument, null)); moduleSpecCreatedSuccessfully = false; continue; @@ -1376,9 +1376,9 @@ public static bool TryCreateModuleSpecification( else { errorList.Add(new ErrorRecord( - new ArgumentException($"ModuleSpecification object was not able to be created for {moduleSpecName}"), - "ModuleSpecificationNotCreated", - ErrorCategory.InvalidArgument, + new ArgumentException($"ModuleSpecification object was not able to be created for {moduleSpecName}"), + "ModuleSpecificationNotCreated", + ErrorCategory.InvalidArgument, null)); moduleSpecCreatedSuccessfully = false; continue; @@ -1395,9 +1395,9 @@ public static bool TryCreateModuleSpecification( if (String.IsNullOrEmpty(moduleSpecMaxVersion) && String.IsNullOrEmpty(moduleSpecModuleVersion) && String.IsNullOrEmpty(moduleSpecRequiredVersion)) { errorList.Add(new ErrorRecord( - new ArgumentException($"ModuleSpecification hashtable requires one of the following keys: MaximumVersion, ModuleVersion, RequiredVersion and failed to be created for {moduleSpecName}"), - "MissingModuleSpecificationMember", - ErrorCategory.InvalidArgument, + new ArgumentException($"ModuleSpecification hashtable requires one of the following keys: MaximumVersion, ModuleVersion, RequiredVersion and failed to be created for {moduleSpecName}"), + "MissingModuleSpecificationMember", + ErrorCategory.InvalidArgument, null)); moduleSpecCreatedSuccessfully = false; continue; @@ -1433,9 +1433,9 @@ public static bool TryCreateModuleSpecification( catch (Exception e) { errorList.Add(new ErrorRecord( - new ArgumentException($"ModuleSpecification instance was not able to be created with hashtable constructor due to: {e.Message}"), - "ModuleSpecificationNotCreated", - ErrorCategory.InvalidArgument, + new ArgumentException($"ModuleSpecification instance was not able to be created with hashtable constructor due to: {e.Message}"), + "ModuleSpecificationNotCreated", + ErrorCategory.InvalidArgument, null)); moduleSpecCreatedSuccessfully = false; } @@ -1492,6 +1492,10 @@ public static void DeleteDirectoryWithRestore(string dirPath) ex); } } + catch (Exception e) + { + throw e; + } finally { if (Directory.Exists(tempDirPath)) @@ -1907,9 +1911,9 @@ internal static bool CheckAuthenticodeSignature( string[] listOfExtensions = { "*.ps1", "*.psd1", "*.psm1", "*.mof", "*.cat", "*.ps1xml" }; authenticodeSignatures = cmdletPassedIn.InvokeCommand.InvokeScript( script: @"param ( - [string] $tempDirNameVersion, + [string] $tempDirNameVersion, [string[]] $listOfExtensions - ) + ) Get-ChildItem $tempDirNameVersion -Recurse -Include $listOfExtensions | Get-AuthenticodeSignature -ErrorAction SilentlyContinue", useNewScope: true, writeToPipeline: System.Management.Automation.Runspaces.PipelineResultTypes.None, @@ -1919,9 +1923,9 @@ internal static bool CheckAuthenticodeSignature( catch (Exception e) { errorRecord = new ErrorRecord( - new ArgumentException(e.Message), - "GetAuthenticodeSignatureError", - ErrorCategory.InvalidResult, + new ArgumentException(e.Message), + "GetAuthenticodeSignatureError", + ErrorCategory.InvalidResult, cmdletPassedIn); return false; @@ -1934,9 +1938,9 @@ internal static bool CheckAuthenticodeSignature( if (!signature.Status.Equals(SignatureStatus.Valid)) { errorRecord = new ErrorRecord( - new ArgumentException($"The signature for '{pkgName}' is '{signature.Status}."), - "GetAuthenticodeSignatureError", - ErrorCategory.InvalidResult, + new ArgumentException($"The signature for '{pkgName}' is '{signature.Status}."), + "GetAuthenticodeSignatureError", + ErrorCategory.InvalidResult, cmdletPassedIn); return false; @@ -1945,7 +1949,7 @@ internal static bool CheckAuthenticodeSignature( return true; } - + #endregion } From b1a8061dc11d816539924792314183837cac6ee9 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 14:55:16 -0800 Subject: [PATCH 39/57] Add logging --- .../PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 8f7bda99c..47c0802a0 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -230,6 +230,8 @@ Describe "Test Publish-PSResource" -tags 'CI' { { Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName -ErrorAction Stop } | Should -Not -Throw + Write-Host "TestDrive + $TestDrive" + Write-Host "PublishModuleName + $script:PublishModuleName" Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell $nupkgPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName.$version.nupkg" From e969e5e60fdc66aaa23acf7d6c203fc6498c10eb Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 15:22:45 -0800 Subject: [PATCH 40/57] Add -Verbose -Debug to Save --- .../PublishPSResourceACRServer.Tests.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 47c0802a0..06bdf4976 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -232,7 +232,8 @@ Describe "Test Publish-PSResource" -tags 'CI' { Write-Host "TestDrive + $TestDrive" Write-Host "PublishModuleName + $script:PublishModuleName" - Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive + $DebugPreference = 'SilentlyContinue' + Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive -Verbose -Debug # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell $nupkgPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName.$version.nupkg" $zipPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName.$version.zip" From 5827c8feca65f228bd6411e83e6814c269743644 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 15:47:46 -0800 Subject: [PATCH 41/57] Add -TrustRepository to Save --- .../PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 06bdf4976..baefcfba3 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -233,7 +233,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { Write-Host "TestDrive + $TestDrive" Write-Host "PublishModuleName + $script:PublishModuleName" $DebugPreference = 'SilentlyContinue' - Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive -Verbose -Debug + Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive -Verbose -Debug -TrustRepository # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell $nupkgPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName.$version.nupkg" $zipPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName.$version.zip" From d62d2f40d5ebc5f2a5afb1996515882a44a1724a Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 16:22:18 -0800 Subject: [PATCH 42/57] Add WriteError to ACRServerAPICalls class --- src/code/ACRServerAPICalls.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/code/ACRServerAPICalls.cs b/src/code/ACRServerAPICalls.cs index 638bc1c0c..5b22996cb 100644 --- a/src/code/ACRServerAPICalls.cs +++ b/src/code/ACRServerAPICalls.cs @@ -156,6 +156,7 @@ public override FindResults FindName(string packageName, bool includePrerelease, var acrRefreshToken = GetAcrRefreshToken(registry, tenantID, accessToken, out errRecord); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -163,6 +164,7 @@ public override FindResults FindName(string packageName, bool includePrerelease, var acrAccessToken = GetAcrAccessToken(registry, acrRefreshToken, out errRecord); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -202,6 +204,7 @@ public override FindResults FindName(string packageName, bool includePrerelease, latestVersionResponse.Add(GetACRMetadata(registry, packageName, pkgVersion, acrAccessToken, out errRecord)); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: latestVersionResponse.ToArray(), responseType: acrFindResponseType); } @@ -307,6 +310,7 @@ public override FindResults FindVersionGlobbing(string packageName, VersionRange var acrRefreshToken = GetAcrRefreshToken(registry, tenantID, accessToken, out errRecord); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -314,6 +318,7 @@ public override FindResults FindVersionGlobbing(string packageName, VersionRange var acrAccessToken = GetAcrAccessToken(registry, acrRefreshToken, out errRecord); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -358,6 +363,7 @@ public override FindResults FindVersionGlobbing(string packageName, VersionRange latestVersionResponse.Add(GetACRMetadata(registry, packageName, pkgVersion, acrAccessToken, out errRecord)); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: latestVersionResponse.ToArray(), responseType: acrFindResponseType); } } @@ -414,6 +420,7 @@ public override FindResults FindVersion(string packageName, string version, Reso var acrRefreshToken = GetAcrRefreshToken(registry, tenantID, accessToken, out errRecord); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -421,6 +428,7 @@ public override FindResults FindVersion(string packageName, string version, Reso var acrAccessToken = GetAcrAccessToken(registry, acrRefreshToken, out errRecord); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -431,6 +439,7 @@ public override FindResults FindVersion(string packageName, string version, Reso }; if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: results.ToArray(), responseType: acrFindResponseType); } @@ -517,6 +526,7 @@ private Stream InstallVersion( var acrRefreshToken = GetAcrRefreshToken(registry, tenantID, accessToken, out errRecord); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return null; } @@ -524,6 +534,7 @@ private Stream InstallVersion( var acrAccessToken = GetAcrAccessToken(registry, acrRefreshToken, out errRecord); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return null; } @@ -531,11 +542,13 @@ private Stream InstallVersion( var manifest = GetAcrRepositoryManifestAsync(registry, moduleName, moduleVersion, acrAccessToken, out errRecord); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return null; } string digest = GetDigestFromManifest(manifest, out errRecord); if (errRecord != null) { + _cmdletPassedIn.WriteError(errRecord); return null; } From 2547e36c89e459fdc4e14edbd0f29d510f7a9570 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 16:52:56 -0800 Subject: [PATCH 43/57] Add more WriteErrors in ACR Server class --- src/code/ACRServerAPICalls.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/code/ACRServerAPICalls.cs b/src/code/ACRServerAPICalls.cs index 5b22996cb..636ad7bb7 100644 --- a/src/code/ACRServerAPICalls.cs +++ b/src/code/ACRServerAPICalls.cs @@ -172,6 +172,7 @@ public override FindResults FindName(string packageName, bool includePrerelease, var foundTags = FindAcrImageTags(registry, packageName, "*", acrAccessToken, out errRecord); if (errRecord != null || foundTags == null) { + _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -326,6 +327,7 @@ public override FindResults FindVersionGlobbing(string packageName, VersionRange var foundTags = FindAcrImageTags(registry, packageName, "*", acrAccessToken, out errRecord); if (errRecord != null || foundTags == null) { + _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -690,6 +692,7 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers var foundTags = FindAcrManifest(registry, packageName, requiredVersion.ToNormalizedString(), acrAccessToken, out errRecord); if (errRecord != null || foundTags == null) { + _cmdletPassedIn.WriteError(errRecord); return requiredVersionResponse; } From d0d426ca496f3745768eed8ddd36dcdefab741f4 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 17:29:40 -0800 Subject: [PATCH 44/57] Write more verbose messaging --- src/code/ACRServerAPICalls.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/code/ACRServerAPICalls.cs b/src/code/ACRServerAPICalls.cs index 636ad7bb7..88a307e36 100644 --- a/src/code/ACRServerAPICalls.cs +++ b/src/code/ACRServerAPICalls.cs @@ -690,6 +690,7 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers Hashtable requiredVersionResponse = new Hashtable(); var foundTags = FindAcrManifest(registry, packageName, requiredVersion.ToNormalizedString(), acrAccessToken, out errRecord); + _cmdletPassedIn.WriteVerbose("Found ACR Manifest"); if (errRecord != null || foundTags == null) { _cmdletPassedIn.WriteError(errRecord); @@ -718,11 +719,11 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers * } */ + _cmdletPassedIn.WriteVerbose("GetMetadataProperty"); Tuple metadataTuple = GetMetadataProperty(foundTags, packageName, out Exception exception); if (exception != null) { errRecord = new ErrorRecord(exception, "FindNameFailure", ErrorCategory.InvalidResult, this); - return requiredVersionResponse; } @@ -761,6 +762,7 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack { exception = null; var emptyTuple = new Tuple(string.Empty, string.Empty); + _cmdletPassedIn.WriteVerbose("Attempting to parse layers"); var layers = foundTags["layers"]; if (layers == null || layers[0] == null) { @@ -769,6 +771,7 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack return emptyTuple; } + _cmdletPassedIn.WriteVerbose("Attempting to parse annotations"); var annotations = layers[0]["annotations"]; if (annotations == null) { @@ -777,6 +780,7 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack return emptyTuple; } + _cmdletPassedIn.WriteVerbose("Attempting to parse metadata"); if (annotations["metadata"] == null) { exception = new InvalidOrEmptyResponse($"Response does not contain 'metadata' element in manifest for package '{packageName}' in '{Repository.Name}'."); @@ -786,6 +790,7 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack var metadata = annotations["metadata"].ToString(); + _cmdletPassedIn.WriteVerbose("Attempting to parse org.opencontainers.image.title"); var metadataPkgTitleJToken = annotations["org.opencontainers.image.title"]; if (metadataPkgTitleJToken == null) { From 09d5b3989b4cee2330df553c26e74b1d42fb3bba Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 17:48:34 -0800 Subject: [PATCH 45/57] Add more logging --- src/code/ACRServerAPICalls.cs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/code/ACRServerAPICalls.cs b/src/code/ACRServerAPICalls.cs index 88a307e36..46936392e 100644 --- a/src/code/ACRServerAPICalls.cs +++ b/src/code/ACRServerAPICalls.cs @@ -723,18 +723,40 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers Tuple metadataTuple = GetMetadataProperty(foundTags, packageName, out Exception exception); if (exception != null) { + _cmdletPassedIn.WriteVerbose("Exception found"); errRecord = new ErrorRecord(exception, "FindNameFailure", ErrorCategory.InvalidResult, this); return requiredVersionResponse; } + + if (metadataTuple == null) + { + _cmdletPassedIn.WriteVerbose("Tuple is null"); + + } + + if (metadataTuple.Item1 == null) + { + _cmdletPassedIn.WriteVerbose("tuple item 1 is null"); + } + if (metadataTuple.Item2 == null) + { + _cmdletPassedIn.WriteVerbose("tuple item 2 is null"); + } string metadataPkgName = metadataTuple.Item1; + _cmdletPassedIn.WriteVerbose($"tuple item 1 is: {metadataPkgName}"); + string metadata = metadataTuple.Item2; + _cmdletPassedIn.WriteVerbose($"tuple item 1 is: {metadata}"); + using (JsonDocument metadataJSONDoc = JsonDocument.Parse(metadata)) { + _cmdletPassedIn.WriteVerbose($"tuple item 1 is: {metadata}"); JsonElement rootDom = metadataJSONDoc.RootElement; if (!rootDom.TryGetProperty("ModuleVersion", out JsonElement pkgVersionElement) && !rootDom.TryGetProperty("Version", out pkgVersionElement)) { + _cmdletPassedIn.WriteVerbose($"Error getting properties"); errRecord = new ErrorRecord( new InvalidOrEmptyResponse($"Response does not contain 'ModuleVersion' or 'Version' property in metadata for package '{packageName}' in '{Repository.Name}'."), "FindNameFailure", @@ -744,6 +766,8 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers return requiredVersionResponse; } + _cmdletPassedIn.WriteVerbose($"try to parse pkgVersionelement"); + if (NuGetVersion.TryParse(pkgVersionElement.ToString(), out NuGetVersion pkgVersion)) { _cmdletPassedIn.WriteDebug($"'{packageName}' version parsed as '{pkgVersion}'"); @@ -755,6 +779,8 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers } } + _cmdletPassedIn.WriteVerbose($"Successfully reached end of GetACRMetadata"); + return requiredVersionResponse; } @@ -807,6 +833,7 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack return emptyTuple; } + _cmdletPassedIn.WriteVerbose("Successfully parsed all metadata"); return new Tuple(metadataPkgName, metadata); } From 379f4bd8a6103ad16cdaa04c858b031ff6902110 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 18:22:05 -0800 Subject: [PATCH 46/57] Add more logging --- src/code/ACRServerAPICalls.cs | 9 +++++++-- src/code/FindHelper.cs | 2 ++ src/code/InstallHelper.cs | 1 + 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/code/ACRServerAPICalls.cs b/src/code/ACRServerAPICalls.cs index 46936392e..7759edfa1 100644 --- a/src/code/ACRServerAPICalls.cs +++ b/src/code/ACRServerAPICalls.cs @@ -205,16 +205,21 @@ public override FindResults FindName(string packageName, bool includePrerelease, latestVersionResponse.Add(GetACRMetadata(registry, packageName, pkgVersion, acrAccessToken, out errRecord)); if (errRecord != null) { + _cmdletPassedIn.WriteVerbose("errRecord is not null"); _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: latestVersionResponse.ToArray(), responseType: acrFindResponseType); } + _cmdletPassedIn.WriteVerbose("About to break"); + break; } } } } + _cmdletPassedIn.WriteVerbose("Returning from FindName"); + return new FindResults(stringResponse: new string[] {}, hashtableResponse: latestVersionResponse.ToArray(), responseType: acrFindResponseType); } @@ -747,11 +752,11 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers _cmdletPassedIn.WriteVerbose($"tuple item 1 is: {metadataPkgName}"); string metadata = metadataTuple.Item2; - _cmdletPassedIn.WriteVerbose($"tuple item 1 is: {metadata}"); + _cmdletPassedIn.WriteVerbose($"tuple item 2 is: {metadata}"); using (JsonDocument metadataJSONDoc = JsonDocument.Parse(metadata)) { - _cmdletPassedIn.WriteVerbose($"tuple item 1 is: {metadata}"); + _cmdletPassedIn.WriteVerbose($"marsing metadata into jsondocument"); JsonElement rootDom = metadataJSONDoc.RootElement; if (!rootDom.TryGetProperty("ModuleVersion", out JsonElement pkgVersionElement) && !rootDom.TryGetProperty("Version", out pkgVersionElement)) diff --git a/src/code/FindHelper.cs b/src/code/FindHelper.cs index 1d3fce098..507f29b9d 100644 --- a/src/code/FindHelper.cs +++ b/src/code/FindHelper.cs @@ -745,6 +745,7 @@ private IEnumerable SearchByNames(ServerApiCall currentServer, R FindResults responses = null; if (_tag.Length == 0) { + _cmdletPassedIn.WriteVerbose("*** In find helper"); responses = currentServer.FindName(pkgName, _prerelease, _type, out errRecord); } else @@ -1051,6 +1052,7 @@ internal IEnumerable FindDependencyPackages( if (dep.VersionRange.Equals(VersionRange.All)) { + _cmdletPassedIn.WriteVerbose("*** IN FIND HELPER VERSION RANGE ALL"); FindResults responses = currentServer.FindName(dep.Name, includePrerelease: true, _type, out ErrorRecord errRecord); if (errRecord != null) { diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index a2135ab76..336b29dd0 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -748,6 +748,7 @@ private Hashtable BeginPackageInstall( default: // VersionType.NoVersion + _cmdletPassedIn.WriteVerbose("*** In install helper"); responses = currentServer.FindName(pkgNameToInstall, _prerelease, ResourceType.None, out ErrorRecord findNameErrRecord); if (findNameErrRecord != null) { From a55f07fcdd0e5f5e5001725c61ed4236a25418c1 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 19:00:00 -0800 Subject: [PATCH 47/57] Add more debugging in installhelper --- src/code/InstallHelper.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index 336b29dd0..153a4be13 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -759,6 +759,9 @@ private Hashtable BeginPackageInstall( break; } + _cmdletPassedIn.WriteVerbose("** Got response"); + + PSResourceInfo pkgToInstall = null; foreach (PSResourceResult currentResult in currentResponseUtil.ConvertToPSResourceResult(responses)) { @@ -794,16 +797,26 @@ private Hashtable BeginPackageInstall( } } + _cmdletPassedIn.WriteVerbose("*** Got PSResourceResult "); + if (pkgToInstall == null) { return packagesHash; } + _cmdletPassedIn.WriteVerbose($"Checking repo uri"); + pkgToInstall.RepositorySourceLocation = repository.Uri.ToString(); + + _cmdletPassedIn.WriteVerbose($"Checking normalized version"); + pkgToInstall.AdditionalMetadata.TryGetValue("NormalizedVersion", out string pkgVersion); if (pkgVersion == null) { pkgVersion = pkgToInstall.Version.ToString(); } + + _cmdletPassedIn.WriteVerbose($"Reinstall is {_reinstall}"); + // Check to see if the pkg is already installed (ie the pkg is installed and the version satisfies the version range provided via param) if (!_reinstall) { @@ -819,6 +832,8 @@ private Hashtable BeginPackageInstall( } } + _cmdletPassedIn.WriteVerbose($"Checking packagesHash"); + if (packagesHash.ContainsKey(pkgToInstall.Name)) { return packagesHash; @@ -827,6 +842,8 @@ private Hashtable BeginPackageInstall( Hashtable updatedPackagesHash = packagesHash; + _cmdletPassedIn.WriteVerbose($"WhatIF processing about to happen"); + // -WhatIf processing. if (_savePkg && !_cmdletPassedIn.ShouldProcess($"Package to save: '{pkgToInstall.Name}', version: '{pkgVersion}'")) { From 3acd8b464c028bf557f249060a669c81ecca5229 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 19:15:52 -0800 Subject: [PATCH 48/57] Add more logging --- src/code/InstallHelper.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index 153a4be13..bfb230952 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -847,6 +847,8 @@ private Hashtable BeginPackageInstall( // -WhatIf processing. if (_savePkg && !_cmdletPassedIn.ShouldProcess($"Package to save: '{pkgToInstall.Name}', version: '{pkgVersion}'")) { + _cmdletPassedIn.WriteVerbose($"in save should process"); + if (!updatedPackagesHash.ContainsKey(pkgToInstall.Name)) { updatedPackagesHash.Add(pkgToInstall.Name, new Hashtable(StringComparer.InvariantCultureIgnoreCase) @@ -863,6 +865,8 @@ private Hashtable BeginPackageInstall( } else if (!_cmdletPassedIn.ShouldProcess($"Package to install: '{pkgToInstall.Name}', version: '{pkgVersion}'")) { + _cmdletPassedIn.WriteVerbose($"in install should process"); + if (!updatedPackagesHash.ContainsKey(pkgToInstall.Name)) { updatedPackagesHash.Add(pkgToInstall.Name, new Hashtable(StringComparer.InvariantCultureIgnoreCase) @@ -879,8 +883,12 @@ private Hashtable BeginPackageInstall( } else { + _cmdletPassedIn.WriteVerbose($"In else statement"); + // Download the package. string pkgName = pkgToInstall.Name; + _cmdletPassedIn.WriteVerbose($"About to install package"); + Stream responseStream = currentServer.InstallPackage(pkgName, pkgVersion, _prerelease, out ErrorRecord installNameErrRecord); if (installNameErrRecord != null) { From d336f55046e0b93dd27a9bb9f08aaf73308454c9 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 19:41:21 -0800 Subject: [PATCH 49/57] Add more logging --- src/code/InstallHelper.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index bfb230952..c797e5bf9 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -843,6 +843,17 @@ private Hashtable BeginPackageInstall( Hashtable updatedPackagesHash = packagesHash; _cmdletPassedIn.WriteVerbose($"WhatIF processing about to happen"); + _cmdletPassedIn.WriteVerbose($"_savePkg is: {_savePkg}"); + _cmdletPassedIn.WriteVerbose($"pkgVersion is: {pkgVersion}"); + if (pkgToInstall == null) + { + _cmdletPassedIn.WriteVerbose($"pkgToInstall is null"); + } + if (pkgToInstall.Name == null) + { + _cmdletPassedIn.WriteVerbose($"pkgToInstall.Name is null"); + } + _cmdletPassedIn.WriteVerbose($"pkgToInstall.Name is: {pkgToInstall.Name}"); // -WhatIf processing. if (_savePkg && !_cmdletPassedIn.ShouldProcess($"Package to save: '{pkgToInstall.Name}', version: '{pkgVersion}'")) From fa805ee0755b007f1fadc2e7ab39bc08640a838f Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Feb 2024 19:58:24 -0800 Subject: [PATCH 50/57] Remove -Verbose -Debug from Save --- .../PublishPSResourceACRServer.Tests.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index baefcfba3..cf8464d1d 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -233,7 +233,8 @@ Describe "Test Publish-PSResource" -tags 'CI' { Write-Host "TestDrive + $TestDrive" Write-Host "PublishModuleName + $script:PublishModuleName" $DebugPreference = 'SilentlyContinue' - Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive -Verbose -Debug -TrustRepository + + Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive -TrustRepository # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell $nupkgPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName.$version.nupkg" $zipPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName.$version.zip" From d1e509871466f49e838dc3f2051ec19a91b7118a Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 20 Feb 2024 10:23:15 -0800 Subject: [PATCH 51/57] Clean up files --- src/code/ACRServerAPICalls.cs | 35 +---------------- src/code/FindHelper.cs | 2 - src/code/InstallHelper.cs | 38 ------------------- .../PublishPSResourceACRServer.Tests.ps1 | 6 +-- 4 files changed, 3 insertions(+), 78 deletions(-) diff --git a/src/code/ACRServerAPICalls.cs b/src/code/ACRServerAPICalls.cs index 7759edfa1..3153e7829 100644 --- a/src/code/ACRServerAPICalls.cs +++ b/src/code/ACRServerAPICalls.cs @@ -205,21 +205,16 @@ public override FindResults FindName(string packageName, bool includePrerelease, latestVersionResponse.Add(GetACRMetadata(registry, packageName, pkgVersion, acrAccessToken, out errRecord)); if (errRecord != null) { - _cmdletPassedIn.WriteVerbose("errRecord is not null"); _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: latestVersionResponse.ToArray(), responseType: acrFindResponseType); } - _cmdletPassedIn.WriteVerbose("About to break"); - break; } } } } - _cmdletPassedIn.WriteVerbose("Returning from FindName"); - return new FindResults(stringResponse: new string[] {}, hashtableResponse: latestVersionResponse.ToArray(), responseType: acrFindResponseType); } @@ -695,7 +690,6 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers Hashtable requiredVersionResponse = new Hashtable(); var foundTags = FindAcrManifest(registry, packageName, requiredVersion.ToNormalizedString(), acrAccessToken, out errRecord); - _cmdletPassedIn.WriteVerbose("Found ACR Manifest"); if (errRecord != null || foundTags == null) { _cmdletPassedIn.WriteError(errRecord); @@ -723,30 +717,12 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers * ] * } */ - - _cmdletPassedIn.WriteVerbose("GetMetadataProperty"); Tuple metadataTuple = GetMetadataProperty(foundTags, packageName, out Exception exception); if (exception != null) { - _cmdletPassedIn.WriteVerbose("Exception found"); errRecord = new ErrorRecord(exception, "FindNameFailure", ErrorCategory.InvalidResult, this); return requiredVersionResponse; } - - if (metadataTuple == null) - { - _cmdletPassedIn.WriteVerbose("Tuple is null"); - - } - - if (metadataTuple.Item1 == null) - { - _cmdletPassedIn.WriteVerbose("tuple item 1 is null"); - } - if (metadataTuple.Item2 == null) - { - _cmdletPassedIn.WriteVerbose("tuple item 2 is null"); - } string metadataPkgName = metadataTuple.Item1; _cmdletPassedIn.WriteVerbose($"tuple item 1 is: {metadataPkgName}"); @@ -756,12 +732,10 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers using (JsonDocument metadataJSONDoc = JsonDocument.Parse(metadata)) { - _cmdletPassedIn.WriteVerbose($"marsing metadata into jsondocument"); JsonElement rootDom = metadataJSONDoc.RootElement; if (!rootDom.TryGetProperty("ModuleVersion", out JsonElement pkgVersionElement) && !rootDom.TryGetProperty("Version", out pkgVersionElement)) { - _cmdletPassedIn.WriteVerbose($"Error getting properties"); errRecord = new ErrorRecord( new InvalidOrEmptyResponse($"Response does not contain 'ModuleVersion' or 'Version' property in metadata for package '{packageName}' in '{Repository.Name}'."), "FindNameFailure", @@ -771,8 +745,6 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers return requiredVersionResponse; } - _cmdletPassedIn.WriteVerbose($"try to parse pkgVersionelement"); - if (NuGetVersion.TryParse(pkgVersionElement.ToString(), out NuGetVersion pkgVersion)) { _cmdletPassedIn.WriteDebug($"'{packageName}' version parsed as '{pkgVersion}'"); @@ -784,8 +756,6 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers } } - _cmdletPassedIn.WriteVerbose($"Successfully reached end of GetACRMetadata"); - return requiredVersionResponse; } @@ -793,7 +763,6 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack { exception = null; var emptyTuple = new Tuple(string.Empty, string.Empty); - _cmdletPassedIn.WriteVerbose("Attempting to parse layers"); var layers = foundTags["layers"]; if (layers == null || layers[0] == null) { @@ -811,7 +780,7 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack return emptyTuple; } - _cmdletPassedIn.WriteVerbose("Attempting to parse metadata"); + _cmdletPassedIn.WriteVerbose("Attempting to parse package metadata"); if (annotations["metadata"] == null) { exception = new InvalidOrEmptyResponse($"Response does not contain 'metadata' element in manifest for package '{packageName}' in '{Repository.Name}'."); @@ -838,7 +807,7 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack return emptyTuple; } - _cmdletPassedIn.WriteVerbose("Successfully parsed all metadata"); + _cmdletPassedIn.WriteVerbose("Successfully parsed all manifest metadata"); return new Tuple(metadataPkgName, metadata); } diff --git a/src/code/FindHelper.cs b/src/code/FindHelper.cs index 507f29b9d..1d3fce098 100644 --- a/src/code/FindHelper.cs +++ b/src/code/FindHelper.cs @@ -745,7 +745,6 @@ private IEnumerable SearchByNames(ServerApiCall currentServer, R FindResults responses = null; if (_tag.Length == 0) { - _cmdletPassedIn.WriteVerbose("*** In find helper"); responses = currentServer.FindName(pkgName, _prerelease, _type, out errRecord); } else @@ -1052,7 +1051,6 @@ internal IEnumerable FindDependencyPackages( if (dep.VersionRange.Equals(VersionRange.All)) { - _cmdletPassedIn.WriteVerbose("*** IN FIND HELPER VERSION RANGE ALL"); FindResults responses = currentServer.FindName(dep.Name, includePrerelease: true, _type, out ErrorRecord errRecord); if (errRecord != null) { diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index c797e5bf9..8636aed52 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -748,7 +748,6 @@ private Hashtable BeginPackageInstall( default: // VersionType.NoVersion - _cmdletPassedIn.WriteVerbose("*** In install helper"); responses = currentServer.FindName(pkgNameToInstall, _prerelease, ResourceType.None, out ErrorRecord findNameErrRecord); if (findNameErrRecord != null) { @@ -759,9 +758,6 @@ private Hashtable BeginPackageInstall( break; } - _cmdletPassedIn.WriteVerbose("** Got response"); - - PSResourceInfo pkgToInstall = null; foreach (PSResourceResult currentResult in currentResponseUtil.ConvertToPSResourceResult(responses)) { @@ -797,26 +793,17 @@ private Hashtable BeginPackageInstall( } } - _cmdletPassedIn.WriteVerbose("*** Got PSResourceResult "); - if (pkgToInstall == null) { return packagesHash; } - _cmdletPassedIn.WriteVerbose($"Checking repo uri"); - pkgToInstall.RepositorySourceLocation = repository.Uri.ToString(); - - _cmdletPassedIn.WriteVerbose($"Checking normalized version"); - pkgToInstall.AdditionalMetadata.TryGetValue("NormalizedVersion", out string pkgVersion); if (pkgVersion == null) { pkgVersion = pkgToInstall.Version.ToString(); } - _cmdletPassedIn.WriteVerbose($"Reinstall is {_reinstall}"); - // Check to see if the pkg is already installed (ie the pkg is installed and the version satisfies the version range provided via param) if (!_reinstall) { @@ -832,34 +819,15 @@ private Hashtable BeginPackageInstall( } } - _cmdletPassedIn.WriteVerbose($"Checking packagesHash"); - if (packagesHash.ContainsKey(pkgToInstall.Name)) { return packagesHash; } - Hashtable updatedPackagesHash = packagesHash; - - _cmdletPassedIn.WriteVerbose($"WhatIF processing about to happen"); - _cmdletPassedIn.WriteVerbose($"_savePkg is: {_savePkg}"); - _cmdletPassedIn.WriteVerbose($"pkgVersion is: {pkgVersion}"); - if (pkgToInstall == null) - { - _cmdletPassedIn.WriteVerbose($"pkgToInstall is null"); - } - if (pkgToInstall.Name == null) - { - _cmdletPassedIn.WriteVerbose($"pkgToInstall.Name is null"); - } - _cmdletPassedIn.WriteVerbose($"pkgToInstall.Name is: {pkgToInstall.Name}"); - // -WhatIf processing. if (_savePkg && !_cmdletPassedIn.ShouldProcess($"Package to save: '{pkgToInstall.Name}', version: '{pkgVersion}'")) { - _cmdletPassedIn.WriteVerbose($"in save should process"); - if (!updatedPackagesHash.ContainsKey(pkgToInstall.Name)) { updatedPackagesHash.Add(pkgToInstall.Name, new Hashtable(StringComparer.InvariantCultureIgnoreCase) @@ -876,8 +844,6 @@ private Hashtable BeginPackageInstall( } else if (!_cmdletPassedIn.ShouldProcess($"Package to install: '{pkgToInstall.Name}', version: '{pkgVersion}'")) { - _cmdletPassedIn.WriteVerbose($"in install should process"); - if (!updatedPackagesHash.ContainsKey(pkgToInstall.Name)) { updatedPackagesHash.Add(pkgToInstall.Name, new Hashtable(StringComparer.InvariantCultureIgnoreCase) @@ -894,12 +860,8 @@ private Hashtable BeginPackageInstall( } else { - _cmdletPassedIn.WriteVerbose($"In else statement"); - // Download the package. string pkgName = pkgToInstall.Name; - _cmdletPassedIn.WriteVerbose($"About to install package"); - Stream responseStream = currentServer.InstallPackage(pkgName, pkgVersion, _prerelease, out ErrorRecord installNameErrRecord); if (installNameErrRecord != null) { diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index cf8464d1d..766262bf1 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -228,11 +228,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" New-Item -Path (Join-Path -Path $script:PublishModuleBase -ChildPath $testFile) -Force - { Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName -ErrorAction Stop } | Should -Not -Throw - - Write-Host "TestDrive + $TestDrive" - Write-Host "PublishModuleName + $script:PublishModuleName" - $DebugPreference = 'SilentlyContinue' + Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName -ErrorAction Stop Save-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -AsNupkg -Path $TestDrive -TrustRepository # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell From d8d8c0ce034b1dc65397be06b22270dca2371298 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Tue, 20 Feb 2024 11:17:21 -0800 Subject: [PATCH 52/57] Clean up a bit more --- src/code/ACRServerAPICalls.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/code/ACRServerAPICalls.cs b/src/code/ACRServerAPICalls.cs index 3153e7829..74186df48 100644 --- a/src/code/ACRServerAPICalls.cs +++ b/src/code/ACRServerAPICalls.cs @@ -725,11 +725,8 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers } string metadataPkgName = metadataTuple.Item1; - _cmdletPassedIn.WriteVerbose($"tuple item 1 is: {metadataPkgName}"); - string metadata = metadataTuple.Item2; - _cmdletPassedIn.WriteVerbose($"tuple item 2 is: {metadata}"); - + _cmdletPassedIn.WriteVerbose($"package name is '{metadataPkgName}', package metadata is '{metadata}'"); using (JsonDocument metadataJSONDoc = JsonDocument.Parse(metadata)) { JsonElement rootDom = metadataJSONDoc.RootElement; From a4c3ca874d7f593ad72780cbbefe6b7ac5f93915 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 21 Feb 2024 20:06:40 -0800 Subject: [PATCH 53/57] remove whitespace --- src/code/InstallHelper.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index 8636aed52..a2135ab76 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -803,7 +803,6 @@ private Hashtable BeginPackageInstall( if (pkgVersion == null) { pkgVersion = pkgToInstall.Version.ToString(); } - // Check to see if the pkg is already installed (ie the pkg is installed and the version satisfies the version range provided via param) if (!_reinstall) { @@ -824,7 +823,9 @@ private Hashtable BeginPackageInstall( return packagesHash; } + Hashtable updatedPackagesHash = packagesHash; + // -WhatIf processing. if (_savePkg && !_cmdletPassedIn.ShouldProcess($"Package to save: '{pkgToInstall.Name}', version: '{pkgVersion}'")) { From b9a7d092d5083536559999038d8a274aa95f8fe9 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 21 Feb 2024 20:15:16 -0800 Subject: [PATCH 54/57] Remove unnecessary write errors --- src/code/ACRServerAPICalls.cs | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/src/code/ACRServerAPICalls.cs b/src/code/ACRServerAPICalls.cs index 74186df48..817f77962 100644 --- a/src/code/ACRServerAPICalls.cs +++ b/src/code/ACRServerAPICalls.cs @@ -156,7 +156,6 @@ public override FindResults FindName(string packageName, bool includePrerelease, var acrRefreshToken = GetAcrRefreshToken(registry, tenantID, accessToken, out errRecord); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -164,7 +163,6 @@ public override FindResults FindName(string packageName, bool includePrerelease, var acrAccessToken = GetAcrAccessToken(registry, acrRefreshToken, out errRecord); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -172,7 +170,6 @@ public override FindResults FindName(string packageName, bool includePrerelease, var foundTags = FindAcrImageTags(registry, packageName, "*", acrAccessToken, out errRecord); if (errRecord != null || foundTags == null) { - _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -205,7 +202,6 @@ public override FindResults FindName(string packageName, bool includePrerelease, latestVersionResponse.Add(GetACRMetadata(registry, packageName, pkgVersion, acrAccessToken, out errRecord)); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: latestVersionResponse.ToArray(), responseType: acrFindResponseType); } @@ -311,7 +307,6 @@ public override FindResults FindVersionGlobbing(string packageName, VersionRange var acrRefreshToken = GetAcrRefreshToken(registry, tenantID, accessToken, out errRecord); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -319,7 +314,6 @@ public override FindResults FindVersionGlobbing(string packageName, VersionRange var acrAccessToken = GetAcrAccessToken(registry, acrRefreshToken, out errRecord); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -327,7 +321,6 @@ public override FindResults FindVersionGlobbing(string packageName, VersionRange var foundTags = FindAcrImageTags(registry, packageName, "*", acrAccessToken, out errRecord); if (errRecord != null || foundTags == null) { - _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -365,7 +358,6 @@ public override FindResults FindVersionGlobbing(string packageName, VersionRange latestVersionResponse.Add(GetACRMetadata(registry, packageName, pkgVersion, acrAccessToken, out errRecord)); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: latestVersionResponse.ToArray(), responseType: acrFindResponseType); } } @@ -422,7 +414,6 @@ public override FindResults FindVersion(string packageName, string version, Reso var acrRefreshToken = GetAcrRefreshToken(registry, tenantID, accessToken, out errRecord); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -430,7 +421,6 @@ public override FindResults FindVersion(string packageName, string version, Reso var acrAccessToken = GetAcrAccessToken(registry, acrRefreshToken, out errRecord); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: emptyHashResponses, responseType: acrFindResponseType); } @@ -441,7 +431,6 @@ public override FindResults FindVersion(string packageName, string version, Reso }; if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return new FindResults(stringResponse: new string[] { }, hashtableResponse: results.ToArray(), responseType: acrFindResponseType); } @@ -528,7 +517,6 @@ private Stream InstallVersion( var acrRefreshToken = GetAcrRefreshToken(registry, tenantID, accessToken, out errRecord); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return null; } @@ -536,7 +524,6 @@ private Stream InstallVersion( var acrAccessToken = GetAcrAccessToken(registry, acrRefreshToken, out errRecord); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return null; } @@ -544,13 +531,11 @@ private Stream InstallVersion( var manifest = GetAcrRepositoryManifestAsync(registry, moduleName, moduleVersion, acrAccessToken, out errRecord); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return null; } string digest = GetDigestFromManifest(manifest, out errRecord); if (errRecord != null) { - _cmdletPassedIn.WriteError(errRecord); return null; } @@ -692,7 +677,6 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers var foundTags = FindAcrManifest(registry, packageName, requiredVersion.ToNormalizedString(), acrAccessToken, out errRecord); if (errRecord != null || foundTags == null) { - _cmdletPassedIn.WriteError(errRecord); return requiredVersionResponse; } @@ -726,7 +710,6 @@ internal Hashtable GetACRMetadata(string registry, string packageName, NuGetVers string metadataPkgName = metadataTuple.Item1; string metadata = metadataTuple.Item2; - _cmdletPassedIn.WriteVerbose($"package name is '{metadataPkgName}', package metadata is '{metadata}'"); using (JsonDocument metadataJSONDoc = JsonDocument.Parse(metadata)) { JsonElement rootDom = metadataJSONDoc.RootElement; @@ -768,7 +751,6 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack return emptyTuple; } - _cmdletPassedIn.WriteVerbose("Attempting to parse annotations"); var annotations = layers[0]["annotations"]; if (annotations == null) { @@ -777,7 +759,6 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack return emptyTuple; } - _cmdletPassedIn.WriteVerbose("Attempting to parse package metadata"); if (annotations["metadata"] == null) { exception = new InvalidOrEmptyResponse($"Response does not contain 'metadata' element in manifest for package '{packageName}' in '{Repository.Name}'."); @@ -786,8 +767,6 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack } var metadata = annotations["metadata"].ToString(); - - _cmdletPassedIn.WriteVerbose("Attempting to parse org.opencontainers.image.title"); var metadataPkgTitleJToken = annotations["org.opencontainers.image.title"]; if (metadataPkgTitleJToken == null) { @@ -804,7 +783,6 @@ internal Tuple GetMetadataProperty(JObject foundTags, string pack return emptyTuple; } - _cmdletPassedIn.WriteVerbose("Successfully parsed all manifest metadata"); return new Tuple(metadataPkgName, metadata); } From 1a37443bf7cdc0e2b88b77860a2cefed4d5706a6 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Thu, 22 Feb 2024 10:20:23 -0800 Subject: [PATCH 55/57] Update test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 Co-authored-by: Aditya Patwardhan --- test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 | 1 - 1 file changed, 1 deletion(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 766262bf1..31361d8d7 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -4,7 +4,6 @@ $modPath = "$psscriptroot/../PSGetTestUtils.psm1" Import-Module $modPath -Force -Verbose - function CreateTestModule { param ( From d38e5d743e883ef71cf4c7d1b9cc310bf985c575 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Thu, 22 Feb 2024 10:21:07 -0800 Subject: [PATCH 56/57] Update test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 Co-authored-by: Aditya Patwardhan --- .../PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 31361d8d7..7398d65ed 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -77,7 +77,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $script:tmpScriptsFolderPath = Join-Path -Path $TestDrive -ChildPath "tmpScriptsPath" if(!(Test-Path $script:tmpScriptsFolderPath)) { - New-Item -Path $script:tmpScriptsFolderPath -ItemType Directory -Force + $null = New-Item -Path $script:tmpScriptsFolderPath -ItemType Directory -Force } # Path to folder, within our test folder, where we store invalid module and script files used for testing From 1a8745df66b11f3ff76cc0bb264d9cf408cb37e6 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Thu, 22 Feb 2024 10:23:39 -0800 Subject: [PATCH 57/57] Update test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 Co-authored-by: Aditya Patwardhan --- .../PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 index 7398d65ed..2b1a3ea64 100644 --- a/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceACRServer.Tests.ps1 @@ -71,7 +71,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { # Create temp destination path $script:destinationPath = [IO.Path]::GetFullPath((Join-Path -Path $TestDrive -ChildPath "tmpDestinationPath")) - New-Item $script:destinationPath -ItemType directory -Force + $null = New-Item $script:destinationPath -ItemType directory -Force #Create folder where we shall place all script files to be published for these tests $script:tmpScriptsFolderPath = Join-Path -Path $TestDrive -ChildPath "tmpScriptsPath"