From 5f2921598d8bb9adb71258e54ecbfbe0f0724433 Mon Sep 17 00:00:00 2001 From: "G.Reijn" <26114636+Gijsreyn@users.noreply.github.com> Date: Sun, 20 Sep 2026 05:55:02 +0200 Subject: [PATCH 1/2] fix(dsc): make PSResourceList test, set and what-if agree on desired state --- src/dsc/psresourceget.ps1 | 235 +++++++------ .../PSResourceGetDSCResource.Tests.ps1 | 315 ++++++++++++++++++ 2 files changed, 450 insertions(+), 100 deletions(-) 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 + } + } } From 29f5aa050cb0dabf6d515b4f70c28ce608c956f3 Mon Sep 17 00:00:00 2001 From: "G.Reijn" <26114636+Gijsreyn@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:24:27 +0200 Subject: [PATCH 2/2] Resolve remarks Aditya --- src/dsc/psresourceget.ps1 | 260 +++++++----------- .../PSResourceGetDSCResource.Tests.ps1 | 70 +++++ 2 files changed, 162 insertions(+), 168 deletions(-) diff --git a/src/dsc/psresourceget.ps1 b/src/dsc/psresourceget.ps1 index b4a88d0fc..3a15f055d 100644 --- a/src/dsc/psresourceget.ps1 +++ b/src/dsc/psresourceget.ps1 @@ -120,27 +120,6 @@ class PSResourceList { $this.trustedRepository = $trustedRepository } - [bool] IsInDesiredState([PSResourceList] $other) { - if ($this.repositoryName -ne $other.repositoryName) { - Write-Trace -message "RepositoryName mismatch: $($this.repositoryName) vs $($other.repositoryName)" -level debug - return $false - } - - 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 - } - - ## 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' }) - - foreach ($pendingAction in $pendingActions) { - Write-Trace -message "Resource mismatch for: $($pendingAction.desired.name). Required action: $($pendingAction.action)" -level debug - } - - return $pendingActions.Count -eq 0 - } - [string] ToJson() { ## Assign the array directly so that an empty list serializes as [] rather than null [object[]]$resourceObjects = @() @@ -296,126 +275,117 @@ trap { exit [ExitCode]::Error } +## The current state of a PSResourceList is the current resource of every desired resource, in input order function GetPSResourceList { param( [PSCustomObject]$inputObj ) - $inputResources = @(ConvertInputToPSResourceList -inputObj $inputObj) - $repositoryState = Get-PSResourceRepository -Name $inputObj.repositoryName -ErrorAction SilentlyContinue + $currentResources = @(GetPSResourceListActions -inputObj $inputObj | ForEach-Object { $_.current }) - if (-not $repositoryState) { - Write-Trace -message "Repository not found: $($inputObj.repositoryName)" -level info - $emptyResources = @() - $emptyResources += $inputResources | ForEach-Object { - [PSResource]::new($_.Name) - } - - return [PSResourceList]::new($inputObj.repositoryName, $emptyResources, $false) - } + return [PSResourceList]::new($inputObj.repositoryName, $currentResources, [bool]$repositoryState.Trusted) +} - $inputPSResourceList = [PSResourceList]::new($inputObj.repositoryName, $inputResources, $repositoryState.Trusted) +function ConvertInputToPSResourceList { + param( + [PSCustomObject]$inputObj + ) - $allPSResources = @() - if ($inputPSResourceList.repositoryName) { - $currentUserPSResources = Get-PSResource -Scope CurrentUser -ErrorAction SilentlyContinue | Where-Object { $_.Repository -eq $inputPSResourceList.RepositoryName } - $allUsersPSResources = Get-PSResource -Scope AllUsers -ErrorAction SilentlyContinue | Where-Object { $_.Repository -eq $inputPSResourceList.RepositoryName } + if ($inputObj.resources) { + $inputObj.resources | ForEach-Object { + ConvertInputToPSResource -inputObj $_ -repositoryName $inputObj.repositoryName + } } +} - $allPSResources += $currentUserPSResources | ForEach-Object { - [PSResource]::new( - $_.Name, - $_.Prerelease ? $_.Version.ToString() + "-" + $_.Prerelease : $_.Version.ToString(), - [Scope]"CurrentUser", - $_.Repository, - $_.PreRelease - ) - } +## Gets the resources that are installed from the repository, in both scopes +function GetInstalledPSResources { + param( + [string]$repositoryName + ) - $allPSResources += $allUsersPSResources | ForEach-Object { - [PSResource]::new( - $_.Name, - $_.Prerelease ? $_.Version.ToString() + "-" + $_.Prerelease : $_.Version.ToString(), - [Scope]"AllUsers", - $_.Repository, - $_.PreRelease ? $true : $false - ) + if (-not $repositoryName) { + return } - $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 } - - if ($matchingResources) { - $preferred = $null - if ($inputResource.Version) { - $preferred = $matchingResources | Where-Object { - try { SatisfiesVersion -version $_.Version -versionRange $inputResource.Version } catch { $false } - } | Select-Object -First 1 - } - else { - # No version constraint: any installed version means the resource exists. - 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 - } - - if ($preferred) { - Write-Trace -message "Resource '$($inputResource.Name)' version '$($preferred.Version)' satisfies requested range '$($inputResource.Version)'." -level debug - $resolvedResources += $preferred - } - else { - # Installed but doesn't satisfy the version range - report actual installed version with _exist = false - # 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 - } - } - else { - Write-Trace -message "Resource '$($inputResource.Name)' is not installed. Reporting _exist = false." -level debug - $resolvedResources += [PSResource]::new($inputResource.Name) + foreach ($scope in @('CurrentUser', 'AllUsers')) { + Get-PSResource -Scope $scope -ErrorAction SilentlyContinue | Where-Object { $_.Repository -eq $repositoryName } | ForEach-Object { + [PSResource]::new( + $_.Name, + $_.Prerelease ? $_.Version.ToString() + "-" + $_.Prerelease : $_.Version.ToString(), + [Scope]$scope, + $_.Repository, + $_.Prerelease ? $true : $false + ) } } - - PopulatePSResourceListObjectByRepository -resourcesExist $resolvedResources -inputResources $inputResources -repositoryName $inputPSResourceList.RepositoryName -trustedRepository $inputPSResourceList.trustedRepository } -function ConvertInputToPSResourceList { +## Resolves the current state of one desired resource. The installed resources are matched by name, and a copy in the +## desired scope is preferred over a copy in the other scope, so that set converges when the resource is installed in both. +function ResolveCurrentPSResource { param( - [PSCustomObject]$inputObj + [PSResource]$desiredResource, + [PSResource[]]$installedResources ) - ## 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 - } + $name = $desiredResource.name + $matchingResources = @($installedResources | Where-Object { $_.name -eq $name }) + + if ($matchingResources.Count -eq 0) { + Write-Trace -message "Resource '$name' is not installed. Reporting _exist = false." -level debug + return [PSResource]::new($name) } + + $candidates = @($matchingResources | Where-Object { $_.scope -eq $desiredResource.scope }) + @($matchingResources | Where-Object { $_.scope -ne $desiredResource.scope }) + + if (-not $desiredResource.version) { + # No version constraint: any installed version means the resource exists. + Write-Trace -message "No version constraint for input: $name. Treating installed version $($candidates[0].version) in scope $($candidates[0].scope) as a match." -level debug + return $candidates[0] + } + + $preferred = $candidates | Where-Object { + try { SatisfiesVersion -version $_.version -versionRange $desiredResource.version } catch { $false } + } | Select-Object -First 1 + + if ($preferred) { + Write-Trace -message "Resource '$name' version '$($preferred.version)' in scope $($preferred.scope) satisfies requested range '$($desiredResource.version)'." -level debug + return $preferred + } + + # Installed but doesn't satisfy the version range - report actual installed version with _exist = false + # Use a copy, the installed resource can also be the current resource of another desired resource with the same name + $installed = $candidates[0] + Write-Trace -message "Resource '$name' installed at '$($installed.version)' does not satisfy requested range '$($desiredResource.version)'. Reporting _exist = false." -level debug + $fallback = [PSResource]::new($installed.name, $installed.version, $installed.scope, $installed.repositoryName, $installed.preRelease) + $fallback._exist = $false + return $fallback } ## 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. +## Every desired resource resolves its own current resource by name, so the order of the installed resources does not matter. +## The get, 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 + [PSCustomObject]$inputObj ) - if ($desiredResources.Count -ne $currentResources.Count) { - throw "Cannot pair the desired and current resources. Desired count: $($desiredResources.Count), current count: $($currentResources.Count)." + $desiredResources = @(ConvertInputToPSResourceList -inputObj $inputObj) + + if (Get-PSResourceRepository -Name $inputObj.repositoryName -ErrorAction SilentlyContinue) { + $installedResources = @(GetInstalledPSResources -repositoryName $inputObj.repositoryName) + } + else { + ## Nothing counts as installed from a repository that is not registered + Write-Trace -message "Repository not found: $($inputObj.repositoryName)" -level info + $installedResources = @() } - for ($i = 0; $i -lt $desiredResources.Count; $i++) { - $desired = $desiredResources[$i] - $current = $currentResources[$i] + foreach ($desired in $desiredResources) { + $current = ResolveCurrentPSResource -desiredResource $desired -installedResources $installedResources $action = if ($current.IsInDesiredState($desired)) { 'None' @@ -518,9 +488,14 @@ function TestPSResourceList { $inputPSResourceList = [PSResourceList]::new($inputObj.repositoryName, $inputResources, $repositoryState.Trusted) - $currentState = GetPSResourceList -inputObj $inputObj - $inDesiredState = $currentState.IsInDesiredState($inputPSResourceList) + $resourceActions = @(GetPSResourceListActions -inputObj $inputObj) + $currentState = [PSResourceList]::new($inputObj.repositoryName, @($resourceActions | ForEach-Object { $_.current }), $repositoryState.Trusted) + $pendingActions = @($resourceActions | Where-Object { $_.action -ne 'None' }) + foreach ($pendingAction in $pendingActions) { + Write-Trace -message "Resource mismatch for: $($pendingAction.desired.name). Required action: $($pendingAction.action)" -level debug + } + $inDesiredState = $pendingActions.Count -eq 0 $currentState._inDesiredState = $inDesiredState if ($inDesiredState) { @@ -614,12 +589,11 @@ function WhatIfPSResourceList { ) $repositoryName = $inputObj.repositoryName - $desiredResources = @(ConvertInputToPSResourceList -inputObj $inputObj) - $currentState = GetPSResourceList -inputObj $inputObj + $psRepository = Get-PSResourceRepository -Name $repositoryName -ErrorAction SilentlyContinue $projectedResources = @() ## 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)) { + foreach ($resourceAction in @(GetPSResourceListActions -inputObj $inputObj)) { $resourceDesiredState = $resourceAction.desired $currentResource = $resourceAction.current $name = $resourceDesiredState.name @@ -656,8 +630,6 @@ function WhatIfPSResourceList { ## Report the same failures a real set operation would hit before installing anything $installRequired = @($projectedResources | Where-Object { $_._exist -and $null -ne $_._metadata }).Count -gt 0 if ($installRequired) { - $psRepository = Get-PSResourceRepository -Name $repositoryName -ErrorAction SilentlyContinue - if (-not $psRepository) { Write-Trace -level error -message "Repository '$repositoryName' not found. Cannot install resources." exit [ExitCode]::RepositoryNotFound @@ -669,7 +641,7 @@ function WhatIfPSResourceList { } } - $list = [PSResourceList]::new($repositoryName, $projectedResources, $currentState.trustedRepository) + $list = [PSResourceList]::new($repositoryName, $projectedResources, [bool]$psRepository.Trusted) $list.ToJson() } @@ -689,10 +661,7 @@ function SetPSResourceList { $resourcesChanged = $false - $desiredResources = @(ConvertInputToPSResourceList -inputObj $inputObj) - $currentState = GetPSResourceList -inputObj $inputObj - - foreach ($resourceAction in @(GetPSResourceListActions -desiredResources $desiredResources -currentResources $currentState.resources)) { + foreach ($resourceAction in @(GetPSResourceListActions -inputObj $inputObj)) { $resourceDesiredState = $resourceAction.desired $name = $resourceDesiredState.name $versionStr = if ($resourceDesiredState.version) { $resourceDesiredState.version } else { 'latest' } @@ -709,7 +678,8 @@ function SetPSResourceList { # 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() + # The same name and version can be requested in both scopes, so the scope is part of the key + $key = $name.ToLowerInvariant() + '-' + $versionStr.ToLowerInvariant() + '-' + $resourceDesiredState.scope if (-not $resourcesToInstall.ContainsKey($key)) { $resourcesToInstall[$key] = $resourceDesiredState } @@ -896,52 +866,6 @@ function DeleteOperation { } } -function PopulatePSResourceListObjectByRepository { - param ( - $resourcesExist, - $inputResources, - $repositoryName, - $trustedRepository - ) - - $resources = @() - - if (-not $resourcesExist) { - $resources = $inputResources | ForEach-Object { - [PSResource]::new( - $_.Name - ) - } - } - else { - $resources += $resourcesExist | ForEach-Object { - $srcExist = $_._exist - $r = if ($_.version) { - [PSResource]::new( - $_.Name, - $_.Version.ToString(), - $_.Scope, - $_.RepositoryName, - $_.PreRelease ? $true : $false - ) - } else { - [PSResource]::new($_.Name) - } - $r._exist = $srcExist - $r - } - } - - $psresourceListObj = - [PSResourceList]::new( - $repositoryName, - $resources, - $trustedRepository - ) - - return $psresourceListObj -} - function PopulatePSResourceListObject { param ( $allUsersPSResources, diff --git a/test/DscResource/PSResourceGetDSCResource.Tests.ps1 b/test/DscResource/PSResourceGetDSCResource.Tests.ps1 index e093e2bd6..2a7b52a4b 100644 --- a/test/DscResource/PSResourceGetDSCResource.Tests.ps1 +++ b/test/DscResource/PSResourceGetDSCResource.Tests.ps1 @@ -907,6 +907,23 @@ Describe 'PSResourceList desired state tests' -Tags 'CI' { $testResult.inDesiredState | Should -BeFalse } + It 'Test is in desired state regardless of the order of the resources' { + 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 + Install-PSResource -Name $script:testModuleName3 -Version '1.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + + $first = @{ name = $script:testModuleName; version = '5.0.0' } + $second = @{ name = $script:testModuleName2 } + $third = @{ name = $script:testModuleName3; version = '[1.0.0,2.0.0)' } + + $testResult = InvokePSResourceListOperation -Operation test -Properties @{ repositoryName = $script:localRepo; resources = @($first, $second, $third) } + $testResult.inDesiredState | Should -BeTrue + + $testResult = InvokePSResourceListOperation -Operation test -Properties @{ repositoryName = $script:localRepo; resources = @($third, $first, $second) } + $testResult.inDesiredState | Should -BeTrue + } + 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 @@ -1079,4 +1096,57 @@ Describe 'PSResourceList desired state tests' -Tags 'CI' { Uninstall-PSResource -Name $script:testModuleName -Scope AllUsers -ErrorAction SilentlyContinue } } + + It 'Set converges on the AllUsers scope when the resource is already installed for the current user - Windows only' -Skip:(!((Get-IsWindows) -and (Test-IsAdmin)) -or $PSVersionTable.PSVersion.Major -lt 6) { + ResetDscTestModules + Uninstall-PSResource -Name $script:testModuleName -Scope AllUsers -ErrorAction SilentlyContinue + Install-PSResource -Name $script:testModuleName -Version '5.0.0' -Repository $script:localRepo -TrustRepository -Reinstall + + try { + $properties = @{ + repositoryName = $script:localRepo + trustedRepository = $true + resources = @(@{ name = $script:testModuleName; scope = 'AllUsers' }) + } + + $setResult = InvokePSResourceListOperation -Operation set -Properties $properties + $LASTEXITCODE | Should -Be 0 + $setResult.changedProperties | Should -Contain 'resources' + Get-PSResource -Name $script:testModuleName -Scope AllUsers -ErrorAction SilentlyContinue | Should -Not -BeNullOrEmpty + + # The CurrentUser copy must not hide the AllUsers copy, otherwise set never converges + $testResult = InvokePSResourceListOperation -Operation test -Properties $properties + $testResult.inDesiredState | Should -BeTrue + + $setResult = InvokePSResourceListOperation -Operation set -Properties $properties + $LASTEXITCODE | Should -Be 0 + $setResult.changedProperties | Should -BeNullOrEmpty + } + finally { + Uninstall-PSResource -Name $script:testModuleName -Scope AllUsers -ErrorAction SilentlyContinue + } + } + + It 'Set installs the same resource in both scopes - 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' }, + @{ name = $script:testModuleName; version = '5.0.0'; scope = 'AllUsers' } + ) + } + + $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 -Not -BeNullOrEmpty + } + finally { + Uninstall-PSResource -Name $script:testModuleName -Scope AllUsers -ErrorAction SilentlyContinue + } + } }