diff --git a/src/dsc/psresourceget.ps1 b/src/dsc/psresourceget.ps1 index 9c8752722..b4a88d0fc 100644 --- a/src/dsc/psresourceget.ps1 +++ b/src/dsc/psresourceget.ps1 @@ -59,42 +59,35 @@ class PSResource { $this._exist = $false } + ## $this is the current state of the resource and $other is the desired state [bool] IsInDesiredState([PSResource] $other) { $retValue = $true - $psResourceSplat = @{ - Name = $this.name - Version = if ($this.version) { $this.version } else { '*' } - } - - Get-PSResource @psResourceSplat | Where-Object { - ($null -eq $this.scope -or $_.Scope -eq $this.scope) -and - ($null -eq $this.repositoryName -or $_.Repository -eq $this.repositoryName) - } | Select-Object -First 1 | ForEach-Object { - Write-Trace -message "Matching resource found: Name=$($_.Name), Version=$($_.Version), Scope=$($_.Scope), Repository=$($_.Repository), PreRelease=$($_.PreRelease)" -level debug - $this._exist = $true - } - if ($this.name -ne $other.name) { Write-Trace -message "Name mismatch: $($this.name) vs $($other.name)" -level debug $retValue = $false } - elseif ($null -ne $this.version -and $null -ne $other.version -and -not (SatisfiesVersion -version $this.version -versionRange $other.version)) { + ## Compare _exist first. When the resource should not exist, only its absence matters + elseif ($this._exist -ne $other._exist) { + Write-Trace -message "_exist mismatch: $($this._exist) vs $($other._exist)" -level debug + $retValue = $false + } + elseif (-not $other._exist) { + Write-Trace -message "Resource '$($this.name)' does not exist, as desired." -level debug + } + ## The string properties are empty instead of null when not specified, which means there is no constraint + elseif (-not [string]::IsNullOrEmpty($other.version) -and -not (SatisfiesVersion -version $this.version -versionRange $other.version)) { Write-Trace -message "Version mismatch: $($this.version) vs $($other.version)" -level debug $retValue = $false } - elseif ($null -ne $this.scope -and $this.scope -ne $other.scope) { + elseif ($this.scope -ne $other.scope) { Write-Trace -message "Scope mismatch: $($this.scope) vs $($other.scope)" -level debug $retValue = $false } - elseif ($null -ne $this.repositoryName -and $this.repositoryName -ne $other.repositoryName) { + elseif (-not [string]::IsNullOrEmpty($other.repositoryName) -and $this.repositoryName -ne $other.repositoryName) { Write-Trace -message "Repository mismatch: $($this.repositoryName) vs $($other.repositoryName)" -level debug $retValue = $false } - elseif ($this._exist -ne $other._exist) { - Write-Trace -message "_exist mismatch: $($this._exist) vs $($other._exist)" -level debug - $retValue = $false - } return $retValue } @@ -133,31 +126,19 @@ class PSResourceList { return $false } - if ($null -ne $this.resources -and $this.resources.Count -ne $other.resources.Count) { + if ($this.resources.Count -ne $other.resources.Count) { Write-Trace -message "Resources count mismatch: $($this.resources.Count) vs $($other.resources.Count)" -level debug return $false } - foreach ($otherResource in $other.resources) { - $found = $false - foreach ($resource in $this.resources) { - if ($resource.IsInDesiredState($otherResource)) { - $found = $true - break - } - } + ## Every desired resource has to be in desired state, not only the first one + $pendingActions = @(GetPSResourceListActions -desiredResources $other.resources -currentResources $this.resources | Where-Object { $_.action -ne 'None' }) - if ($found) { - Write-Trace -message "Resource match found for: $($otherResource.name)" -level debug - break - } - else { - Write-Trace -message "Resource mismatch for: $($otherResource.name)" -level debug - return $false - } + foreach ($pendingAction in $pendingActions) { + Write-Trace -message "Resource mismatch for: $($pendingAction.desired.name). Required action: $($pendingAction.action)" -level debug } - return $true + return $pendingActions.Count -eq 0 } [string] ToJson() { @@ -309,8 +290,9 @@ function ConvertInputToPSResource( } # catch any un-caught exception and write it to the error stream +# trace it as an error, otherwise only the exit code description from the manifest is shown to the user trap { - Write-Trace -message "Exiting with error code 1 due to unhandled exception: $($_.Exception.Message)" -level debug + Write-Trace -message "Exiting with error code 1 due to unhandled exception: $($_.Exception.Message)" -level error exit [ExitCode]::Error } @@ -319,12 +301,7 @@ function GetPSResourceList { [PSCustomObject]$inputObj ) - $inputResources = @() - $inputResources += if ($inputObj.resources) { - $inputObj.resources | ForEach-Object { - ConvertInputToPSResource -inputObj $_ -repositoryName $inputObj.repositoryName - } - } + $inputResources = @(ConvertInputToPSResourceList -inputObj $inputObj) $repositoryState = Get-PSResourceRepository -Name $inputObj.repositoryName -ErrorAction SilentlyContinue @@ -369,6 +346,8 @@ function GetPSResourceList { $resolvedResources = @() + # Resolve exactly one current resource per input resource, in input order. + # GetPSResourceListActions relies on this to pair the desired and the current resources by index. foreach ($inputResource in $inputResources) { $matchingResources = $allPSResources | Where-Object { $_.Name -eq $inputResource.Name } @@ -379,9 +358,8 @@ function GetPSResourceList { try { SatisfiesVersion -version $_.Version -versionRange $inputResource.Version } catch { $false } } | Select-Object -First 1 } - elseif (-not ($resolvedResources | Where-Object { $_.Name -eq $inputResource.Name })) { + else { # No version constraint: any installed version means the resource exists. - # Only record the first match so that one input resource maps to one current resource. Write-Trace -message "No version constraint for input: $($inputResource.Name). Treating installed version $($matchingResources[0].Version) as a match." -level debug $preferred = $matchingResources | Select-Object -First 1 } @@ -392,8 +370,10 @@ function GetPSResourceList { } else { # Installed but doesn't satisfy the version range - report actual installed version with _exist = false - $fallback = $matchingResources | Select-Object -First 1 - Write-Trace -message "Resource '$($inputResource.Name)' installed at '$($fallback.Version)' does not satisfy requested range '$($inputResource.Version)'. Reporting _exist = false." -level debug + # Use a copy, the installed resource can already be resolved for another input resource with the same name + $installed = $matchingResources | Select-Object -First 1 + Write-Trace -message "Resource '$($inputResource.Name)' installed at '$($installed.Version)' does not satisfy requested range '$($inputResource.Version)'. Reporting _exist = false." -level debug + $fallback = [PSResource]::new($installed.name, $installed.version, $installed.scope, $installed.repositoryName, $installed.preRelease) $fallback._exist = $false $resolvedResources += $fallback } @@ -407,6 +387,54 @@ function GetPSResourceList { PopulatePSResourceListObjectByRepository -resourcesExist $resolvedResources -inputResources $inputResources -repositoryName $inputPSResourceList.RepositoryName -trustedRepository $inputPSResourceList.trustedRepository } +function ConvertInputToPSResourceList { + param( + [PSCustomObject]$inputObj + ) + + ## Piping a missing resources property would still run ForEach-Object once with a null input + if ($inputObj.resources) { + $inputObj.resources | ForEach-Object { + ConvertInputToPSResource -inputObj $_ -repositoryName $inputObj.repositoryName + } + } +} + +## Pairs every desired resource with its current resource and decides the action needed to reach the desired state. +## GetPSResourceList returns exactly one current resource per input resource, in input order, so they are paired by index. +## The test, set and what-if operations all use this, so that they always agree on what has to happen. +function GetPSResourceListActions { + param( + [PSResource[]]$desiredResources, + [PSResource[]]$currentResources + ) + + if ($desiredResources.Count -ne $currentResources.Count) { + throw "Cannot pair the desired and current resources. Desired count: $($desiredResources.Count), current count: $($currentResources.Count)." + } + + for ($i = 0; $i -lt $desiredResources.Count; $i++) { + $desired = $desiredResources[$i] + $current = $currentResources[$i] + + $action = if ($current.IsInDesiredState($desired)) { + 'None' + } + elseif ($desired._exist) { + 'Install' + } + else { + 'Uninstall' + } + + [pscustomobject]@{ + desired = $desired + current = $current + action = $action + } + } +} + function GetOperation { param( [string]$ResourceType @@ -474,8 +502,7 @@ function TestPSResourceList { [PSCustomObject]$inputObj ) - $inputResources = @() - $inputResources += $inputObj.resources | ForEach-Object { ConvertInputToPSResource -inputObj $_ -repositoryName $inputObj.repositoryName } + $inputResources = @(ConvertInputToPSResourceList -inputObj $inputObj) $repositoryState = Get-PSResourceRepository -Name $inputObj.repositoryName -ErrorAction SilentlyContinue @@ -485,6 +512,8 @@ function TestPSResourceList { $retValue._inDesiredState = $false $retValue.ToJsonForTest() '["repositoryName", "resources"]' + ## DSC expects exactly one state and one diff line + return } $inputPSResourceList = [PSResourceList]::new($inputObj.repositoryName, $inputResources, $repositoryState.Trusted) @@ -585,17 +614,19 @@ function WhatIfPSResourceList { ) $repositoryName = $inputObj.repositoryName + $desiredResources = @(ConvertInputToPSResourceList -inputObj $inputObj) $currentState = GetPSResourceList -inputObj $inputObj $projectedResources = @() - $inputObj.resources | ForEach-Object { - $resourceDesiredState = ConvertInputToPSResource -inputObj $_ -repositoryName $repositoryName + + ## Use the same actions as the set operation, so that what-if reports what set is going to do + foreach ($resourceAction in @(GetPSResourceListActions -desiredResources $desiredResources -currentResources $currentState.resources)) { + $resourceDesiredState = $resourceAction.desired + $currentResource = $resourceAction.current $name = $resourceDesiredState.name $version = $resourceDesiredState.version - $scope = if ($resourceDesiredState.scope) { $resourceDesiredState.scope } else { [Scope]'CurrentUser' } - $currentResource = $currentState.resources | Where-Object { $_.name -eq $name } | Select-Object -First 1 - if (-not $resourceDesiredState._exist -and $null -ne $currentResource -and $currentResource._exist) { - $msg = "Would uninstall resource '$name'" + if ($resourceAction.action -eq 'Uninstall') { + $msg = if ($version) { "Would uninstall resource '$name' version '$version'" } else { "Would uninstall resource '$name'" } Write-Trace -message "WhatIf: $msg." -level debug $resource = [PSResource]::new( $currentResource.name, @@ -608,22 +639,17 @@ function WhatIfPSResourceList { $resource._metadata = [pscustomobject]@{ whatIf = @($msg) } $projectedResources += $resource } - elseif ($resourceDesiredState._exist -and ($null -eq $currentResource -or -not $currentResource._exist)) { + elseif ($resourceAction.action -eq 'Install') { $versionStr = if ($version) { $version } else { 'latest' } $msg = "Would install resource '$name' version '$versionStr'" Write-Trace -message "WhatIf: $msg." -level debug - $resource = [PSResource]::new($name, $versionStr, [Scope]$scope, $repositoryName, $resourceDesiredState.preRelease) + $resource = [PSResource]::new($name, $versionStr, $resourceDesiredState.scope, $repositoryName, $resourceDesiredState.preRelease) $resource._metadata = [pscustomobject]@{ whatIf = @($msg) } $projectedResources += $resource } else { Write-Trace -message "WhatIf: Resource '$name' is already in desired state." -level debug - if ($null -ne $currentResource) { - $projectedResources += $currentResource - } - else { - $projectedResources += $resourceDesiredState - } + $projectedResources += $currentResource } } @@ -658,50 +684,53 @@ function SetPSResourceList { } $repositoryName = $inputObj.repositoryName - $resourcesToUninstall = @() + $resourcesToUninstall = [System.Collections.Generic.Dictionary[string, psobject]]::new() $resourcesToInstall = [System.Collections.Generic.Dictionary[string, psobject]]::new() $resourcesChanged = $false + $desiredResources = @(ConvertInputToPSResourceList -inputObj $inputObj) $currentState = GetPSResourceList -inputObj $inputObj - $inputObj.resources | ForEach-Object { - $resourceDesiredState = ConvertInputToPSResource -inputObj $_ -repositoryName $repositoryName + foreach ($resourceAction in @(GetPSResourceListActions -desiredResources $desiredResources -currentResources $currentState.resources)) { + $resourceDesiredState = $resourceAction.desired $name = $resourceDesiredState.name - $version = $resourceDesiredState.version - $scope = if ($resourceDesiredState.scope) { $resourceDesiredState.scope } else { "CurrentUser" } - - # Resource should not exist - uninstall if it does - $currentState.resources | ForEach-Object { - - $isInDesiredState = $_.IsInDesiredState($resourceDesiredState) - - # Uninstall if resource should not exist but does - if (-not $resourceDesiredState._exist -and $_._exist) { - Write-Trace -message "Resource $($resourceDesiredState.name) exists but _exist is false. Adding to uninstall list." -level debug - $resourcesToUninstall += $_ - } - # Install if resource should exist but doesn't, or exists but not in desired state - elseif ($resourceDesiredState._exist -and (-not $_._exist -or -not $isInDesiredState)) { - Write-Trace -message "Resource $($resourceDesiredState.name) needs to be installed." -level debug - $versionStr = if ($version) { $resourceDesiredState.version } else { 'latest' } - $key = $name.ToLowerInvariant() + '-' + $versionStr.ToLowerInvariant() - if (-not $resourcesToInstall.ContainsKey($key)) { - $resourcesToInstall[$key] = $resourceDesiredState - } + $versionStr = if ($resourceDesiredState.version) { $resourceDesiredState.version } else { 'latest' } + + # Uninstall if resource should not exist but does + if ($resourceAction.action -eq 'Uninstall') { + Write-Trace -message "Resource $name exists but _exist is false. Adding to uninstall list." -level debug + # The resource has to be removed from the scope it is currently installed in + $key = $name.ToLowerInvariant() + '-' + $versionStr.ToLowerInvariant() + '-' + $resourceAction.current.scope + if (-not $resourcesToUninstall.ContainsKey($key)) { + $resourcesToUninstall[$key] = $resourceAction } - # Otherwise resource is in desired state, no action needed - else { - Write-Trace -message "Resource $($resourceDesiredState.name) is in desired state." -level debug + } + # Install if resource should exist but doesn't, or exists but not in desired state + elseif ($resourceAction.action -eq 'Install') { + Write-Trace -message "Resource $name needs to be installed." -level debug + $key = $name.ToLowerInvariant() + '-' + $versionStr.ToLowerInvariant() + if (-not $resourcesToInstall.ContainsKey($key)) { + $resourcesToInstall[$key] = $resourceDesiredState } } + # Otherwise resource is in desired state, no action needed + else { + Write-Trace -message "Resource $name is in desired state." -level debug + } } if ($resourcesToUninstall.Count -gt 0) { - Write-Trace -message "Uninstalling resources: $($resourcesToUninstall | ForEach-Object { "$($_.Name) - $($_.Version)" })" -level debug - $resourcesToUninstall | ForEach-Object { + Write-Trace -message "Uninstalling resources: $($resourcesToUninstall.Values | ForEach-Object { "$($_.current.name) - $($_.current.version)" })" -level debug + $resourcesToUninstall.Values | ForEach-Object { + # Only remove the requested version (range) when there is one, otherwise all versions are removed + $versionParam = @{} + if ($_.desired.version) { + $versionParam['Version'] = $_.desired.version + } + $cmdWarnings = $null - Uninstall-PSResource -Name $_.Name -Scope $scope -ErrorAction Stop -WarningVariable cmdWarnings + Uninstall-PSResource -Name $_.current.name @versionParam -Scope $_.current.scope -ErrorAction Stop -WarningVariable cmdWarnings foreach ($w in $cmdWarnings) { Write-Trace -message ([string]$w) -level warn } @@ -731,9 +760,15 @@ function SetPSResourceList { $name = $_.Name $version = $_.Version + # Install-PSResource does not accept an empty version, leave it out to install the latest version + $versionParam = @{} + if ($version) { + $versionParam['Version'] = $version + } + try { $cmdWarnings = $null - Install-PSResource -Name $_.Name -Version $_.Version -Scope $scope -Repository $repositoryName -ErrorAction Stop -TrustRepository:$inputObj.trustedRepository -Prerelease:$usePrerelease -Reinstall -WarningVariable cmdWarnings + Install-PSResource -Name $_.Name @versionParam -Scope $_.Scope -Repository $repositoryName -ErrorAction Stop -TrustRepository:$inputObj.trustedRepository -Prerelease:$usePrerelease -Reinstall -WarningVariable cmdWarnings foreach ($w in $cmdWarnings) { Write-Trace -message ([string]$w) -level warn } @@ -788,15 +823,15 @@ function SetOperation { } if ($null -eq $rep -and $inputObj._exist -ne $false) { - Register-PSResourceRepository @splatt + Register-PSResourceRepository @splatt -ErrorAction Stop } else { if ($inputObj._exist -eq $false) { Write-Trace -message "Repository $($inputObj.Name) exists and _exist is false. Deleting it." -level debug - Unregister-PSResourceRepository -Name $inputObj.Name + Unregister-PSResourceRepository -Name $inputObj.Name -ErrorAction Stop } else { - Set-PSResourceRepository @splatt + Set-PSResourceRepository @splatt -ErrorAction Stop } } @@ -834,7 +869,7 @@ function DeleteOperation { $rep = Get-PSResourceRepository -Name $inputObj.Name -ErrorAction SilentlyContinue if ($null -ne $rep) { - Unregister-PSResourceRepository -Name $inputObj.Name + Unregister-PSResourceRepository -Name $inputObj.Name -ErrorAction Stop } else { Write-Trace -message "Repository not found: $($inputObj.Name). Nothing to delete." -level debug diff --git a/test/DscResource/PSResourceGetDSCResource.Tests.ps1 b/test/DscResource/PSResourceGetDSCResource.Tests.ps1 index fafc91006..e093e2bd6 100644 --- a/test/DscResource/PSResourceGetDSCResource.Tests.ps1 +++ b/test/DscResource/PSResourceGetDSCResource.Tests.ps1 @@ -50,6 +50,23 @@ function SetupTestRepos { New-TestModule -moduleName $script:testModuleName3 -repoName $script:localRepo -packageVersion "1.0.0" -prereleaseLabel "" -tags @() } +function ResetDscTestModules { + # Remove the local test modules so that a test does not depend on the state left by another test + foreach ($moduleToRemove in @($script:testModuleName, $script:testModuleName2, $script:testModuleName3)) { + Uninstall-PSResource -Name $moduleToRemove -ErrorAction SilentlyContinue + } +} + +function InvokePSResourceListOperation { + param( + [string]$Operation, + [hashtable]$Properties + ) + + $resourceInput = $Properties | ConvertTo-Json -Depth 5 + & $script:dscExe resource $Operation --resource Microsoft.PowerShell.PSResourceGet/PSResourceList --input $resourceInput -o json | ConvertFrom-Json +} + Describe "DSC resource schema tests" -tags 'CI' { BeforeAll { @@ -79,6 +96,18 @@ Describe "DSC resource schema tests" -tags 'CI' { $pkgResource | Should -BeExactly 'Microsoft.PowerShell.PSResourceGet/PSResourceList' } + It 'DSC v3 resources are loaded from the build output' -Skip:$skipTest { + # DSC can also discover the resources of an installed PSResourceGet module. The manifest versions are the same, + # so that copy can win and the tests would then not run against the resources that were just built. + $expectedModulePath = (Resolve-Path -Path (Join-Path $env:BUILD_SOURCESDIRECTORY 'out')).Path + $resources = & $script:dscExe resource list 'Microsoft.PowerShell.PSResourceGet/*' -o json | ConvertFrom-Json + + $resources | Should -Not -BeNullOrEmpty + foreach ($resource in $resources) { + $resource.directory | Should -BeLike "$expectedModulePath*" -Because "the tests have to run against the built resources. Set DSC_RESOURCE_PATH to the module folder in 'out' (and the folder of pwsh) when another copy is discovered" + } + } + It 'Repository resource has expected properties' { $repoResource = & $script:dscExe resource schema --resource Microsoft.PowerShell.PSResourceGet/Repository -o json | convertfrom-json | select-object -first 1 $repoResource.properties.name.title | Should -BeExactly 'Name' @@ -182,6 +211,23 @@ Describe 'Repository Resource Tests' -Tags 'CI' { $outputText | Should -Not -Match 'Unhandled exception' } + It 'Shows the error message when an operation fails' { + # The uri scheme is not supported, so registering the repository fails without changing anything + $repoParams = @{ + name = 'TestRepoWithInvalidUri' + uri = 'ssh://www.doesnotexist.com/repo' + } + + $resourceInput = $repoParams | ConvertTo-Json -Depth 5 + + # The default trace level has to show the reason, and not only the description of the exit code + $output = & $script:dscExe resource set --resource Microsoft.PowerShell.PSResourceGet/Repository --input $resourceInput 2>&1 + $LASTEXITCODE | Should -Not -Be 0 + $output | Out-String | Should -Match 'Invalid Uri' + + Get-PSResourceRepository -Name 'TestRepoWithInvalidUri' -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } + It 'Can delete a Repository resource instance' { # First, create a repository to delete Register-PSResourceRepository -Name 'TestRepoToDelete' -uri 'https://www.doesnotexist.com' -ErrorAction SilentlyContinue -APIVersion Local @@ -444,6 +490,25 @@ Describe "PSResourceList Resource Tests" -Tags 'CI' { $getResult.actualState.resources[0].version | Should -BeExactly '5.0.0' $getResult.actualState.resources[0]._exist | Should -BeTrue } + + It 'Test returns one state and one diff when the repository does not exist' { + $resourceInput = @{ + repositoryName = 'RepositoryThatDoesNotExist' + resources = @(@{ name = $script:testModuleName }) + } | ConvertTo-Json -Depth 5 -Compress + + $testResult = & $script:dscExe resource test --resource Microsoft.PowerShell.PSResourceGet/PSResourceList --input $resourceInput -o json | ConvertFrom-Json + $LASTEXITCODE | Should -Be 0 + $testResult.inDesiredState | Should -BeFalse + + # DSC only reads the first two lines of the output, so invoke the resource script directly to verify all of it + $resourceDirectory = (& $script:dscExe resource list Microsoft.PowerShell.PSResourceGet/PSResourceList -o json | ConvertFrom-Json).directory + $resourceScript = Join-Path -Path $resourceDirectory -ChildPath 'psresourceget.ps1' + $stdout = $resourceInput | pwsh -NoLogo -NonInteractive -NoProfile -Command "`$Input | & '$resourceScript' -ResourceType psresourcelist -Operation test" 2>$null + + @($stdout).Count | Should -Be 2 + ($stdout[0] | ConvertFrom-Json)._inDesiredState | Should -BeFalse + } } Describe 'E2E tests for Repository resource' -Tags 'CI' { @@ -764,4 +829,254 @@ resources: $result = $out.results.result[0].afterState $result.resources[0]._metadata | Should -BeNullOrEmpty } + + It 'What-if only reports the version that is not installed when a resource is listed twice' { + Uninstall-PSResource -Name $script:testModuleName -ErrorAction SilentlyContinue + Install-PSResource -Name $script:testModuleName -Version '1.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + + $config_yaml = @" +`$schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json +resources: +- name: PSResourceList what-if same resource twice + type: Microsoft.PowerShell.PSResourceGet/PSResourceList + properties: + repositoryName: $script:localRepo + trustedRepository: true + resources: + - name: $script:testModuleName + version: '[[1.0.0,2.0.0)' + - name: $script:testModuleName + version: '[[5.0.0,6.0.0)' +"@ + + $out = & $script:dscExe config set --what-if --input $config_yaml 2>$TestDrive/error.log | ConvertFrom-Json + $LASTEXITCODE | Should -Be 0 -Because (Get-Content -Path $TestDrive/error.log -Raw) + + $result = $out.results.result[0].afterState + $result.resources.Count | Should -Be 2 + $result.resources[0]._exist | Should -BeTrue + $result.resources[0]._metadata | Should -BeNullOrEmpty + $result.resources[1]._metadata.whatIf[0] | Should -Match 'Would install' + + Get-PSResource -Name $script:testModuleName -Version '5.0.0' -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } +} + +Describe 'PSResourceList desired state tests' -Tags 'CI' { + BeforeAll { + $skipTest = $null -eq (Get-Command -Type Application -Name pwsh -ErrorAction SilentlyContinue) + + if ($skipTest) { + $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() + $PSDefaultParameterValues['it:skip'] = $skipTest + return + } + + SetupDsc + SetupTestRepos + + ## The tests install modules in-process to set up the state. DSC uses PowerShell 7, which does not see modules installed by Windows PowerShell. + $isOnWindowsPowerShell = $PSVersionTable.PSVersion.Major -lt 6 + + $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() + $PSDefaultParameterValues['it:skip'] = $isOnWindowsPowerShell + } + + AfterAll { + $global:PSDefaultParameterValues = $originalDefaultParameterValues + + if ($skipTest) { + return + } + + ResetDscTestModules + Get-RevertPSResourceRepositoryFile + } + + It 'Test checks every resource and not only the first one' { + ResetDscTestModules + Install-PSResource -Name $script:testModuleName -Version '5.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + + $installed = @{ name = $script:testModuleName; version = '5.0.0' } + $notInstalled = @{ name = $script:testModuleName3; version = '1.0.0' } + + $testResult = InvokePSResourceListOperation -Operation test -Properties @{ repositoryName = $script:localRepo; resources = @($installed, $notInstalled) } + $testResult.inDesiredState | Should -BeFalse + + $testResult = InvokePSResourceListOperation -Operation test -Properties @{ repositoryName = $script:localRepo; resources = @($notInstalled, $installed) } + $testResult.inDesiredState | Should -BeFalse + } + + It 'Test is in desired state for an installed resource without a version' { + ResetDscTestModules + Install-PSResource -Name $script:testModuleName -Version '5.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + + $testResult = InvokePSResourceListOperation -Operation test -Properties @{ + repositoryName = $script:localRepo + resources = @(@{ name = $script:testModuleName }) + } + + $testResult.inDesiredState | Should -BeTrue + } + + It 'Test is in desired state when the version that should not exist is not installed' { + ResetDscTestModules + Install-PSResource -Name $script:testModuleName -Version '5.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + + $testResult = InvokePSResourceListOperation -Operation test -Properties @{ + repositoryName = $script:localRepo + resources = @(@{ name = $script:testModuleName; version = '[1.0.0,2.0.0)'; _exist = $false }) + } + + $testResult.inDesiredState | Should -BeTrue + } + + It 'Set installs a resource without a version and does not install it again' { + ResetDscTestModules + + $properties = @{ + repositoryName = $script:localRepo + trustedRepository = $true + resources = @(@{ name = $script:testModuleName3 }) + } + + $setResult = InvokePSResourceListOperation -Operation set -Properties $properties + $LASTEXITCODE | Should -Be 0 + $setResult.changedProperties | Should -Contain 'resources' + + $installed = Get-PSResource -Name $script:testModuleName3 + $installed.Version | Should -Be '1.0.0' + + $setResult = InvokePSResourceListOperation -Operation set -Properties $properties + $LASTEXITCODE | Should -Be 0 + $setResult.changedProperties | Should -BeNullOrEmpty + (Get-PSResource -Name $script:testModuleName3).InstalledDate | Should -Be $installed.InstalledDate + } + + It 'Set does not install resources again that are in desired state' { + ResetDscTestModules + Install-PSResource -Name $script:testModuleName -Version '5.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + Install-PSResource -Name $script:testModuleName2 -Version '5.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + $installedDates = (Get-PSResource -Name $script:testModuleName, $script:testModuleName2).InstalledDate + + $setResult = InvokePSResourceListOperation -Operation set -Properties @{ + repositoryName = $script:localRepo + trustedRepository = $true + resources = @( + @{ name = $script:testModuleName; version = '5.0.0' }, + @{ name = $script:testModuleName2; version = '5.0.0' } + ) + } + + $LASTEXITCODE | Should -Be 0 + $setResult.changedProperties | Should -BeNullOrEmpty + (Get-PSResource -Name $script:testModuleName, $script:testModuleName2).InstalledDate | Should -Be $installedDates + } + + It 'Set only uninstalls the resource that should not exist' { + ResetDscTestModules + Install-PSResource -Name $script:testModuleName -Version '1.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + Install-PSResource -Name $script:testModuleName -Version '5.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + Install-PSResource -Name $script:testModuleName2 -Version '5.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + $installedDate = (Get-PSResource -Name $script:testModuleName -Version '5.0.0').InstalledDate + + $null = InvokePSResourceListOperation -Operation set -Properties @{ + repositoryName = $script:localRepo + trustedRepository = $true + resources = @( + @{ name = $script:testModuleName; version = '5.0.0' }, + @{ name = $script:testModuleName2; _exist = $false } + ) + } + + $LASTEXITCODE | Should -Be 0 + Get-PSResource -Name $script:testModuleName2 -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + Get-PSResource -Name $script:testModuleName | Should -HaveCount 2 + (Get-PSResource -Name $script:testModuleName -Version '5.0.0').InstalledDate | Should -Be $installedDate + } + + It 'Set only uninstalls the version that should not exist' { + ResetDscTestModules + Install-PSResource -Name $script:testModuleName -Version '1.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + Install-PSResource -Name $script:testModuleName -Version '5.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + $installedDate = (Get-PSResource -Name $script:testModuleName -Version '5.0.0').InstalledDate + + $null = InvokePSResourceListOperation -Operation set -Properties @{ + repositoryName = $script:localRepo + trustedRepository = $true + resources = @( + @{ name = $script:testModuleName; version = '5.0.0' }, + @{ name = $script:testModuleName; version = '[1.0.0,2.0.0)'; _exist = $false } + ) + } + + $LASTEXITCODE | Should -Be 0 + $installed = Get-PSResource -Name $script:testModuleName + $installed | Should -HaveCount 1 + $installed.Version | Should -Be '5.0.0' + $installed.InstalledDate | Should -Be $installedDate + } + + It 'Set uninstalls a resource from the scope it is installed in' { + ResetDscTestModules + Install-PSResource -Name $script:testModuleName -Version '5.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + + # The scope of the last resource must not be used for the other resources + $null = InvokePSResourceListOperation -Operation set -Properties @{ + repositoryName = $script:localRepo + resources = @( + @{ name = $script:testModuleName; _exist = $false }, + @{ name = $script:testModuleName3; scope = 'AllUsers'; _exist = $false } + ) + } + + $LASTEXITCODE | Should -Be 0 + Get-PSResource -Name $script:testModuleName -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } + + It 'Set installs a resource in its own scope' { + ResetDscTestModules + + try { + # The scope of the last resource must not be used for the other resources + $null = InvokePSResourceListOperation -Operation set -Properties @{ + repositoryName = $script:localRepo + trustedRepository = $true + resources = @( + @{ name = $script:testModuleName; version = '5.0.0' }, + @{ name = $script:testModuleName3; scope = 'AllUsers'; _exist = $false } + ) + } + + $LASTEXITCODE | Should -Be 0 + Get-PSResource -Name $script:testModuleName -Scope CurrentUser -ErrorAction SilentlyContinue | Should -Not -BeNullOrEmpty + Get-PSResource -Name $script:testModuleName -Scope AllUsers -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } + finally { + Uninstall-PSResource -Name $script:testModuleName -Scope AllUsers -ErrorAction SilentlyContinue + } + } + + It 'Set installs a resource in the AllUsers scope - Windows only' -Skip:(!((Get-IsWindows) -and (Test-IsAdmin)) -or $PSVersionTable.PSVersion.Major -lt 6) { + ResetDscTestModules + Uninstall-PSResource -Name $script:testModuleName -Scope AllUsers -ErrorAction SilentlyContinue + + try { + $null = InvokePSResourceListOperation -Operation set -Properties @{ + repositoryName = $script:localRepo + trustedRepository = $true + resources = @( + @{ name = $script:testModuleName; version = '5.0.0'; scope = 'AllUsers' }, + @{ name = $script:testModuleName3; _exist = $false } + ) + } + + $LASTEXITCODE | Should -Be 0 + Get-PSResource -Name $script:testModuleName -Scope AllUsers -ErrorAction SilentlyContinue | Should -Not -BeNullOrEmpty + Get-PSResource -Name $script:testModuleName -Scope CurrentUser -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } + finally { + Uninstall-PSResource -Name $script:testModuleName -Scope AllUsers -ErrorAction SilentlyContinue + } + } }