diff --git a/.ci/ci_auto.yml b/.ci/ci_auto.yml index ae0720d8c..8178c08e1 100644 --- a/.ci/ci_auto.yml +++ b/.ci/ci_auto.yml @@ -109,7 +109,6 @@ stages: } Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "PowerShellGet.psd1") -Dest $createdSignSrcPath -Force -Verbose Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "PSGet.Format.ps1xml") -Dest $createdSignSrcPath -Force -Verbose - Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "DscResources") -Dest $createdSignSrcPath -Recurse -Force -Verbose Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "Modules") -Dest $createdSignSrcPath -Recurse -Force -Verbose $netStandardPath = Join-Path -Path $createdSignSrcPath -ChildPath "netstandard2.0" diff --git a/.ci/ci_release.yml b/.ci/ci_release.yml index d9133e0cd..722528604 100644 --- a/.ci/ci_release.yml +++ b/.ci/ci_release.yml @@ -98,7 +98,6 @@ stages: } Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "PowerShellGet.psd1") -Dest $createdSignSrcPath -Force -Verbose Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "PSGet.Format.ps1xml") -Dest $createdSignSrcPath -Force -Verbose - Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "DscResources") -Dest $createdSignSrcPath -Recurse -Force -Verbose Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "Modules") -Dest $createdSignSrcPath -Recurse -Force -Verbose $netStandardPath = Join-Path -Path $createdSignSrcPath -ChildPath "netstandard2.0" diff --git a/DSC/DSC.psd1 b/DSC/DSC.psd1 deleted file mode 100644 index 9e56bc3b9..000000000 --- a/DSC/DSC.psd1 +++ /dev/null @@ -1,63 +0,0 @@ -<# - This is a dummy PowerShell manifest file so that the DscResource.Tests - test framework recognize the module folder as correct (expected) folder - and file structure. - THIS FILE IS NOT USE DURING DEPLOYMENT. -#> -@{ - # Version number of this module. - moduleVersion = '0.0.0.1' - - # ID used to uniquely identify this module - GUID = 'e102ebd2-bdc3-4d0f-bc93-4b8cc3eb7074' - - # Author of this module - Author = 'Microsoft Corporation' - - # Company or vendor of this module - CompanyName = 'Microsoft Corporation' - - # Copyright statement for this module - Copyright = '(c) 2019 Microsoft Corporation. All rights reserved.' - - # Description of the functionality provided by this module - Description = 'Module with DSC Resources for deployment of PowerShell modules.' - - # Minimum version of the Windows PowerShell engine required by this module - PowerShellVersion = '5.0' - - # Minimum version of the common language runtime (CLR) required by this module - CLRVersion = '4.0' - - # Functions to export from this module - FunctionsToExport = @() - - # Cmdlets to export from this module - CmdletsToExport = @() - - RequiredAssemblies = @() - - <# - Private data to pass to the module specified in RootModule/ModuleToProcess. - This may also contain a PSData hashtable with additional module metadata used by PowerShell. - #> - PrivateData = @{ - - PSData = @{ - - # Tags applied to this module. These help with module discovery in online galleries. - Tags = @('DesiredStateConfiguration', 'DSC', 'DSCResource') - - # A URL to the license for this module. - LicenseUri = 'https://github.com/PowerShell/PowerShellGet/blob/master/LICENSE' - - # A URL to the main website for this project. - ProjectUri = 'https://github.com/PowerShell/PowerShellGet' - - # ReleaseNotes of this module - ReleaseNotes = '' - - } # End of PSData hashtable - - } # End of PrivateData hashtable -} diff --git a/DSC/DscResources/MSFT_PSModule/MSFT_PSModule.psm1 b/DSC/DscResources/MSFT_PSModule/MSFT_PSModule.psm1 deleted file mode 100644 index 2f58af1b3..000000000 --- a/DSC/DscResources/MSFT_PSModule/MSFT_PSModule.psm1 +++ /dev/null @@ -1,625 +0,0 @@ -# -# Copyright (c) Microsoft Corporation. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# - -$resourceModuleRoot = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent - -# Import localization helper functions. -$helperName = 'PowerShellGet.LocalizationHelper' -$dscResourcesFolderFilePath = Join-Path -Path $resourceModuleRoot -ChildPath "Modules\$helperName\$helperName.psm1" -Import-Module -Name $dscResourcesFolderFilePath - -$script:localizedData = Get-LocalizedData -ResourceName 'MSFT_PSModule' -ScriptRoot $PSScriptRoot - -# Import resource helper functions. -$helperName = 'PowerShellGet.ResourceHelper' -$dscResourcesFolderFilePath = Join-Path -Path $resourceModuleRoot -ChildPath "Modules\$helperName\$helperName.psm1" -Import-Module -Name $dscResourcesFolderFilePath -Force - -<# - .SYNOPSIS - This DSC resource provides a mechanism to download PowerShell modules from the PowerShell - Gallery and install it on your computer. - - Get-TargetResource returns the current state of the resource. - - .PARAMETER Name - Specifies the name of the PowerShell module to be installed or uninstalled. - - .PARAMETER Repository - Specifies the name of the module source repository where the module can be found. - - .PARAMETER Version - Provides the version of the module you want to install or uninstall. - - .PARAMETER NoClobber - Does not allow the installation of modules if other existing module on the computer have cmdlets - of the same name. - - .PARAMETER SkipPublisherCheck - Allows the installation of modules that have not been catalog signed. -#> -function Get-TargetResource { - <# - These suppressions are added because this repository have other Visual Studio Code workspace - settings than those in DscResource.Tests DSC test framework. - Only those suppression that contradict this repository guideline is added here. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-ForEachStatement', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-FunctionBlockBraces', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-IfStatement', '')] - [CmdletBinding()] - [OutputType([System.Collections.Hashtable])] - param - ( - [Parameter(Mandatory = $true)] - [System.String] - $Name, - - [Parameter()] - [System.String] - $Repository = 'PSGallery', - - [Parameter()] - [System.String] - $Version, - - [Parameter()] - [System.Boolean] - $NoClobber, - - [Parameter()] - [System.Boolean] - $SkipPublisherCheck - ) - - $returnValue = @{ - Ensure = 'Absent' - Name = $Name - Repository = $Repository - Priority = $null - Description = $null - Guid = $null - ModuleBase = $null - ModuleType = $null - Author = $null - InstalledVersion = $null - Version = $Version - NoClobber = $NoClobber - SkipPublisherCheck = $SkipPublisherCheck - InstallationPolicy = $null - Trusted = $false - } - - Write-Verbose -Message ($localizedData.GetTargetResourceMessage -f $Name) - Write-Verbose("Name:") - - Write-Verbose("Name: $Name") - Write-Verbose("Repository: $Repository") - Write-Verbose("Version: $Version") - - $extractedArguments = New-SplatParameterHashTable -FunctionBoundParameters $PSBoundParameters ` - -ArgumentNames ('Name', 'Repository', 'Version') - - # Get the module with the right version and repository properties. - $modules = Get-RightModule @extractedArguments -ErrorAction SilentlyContinue -WarningAction SilentlyContinue - - # If the module is found, the count > 0 - if ($modules.Count -gt 0) { - Write-Verbose -Message ($localizedData.ModuleFound -f $Name) - - # Find a module with the latest version and return its properties. - $latestModule = $modules[0] - - foreach ($module in $modules) { - if ($module.Version -gt $latestModule.Version) { - $latestModule = $module - } - } - - # Check if the repository matches. - $repositoryName = Get-ModuleRepositoryName -Module $latestModule -ErrorAction SilentlyContinue -WarningAction SilentlyContinue - - ##if ($repositoryName) { - ## $installationPolicy = Get-InstallationPolicy -RepositoryName $repositoryName -ErrorAction SilentlyContinue -WarningAction SilentlyContinue - ##} - - ##if ($installationPolicy) { - ## $installationPolicyReturnValue = 'Trusted' - ## $Trusted = $true - ##} - ##else { - ##$installationPolicyReturnValue = 'Untrusted' - ##$Trusted = $false - ##} - - Write-Verbose("returning value") - $returnValue.Ensure = 'Present' - $returnValue.Repository = $repositoryName - $returnValue.Description = $latestModule.Description - $returnValue.Guid = $latestModule.Guid - $returnValue.ModuleBase = $latestModule.ModuleBase - $returnValue.ModuleType = $latestModule.ModuleType - $returnValue.Author = $latestModule.Author - $returnValue.InstalledVersion = $latestModule.Version - $returnValue.InstallationPolicy = $installationPolicyReturnValue - $returnValue.Trusted = $trusted - } - else { - Write-Verbose -Message ($localizedData.ModuleNotFound -f $Name) - } - - return $returnValue -} - -<# - .SYNOPSIS - This DSC resource provides a mechanism to download PowerShell modules from the PowerShell - Gallery and install it on your computer. - - Test-TargetResource validates whether the resource is currently in the desired state. - - .PARAMETER Ensure - Determines whether the module to be installed or uninstalled. - - .PARAMETER Name - Specifies the name of the PowerShell module to be installed or uninstalled. - - .PARAMETER Repository - Specifies the name of the module source repository where the module can be found. - - .PARAMETER InstallationPolicy - Determines whether you trust the source repository where the module resides. - - .PARAMETER Trusted - Determines whether you trust the source repository where the module resides. - - .PARAMETER Version - Provides the version of the module you want to install or uninstall. - - .PARAMETER NoClobber - Does not allow the installation of modules if other existing module on the computer have cmdlets - of the same name. - - .PARAMETER SkipPublisherCheck - Allows the installation of modules that have not been catalog signed. -#> -function Test-TargetResource { - <# - These suppressions are added because this repository have other Visual Studio Code workspace - settings than those in DscResource.Tests DSC test framework. - Only those suppression that contradict this repository guideline is added here. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-FunctionBlockBraces', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-IfStatement', '')] - [CmdletBinding()] - [OutputType([System.Boolean])] - param - ( - [Parameter()] - [ValidateSet('Present', 'Absent')] - [System.String] - $Ensure = 'Present', - - [Parameter(Mandatory = $true)] - [System.String] - $Name, - - [Parameter()] - [System.String] - $Repository = 'PSGallery', - - [Parameter()] - [ValidateSet('Trusted', 'Untrusted')] - [System.String] - $InstallationPolicy = 'Untrusted', - - [Parameter()] - [System.Boolean] - $Trusted = $false, - - [Parameter()] - [System.String] - $Version, - - [Parameter()] - [System.Boolean] - $NoClobber, - - [Parameter()] - [System.Boolean] - $SkipPublisherCheck - ) - - Write-Verbose -Message ($localizedData.TestTargetResourceMessage -f $Name) - - $extractedArguments = New-SplatParameterHashTable -FunctionBoundParameters $PSBoundParameters ` - -ArgumentNames ('Name', 'Repository', 'Version') - - $status = Get-TargetResource @extractedArguments - - # The ensure returned from Get-TargetResource is not equal to the desired $Ensure. - if ($status.Ensure -ieq $Ensure) { - Write-Verbose -Message ($localizedData.InDesiredState -f $Name) - return $true - } - else { - Write-Verbose -Message ($localizedData.NotInDesiredState -f $Name) - return $false - } -} - -<# - .SYNOPSIS - This DSC resource provides a mechanism to download PowerShell modules from the PowerShell - Gallery and install it on your computer. - - Set-TargetResource sets the resource to the desired state. "Make it so". - - .PARAMETER Ensure - Determines whether the module to be installed or uninstalled. - - .PARAMETER Name - Specifies the name of the PowerShell module to be installed or uninstalled. - - .PARAMETER Repository - Specifies the name of the module source repository where the module can be found. - - .PARAMETER InstallationPolicy - Determines whether you trust the source repository where the module resides. - - .PARAMETER Trusted - Determines whether you trust the source repository where the module resides. - - .PARAMETER Version - Provides the version of the module you want to install or uninstall. - - .PARAMETER NoClobber - Does not allow the installation of modules if other existing module on the computer have cmdlets - of the same name. - - .PARAMETER SkipPublisherCheck - Allows the installation of modules that have not been catalog signed. -#> -function Set-TargetResource { - <# - These suppressions are added because this repository have other Visual Studio Code workspace - settings than those in DscResource.Tests DSC test framework. - Only those suppression that contradict this repository guideline is added here. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-ForEachStatement', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-FunctionBlockBraces', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-IfStatement', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-TryStatement', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-CatchClause', '')] - [CmdletBinding()] - param - ( - [Parameter()] - [ValidateSet('Present', 'Absent')] - [System.String] - $Ensure = 'Present', - - [Parameter(Mandatory = $true)] - [System.String] - $Name, - - [Parameter()] - [System.String] - $Repository = 'PSGallery', - - [Parameter()] - [ValidateSet('Trusted', 'Untrusted')] - [System.String] - $InstallationPolicy = 'Untrusted', - - [Parameter()] - [System.Boolean] - $Trusted = $false, - - [Parameter()] - [System.String] - $Version, - - [Parameter()] - [System.Boolean] - $NoClobber, - - [Parameter()] - [System.Boolean] - $SkipPublisherCheck - ) - - # Validate the repository argument - if ($PSBoundParameters.ContainsKey('Repository')) { - #Test-ParameterValue -Value $Repository -Type 'PackageSource' -Verbose - } - - if ($Ensure -ieq 'Present') { - # Version check - $extractedArguments = New-SplatParameterHashTable -FunctionBoundParameters $PSBoundParameters ` - -ArgumentNames ('Version') - - # $null = Test-VersionParameter @extractedArguments - - $trusted = $null - $moduleFound = $null - - try { - $extractedArguments = New-SplatParameterHashTable -FunctionBoundParameters $PSBoundParameters ` - -ArgumentNames ('Name', 'Repository', 'Version') - - Write-Verbose -Message ($localizedData.StartFindModule -f $Name) - Write-verbose ("Name is: $name") - Write-verbose ("Repository is: $repository") - Write-verbose ("Version is: $Version") - - $modules = Find-PSResource @extractedArguments -ErrorVariable ev -ErrorAction SilentlyContinue - - Write-verbose ("modules is: $modules") - $moduleFound = $modules[0] - } - catch { - $errorMessage = $script:localizedData.ModuleNotFoundInRepository -f $Name - New-InvalidOperationException -Message $errorMessage -ErrorRecord $_ - } - - - foreach ($m in $modules) { - # Check for the installation policy. - #$trusted = Get-InstallationPolicy -RepositoryName $m.Repository -ErrorAction SilentlyContinue -WarningAction SilentlyContinue - - # Stop the loop if found a trusted repository. - #if ($trusted) { - # $moduleFound = $m - # break; - #} - } - - try { - # The repository is trusted, so we install it. - #if ($trusted) { - # Write-Verbose -Message ($localizedData.StartInstallModule -f $Name, $moduleFound.Version.toString(), $moduleFound.Repository) - - # Extract the installation options. - ## $extractedSwitches = New-SplatParameterHashTable -FunctionBoundParameters $PSBoundParameters -ArgumentNames ('Force', 'AllowClobber', 'SkipPublisherCheck') - - ## $moduleFound | Install-Module @extractedSwitches 2>&1 | out-string | Write-Verbose - Install-PSResource -name $moduleFound.Name -Repository $moduleFound.Repository -version $moduleFound.Version -TrustRepository:$true -NoClobber:$NoClobber -Verbose #$SkipPublisherCheck, - - ##} - # The repository is untrusted but user's installation policy is trusted, so we install it with a warning. - ##elseif ($InstallationPolicy -ieq $true) { - ## Write-Warning -Message ($localizedData.InstallationPolicyWarning -f $Name, $modules[0].Repository, $InstallationPolicy) - - # Extract installation options (Force implied by InstallationPolicy). - ## $extractedSwitches = New-SplatParameterHashTable -FunctionBoundParameters $PSBoundParameters -ArgumentNames ('AllowClobber', 'SkipPublisherCheck') - - # If all the repositories are untrusted, we choose the first one. - ## $modules[0] | Install-Module @extractedSwitches -Force 2>&1 | out-string | Write-Verbose - ## } - # Both user and repository is untrusted - ##else { - ## $errorMessage = $script:localizedData.InstallationPolicyFailed -f $InstallationPolicy, 'Untrusted' - ## New-InvalidOperationException -Message $errorMessage - ##} - - Write-Verbose -Message ($localizedData.InstalledSuccess -f $Name) - } - catch { - $errorMessage = $script:localizedData.FailToInstall -f $Name - New-InvalidOperationException -Message $errorMessage -ErrorRecord $_ - } - } - # Ensure=Absent - else { - - $extractedArguments = New-SplatParameterHashTable -FunctionBoundParameters $PSBoundParameters ` - -ArgumentNames ('Name', 'Repository', 'Version') - - # Get the module with the right version and repository properties. - $modules = Get-RightModule @extractedArguments - - if (-not $modules) { - $errorMessage = $script:localizedData.ModuleWithRightPropertyNotFound -f $Name - New-InvalidOperationException -Message $errorMessage - } - - foreach ($module in $modules) { - # Get the path where the module is installed. - $path = $module.ModuleBase - - Write-Verbose -Message ($localizedData.StartUnInstallModule -f $Name) - - try { - <# - There is no Uninstall-Module cmdlet for Windows PowerShell 4.0, - so we will remove the ModuleBase folder as an uninstall operation. - #> - Microsoft.PowerShell.Management\Remove-Item -Path $path -Force -Recurse - - Write-Verbose -Message ($localizedData.UnInstalledSuccess -f $module.Name) - } - catch { - $errorMessage = $script:localizedData.FailToUninstall -f $module.Name - New-InvalidOperationException -Message $errorMessage -ErrorRecord $_ - } - } # foreach - } # Ensure=Absent -} - -<# - .SYNOPSIS - This is a helper function. It returns the modules that meet the specified versions and the repository requirements. - - .PARAMETER Name - Specifies the name of the PowerShell module. - - .PARAMETER Version - Provides the version of the module you want to install or uninstall. - - .PARAMETER Repository - Specifies the name of the module source repository where the module can be found. -#> -function Get-RightModule { - <# - These suppressions are added because this repository have other Visual Studio Code workspace - settings than those in DscResource.Tests DSC test framework. - Only those suppression that contradict this repository guideline is added here. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-ForEachStatement', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-FunctionBlockBraces', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-IfStatement', '')] - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $Name, - - [Parameter()] - [System.String] - $Version, - - [Parameter()] - [System.String] - $Repository - ) - - Write-Verbose -Message ($localizedData.StartGetModule -f $($Name)) - - $modules = Microsoft.PowerShell.Core\Get-Module -Name $Name -ListAvailable -ErrorAction SilentlyContinue -WarningAction SilentlyContinue - - if (-not $modules) { - return $null - } - - <# - As Get-Module does not take RequiredVersion, MinimumVersion, MaximumVersion, or Repository, - below we need to check whether the modules are containing the right version and repository - location. - #> - - $extractedArguments = New-SplatParameterHashTable -FunctionBoundParameters $PSBoundParameters ` - -ArgumentNames ('Version') - $returnVal = @() - - foreach ($m in $modules) { - $versionMatch = $false - $installedVersion = $m.Version - - # Case 1 - a user provides none of RequiredVersion, MinimumVersion, MaximumVersion - if ($extractedArguments.Count -eq 0) { - $versionMatch = $true - } - - ########### COME BACK HERE - # Case 2 - a user provides RequiredVersion - elseif ($extractedArguments.ContainsKey('Version')) { - # Check if it matches with the installed version - $versionMatch = ($installedVersion -eq [System.Version] $RequiredVersion) - } - <# - else { - - # Case 3 - a user provides MinimumVersion - if ($extractedArguments.ContainsKey('MinimumVersion')) { - $versionMatch = ($installedVersion -ge [System.Version] $extractedArguments['MinimumVersion']) - } - - # Case 4 - a user provides MaximumVersion - if ($extractedArguments.ContainsKey('MaximumVersion')) { - $isLessThanMax = ($installedVersion -le [System.Version] $extractedArguments['MaximumVersion']) - - if ($extractedArguments.ContainsKey('MinimumVersion')) { - $versionMatch = $versionMatch -and $isLessThanMax - } - else { - $versionMatch = $isLessThanMax - } - } - - # Case 5 - Both MinimumVersion and MaximumVersion are provided. It's covered by the above. - # Do not return $false yet to allow the foreach to continue - if (-not $versionMatch) { - Write-Verbose -Message ($localizedData.VersionMismatch -f $Name, $installedVersion) - $versionMatch = $false - } - } - #> - - # Case 6 - Version matches but need to check if the module is from the right repository. - if ($versionMatch) { - # A user does not provide Repository, we are good - if (-not $PSBoundParameters.ContainsKey('Repository')) { - Write-Verbose -Message ($localizedData.ModuleFound -f "$Name $installedVersion") - $returnVal += $m - } - else { - # Check if the Repository matches - $sourceName = Get-ModuleRepositoryName -Module $m - - if ($Repository -ieq $sourceName) { - Write-Verbose -Message ($localizedData.ModuleFound -f "$Name $installedVersion") - $returnVal += $m - } - else { - Write-Verbose -Message ($localizedData.RepositoryMismatch -f $($Name), $($sourceName)) - } - } - } - } # foreach - - return $returnVal -} - -<# - .SYNOPSIS - This is a helper function that returns the module's repository name. - - .PARAMETER Module - Specifies the name of the PowerShell module. -#> -function Get-ModuleRepositoryName { - <# - These suppressions are added because this repository have other Visual Studio Code workspace - settings than those in DscResource.Tests DSC test framework. - Only those suppression that contradict this repository guideline is added here. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-FunctionBlockBraces', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-IfStatement', '')] - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.Object] - $Module - ) - - <# - RepositorySourceLocation property is supported in PS V5 only. To work with the earlier - PowerShell version, we need to do a different way. PSGetModuleInfo.xml exists for any - PowerShell modules downloaded through PSModule provider. - #> - $psGetModuleInfoFileName = 'PSGetModuleInfo.xml' - $psGetModuleInfoPath = Microsoft.PowerShell.Management\Join-Path -Path $Module.ModuleBase -ChildPath $psGetModuleInfoFileName - - Write-Verbose -Message ($localizedData.FoundModulePath -f $psGetModuleInfoPath) - - if (Microsoft.PowerShell.Management\Test-path -Path $psGetModuleInfoPath) { - $psGetModuleInfo = Microsoft.PowerShell.Utility\Import-Clixml -Path $psGetModuleInfoPath - - return $psGetModuleInfo.Repository - } -} diff --git a/DSC/DscResources/MSFT_PSModule/MSFT_PSModule.schema.mfl b/DSC/DscResources/MSFT_PSModule/MSFT_PSModule.schema.mfl deleted file mode 100644 index db8de1e01..000000000 --- a/DSC/DscResources/MSFT_PSModule/MSFT_PSModule.schema.mfl +++ /dev/null @@ -1,21 +0,0 @@ -#pragma namespace("\\\\.\\root\\default") -instance of __namespace{ name="MS_409";}; -#pragma namespace("\\\\.\\root\\default\\MS_409") - -[AMENDMENT, LOCALE("MS_409")] -class MSFT_PSModule : OMI_BaseResource -{ - [Key,Description("Name of the module\n") : Amended] String Name; - [Description("Whether the module is to be installed or uninstalled.\nPresent {default} \nAbsent \n") : Amended] String Ensure; - [Description("The name of the module source where the module can be found.\n") : Amended] String Repository; - [Description("Whether the package is trusted or untrusted.\nTrusted {default} \nUntrusted \n") : Amended] String InstallationPolicy; - [Description("The version of the module.\n") : Amended] String Version; - [Description("Does not allow installation when existing cmdlets of the same name exist.\n" : Amended] Boolean NoClobber; - [Description("Allows installation when module is not signed.\n" : Amended] Boolean SkipPublisherCheck; - [Description("The brief description of the module.\n") : Amended] string Description; - [Description("The version of the module that is installed.\n") : Amended] String InstalledVersion; - [Description("The identifier of the module.\n") : Amended] String Guid; - [Description("The base location where the module is installed.\n") : Amended] String ModuleBase; - [Description("The type of the module.\n") : Amended] String ModuleType; - [Description("The author of the module.\n") : Amended] String Author; -}; diff --git a/DSC/DscResources/MSFT_PSModule/MSFT_PSModule.schema.mof b/DSC/DscResources/MSFT_PSModule/MSFT_PSModule.schema.mof deleted file mode 100644 index 400185899..000000000 --- a/DSC/DscResources/MSFT_PSModule/MSFT_PSModule.schema.mof +++ /dev/null @@ -1,19 +0,0 @@ - -[ClassVersion("1.0.0.0"),FriendlyName("PSModule")] -class MSFT_PSModule : OMI_BaseResource -{ - [Key] String Name; - [Write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] String Ensure; - [Write] String Repository; - [Write,ValueMap{"Trusted", "Untrusted"},Values{"Trusted", "Untrusted"}] String InstallationPolicy; - [Write] Boolean Trusted; - [Write] String Version; - [Write] Boolean NoClobber; - [Write] Boolean SkipPublisherCheck; - [Read] string Description; - [Read] String InstalledVersion; - [Read] String Guid; - [Read] String ModuleBase; - [Read] String ModuleType; - [Read] String Author; -}; diff --git a/DSC/DscResources/MSFT_PSModule/en-US/MSFT_PSModule.strings.psd1 b/DSC/DscResources/MSFT_PSModule/en-US/MSFT_PSModule.strings.psd1 deleted file mode 100644 index e1a37ac0f..000000000 --- a/DSC/DscResources/MSFT_PSModule/en-US/MSFT_PSModule.strings.psd1 +++ /dev/null @@ -1,35 +0,0 @@ -# -# Copyright (c) Microsoft Corporation. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# culture = "en-US" -ConvertFrom-StringData -StringData @' - FailToUninstall = Failed to uninstall the module '{0}'. - FailToInstall = Failed to install the module '{0}'. - InDesiredState = Resource '{0}' is in the desired state. - NotInDesiredState = Resource '{0}' is not in the desired state. - ModuleFound = Module '{0}' is found on the node. - ModuleNotFound = Module '{0}' is not found on the node. - ModuleWithRightPropertyNotFound = Module '{0}' with the right version or other properties not found in the node. - ModuleNotFoundInRepository = Module '{0}' with the right version or other properties not found in the repository. - StartGetModule = Begin invoking Get-Module '{0}'. - StartFindModule = Begin invoking Find-PSResource '{0}'. - StartInstallModule = Begin invoking Install-PSResource '{0}' version '{1}' from '{2}' repository. - StartUnInstallModule = Begin invoking Remove-Item to remove the module '{0}' from the file system. - InstalledSuccess = Successfully installed the module '{0}' - UnInstalledSuccess = Successfully uninstalled the module '{0}' - VersionMismatch = The installed module '{0}' has the version: '{1}' - RepositoryMismatch = The installed module '{0}' is from the '{1}' repository. - FoundModulePath = Found the module path: '{0}'. - InstallationPolicyWarning = The module '{0}' was installed from the untrusted repository' {1}'. The InstallationPolicy is set to '{2}' to override the repository installation policy. If you trust the repository, set the repository installation policy to 'Trusted', that will also remove this warning. - InstallationPolicyFailed = The current installation policy do not allow installation from this repository. Your current installation policy is '{0}' and the repository installation policy is '{1}'. If you trust the repository, either change the repository installation policy, or set the parameter InstallationPolicy to 'Trusted' to override the repository installation policy. - GetTargetResourceMessage = Getting the current state of the module '{0}'. - TestTargetResourceMessage = Determining if the module '{0}' is in the desired state. -'@ diff --git a/DSC/DscResources/MSFT_PSRepository/MSFT_PSRepository.psm1 b/DSC/DscResources/MSFT_PSRepository/MSFT_PSRepository.psm1 deleted file mode 100644 index 30c0dfe44..000000000 --- a/DSC/DscResources/MSFT_PSRepository/MSFT_PSRepository.psm1 +++ /dev/null @@ -1,273 +0,0 @@ -$resourceModuleRoot = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent - -# Import localization helper functions. -$helperName = 'PowerShellGet.LocalizationHelper' -$dscResourcesFolderFilePath = Join-Path -Path $resourceModuleRoot -ChildPath "Modules\$helperName\$helperName.psm1" -Import-Module -Name $dscResourcesFolderFilePath - -$script:localizedData = Get-LocalizedData -ResourceName 'MSFT_PSRepository' -ScriptRoot $PSScriptRoot - -# Import resource helper functions. -$helperName = 'PowerShellGet.ResourceHelper' -$dscResourcesFolderFilePath = Join-Path -Path $resourceModuleRoot -ChildPath "Modules\$helperName\$helperName.psm1" -Import-Module -Name $dscResourcesFolderFilePath - -<# - .SYNOPSIS - Returns the current state of the repository. - - .PARAMETER Name - Specifies the name of the repository to manage. -#> -function Get-TargetResource { - <# - These suppressions are added because this repository have other Visual Studio Code workspace - settings than those in DscResource.Tests DSC test framework. - Only those suppression that contradict this repository guideline is added here. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-FunctionBlockBraces', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-IfStatement', '')] - [CmdletBinding()] - [OutputType([System.Collections.Hashtable])] - param - ( - [Parameter(Mandatory = $true)] - [System.String] - $Name - ) - - $returnValue = @{ - Ensure = 'Absent' - Name = $Name - URL = $null - Priority = $null - #InstallationPolicy = $null - #Trusted = $false - Registered = $false - } - - Write-Verbose -Message ($localizedData.GetTargetResourceMessage -f $Name) - - $repository = Get-PSResourceRepository -Name $Name -ErrorAction 'SilentlyContinue' - - if ($repository) { - $returnValue.Ensure = 'Present' - $returnValue.SourceLocation = $repository.SourceLocation - $returnValue.ScriptSourceLocation = $repository.ScriptSourceLocation - $returnValue.PublishLocation = $repository.PublishLocation - $returnValue.ScriptPublishLocation = $repository.ScriptPublishLocation - $returnValue.InstallationPolicy = $repository.InstallationPolicy - $returnValue.PackageManagementProvider = $repository.PackageManagementProvider - $returnValue.Trusted = $repository.Trusted - $returnValue.Registered = $repository.Registered - } - else { - Write-Verbose -Message ($localizedData.RepositoryNotFound -f $Name) - } - - return $returnValue -} - -<# - .SYNOPSIS - Determines if the repository is in the desired state. - - .PARAMETER Ensure - If the repository should be present or absent on the server - being configured. Default values is 'Present'. - - .PARAMETER Name - Specifies the name of the repository to manage. - - .PARAMETER SourceLocation - Specifies the URI for discovering and installing modules from - this repository. A URI can be a NuGet server feed, HTTP, HTTPS, - FTP or file location. - - .PARAMETER ScriptSourceLocation - Specifies the URI for the script source location. - - .PARAMETER PublishLocation - Specifies the URI of the publish location. For example, for - NuGet-based repositories, the publish location is similar - to http://someNuGetUrl.com/api/v2/Packages. - - .PARAMETER ScriptPublishLocation - Specifies the URI for the script publish location. - - .PARAMETER InstallationPolicy - Specifies the installation policy. Valid values are 'Trusted' - or 'Untrusted'. The default value is 'Untrusted'. - - .PARAMETER PackageManagementProvider - Specifies a OneGet package provider. Default value is 'NuGet'. -#> -function Test-TargetResource { - <# - These suppressions are added because this repository have other Visual Studio Code workspace - settings than those in DscResource.Tests DSC test framework. - Only those suppression that contradict this repository guideline is added here. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-FunctionBlockBraces', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-IfStatement', '')] - [CmdletBinding()] - [OutputType([System.Boolean])] - param - ( - [Parameter()] - [ValidateSet('Present', 'Absent')] - [System.String] - $Ensure = 'Present', - - [Parameter(Mandatory = $true)] - [System.String] - $Name, - - [Parameter()] - [System.String] - $URL, - - [Parameter()] - [System.String] - $Priority, - - [Parameter()] - [ValidateSet('Trusted', 'Untrusted')] - [System.String] - $InstallationPolicy = 'Untrusted' - ) - - Write-Verbose -Message ($localizedData.TestTargetResourceMessage -f $Name) - - $returnValue = $false - - $getTargetResourceResult = Get-TargetResource -Name $Name - - if ($Ensure -eq $getTargetResourceResult.Ensure) { - if ($getTargetResourceResult.Ensure -eq 'Present' ) { - $returnValue = Test-DscParameterState ` - -CurrentValues $getTargetResourceResult ` - -DesiredValues $PSBoundParameters ` - -ValuesToCheck @( - 'URL' - 'Priority' - #'InstallationPolicy' - ) - } - else { - $returnValue = $true - } - } - - if ($returnValue) { - Write-Verbose -Message ($localizedData.InDesiredState -f $Name) - } - else { - Write-Verbose -Message ($localizedData.NotInDesiredState -f $Name) - } - - return $returnValue -} - -<# - .SYNOPSIS - Creates, removes or updates the repository. - - .PARAMETER Ensure - If the repository should be present or absent on the server - being configured. Default values is 'Present'. - - .PARAMETER Name - Specifies the name of the repository to manage. - - .PARAMETER SourceLocation - Specifies the URI for discovering and installing modules from - this repository. A URI can be a NuGet server feed, HTTP, HTTPS, - FTP or file location. - - .PARAMETER ScriptSourceLocation - Specifies the URI for the script source location. - - .PARAMETER PublishLocation - Specifies the URI of the publish location. For example, for - NuGet-based repositories, the publish location is similar - to http://someNuGetUrl.com/api/v2/Packages. - - .PARAMETER ScriptPublishLocation - Specifies the URI for the script publish location. - - .PARAMETER InstallationPolicy - Specifies the installation policy. Valid values are 'Trusted' - or 'Untrusted'. The default value is 'Untrusted'. - - .PARAMETER PackageManagementProvider - Specifies a OneGet package provider. Default value is 'NuGet'. -#> -function Set-TargetResource { - <# - These suppressions are added because this repository have other Visual Studio Code workspace - settings than those in DscResource.Tests DSC test framework. - Only those suppression that contradict this repository guideline is added here. - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-FunctionBlockBraces', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('DscResource.AnalyzerRules\Measure-IfStatement', '')] - [CmdletBinding()] - param - ( - [Parameter()] - [ValidateSet('Present', 'Absent')] - [System.String] - $Ensure = 'Present', - - [Parameter(Mandatory = $true)] - [System.String] - $Name, - - [Parameter()] - [System.String] - $URL, - - [Parameter()] - [ValidateSet('Trusted', 'Untrusted')] - [System.String] - $InstallationPolicy = 'Untrusted' - ) - - $getTargetResourceResult = Get-TargetResource -Name $Name - - Write-Verbose("Name: $Name") - Write-Verbose("URL: $URL") - # Determine if the repository should be present or absent. - if ($Ensure -eq 'Present') { - $repositoryParameters = New-SplatParameterHashTable ` - -FunctionBoundParameters $PSBoundParameters ` - -ArgumentNames @( - 'Name' - 'URL' - #'InstallationPolicy' - ) - - # Determine if the repository is already present. - if ($getTargetResourceResult.Ensure -eq 'Present') { - Write-Verbose -Message ($localizedData.RepositoryExist -f $Name) - - # Repository exist, update the properties. - Set-PSResourceRepository @repositoryParameters -ErrorAction 'Stop' - } - else { - Write-Verbose -Message ($localizedData.RepositoryDoesNotExist -f $Name) - - # Repository did not exist, create the repository. - Register-PSResourceRepository @repositoryParameters -ErrorAction 'Stop' - } - } - else { - if ($getTargetResourceResult.Ensure -eq 'Present') { - Write-Verbose -Message ($localizedData.RemoveExistingRepository -f $Name) - - # Repository did exist, remove the repository. - Unregister-PSResourceRepository -Name $Name -ErrorAction 'Stop' - } - } -} diff --git a/DSC/DscResources/MSFT_PSRepository/MSFT_PSRepository.schema.mfl b/DSC/DscResources/MSFT_PSRepository/MSFT_PSRepository.schema.mfl deleted file mode 100644 index 20d1871cc..000000000 --- a/DSC/DscResources/MSFT_PSRepository/MSFT_PSRepository.schema.mfl +++ /dev/null @@ -1,15 +0,0 @@ -#pragma namespace("\\\\.\\root\\default") -instance of __namespace{ name="MS_409";}; -#pragma namespace("\\\\.\\root\\default\\MS_409") - -[AMENDMENT, LOCALE("MS_409")] -class MSFT_PSModule : OMI_BaseResource -{ - [Key, Description("Specifies the name of the repository to manage.") : Amended] String Name; - [Description("If the repository should be present or absent on the server being configured. Default values is 'Present'.") : Amended] String Ensure; - [Description("Specifies the URI for discovering and installing modules from this repository. A URI can be a NuGet server feed, HTTP, HTTPS, FTP or file location.") : Amended] String URL; - [Description("Specifies the priority for the repository.") : Amended] String Priority; - [Description("Specifies the installation policy. Valid values are 'Trusted' or 'Untrusted'. The default value is 'Untrusted'.") : Amended] String InstallationPolicy; - [Description("Specifies if the repository is trusted.") : Amended] Boolean Trusted; - [Description("Specifies if the repository is registered.") : Amended] Boolean Registered; -}; diff --git a/DSC/DscResources/MSFT_PSRepository/MSFT_PSRepository.schema.mof b/DSC/DscResources/MSFT_PSRepository/MSFT_PSRepository.schema.mof deleted file mode 100644 index 46dcb7f49..000000000 --- a/DSC/DscResources/MSFT_PSRepository/MSFT_PSRepository.schema.mof +++ /dev/null @@ -1,11 +0,0 @@ -[ClassVersion("1.0.0.0"),FriendlyName("PSRepository")] -class MSFT_PSRepository : OMI_BaseResource -{ - [Key] String Name; - [Write, ValueMap{"Present","Absent"}, Values{"Present","Absent"}] String Ensure; - [Write] String URL; - [Write] String Priority; - [Write, ValueMap{"Trusted","Untrusted"}, Values{"Trusted","Untrusted"}] String InstallationPolicy; - [Read] Boolean Trusted; - [Read] Boolean Registered; -}; diff --git a/DSC/DscResources/MSFT_PSRepository/en-US/MSFT_PSRepository.strings.psd1 b/DSC/DscResources/MSFT_PSRepository/en-US/MSFT_PSRepository.strings.psd1 deleted file mode 100644 index 81c7c7555..000000000 --- a/DSC/DscResources/MSFT_PSRepository/en-US/MSFT_PSRepository.strings.psd1 +++ /dev/null @@ -1,22 +0,0 @@ -# -# Copyright (c) Microsoft Corporation. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# culture = "en-US" -ConvertFrom-StringData -StringData @' - GetTargetResourceMessage = Return the current state of the repository '{0}'. - RepositoryNotFound = The repository '{0}' was not found. - TestTargetResourceMessage = Determining if the repository '{0}' is in the desired state. - InDesiredState = Repository '{0}' is in the desired state. - NotInDesiredState = Repository '{0}' is not in the desired state. - RepositoryExist = Updating the properties of the repository '{0}'. - RepositoryDoesNotExist = Creating the repository '{0}'. - RemoveExistingRepository = Removing the repository '{0}'. -'@ diff --git a/DSC/Examples/.gitattributes b/DSC/Examples/.gitattributes deleted file mode 100644 index 92be83e26..000000000 --- a/DSC/Examples/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -* text eol=crlf diff --git a/DSC/Examples/README.md b/DSC/Examples/README.md deleted file mode 100644 index a027a5494..000000000 --- a/DSC/Examples/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Examples - -## Resource examples - -These are the links to the examples for each individual resource. - -- [PSModule](Resources/PSModule) -- [PSRepository](Resources/PSRepository) diff --git a/DSC/Examples/Resources/PSModule/1-PSModule_InstallModuleConfig.ps1 b/DSC/Examples/Resources/PSModule/1-PSModule_InstallModuleConfig.ps1 deleted file mode 100644 index e8583e891..000000000 --- a/DSC/Examples/Resources/PSModule/1-PSModule_InstallModuleConfig.ps1 +++ /dev/null @@ -1,73 +0,0 @@ -<#PSScriptInfo -.VERSION 1.0.0 -.GUID 45d8677b-817f-4b2a-8d47-a802c4f758b1 -.AUTHOR Microsoft Corporation -.COMPANYNAME Microsoft Corporation -.COPYRIGHT -.TAGS DSCConfiguration -.LICENSEURI https://github.com/PowerShell/PowerShellGet/blob/master/LICENSE -.PROJECTURI https://github.com/PowerShell/PowerShellGet -.ICONURI -.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES -.RELEASENOTES First version. -.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core -#> - -#Requires -module PowerShellGet - -<# - .SYNOPSIS - Configuration that installs a module. - - .DESCRIPTION - Configuration that installs a module. - - .PARAMETER NodeName - The names of one or more nodes to compile a configuration for. - Defaults to 'localhost'. - - .PARAMETER ModuleName - The name of the module to be downloaded and installed. - - .EXAMPLE - PSModule_InstallModuleConfig -ModuleName 'PSLogging' - - Compiles a configuration that downloads and installs the module 'PSLogging'. - - .EXAMPLE - $configurationParameters = @{ - ModuleName = 'PSLogging' - } - Start-AzureRmAutomationDscCompilationJob -ResourceGroupName '' -AutomationAccountName '' -ConfigurationName 'PSModule_InstallModuleConfig' -Parameters $configurationParameters - - Compiles a configuration in Azure Automation that downloads and installs - the module 'PSLogging'. - - Replace the and with correct values. -#> -configuration PSModule_InstallModuleConfig -{ - param - ( - [Parameter()] - [System.String[]] - $NodeName = 'localhost', - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $ModuleName - ) - - Import-DscResource -ModuleName 'PowerShellGet' - - Node $nodeName - { - PSModule 'InstallModule' - { - Name = $ModuleName - } - } -} diff --git a/DSC/Examples/Resources/PSModule/2-PSModule_InstallModuleTrustedConfig.ps1 b/DSC/Examples/Resources/PSModule/2-PSModule_InstallModuleTrustedConfig.ps1 deleted file mode 100644 index 84b6635c4..000000000 --- a/DSC/Examples/Resources/PSModule/2-PSModule_InstallModuleTrustedConfig.ps1 +++ /dev/null @@ -1,76 +0,0 @@ -<#PSScriptInfo -.VERSION 1.0.0 -.GUID d16da19d-439a-4730-8e02-6928d6a8ed28 -.AUTHOR Microsoft Corporation -.COMPANYNAME Microsoft Corporation -.COPYRIGHT -.TAGS DSCConfiguration -.LICENSEURI https://github.com/PowerShell/PowerShellGet/blob/master/LICENSE -.PROJECTURI https://github.com/PowerShell/PowerShellGet -.ICONURI -.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES -.RELEASENOTES First version. -.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core -#> - -#Requires -module PowerShellGet - -<# - .SYNOPSIS - Configuration that installs a module, and overrides the - current trust level for the package source. - - .DESCRIPTION - Configuration that installs a module, and overrides the - current trust level for the package source. - - .PARAMETER NodeName - The names of one or more nodes to compile a configuration for. - Defaults to 'localhost'. - - .PARAMETER ModuleName - The name of the module to be downloaded and installed. - - .EXAMPLE - PSModule_InstallModuleTrustedConfig -ModuleName 'PSLogging' - - Compiles a configuration that downloads and installs the module 'PSLogging'. - - .EXAMPLE - $configurationParameters = @{ - ModuleName = 'PSLogging' - } - Start-AzureRmAutomationDscCompilationJob -ResourceGroupName '' -AutomationAccountName '' -ConfigurationName 'PSModule_InstallModuleTrustedConfig' -Parameters $configurationParameters - - Compiles a configuration in Azure Automation that downloads and installs - the module 'PSLogging'. - - Replace the and with correct values. -#> -configuration PSModule_InstallModuleTrustedConfig -{ - param - ( - [Parameter()] - [System.String[]] - $NodeName = 'localhost', - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $ModuleName - ) - - Import-DscResource -ModuleName 'PowerShellGet' - - Node $nodeName - { - PSModule 'InstallModuleAsTrusted' - { - Name = $ModuleName - InstallationPolicy = 'Trusted' - } - } -} diff --git a/DSC/Examples/Resources/PSModule/3-PSModule_InstallModuleAllowClobberConfig.ps1 b/DSC/Examples/Resources/PSModule/3-PSModule_InstallModuleAllowClobberConfig.ps1 deleted file mode 100644 index 335216206..000000000 --- a/DSC/Examples/Resources/PSModule/3-PSModule_InstallModuleAllowClobberConfig.ps1 +++ /dev/null @@ -1,74 +0,0 @@ -<#PSScriptInfo -.VERSION 1.0.0 -.GUID 47eb256b-9c81-437d-9148-890bc94f15ed -.AUTHOR Microsoft Corporation -.COMPANYNAME Microsoft Corporation -.COPYRIGHT -.TAGS DSCConfiguration -.LICENSEURI https://github.com/PowerShell/PowerShellGet/blob/master/LICENSE -.PROJECTURI https://github.com/PowerShell/PowerShellGet -.ICONURI -.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES -.RELEASENOTES First version. -.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core -#> - -#Requires -module PowerShellGet - -<# - .SYNOPSIS - Configuration that installs a module and allows clobber. - - .DESCRIPTION - Configuration that installs a module and allows clobber. - - .PARAMETER NodeName - The names of one or more nodes to compile a configuration for. - Defaults to 'localhost'. - - .PARAMETER ModuleName - The name of the module to be downloaded and installed. - - .EXAMPLE - PSModule_InstallModuleAllowClobberConfig -ModuleName 'SqlServer' - - Compiles a configuration that downloads and installs the module 'SqlServer'. - - .EXAMPLE - $configurationParameters = @{ - ModuleName = 'SqlServer' - } - Start-AzureRmAutomationDscCompilationJob -ResourceGroupName '' -AutomationAccountName '' -ConfigurationName 'PSModule_InstallModuleAllowClobberConfig' -Parameters $configurationParameters - - Compiles a configuration in Azure Automation that downloads and installs - the module 'SqlServer'. - - Replace the and with correct values. -#> -configuration PSModule_InstallModuleAllowClobberConfig -{ - param - ( - [Parameter()] - [System.String[]] - $NodeName = 'localhost', - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $ModuleName - ) - - Import-DscResource -ModuleName 'PowerShellGet' - - Node $nodeName - { - PSModule 'InstallModuleAndAllowClobber' - { - Name = $ModuleName - NoClobber = $false - } - } -} diff --git a/DSC/Examples/Resources/PSModule/4-PSModule_InstallModuleSpecificVersionConfig.ps1 b/DSC/Examples/Resources/PSModule/4-PSModule_InstallModuleSpecificVersionConfig.ps1 deleted file mode 100644 index 5f6b8cb2f..000000000 --- a/DSC/Examples/Resources/PSModule/4-PSModule_InstallModuleSpecificVersionConfig.ps1 +++ /dev/null @@ -1,83 +0,0 @@ -<#PSScriptInfo -.VERSION 1.0.0 -.GUID cbed3f85-50cf-49ca-bde4-1b3ef0e33687 -.AUTHOR Microsoft Corporation -.COMPANYNAME Microsoft Corporation -.COPYRIGHT -.TAGS DSCConfiguration -.LICENSEURI https://github.com/PowerShell/PowerShellGet/blob/master/LICENSE -.PROJECTURI https://github.com/PowerShell/PowerShellGet -.ICONURI -.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES -.RELEASENOTES First version. -.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core -#> - -#Requires -module PowerShellGet - -<# - .SYNOPSIS - Configuration that installs a module with a specific version. - - .DESCRIPTION - Configuration that installs a module with a specific version. - - .PARAMETER NodeName - The names of one or more nodes to compile a configuration for. - Defaults to 'localhost'. - - .PARAMETER ModuleName - The name of the module to be downloaded and installed. - - .PARAMETER Version - The version of the module to download and install. - - .EXAMPLE - PSModule_InstallModuleSpecificVersionConfig -ModuleName 'SqlServer' -RequiredVersion '21.1.18068' - - Compiles a configuration that downloads and installs the module 'SqlServer'. - - .EXAMPLE - $configurationParameters = @{ - ModuleName = 'SqlServer' - RequiredVersion = '21.1.18068' - } - Start-AzureRmAutomationDscCompilationJob -ResourceGroupName '' -AutomationAccountName '' -ConfigurationName 'PSModule_InstallModuleSpecificVersionConfig' -Parameters $configurationParameters - - Compiles a configuration in Azure Automation that downloads and installs - the module 'SqlServer'. - - Replace the and with correct values. -#> -configuration PSModule_InstallModuleSpecificVersionConfig -{ - param - ( - [Parameter()] - [System.String[]] - $NodeName = 'localhost', - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $ModuleName, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $Version - ) - - Import-DscResource -ModuleName 'PowerShellGet' - - Node $nodeName - { - PSModule 'InstallModuleAndAllowClobber' - { - Name = $ModuleName - Version = $Version - } - } -} diff --git a/DSC/Examples/Resources/PSModule/5-PSModule_InstallModuleWithinVersionRangeConfig.ps1 b/DSC/Examples/Resources/PSModule/5-PSModule_InstallModuleWithinVersionRangeConfig.ps1 deleted file mode 100644 index 3264218d6..000000000 --- a/DSC/Examples/Resources/PSModule/5-PSModule_InstallModuleWithinVersionRangeConfig.ps1 +++ /dev/null @@ -1,92 +0,0 @@ -<#PSScriptInfo -.VERSION 1.0.0 -.GUID b3a8515b-9164-4fc5-9df0-e883f6420a83 -.AUTHOR Microsoft Corporation -.COMPANYNAME Microsoft Corporation -.COPYRIGHT -.TAGS DSCConfiguration -.LICENSEURI https://github.com/PowerShell/PowerShellGet/blob/master/LICENSE -.PROJECTURI https://github.com/PowerShell/PowerShellGet -.ICONURI -.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES -.RELEASENOTES First version. -.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core -#> - -#Requires -module PowerShellGet - -<# - .SYNOPSIS - Configuration that installs a module withing a specific version range. - - .DESCRIPTION - Configuration that installs a module withing a specific version range. - - .PARAMETER NodeName - The names of one or more nodes to compile a configuration for. - Defaults to 'localhost'. - - .PARAMETER ModuleName - The name of the module to be downloaded and installed. - - .PARAMETER MinimumVersion - The minimum version of the module to download and install. - - .PARAMETER MaximumVersion - The maximum version of the module to download and install. - - .EXAMPLE - PSModule_InstallModuleWithinVersionRangeConfig -ModuleName 'SqlServer' -MinimumVersion '21.0.17199' -MaximumVersion '21.1.18068' - - Compiles a configuration that downloads and installs the module 'SqlServer'. - - .EXAMPLE - $configurationParameters = @{ - ModuleName = 'SqlServer' - MinimumVersion = '21.0.17199' - MaximumVersion = '21.1.18068' - } - Start-AzureRmAutomationDscCompilationJob -ResourceGroupName '' -AutomationAccountName '' -ConfigurationName 'PSModule_InstallModuleWithinVersionRangeConfig' -Parameters $configurationParameters - - Compiles a configuration in Azure Automation that downloads and installs - the module 'SqlServer'. - - Replace the and with correct values. -#> -configuration PSModule_InstallModuleWithinVersionRangeConfig -{ - param - ( - [Parameter()] - [System.String[]] - $NodeName = 'localhost', - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $ModuleName, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $MinimumVersion, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $MaximumVersion - ) - - Import-DscResource -ModuleName 'PowerShellGet' - - Node $nodeName - { - PSModule 'InstallModuleAndAllowClobber' - { - Name = $ModuleName - Version = "[$MinimumVersion, $MaximumVersion]" - } - } -} diff --git a/DSC/Examples/Resources/PSModule/6-PSModule_UninstallModuleConfig.ps1 b/DSC/Examples/Resources/PSModule/6-PSModule_UninstallModuleConfig.ps1 deleted file mode 100644 index b255a121d..000000000 --- a/DSC/Examples/Resources/PSModule/6-PSModule_UninstallModuleConfig.ps1 +++ /dev/null @@ -1,74 +0,0 @@ -<#PSScriptInfo -.VERSION 1.0.0 -.GUID 83a844ed-4e23-427d-94c9-72bdcae0e1bb -.AUTHOR Microsoft Corporation -.COMPANYNAME Microsoft Corporation -.COPYRIGHT -.TAGS DSCConfiguration -.LICENSEURI https://github.com/PowerShell/PowerShellGet/blob/master/LICENSE -.PROJECTURI https://github.com/PowerShell/PowerShellGet -.ICONURI -.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES -.RELEASENOTES First version. -.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core -#> - -#Requires -module PowerShellGet - -<# - .SYNOPSIS - Configuration that uninstalls an installed module. - - .DESCRIPTION - Configuration that uninstalls an installed module. - - .PARAMETER NodeName - The names of one or more nodes to compile a configuration for. - Defaults to 'localhost'. - - .PARAMETER ModuleName - The name of the module to be uninstalled. - - .EXAMPLE - PSModule_UninstallModuleConfig -ModuleName 'PSLogging' - - Compiles a configuration that downloads and installs the module 'PSLogging'. - - .EXAMPLE - $configurationParameters = @{ - ModuleName = 'PSLogging' - } - Start-AzureRmAutomationDscCompilationJob -ResourceGroupName '' -AutomationAccountName '' -ConfigurationName 'PSModule_UninstallModuleConfig' -Parameters $configurationParameters - - Compiles a configuration in Azure Automation that downloads and installs - the module 'PSLogging'. - - Replace the and with correct values. -#> -configuration PSModule_UninstallModuleConfig -{ - param - ( - [Parameter()] - [System.String[]] - $NodeName = 'localhost', - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $ModuleName - ) - - Import-DscResource -ModuleName 'PowerShellGet' - - Node $nodeName - { - PSModule 'InstallModule' - { - Ensure = 'Absent' - Name = $ModuleName - } - } -} diff --git a/DSC/Examples/Resources/PSRepository/1-PSRepository_AddRepositoryConfig.ps1 b/DSC/Examples/Resources/PSRepository/1-PSRepository_AddRepositoryConfig.ps1 deleted file mode 100644 index 26beff701..000000000 --- a/DSC/Examples/Resources/PSRepository/1-PSRepository_AddRepositoryConfig.ps1 +++ /dev/null @@ -1,76 +0,0 @@ -<#PSScriptInfo -.VERSION 1.0.0 -.GUID a1f8ee59-31b6-49be-9175-f7a49b5e03f1 -.AUTHOR Microsoft Corporation -.COMPANYNAME Microsoft Corporation -.COPYRIGHT -.TAGS DSCConfiguration -.LICENSEURI https://github.com/PowerShell/PowerShellGet/blob/master/LICENSE -.PROJECTURI https://github.com/PowerShell/PowerShellGet -.ICONURI -.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES -.RELEASENOTES First version. -.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core -#> - -#Requires -module PowerShellGet - -<# - .SYNOPSIS - Configuration that installs a module. - - .DESCRIPTION - Configuration that installs a module. - - .PARAMETER NodeName - The names of one or more nodes to compile a configuration for. - Defaults to 'localhost'. - - .PARAMETER RepositoryName - The name of the repository that will be added. - - .EXAMPLE - PSRepository_AddRepositoryConfig -RepositoryName 'PSTestGallery' - - Compiles a configuration that downloads and installs the module 'PSLogging'. - - .EXAMPLE - $configurationParameters = @{ - RepositoryName = 'PSTestGallery' - } - Start-AzureRmAutomationDscCompilationJob -ResourceGroupName '' -AutomationAccountName '' -ConfigurationName 'PSRepository_AddRepositoryConfig' -Parameters $configurationParameters - - Compiles a configuration in Azure Automation that downloads and installs - the module 'PSLogging'. - - Replace the and with correct values. -#> -configuration PSRepository_AddRepositoryConfig -{ - param - ( - [Parameter()] - [System.String[]] - $NodeName = 'localhost', - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $RepositoryName - ) - - Import-DscResource -ModuleName 'PowerShellGet' - - Node $nodeName - { - PSRepository 'AddRepository' - { - Name = $RepositoryName - URL = 'https://www.poshtestgallery.com/api/v2' - Priority = 1 - Trusted = 'True' - } - } -} diff --git a/DSC/Examples/Resources/PSRepository/2-PSRepository_RemoveRepositoryConfig.ps1 b/DSC/Examples/Resources/PSRepository/2-PSRepository_RemoveRepositoryConfig.ps1 deleted file mode 100644 index 3dc9abfd2..000000000 --- a/DSC/Examples/Resources/PSRepository/2-PSRepository_RemoveRepositoryConfig.ps1 +++ /dev/null @@ -1,74 +0,0 @@ -<#PSScriptInfo -.VERSION 1.0.0 -.GUID c9a8b46f-12a6-46e1-8c6b-946ac9995aad -.AUTHOR Microsoft Corporation -.COMPANYNAME Microsoft Corporation -.COPYRIGHT -.TAGS DSCConfiguration -.LICENSEURI https://github.com/PowerShell/PowerShellGet/blob/master/LICENSE -.PROJECTURI https://github.com/PowerShell/PowerShellGet -.ICONURI -.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES -.RELEASENOTES First version. -.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core -#> - -#Requires -module PowerShellGet - -<# - .SYNOPSIS - Configuration that installs a module. - - .DESCRIPTION - Configuration that installs a module. - - .PARAMETER NodeName - The names of one or more nodes to compile a configuration for. - Defaults to 'localhost'. - - .PARAMETER RepositoryName - The name of the repository that will be added. - - .EXAMPLE - PSRepository_RemoveRepositoryConfig -RepositoryName 'PSTestGallery' - - Compiles a configuration that downloads and installs the module 'PSLogging'. - - .EXAMPLE - $configurationParameters = @{ - RepositoryName = 'PSTestGallery' - } - Start-AzureRmAutomationDscCompilationJob -ResourceGroupName '' -AutomationAccountName '' -ConfigurationName 'PSRepository_RemoveRepositoryConfig' -Parameters $configurationParameters - - Compiles a configuration in Azure Automation that downloads and installs - the module 'PSLogging'. - - Replace the and with correct values. -#> -configuration PSRepository_RemoveRepositoryConfig -{ - param - ( - [Parameter()] - [System.String[]] - $NodeName = 'localhost', - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $RepositoryName - ) - - Import-DscResource -ModuleName 'PowerShellGet' - - Node $nodeName - { - PSRepository 'AddRepository' - { - Ensure = 'Absent' - Name = $RepositoryName - } - } -} diff --git a/DSC/Modules/PowerShellGet.LocalizationHelper/PowerShellGet.LocalizationHelper.psm1 b/DSC/Modules/PowerShellGet.LocalizationHelper/PowerShellGet.LocalizationHelper.psm1 deleted file mode 100644 index 9f6b61253..000000000 --- a/DSC/Modules/PowerShellGet.LocalizationHelper/PowerShellGet.LocalizationHelper.psm1 +++ /dev/null @@ -1,254 +0,0 @@ -<# - .SYNOPSIS - Creates and throws an invalid argument exception. - - .PARAMETER Message - The message explaining why this error is being thrown. - - .PARAMETER ArgumentName - The name of the invalid argument that is causing this error to be thrown. -#> -function New-InvalidArgumentException { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $Message, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $ArgumentName - ) - - $argumentException = New-Object -TypeName 'ArgumentException' ` - -ArgumentList @($Message, $ArgumentName) - - $newObjectParameters = @{ - TypeName = 'System.Management.Automation.ErrorRecord' - ArgumentList = @($argumentException, $ArgumentName, 'InvalidArgument', $null) - } - - $errorRecord = New-Object @newObjectParameters - - throw $errorRecord -} - -<# - .SYNOPSIS - Creates and throws an invalid operation exception. - - .PARAMETER Message - The message explaining why this error is being thrown. - - .PARAMETER ErrorRecord - The error record containing the exception that is causing this terminating error. -#> -function New-InvalidOperationException { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $Message, - - [Parameter()] - [ValidateNotNull()] - [System.Management.Automation.ErrorRecord] - $ErrorRecord - ) - - if ($null -eq $ErrorRecord) { - $invalidOperationException = New-Object -TypeName 'InvalidOperationException' ` - -ArgumentList @($Message) - } - else { - $invalidOperationException = New-Object -TypeName 'InvalidOperationException' ` - -ArgumentList @($Message, $ErrorRecord.Exception) - } - - $newObjectParameters = @{ - TypeName = 'System.Management.Automation.ErrorRecord' - ArgumentList = @( - $invalidOperationException.ToString(), - 'MachineStateIncorrect', - 'InvalidOperation', - $null - ) - } - - $errorRecordToThrow = New-Object @newObjectParameters - - throw $errorRecordToThrow -} - -<# - .SYNOPSIS - Creates and throws an object not found exception. - - .PARAMETER Message - The message explaining why this error is being thrown. - - .PARAMETER ErrorRecord - The error record containing the exception that is causing this terminating error. -#> -function New-ObjectNotFoundException { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $Message, - - [Parameter()] - [ValidateNotNull()] - [System.Management.Automation.ErrorRecord] - $ErrorRecord - ) - - if ($null -eq $ErrorRecord) { - $exception = New-Object -TypeName 'System.Exception' ` - -ArgumentList @($Message) - } - else { - $exception = New-Object -TypeName 'System.Exception' ` - -ArgumentList @($Message, $ErrorRecord.Exception) - } - - $newObjectParameters = @{ - TypeName = 'System.Management.Automation.ErrorRecord' - ArgumentList = @( - $exception.ToString(), - 'MachineStateIncorrect', - 'ObjectNotFound', - $null - ) - } - - $errorRecordToThrow = New-Object @newObjectParameters - - throw $errorRecordToThrow -} - -<# - .SYNOPSIS - Creates and throws an invalid result exception. - - .PARAMETER Message - The message explaining why this error is being thrown. - - .PARAMETER ErrorRecord - The error record containing the exception that is causing this terminating error. -#> -function New-InvalidResultException { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $Message, - - [Parameter()] - [ValidateNotNull()] - [System.Management.Automation.ErrorRecord] - $ErrorRecord - ) - - if ($null -eq $ErrorRecord) { - $exception = New-Object -TypeName 'System.Exception' ` - -ArgumentList @($Message) - } - else { - $exception = New-Object -TypeName 'System.Exception' ` - -ArgumentList @($Message, $ErrorRecord.Exception) - } - - $newObjectParameters = @{ - TypeName = 'System.Management.Automation.ErrorRecord' - ArgumentList = @( - $exception.ToString(), - 'MachineStateIncorrect', - 'InvalidResult', - $null - ) - } - - $errorRecordToThrow = New-Object @newObjectParameters - - throw $errorRecordToThrow -} - -<# - .SYNOPSIS - Retrieves the localized string data based on the machine's culture. - Falls back to en-US strings if the machine's culture is not supported. - - .PARAMETER ResourceName - The name of the resource as it appears before '.strings.psd1' of the localized string file. - For example: - For WindowsOptionalFeature: MSFT_WindowsOptionalFeature - For Service: MSFT_ServiceResource - For Registry: MSFT_RegistryResource - For Helper: SqlServerDscHelper - - .PARAMETER ScriptRoot - Optional. The root path where to expect to find the culture folder. This is only needed - for localization in helper modules. This should not normally be used for resources. -#> -function Get-LocalizedData { - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $ResourceName, - - [Parameter()] - [ValidateNotNullOrEmpty()] - [System.String] - $ScriptRoot - ) - - if ( -not $ScriptRoot ) { - $resourceDirectory = Join-Path -Path $PSScriptRoot -ChildPath $ResourceName - $localizedStringFileLocation = Join-Path -Path $resourceDirectory -ChildPath $PSUICulture - } - else { - $localizedStringFileLocation = Join-Path -Path $ScriptRoot -ChildPath $PSUICulture - } - - if (-not (Test-Path -Path $localizedStringFileLocation)) { - # Fallback to en-US - if ( -not $ScriptRoot ) { - $localizedStringFileLocation = Join-Path -Path $resourceDirectory -ChildPath 'en-US' - } - else { - $localizedStringFileLocation = Join-Path -Path $ScriptRoot -ChildPath 'en-US' - } - } - - Import-LocalizedData ` - -BindingVariable 'localizedData' ` - -FileName "$ResourceName.strings.psd1" ` - -BaseDirectory $localizedStringFileLocation - - return $localizedData -} - -Export-ModuleMember -Function @( - 'New-InvalidArgumentException', - 'New-InvalidOperationException', - 'New-ObjectNotFoundException', - 'New-InvalidResultException', - 'Get-LocalizedData' -) diff --git a/DSC/Modules/PowerShellGet.ResourceHelper/PowerShellGet.ResourceHelper.psm1 b/DSC/Modules/PowerShellGet.ResourceHelper/PowerShellGet.ResourceHelper.psm1 deleted file mode 100644 index 2a01934b9..000000000 --- a/DSC/Modules/PowerShellGet.ResourceHelper/PowerShellGet.ResourceHelper.psm1 +++ /dev/null @@ -1,368 +0,0 @@ -# -# Copyright (c) Microsoft Corporation. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# - -<# - Helper functions for PowerShellGet DSC Resources. -#> - -# Import localization helper functions. -$helperName = 'PowerShellGet.LocalizationHelper' -$resourceModuleRoot = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent -$dscResourcesFolderFilePath = Join-Path -Path $resourceModuleRoot -ChildPath "Modules\$helperName\$helperName.psm1" -Import-Module -Name $dscResourcesFolderFilePath - -# Import Localization Strings -$script:localizedData = Get-LocalizedData -ResourceName 'PowerShellGet.ResourceHelper' -ScriptRoot $PSScriptRoot - -<# - .SYNOPSIS - This is a helper function that extract the parameters from a given table. - - .PARAMETER FunctionBoundParameters - Specifies the hash table containing a set of parameters to be extracted. - - .PARAMETER ArgumentNames - Specifies a list of arguments you want to extract. -#> -function New-SplatParameterHashTable { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] - [CmdletBinding()] - [OutputType([System.Collections.Hashtable])] - param - ( - [Parameter(Mandatory = $true)] - [System.Collections.Hashtable] - $FunctionBoundParameters, - - [Parameter(Mandatory = $true)] - [System.String[]] - $ArgumentNames - ) - - Write-Verbose -Message ($script:localizedData.CallingFunction -f $($MyInvocation.MyCommand)) - - $returnValue = @{} - - foreach ($arg in $ArgumentNames) { - if ($FunctionBoundParameters.ContainsKey($arg)) { - # Found an argument we are looking for, so we add it to return collection. - $returnValue.Add($arg, $FunctionBoundParameters[$arg]) - } - } - - return $returnValue -} - -<# - .SYNOPSIS - This is a helper function that validate that a value is correct and used correctly. - - .PARAMETER Value - Specifies the value to be validated. - - .PARAMETER Type - Specifies the type of argument. - - .PARAMETER Type - Specifies the name of the provider. - - .OUTPUTS - None. Throws an error if the test fails. -#> -function Test-ParameterValue { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $Value, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $Type, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $ProviderName - ) - - Write-Verbose -Message ($script:localizedData.CallingFunction -f $($MyInvocation.MyCommand)) - - switch ($Type) { - 'SourceUri' { - # Checks whether given URI represents specific scheme - # Most common schemes: file, http, https, ftp - $scheme = @('http', 'https', 'file', 'ftp') - - $newUri = $Value -as [System.URI] - $returnValue = ($newUri -and $newUri.AbsoluteURI -and ($scheme -icontains $newUri.Scheme)) - - if ($returnValue -eq $false) { - $errorMessage = $script:localizedData.InValidUri -f $Value - New-InvalidArgumentException -ArgumentName $Type -Message $errorMessage - } - } - - 'DestinationPath' { - $returnValue = Test-Path -Path $Value - - if ($returnValue -eq $false) { - $errorMessage = $script:localizedData.PathDoesNotExist -f $Value - New-InvalidArgumentException -ArgumentName $Type -Message $errorMessage - } - } - - <# - 'PackageSource' { - # Value can be either the package source Name or source Uri. - # Check if the source is a Uri. - $uri = $Value -as [System.URI] - - if ($uri -and $uri.AbsoluteURI) { - # Check if it's a valid Uri. - Test-ParameterValue -Value $Value -Type 'SourceUri' -ProviderName $ProviderName - } - else { - # Check if it's a registered package source name. - # $source = PackageManagement\Get-PackageSource -Name $Value -ProviderName $ProviderName -ErrorVariable ev - - if ((-not $source) -or $ev) { - # We do not need to throw error here as Get-PackageSource does already. - Write-Verbose -Message ($script:localizedData.SourceNotFound -f $source) - } - } - } #> - - default { - $errorMessage = $script:localizedData.UnexpectedArgument -f $Type - New-InvalidArgumentException -ArgumentName $Type -Message $errorMessage - } - } -} - -<# - .SYNOPSIS - This is a helper function that does the version validation. - - .PARAMETER Version - Provides the version. -#> -function Test-VersionParameter { - [CmdletBinding()] - param - ( - [Parameter()] - [System.String] - $Version - ) - - Write-Verbose -Message ($localizedData.CallingFunction -f $($MyInvocation.MyCommand)) - - $isValid = $false - - # Case 1: No further check required if a user provides either none or one of these: minimumVersion, maximumVersion, and requiredVersion. - if ($PSBoundParameters.Count -le 1) { - return $true - } - - ########## COME BACK HERE - # Case 2: #If no RequiredVersion is provided. - #if (-not $PSBoundParameters.ContainsKey('Version')) { - # If no RequiredVersion, both MinimumVersion and MaximumVersion are provided. Otherwise fall into the Case #1. - #$isValid = $PSBoundParameters['MinimumVersion'] -le $PSBoundParameters['MaximumVersion'] - #} - $isValid = $true - # Case 3: RequiredVersion is provided. - # In this case MinimumVersion and/or MaximumVersion also are provided. Otherwise fall in to Case #1. - # This is an invalid case. When RequiredVersion is provided, others are not allowed. so $isValid is false, which is already set in the init. - - if ($isValid -eq $false) { - $errorMessage = $script:localizedData.VersionError - New-InvalidArgumentException ` - -ArgumentName 'RequiredVersion, MinimumVersion or MaximumVersion' ` - -Message $errorMessage - } -} - -<# - .SYNOPSIS - This is a helper function that retrieves the InstallationPolicy from the given repository. - - .PARAMETER RepositoryName - Provides the repository Name. -#> -function Get-InstallationPolicy { - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] $RepositoryName - ) - - Write-Verbose -Message ($LocalizedData.CallingFunction -f $($MyInvocation.MyCommand)) - - $repositoryObject = Get-PSResourceRepository -Name $RepositoryName -ErrorAction SilentlyContinue -WarningAction SilentlyContinue - - if ($repositoryObject) { - return $repositoryObject.IsTrusted - } -} - -<# - .SYNOPSIS - This method is used to compare current and desired values for any DSC resource. - - .PARAMETER CurrentValues - This is hash table of the current values that are applied to the resource. - - .PARAMETER DesiredValues - This is a PSBoundParametersDictionary of the desired values for the resource. - - .PARAMETER ValuesToCheck - This is a list of which properties in the desired values list should be checked. - If this is empty then all values in DesiredValues are checked. -#> -function Test-DscParameterState { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [System.Collections.Hashtable] - $CurrentValues, - - [Parameter(Mandatory = $true)] - [System.Object] - $DesiredValues, - - [Parameter()] - [System.Array] - $ValuesToCheck - ) - - $returnValue = $true - - if (($DesiredValues.GetType().Name -ne 'HashTable') ` - -and ($DesiredValues.GetType().Name -ne 'CimInstance') ` - -and ($DesiredValues.GetType().Name -ne 'PSBoundParametersDictionary')) { - $errorMessage = $script:localizedData.PropertyTypeInvalidForDesiredValues -f $($DesiredValues.GetType().Name) - New-InvalidArgumentException -ArgumentName 'DesiredValues' -Message $errorMessage - } - - if (($DesiredValues.GetType().Name -eq 'CimInstance') -and ($null -eq $ValuesToCheck)) { - $errorMessage = $script:localizedData.PropertyTypeInvalidForValuesToCheck - New-InvalidArgumentException -ArgumentName 'ValuesToCheck' -Message $errorMessage - } - - if (($null -eq $ValuesToCheck) -or ($ValuesToCheck.Count -lt 1)) { - $keyList = $DesiredValues.Keys - } - else { - $keyList = $ValuesToCheck - } - - $keyList | ForEach-Object -Process { - if (($_ -ne 'Verbose')) { - if (($CurrentValues.ContainsKey($_) -eq $false) ` - -or ($CurrentValues.$_ -ne $DesiredValues.$_) ` - -or (($DesiredValues.GetType().Name -ne 'CimInstance' -and $DesiredValues.ContainsKey($_) -eq $true) -and ($null -ne $DesiredValues.$_ -and $DesiredValues.$_.GetType().IsArray))) { - if ($DesiredValues.GetType().Name -eq 'HashTable' -or ` - $DesiredValues.GetType().Name -eq 'PSBoundParametersDictionary') { - $checkDesiredValue = $DesiredValues.ContainsKey($_) - } - else { - # If DesiredValue is a CimInstance. - $checkDesiredValue = $false - if (([System.Boolean]($DesiredValues.PSObject.Properties.Name -contains $_)) -eq $true) { - if ($null -ne $DesiredValues.$_) { - $checkDesiredValue = $true - } - } - } - - if ($checkDesiredValue) { - $desiredType = $DesiredValues.$_.GetType() - $fieldName = $_ - if ($desiredType.IsArray -eq $true) { - if (($CurrentValues.ContainsKey($fieldName) -eq $false) ` - -or ($null -eq $CurrentValues.$fieldName)) { - Write-Verbose -Message ($script:localizedData.PropertyValidationError -f $fieldName) -Verbose - - $returnValue = $false - } - else { - $arrayCompare = Compare-Object -ReferenceObject $CurrentValues.$fieldName ` - -DifferenceObject $DesiredValues.$fieldName - if ($null -ne $arrayCompare) { - Write-Verbose -Message ($script:localizedData.PropertiesDoesNotMatch -f $fieldName) -Verbose - - $arrayCompare | ForEach-Object -Process { - Write-Verbose -Message ($script:localizedData.PropertyThatDoesNotMatch -f $_.InputObject, $_.SideIndicator) -Verbose - } - - $returnValue = $false - } - } - } - else { - switch ($desiredType.Name) { - 'String' { - if (-not [System.String]::IsNullOrEmpty($CurrentValues.$fieldName) -or ` - -not [System.String]::IsNullOrEmpty($DesiredValues.$fieldName)) { - Write-Verbose -Message ($script:localizedData.ValueOfTypeDoesNotMatch ` - -f $desiredType.Name, $fieldName, $($CurrentValues.$fieldName), $($DesiredValues.$fieldName)) -Verbose - - $returnValue = $false - } - } - - 'Int32' { - if (-not ($DesiredValues.$fieldName -eq 0) -or ` - -not ($null -eq $CurrentValues.$fieldName)) { - Write-Verbose -Message ($script:localizedData.ValueOfTypeDoesNotMatch ` - -f $desiredType.Name, $fieldName, $($CurrentValues.$fieldName), $($DesiredValues.$fieldName)) -Verbose - - $returnValue = $false - } - } - - { $_ -eq 'Int16' -or $_ -eq 'UInt16'} { - if (-not ($DesiredValues.$fieldName -eq 0) -or ` - -not ($null -eq $CurrentValues.$fieldName)) { - Write-Verbose -Message ($script:localizedData.ValueOfTypeDoesNotMatch ` - -f $desiredType.Name, $fieldName, $($CurrentValues.$fieldName), $($DesiredValues.$fieldName)) -Verbose - - $returnValue = $false - } - } - - default { - Write-Warning -Message ($script:localizedData.UnableToCompareProperty ` - -f $fieldName, $desiredType.Name) - - $returnValue = $false - } - } - } - } - } - } - } - - return $returnValue -} diff --git a/DSC/Modules/PowerShellGet.ResourceHelper/en-US/PowerShellGet.ResourceHelper.strings.psd1 b/DSC/Modules/PowerShellGet.ResourceHelper/en-US/PowerShellGet.ResourceHelper.strings.psd1 deleted file mode 100644 index 8e3522fda..000000000 --- a/DSC/Modules/PowerShellGet.ResourceHelper/en-US/PowerShellGet.ResourceHelper.strings.psd1 +++ /dev/null @@ -1,29 +0,0 @@ -# -# Copyright (c) Microsoft Corporation. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# culture = "en-US" -ConvertFrom-StringData -StringData @' -###PSLOC - InValidUri = InValid Uri: '{0}'. A sample valid uri: https://www.powershellgallery.com/api/v2/. - PathDoesNotExist = Path: '{0}' does not exist. - VersionError = MinimumVersion should be less than the MaximumVersion. The MinimumVersion or MaximumVersion cannot be used with the RequiredVersion in the same command. - UnexpectedArgument = Unexpected argument type: '{0}'. - SourceNotFound = Source '{0}' not found. Please make sure you register it. - CallingFunction = Calling function '{0}'. - PropertyTypeInvalidForDesiredValues = Property 'DesiredValues' must be either a [System.Collections.Hashtable], [CimInstance] or [PSBoundParametersDictionary]. The type detected was {0}. - PropertyTypeInvalidForValuesToCheck = If 'DesiredValues' is a CimInstance, then property 'ValuesToCheck' must contain a value. - PropertyValidationError = Expected to find an array value for property {0} in the current values, but it was either not present or was null. This has caused the test method to return false. - PropertiesDoesNotMatch = Found an array for property {0} in the current values, but this array does not match the desired state. Details of the changes are below. - PropertyThatDoesNotMatch = {0} - {1} - ValueOfTypeDoesNotMatch = {0} value for property {1} does not match. Current state is '{2}' and desired state is '{3}'. - UnableToCompareProperty = Unable to compare property {0} as the type {1} is not handled by the Test-SQLDSCParameterState cmdlet. -###PSLOC -'@ diff --git a/DSC/Tests/Integration/MSFT_PSModule.Integration.Tests.ps1 b/DSC/Tests/Integration/MSFT_PSModule.Integration.Tests.ps1 deleted file mode 100644 index 721b274d5..000000000 --- a/DSC/Tests/Integration/MSFT_PSModule.Integration.Tests.ps1 +++ /dev/null @@ -1,498 +0,0 @@ -<# - .SYNOPSIS - Integration tests for DSC resource PSModule. - - .NOTES - The header and footer was removed that is usually part of the - DscResource.Tests integration test template. - The header was adding the project folder as a PSModulePath which - collide with the PowerShellGet test framework that copies the - module to the regular PowerShell Module folder. -#> - -$script:dscResourceFriendlyName = 'PSModule' -$script:dcsResourceName = "MSFT_$($script:dscResourceFriendlyName)" - -#region Integration Tests -$configurationFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dcsResourceName).config.ps1" -. $configurationFile - -Describe "$($script:dcsResourceName)_Integration" { - $configurationName = "$($script:dcsResourceName)_SetPackageSourceAsNotTrusted_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - } - - $configurationName = "$($script:dcsResourceName)_InstallWithTrusted_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Present' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Module1_Name - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } - - $configurationName = "$($script:dcsResourceName)_UninstallModule1_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Absent' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Module1_Name - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } - - $configurationName = "$($script:dcsResourceName)_SetPackageSourceAsTrusted_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - } - - $configurationName = "$($script:dcsResourceName)_DefaultParameters_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Present' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Module1_Name - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } - - $configurationName = "$($script:dcsResourceName)_UsingAllowClobber_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Present' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Module2_Name - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } - - $configurationName = "$($script:dcsResourceName)_UninstallModule2_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Absent' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Module2_Name - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } - - $configurationName = "$($script:dcsResourceName)_RequiredVersion_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Present' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Module2_Name - $resourceCurrentState.InstalledVersion | Should -Be $ConfigurationData.AllNodes.Module2_RequiredVersion - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } - - <# - This should not install a newer version of the module since the - previous test installed a module within the version range. - #> - $configurationName = "$($script:dcsResourceName)_VersionRange_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Present' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Module2_Name - $resourceCurrentState.InstalledVersion | Should -Be $ConfigurationData.AllNodes.Module2_RequiredVersion - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } - - $configurationName = "$($script:dcsResourceName)_UninstallModule2_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Absent' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Module2_Name - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } - - <# - This should install a newer version of the module since no - module is installed within the version range. - #> - $configurationName = "$($script:dcsResourceName)_VersionRange_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Present' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Module2_Name - $resourceCurrentState.InstalledVersion | Should -Be $ConfigurationData.AllNodes.Module2_MaximumVersion - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } -} -#endregion diff --git a/DSC/Tests/Integration/MSFT_PSModule.config.ps1 b/DSC/Tests/Integration/MSFT_PSModule.config.ps1 deleted file mode 100644 index fcfa4090b..000000000 --- a/DSC/Tests/Integration/MSFT_PSModule.config.ps1 +++ /dev/null @@ -1,227 +0,0 @@ -#region HEADER -# Integration Test Config Template Version: 1.2.0 -#endregion - -$configFile = [System.IO.Path]::ChangeExtension($MyInvocation.MyCommand.Path, 'json') -if (Test-Path -Path $configFile) -{ - <# - Allows reading the configuration data from a JSON file - for real testing scenarios outside of the CI. - #> - $ConfigurationData = Get-Content -Path $configFile | ConvertFrom-Json -} -else -{ - $ConfigurationData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - CertificateFile = $env:DscPublicCertificatePath - - Module1_Name = 'PSLogging' - Module2_Name = 'SqlServer' - - Module2_RequiredVersion = '21.0.17279' - Module2_MinimumVersion = '21.0.17199' - Module2_MaximumVersion = '21.1.18068' - } - ) - } -} - -<# - .SYNOPSIS - Changes the repository (package source) 'PSGallery' to not trusted. - - .NOTES - Since the module is installed by SYSTEM as default this is done in - case the PSGallery is already trusted for SYSTEM. -#> -Configuration MSFT_PSModule_SetPackageSourceAsNotTrusted_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSRepository 'Integration_Test' - { - Name = 'PSGallery' - } - } -} - -<# - .SYNOPSIS - Installs a module as trusted. - - .NOTES - This assumes that the package source 'PSGallery' is not trusted for SYSTEM. -#> -Configuration MSFT_PSModule_InstallWithTrusted_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSModule 'Integration_Test' - { - Name = $Node.Module1_Name - } - } -} - -<# - .SYNOPSIS - Uninstalls a module ($Node.Module1_Name). -#> -Configuration MSFT_PSModule_UninstallModule1_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSModule 'Integration_Test' - { - Ensure = 'Absent' - Name = $Node.Module1_Name - } - } -} - -<# - .SYNOPSIS - Changes the repository (package source) 'PSGallery' to trusted. - - .NOTES - Since the module is installed by SYSTEM as default, the package - source 'PSGallery' must be trusted for SYSTEM for some of the - tests. -#> -Configuration MSFT_PSModule_SetPackageSourceAsTrusted_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSRepository 'Integration_Test' - { - Name = 'PSGallery' - } - } -} - -<# - .SYNOPSIS - Installs a module with the default parameters. -#> -Configuration MSFT_PSModule_DefaultParameters_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSModule 'Integration_Test' - { - Name = $Node.Module1_Name - } - } -} - -<# - .SYNOPSIS - Installed a module using AllowClobber. - - .NOTES - This test uses SqlServer module that actually needs AllowClobber. - On the build worker there are other modules (SQLPS) already installed, - those modules have the same cmdlets in them. -#> -Configuration MSFT_PSModule_UsingAllowClobber_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSModule 'Integration_Test' - { - Name = $Node.Module2_Name - NoClobber = $false - } - } -} - -<# - .SYNOPSIS - Uninstalls a module ($Node.Module2_Name). -#> -Configuration MSFT_PSModule_UninstallModule2_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSModule 'Integration_Test' - { - Ensure = 'Absent' - Name = $Node.Module2_Name - } - } -} - -<# - .SYNOPSIS - Installs a module with the specific version. -#> -Configuration MSFT_PSModule_RequiredVersion_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSModule 'Integration_Test' - { - Name = $Node.Module2_Name - Version = $Node.Module2_RequiredVersion - NoClobber = $false - } - } -} - -<# - .SYNOPSIS - Installs a module with the specific version. -#> -Configuration MSFT_PSModule_RequiredVersion_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSModule 'Integration_Test' - { - Name = $Node.Module2_Name - Version = $Node.Module2_RequiredVersion - NoClobber = $false - } - } -} - -<# - .SYNOPSIS - Installs a module within the specific version range. -#> -Configuration MSFT_PSModule_VersionRange_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSModule 'Integration_Test' - { - Name = $Node.Module2_Name - Version = "[$($Node.Module2_MinimumVersion), $($Node.Module2_MaximumVersion)]" - NoClobber = $false - } - } -} diff --git a/DSC/Tests/Integration/MSFT_PSRepository.Integration.Tests.ps1 b/DSC/Tests/Integration/MSFT_PSRepository.Integration.Tests.ps1 deleted file mode 100644 index 52d7ecbfb..000000000 --- a/DSC/Tests/Integration/MSFT_PSRepository.Integration.Tests.ps1 +++ /dev/null @@ -1,206 +0,0 @@ -<# - .SYNOPSIS - Integration tests for DSC resource PSModule. - - .NOTES - The header and footer was removed that is usually part of the - DscResource.Tests integration test template. - The header was adding the project folder as a PSModulePath which - collide with the PowerShellGet test framework that copies the - module to the regular PowerShell Module folder. -#> - -$script:dscResourceFriendlyName = 'PSRepository' -$script:dcsResourceName = "MSFT_$($script:dscResourceFriendlyName)" - -#region Integration Tests -$configurationFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dcsResourceName).config.ps1" -. $configurationFile - -Describe "$($script:dcsResourceName)_Integration" { - $configurationName = "$($script:dcsResourceName)_AddRepository_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Present' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Name - $resourceCurrentState.SourceLocation | Should -Be $ConfigurationData.AllNodes.TestSourceLocation - $resourceCurrentState.PublishLocation | Should -Be $ConfigurationData.AllNodes.TestPublishLocation - $resourceCurrentState.ScriptSourceLocation | Should -Be $ConfigurationData.AllNodes.TestScriptSourceLocation - $resourceCurrentState.ScriptPublishLocation | Should -Be $ConfigurationData.AllNodes.TestScriptPublishLocation - $resourceCurrentState.PackageManagementProvider | Should -Be 'NuGet' - $resourceCurrentState.Trusted | Should -Be $true - $resourceCurrentState.Registered | Should -Be $true - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } - - $configurationName = "$($script:dcsResourceName)_InstallTestModule_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - } - - $configurationName = "$($script:dcsResourceName)_ChangeRepository_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Present' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Name - $resourceCurrentState.SourceLocation | Should -Be $ConfigurationData.AllNodes.SourceLocation - $resourceCurrentState.PublishLocation | Should -Be $ConfigurationData.AllNodes.PublishLocation - $resourceCurrentState.ScriptSourceLocation | Should -Be $ConfigurationData.AllNodes.ScriptSourceLocation - $resourceCurrentState.ScriptPublishLocation | Should -Be $ConfigurationData.AllNodes.ScriptPublishLocation - $resourceCurrentState.PackageManagementProvider | Should -Be $ConfigurationData.AllNodes.PackageManagementProvider - $resourceCurrentState.Trusted | Should -Be $false - $resourceCurrentState.Registered | Should -Be $true - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } - - $configurationName = "$($script:dcsResourceName)_RemoveRepository_Config" - - Context ('When using configuration {0}' -f $configurationName) { - It 'Should compile and apply the MOF without throwing' { - { - $configurationParameters = @{ - OutputPath = $TestDrive - ConfigurationData = $ConfigurationData - } - - & $configurationName @configurationParameters - - $startDscConfigurationParameters = @{ - Path = $TestDrive - ComputerName = 'localhost' - Wait = $true - Verbose = $true - Force = $true - ErrorAction = 'Stop' - } - - Start-DscConfiguration @startDscConfigurationParameters - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { - $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq $configurationName ` - -and $_.ResourceId -eq "[$($script:dscResourceFriendlyName)]Integration_Test" - } - - $resourceCurrentState.Ensure | Should -Be 'Absent' - $resourceCurrentState.Name | Should -Be $ConfigurationData.AllNodes.Name - $resourceCurrentState.SourceLocation | Should -BeNullOrEmpty - $resourceCurrentState.PublishLocation | Should -BeNullOrEmpty - $resourceCurrentState.ScriptSourceLocation | Should -BeNullOrEmpty - $resourceCurrentState.ScriptPublishLocation | Should -BeNullOrEmpty - $resourceCurrentState.PackageManagementProvider | Should -BeNullOrEmpty - $resourceCurrentState.Trusted | Should -Be $false - $resourceCurrentState.Registered | Should -Be $false - } - - It 'Should return $true when Test-DscConfiguration is run' { - Test-DscConfiguration -Verbose | Should -Be $true - } - } -} -#endregion diff --git a/DSC/Tests/Integration/MSFT_PSRepository.config.ps1 b/DSC/Tests/Integration/MSFT_PSRepository.config.ps1 deleted file mode 100644 index ca7302cd3..000000000 --- a/DSC/Tests/Integration/MSFT_PSRepository.config.ps1 +++ /dev/null @@ -1,108 +0,0 @@ -#region HEADER -# Integration Test Config Template Version: 1.2.0 -#endregion - -$configFile = [System.IO.Path]::ChangeExtension($MyInvocation.MyCommand.Path, 'json') -if (Test-Path -Path $configFile) -{ - <# - Allows reading the configuration data from a JSON file - for real testing scenarios outside of the CI. - #> - $ConfigurationData = Get-Content -Path $configFile | ConvertFrom-Json -} -else -{ - $ConfigurationData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - CertificateFile = $env:DscPublicCertificatePath - - Name = 'PSTestGallery' - - URL = 'https://www.poshtestgallery.com/api/v2' - - - - TestModuleName = 'ContosoServer' - } - ) - } -} - -<# - .SYNOPSIS - Adds a repository. -#> -Configuration MSFT_PSRepository_AddRepository_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSRepository 'Integration_Test' - { - Name = $Node.Name - URL = $Node.TestURL - Priority = $Node.TestPriority - Trusted = $false - } - } -} - -<# - .SYNOPSIS - Installs a module with default parameters from the new repository. -#> -Configuration MSFT_PSRepository_InstallTestModule_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSModule 'Integration_Test' - { - Name = $Node.TestModuleName - Repository = $Node.Name - } - } -} - -<# - .SYNOPSIS - Changes the properties of the repository. -#> -Configuration MSFT_PSRepository_ChangeRepository_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSRepository 'Integration_Test' - { - Name = $Node.Name - URL = $Node.URL - Priority = $Node.Priority - Trusted = $false - } - } -} - -<# - .SYNOPSIS - Removes the repository. -#> -Configuration MSFT_PSRepository_RemoveRepository_Config -{ - Import-DscResource -ModuleName 'PowerShellGet' - - node $AllNodes.NodeName - { - PSRepository 'Integration_Test' - { - Ensure = 'Absent' - Name = $Node.Name - } - } -} diff --git a/DSC/Tests/Unit/MSFT_PSModule.Tests.ps1 b/DSC/Tests/Unit/MSFT_PSModule.Tests.ps1 deleted file mode 100644 index a0f733f83..000000000 --- a/DSC/Tests/Unit/MSFT_PSModule.Tests.ps1 +++ /dev/null @@ -1,613 +0,0 @@ -#region HEADER -# This must be same name as the root folder, and module manifest. -$script:DSCModuleName = 'DSC' -$script:DSCResourceName = 'MSFT_PSModule' - -# Unit Test Template Version: 1.2.4 -$script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) -if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath 'DscResource.Tests')) -} - -Import-Module -Name (Join-Path -Path $script:moduleRoot -ChildPath (Join-Path -Path 'DSCResource.Tests' -ChildPath 'TestHelper.psm1')) -Force - -$TestEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:DSCModuleName ` - -DSCResourceName $script:DSCResourceName ` - -ResourceType 'Mof' ` - -TestType Unit - -#endregion HEADER - -function Invoke-TestSetup { -} - -function Invoke-TestCleanup { - Restore-TestEnvironment -TestEnvironment $TestEnvironment -} - -# Begin Testing -try { - Invoke-TestSetup - - InModuleScope $script:DSCResourceName { - $mockModuleName = 'MockedModule' - $mockRepositoryName = 'PSGalleryTest' - $mockModuleBase = 'TestDrive:\MockPath' - - $mockModule_v1 = New-Object -TypeName Object | - Add-Member -Name 'Name' -MemberType NoteProperty -Value $mockModuleName -PassThru | - Add-Member -Name 'Description' -MemberType NoteProperty -Value 'Mocked description' -PassThru | - Add-Member -Name 'Guid' -MemberType NoteProperty -Value '4c189dbd-d858-4893-bac0-d682423c5fc7' -PassThru | - Add-Member -Name 'ModuleBase' -MemberType NoteProperty -Value $mockModuleBase -PassThru | - Add-Member -Name 'ModuleType' -MemberType NoteProperty -Value 'Script' -PassThru | - Add-Member -Name 'Author' -MemberType NoteProperty -Value 'Mocked Author' -PassThru | - Add-Member -Name 'Version' -MemberType NoteProperty -Value ([System.Version]'1.0.0.0') -PassThru -Force - - $mockModule_v2 = New-Object -TypeName Object | - Add-Member -Name 'Name' -MemberType NoteProperty -Value $mockModuleName -PassThru | - Add-Member -Name 'Description' -MemberType NoteProperty -Value 'Mocked description' -PassThru | - Add-Member -Name 'Guid' -MemberType NoteProperty -Value '4c189dbd-d858-4893-bac0-d682423c5fc7' -PassThru | - Add-Member -Name 'ModuleBase' -MemberType NoteProperty -Value $mockModuleBase -PassThru | - Add-Member -Name 'ModuleType' -MemberType NoteProperty -Value 'Script' -PassThru | - Add-Member -Name 'Author' -MemberType NoteProperty -Value 'Mocked Author' -PassThru | - Add-Member -Name 'Version' -MemberType NoteProperty -Value ([System.Version]'2.0.0.0') -PassThru -Force - - $mockGalleryModule = New-Object -TypeName PSCustomObject | - Add-Member -Name 'Name' -MemberType NoteProperty -Value $mockModuleName -PassThru | - Add-Member -Name 'Repository' -MemberType NoteProperty -Value 'PSGalleryTest' -PassThru | - Add-Member -Name 'Version' -MemberType NoteProperty -Value ([System.Version]'3.0.0.0') -PassThru -Force - - $mockGetRightModule_SingleModule = { - return @($mockModule_v1) - } - - $mockGetRightModule_MultipleModules = { - return @( - $mockModule_v1 - $mockModule_v2 - ) - } - - $mockGetModule_SingleModule = { - return @($mockModule_v1) - } - - $mockGetModule_SingleModule2 = { - return @($mockGalleryModule) - } - - $mockGetModule_MultipleModules = { - return @( - $mockModule_v1 - $mockModule_v2 - ) - } - - $mockGetModuleRepositoryName = { - return $mockRepositoryName - } - - $mockGetInstallationPolicy_Trusted = { - return $true - } - - $mockGetInstallationPolicy_NotTrusted = { - return $false - } - - $mockFindModule = { - return $mockGalleryModule - } - - Describe 'MSFT_PSModule\Get-TargetResource' -Tag 'Get','BVT' { - Context 'When the system is in the desired state' { - Context 'When the configuration is present' { - Context 'When the module is trusted' { - BeforeEach { - Mock -CommandName Get-RightModule -MockWith $mockGetRightModule_SingleModule - Mock -CommandName Get-ModuleRepositoryName -MockWith $mockGetModuleRepositoryName - } - - It 'Should return the same values as passed as parameters' { - $getTargetResourceResult = Get-TargetResource -Name $mockModuleName - $getTargetResourceResult.Name | Should -Be $mockModuleName - - Assert-MockCalled -CommandName Get-RightModule -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Get-ModuleRepositoryName -Exactly -Times 1 -Scope It - } - - It 'Should return the correct values for the other properties' { - $getTargetResourceResult = Get-TargetResource -Name $mockModuleName - - $getTargetResourceResult.Ensure | Should -Be 'Present' - $getTargetResourceResult.Repository | Should -Be $mockRepositoryName - $getTargetResourceResult.Description | Should -Be $mockModule_v1.Description - $getTargetResourceResult.Guid | Should -Be $mockModule_v1.Guid - $getTargetResourceResult.ModuleBase | Should -Be $mockModule_v1.ModuleBase - $getTargetResourceResult.ModuleType | Should -Be $mockModule_v1.ModuleType - $getTargetResourceResult.Author | Should -Be $mockModule_v1.Author - $getTargetResourceResult.InstalledVersion | Should -Be $mockModule_v1.Version - - Assert-MockCalled -CommandName Get-RightModule -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Get-ModuleRepositoryName -Exactly -Times 1 -Scope It - } - } - - Context 'When the module is not trusted' { - BeforeEach { - Mock -CommandName Get-RightModule -MockWith $mockGetRightModule_SingleModule - Mock -CommandName Get-ModuleRepositoryName -MockWith $mockGetModuleRepositoryName - } - - It 'Should return the same values as passed as parameters' { - $getTargetResourceResult = Get-TargetResource -Name $mockModuleName - $getTargetResourceResult.Name | Should -Be $mockModuleName - - Assert-MockCalled -CommandName Get-RightModule -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Get-ModuleRepositoryName -Exactly -Times 1 -Scope It - } - - It 'Should return the correct values for the other properties' { - $getTargetResourceResult = Get-TargetResource -Name $mockModuleName - - $getTargetResourceResult.Ensure | Should -Be 'Present' - $getTargetResourceResult.Repository | Should -Be $mockRepositoryName - $getTargetResourceResult.Description | Should -Be $mockModule_v1.Description - $getTargetResourceResult.Guid | Should -Be $mockModule_v1.Guid - $getTargetResourceResult.ModuleBase | Should -Be $mockModule_v1.ModuleBase - $getTargetResourceResult.ModuleType | Should -Be $mockModule_v1.ModuleType - $getTargetResourceResult.Author | Should -Be $mockModule_v1.Author - $getTargetResourceResult.InstalledVersion | Should -Be $mockModule_v1.Version - - Assert-MockCalled -CommandName Get-RightModule -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Get-ModuleRepositoryName -Exactly -Times 1 -Scope It - } - } - - Context 'When there are multiple version of the same module' { - BeforeEach { - Mock -CommandName Get-RightModule -MockWith $mockGetRightModule_MultipleModules - Mock -CommandName Get-ModuleRepositoryName -MockWith $mockGetModuleRepositoryName - } - - It 'Should return the same values as passed as parameters' { - $getTargetResourceResult = Get-TargetResource -Name $mockModuleName - $getTargetResourceResult.Name | Should -Be $mockModuleName - - Assert-MockCalled -CommandName Get-RightModule -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Get-ModuleRepositoryName -Exactly -Times 1 -Scope It - } - - It 'Should return the correct module version' { - $getTargetResourceResult = Get-TargetResource -Name $mockModuleName - - $getTargetResourceResult.InstalledVersion | Should -Be $mockModule_v2.Version - } - - It 'Should return the correct values for the other properties' { - $getTargetResourceResult = Get-TargetResource -Name $mockModuleName - - $getTargetResourceResult.Ensure | Should -Be 'Present' - $getTargetResourceResult.Repository | Should -Be $mockRepositoryName - $getTargetResourceResult.Description | Should -Be $mockModule_v2.Description - $getTargetResourceResult.Guid | Should -Be $mockModule_v2.Guid - $getTargetResourceResult.ModuleBase | Should -Be $mockModule_v2.ModuleBase - $getTargetResourceResult.ModuleType | Should -Be $mockModule_v2.ModuleType - $getTargetResourceResult.Author | Should -Be $mockModule_v2.Author - - Assert-MockCalled -CommandName Get-RightModule -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Get-ModuleRepositoryName -Exactly -Times 1 -Scope It - } - } - } - - Context 'When the configuration is absent' { - BeforeEach { - Mock -CommandName Get-RightModule - Mock -CommandName Get-ModuleRepositoryName - } - - It 'Should return the same values as passed as parameters' { - $getTargetResourceResult = Get-TargetResource -Name $mockModuleName - $getTargetResourceResult.Name | Should -Be $mockModuleName - #$getTargetResourceResult.Repository | Should -Be $mockRepositoryName - - Assert-MockCalled -CommandName Get-RightModule -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Get-ModuleRepositoryName -Exactly -Times 0 -Scope It - } - - It 'Should return the correct values for the other properties' { - $getTargetResourceResult = Get-TargetResource -Name $mockModuleName - - $getTargetResourceResult.Ensure | Should -Be 'Absent' - $getTargetResourceResult.Description | Should -BeNullOrEmpty - $getTargetResourceResult.Guid | Should -BeNullOrEmpty - $getTargetResourceResult.ModuleBase | Should -BeNullOrEmpty - $getTargetResourceResult.ModuleType | Should -BeNullOrEmpty - $getTargetResourceResult.Author | Should -BeNullOrEmpty - #$getTargetResourceResult.InstalledVersion | Should -BeNullOrEmpty - #$getTargetResourceResult.Trusted | Should -BeNullOrEmpty - $getTargetResourceResult.Version | Should -BeNullOrEmpty - $getTargetResourceResult.NoClobber | Should -Be $false - $getTargetResourceResult.SkipPublisherCheck | Should -Be $false - - Assert-MockCalled -CommandName Get-RightModule -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Get-ModuleRepositoryName -Exactly -Times 0 -Scope It - } - } - } - } - - Describe 'MSFT_PSModule\Set-TargetResource' -Tag 'Set','BVT' { - Context 'When the system is not in the desired state' { - Context 'When the configuration should be present' { - BeforeAll { - Mock -CommandName Find-PSResource -MockWith $mockFindModule - Mock -CommandName Install-PSResource -MockWith $mockFindModule - } - - Context 'When the Repository is ''PSGallery''' { - BeforeAll { - Mock -CommandName Get-InstallationPolicy -MockWith $mockGetInstallationPolicy_Trusted - Mock -CommandName Test-ParameterValue - } - - It 'Should call the Install-PSResource with the correct parameters' { - { Set-TargetResource -Name $mockModuleName -Repository 'PSGalleryTest' -Version '3.0.0.0' -verbose} | Should -Not -Throw - - Assert-MockCalled -CommandName Find-PSResource -ParameterFilter { - $Name -eq $mockModuleName -and $Repository -eq 'PSGalleryTest' - } -Exactly -Times 1 -Scope It - - #Assert-MockCalled -CommandName Install-PSResource -ParameterFilter { - # $InputObject.Name -eq $mockModuleName -and $InputObject.Repository -eq 'PSGalleryTest' - #} -Exactly -Times 1 -Scope It - } - } - - - Context 'When the module name cannot be found' { - BeforeAll { - Mock -CommandName Find-PSResource -MockWith { - throw 'Mocked error' - } - } - - It 'Should throw the correct error' { - { Set-TargetResource -Name $mockModuleName } | - Should -Throw ($localizedData.ModuleNotFoundInRepository -f $mockModuleName) - } - } - } - - Context 'When the configuration should be absent' { - Context 'When uninstalling a module that has a single version' { - BeforeAll { - Mock -CommandName Get-RightModule -MockWith $mockGetRightModule_SingleModule - Mock -CommandName Remove-Item - } - - It 'Should call the Remove-Item with the correct parameters' { - { Set-TargetResource -Name $mockModuleName -Ensure 'Absent' } | Should -Not -Throw - - Assert-MockCalled -CommandName Get-RightModule -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Remove-Item -ParameterFilter { - $path -eq $mockModuleBase - } -Exactly -Times 1 -Scope It - } - } - - Context 'When the module name cannot be found' { - BeforeAll { - Mock -CommandName Get-RightModule - } - - It 'Should throw the correct error' { - { Set-TargetResource -Name $mockModuleName -Ensure 'Absent' } | - Should -Throw ($localizedData.ModuleWithRightPropertyNotFound -f $mockModuleName) - } - } - - Context 'When a module cannot be removed' { - BeforeAll { - Mock -CommandName Get-RightModule -MockWith $mockGetRightModule_SingleModule - Mock -CommandName Remove-Item -MockWith { - throw 'Mock fail to remove module error' - } - } - - It 'Should throw the correct error' { - { Set-TargetResource -Name $mockModuleName -Ensure 'Absent' } | - Should -Throw ($localizedData.FailToUninstall -f $mockModuleName) - } - } - } - } - } - - Describe 'MSFT_PSModule\Test-TargetResource' -Tag 'Test','BVT' { - Context 'When the system is in the desired state' { - Context 'When the configuration is present' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Present' - Name = $mockModuleName - Repository = $mockRepositoryName - Description = $mockModule_v1.Description - Guid = $mockModule_v1.Guid - ModuleBase = $mockModule_v1.ModuleBase - ModuleType = $mockModule_v1.ModuleType - Author = $mockModule_v1.Author - InstalledVersion = $mockModule_v1.Version - #InstallationPolicy = 'Untrusted' - } - } - } - - It 'Should return the state as $true' { - $testTargetResourceResult = Test-TargetResource -Name $mockModuleName - $testTargetResourceResult | Should -Be $true - - Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It - } - } - - Context 'When the configuration is absent' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Absent' - Name = $mockModuleName - Repository = $null - Description = $null - Guid = $null - ModuleBase = $null - ModuleType = $null - Author = $null - InstalledVersion = $null - #InstallationPolicy = $null - } - } - } - - It 'Should return the state as $true' { - $testTargetResourceResult = Test-TargetResource -Ensure 'Absent' -Name $mockModuleName - $testTargetResourceResult | Should -Be $true - - Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It - } - } - } - - Context 'When the system is not in the desired state' { - Context 'When the configuration should be present' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Absent' - Name = $mockModuleName - Repository = $mockRepositoryName - Description = $mockModule_v1.Description - Guid = $mockModule_v1.Guid - ModuleBase = $mockModule_v1.ModuleBase - ModuleType = $mockModule_v1.ModuleType - Author = $mockModule_v1.Author - InstalledVersion = $mockModule_v1.Version - #InstallationPolicy = 'Untrusted' - } - } - } - - It 'Should return the state as $false' { - $testTargetResourceResult = Test-TargetResource -Name $mockModuleName - $testTargetResourceResult | Should -Be $false - - Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It - } - } - - Context 'When the configuration should be absent' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Present' - Name = $mockModuleName - Repository = $null - Description = $null - Guid = $null - ModuleBase = $null - ModuleType = $null - Author = $null - InstalledVersion = $null - # = $null - } - } - } - - It 'Should return the state as $false' { - $testTargetResourceResult = Test-TargetResource -Ensure 'Absent' -Name $mockModuleName - $testTargetResourceResult | Should -Be $false - - Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It - } - } - } - } - - Describe 'MSFT_PSModule\Get-ModuleRepositoryName' -Tag 'Helper' { - BeforeAll { - # Mock the file PSGetModuleInfo.xml in the module base folder. - New-Item -Path $mockModuleBase -ItemType File -Name 'PSGetModuleInfo.xml' -Force - - $mockModule = New-Object -TypeName Object | - Add-Member -Name 'ModuleBase' -MemberType NoteProperty -Value $mockModuleBase -PassThru -Force - - Mock -CommandName Import-Clixml -MockWith { - return New-Object -TypeName Object | - Add-Member -Name 'Repository' -MemberType NoteProperty -Value $mockRepositoryName -PassThru -Force - } - } - - It 'Should return the correct repository name of a module' { - Get-ModuleRepositoryName -Module $mockModule | Should -Be $mockRepositoryName - - Assert-MockCalled -CommandName 'Import-Clixml' -Exactly -Times 1 -Scope It - } - } - - Describe 'MSFT_PSModule\Get-RightModule' -Tag 'Helper' { - BeforeEach { - Mock -CommandName Get-ModuleRepositoryName -MockWith $mockGetModuleRepositoryName - } - - Context 'When the module does not exist' { - BeforeEach { - Mock -CommandName Get-Module - } - - It 'Should return $null' { - Get-RightModule -Name 'UnknownModule' | Should -BeNullOrEmpty - - Assert-MockCalled -CommandName 'Get-Module' -Exactly -Times 1 -Scope It - } - } - - Context 'When one version of the module exist' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_SingleModule - } - - It 'Should return the correct module information' { - $getRightModuleResult = Get-RightModule -Name $mockModuleName - $getRightModuleResult.Name | Should -Be $mockModuleName - - Assert-MockCalled -CommandName 'Get-ModuleRepositoryName' -Exactly -Times 0 -Scope It - Assert-MockCalled -CommandName 'Get-Module' -ParameterFilter { - $Name -eq $mockModuleName - } -Exactly -Times 1 -Scope It - } - } - - Context 'When parameter Repository is specified, and one version of the module exist' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_SingleModule - } - - It 'Should return the correct module information' { - $getRightModuleResult = Get-RightModule -Name $mockModuleName -Repository $mockRepositoryName -Verbose - $getRightModuleResult.Name | Should -Be $mockModuleName - - Assert-MockCalled -CommandName 'Get-ModuleRepositoryName' -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName 'Get-Module' -ParameterFilter { - $Name -eq $mockModuleName - } -Exactly -Times 1 -Scope It - } - } - - Context 'When parameter Repository is specified, and one version of the module exist, but from a different repository' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_SingleModule - } - - It 'Should return $null' { - $getRightModuleResult = Get-RightModule -Name $mockModuleName -Repository 'OtherRepository' -Verbose - $getRightModuleResult.Name | Should -BeNullOrEmpty - - Assert-MockCalled -CommandName 'Get-ModuleRepositoryName' -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName 'Get-Module' -ParameterFilter { - $Name -eq $mockModuleName - } -Exactly -Times 1 -Scope It - } - } - - Context 'When the module is required to have a specific version, and the specific version is installed' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_SingleModule2 - } - - # It 'Should return the correct module information' { - # $getRightModuleResult = Get-RightModule -Name $mockModuleName -Version '3.0.0.0' -Repository 'PSGalleryTest' -Verbose - # $getRightModuleResult.Name | Should -Be $mockModuleName - - # Assert-MockCalled -CommandName 'Get-ModuleRepositoryName' -Exactly -Times 0 -Scope It - # Assert-MockCalled -CommandName 'Get-Module' -ParameterFilter { - # $Name -eq $mockModuleName - # } -Exactly -Times 1 -Scope It - # } - } - - Context 'When the module is required to have a specific version, and the specific version is not installed' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_SingleModule - } - - It 'Should return $null' { - $getRightModuleResult = Get-RightModule -Name $mockModuleName -Version '2.0.0.0' -Verbose - $getRightModuleResult.Name | Should -BeNullOrEmpty - - Assert-MockCalled -CommandName 'Get-ModuleRepositoryName' -Exactly -Times 0 -Scope It - Assert-MockCalled -CommandName 'Get-Module' -ParameterFilter { - $Name -eq $mockModuleName - } -Exactly -Times 1 -Scope It - } - } - - Context 'When the module is required to have a maximum version, and a suitable module is installed' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_SingleModule - } - - } - - Context 'When the module is required to have a minimum version, and a suitable module is installed' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_SingleModule - } - - } - - Context 'When the module is required to have a maximum version, and the suitable module is not installed' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_SingleModule - } - - } - - Context 'When the module is required to have a minimum version, and the suitable module is not installed' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_SingleModule - } - - } - - Context 'When the module is required to have a minimum and maximum version' { - Context 'When a suitable module is installed' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_SingleModule - } - - } - - Context 'When there two suitable modules installed' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_MultipleModules - } - - } - - - Context 'When there two installed modules, but only one module is suitable' { - BeforeEach { - Mock -CommandName Get-Module -MockWith $mockGetModule_MultipleModules - } - } - } - } - } -} -finally { - Invoke-TestCleanup -} diff --git a/DSC/Tests/Unit/MSFT_PSRepository.Tests.ps1 b/DSC/Tests/Unit/MSFT_PSRepository.Tests.ps1 deleted file mode 100644 index 47f68b33d..000000000 --- a/DSC/Tests/Unit/MSFT_PSRepository.Tests.ps1 +++ /dev/null @@ -1,397 +0,0 @@ -#region HEADER -# This must be same name as the root folder, and module manifest. -$script:DSCModuleName = 'DSC' -$script:DSCResourceName = 'MSFT_PSRepository' - -# Unit Test Template Version: 1.2.4 -$script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) -if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath 'DscResource.Tests')) -} - -Import-Module -Name (Join-Path -Path $script:moduleRoot -ChildPath (Join-Path -Path 'DSCResource.Tests' -ChildPath 'TestHelper.psm1')) -Force - -$TestEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:DSCModuleName ` - -DSCResourceName $script:DSCResourceName ` - -ResourceType 'Mof' ` - -TestType Unit - -#endregion HEADER - -function Invoke-TestSetup { -} - -function Invoke-TestCleanup { - Restore-TestEnvironment -TestEnvironment $TestEnvironment -} - -# Begin Testing -try { - Invoke-TestSetup - - InModuleScope $script:DSCResourceName { - $mockRepositoryName = 'PSTestGallery' - $mockSourceLocation = 'https://www.poshtestgallery.com/api/v2' - $mockPriority = 1 - $mockInstallationPolicy_Trusted = $true - $mockInstallationPolicy_NotTrusted = $false - - #$mockInstallationPolicy_Trusted = 'Trusted' - #$mockInstallationPolicy_NotTrusted = 'Untrusted' - - - $mockRepository = New-Object -TypeName Object | - Add-Member -Name 'Name' -MemberType NoteProperty -Value $mockRepositoryName -PassThru | - Add-Member -Name 'URL' -MemberType NoteProperty -Value $mockSourceLocation -PassThru | - Add-Member -Name 'InstallationPolicy' -MemberType NoteProperty -Value $mockInstallationPolicy_Trusted -PassThru | - Add-Member -Name 'Priority' -MemberType NoteProperty -Value $mockPriority -PassThru | - #Add-Member -Name 'Trusted' -MemberType NoteProperty -Value $mockInstallationPolicy_Trusted -PassThru | - Add-Member -Name 'Trusted' -MemberType NoteProperty -Value $true -PassThru | - Add-Member -Name 'Registered' -MemberType NoteProperty -Value $true -PassThru -Force - - $mockGetPSRepository = { - return @($mockRepository) - } - - Describe 'MSFT_PSRepository\Get-TargetResource' -Tag 'Get' { - Context 'When the system is in the desired state' { - Context 'When the configuration is present' { - BeforeAll { - Mock -CommandName Get-PSResourceRepository -MockWith $mockGetPSRepository - } - - #It 'Should return the same values as passed as parameters' { - # $getTargetResourceResult = Get-TargetResource -Name $mockRepositoryName - # $getTargetResourceResult.Name | Should -Be $mockRepositoryName - - # Assert-MockCalled -CommandName Get-PSResourceRepository -Exactly -Times 1 -Scope It - # } - - It 'Should return the correct values for the other properties' { - $getTargetResourceResult = Get-TargetResource -Name $mockRepositoryName -Verbose - - $getTargetResourceResult.Ensure | Should -Be 'Present' - #$getTargetResourceResult.URL | Should -Be $mockRepository.URL - # $getTargetResourceResult.Priority | Should -Be $mockRepository.Priority - #$getTargetResourceResult.InstallationPolicy | Should -Be $mockRepository.InstallationPolicy - #$getTargetResourceResult.Trusted | Should -Be $mockRepository.Trusted - #$getTargetResourceResult.Trusted | Should -Be $true - $getTargetResourceResult.Registered | Should -Be $true - - Assert-MockCalled -CommandName Get-PSResourceRepository -Exactly -Times 1 -Scope It - } - } - - Context 'When the configuration is absent' { - BeforeAll { - Mock -CommandName Get-PSResourceRepository - } - - It 'Should return the same values as passed as parameters' { - $getTargetResourceResult = Get-TargetResource -Name $mockRepositoryName - $getTargetResourceResult.Name | Should -Be $mockRepositoryName - - Assert-MockCalled -CommandName Get-PSResourceRepository -Exactly -Times 1 -Scope It - } - - It 'Should return the correct values for the other properties' { - $getTargetResourceResult = Get-TargetResource -Name $mockRepositoryName - - $getTargetResourceResult.Ensure | Should -Be 'Absent' - $getTargetResourceResult.URL | Should -BeNullOrEmpty - $getTargetResourceResult.Priority | Should -BeNullOrEmpty - #$getTargetResourceResult.InstallationPolicy | Should -BeNullOrEmpty - #$getTargetResourceResult.Trusted | Should -Be $false - $getTargetResourceResult.Registered | Should -Be $false - - Assert-MockCalled -CommandName Get-PSResourceRepository -Exactly -Times 1 -Scope It - } - } - } - } - - Describe 'MSFT_PSRepository\Set-TargetResource' -Tag 'Set' { - Context 'When the system is not in the desired state' { - BeforeAll { - Mock -CommandName Register-PSResourceRepository - Mock -CommandName Unregister-PSResourceRepository - Mock -CommandName Set-PSResourceRepository - } - - Context 'When the configuration should be present' { - Context 'When the repository does not exist' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Absent' - Name = $mockRepositoryName - URL = $null - Priority = $null - #InstallationPolicy = $null - #Trusted = $false - Registered = $false - } - } - } - - It 'Should return call the correct mocks' { - $setTargetResourceParameters = @{ - Name = $mockRepository.Name - URL = $mockRepository.URL - # Priority = $mockRepository.Priority - #Trusted = $mockRepository.Trusted - #InstallationPolicy = $mockRepository.InstallationPolicy - } - - { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - - Assert-MockCalled -CommandName Register-PSResourceRepository -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Unregister-PSResourceRepository -Exactly -Times 0 -Scope It - Assert-MockCalled -CommandName Set-PSresourceRepository -Exactly -Times 0 -Scope It - } - } - - Context 'When the repository do exist but with wrong properties' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Present' - Name = $mockRepository.Name - URL = 'https://www.powershellgallery.com/api/v2' - Priority = '0' - #InstallationPolicy = $mockRepository.InstallationPolicy - #Trusted = $mockRepository.Trusted - Registered = $mockRepository.Registered - } - } - } - - It 'Should return call the correct mocks' { - $setTargetResourceParameters = @{ - Name = $mockRepository.Name - URL = $mockRepository.URL - #Priority = $mockRepository.Priority - #Trusted = $mockRepository.Trusted - #InstallationPolicy = $mockRepository.InstallationPolicy - } - - { MSFT_PSRepository\Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - - Assert-MockCalled -CommandName Register-PSResourceRepository -Exactly -Times 0 -Scope It - Assert-MockCalled -CommandName Unregister-PSresourceRepository -Exactly -Times 0 -Scope It - Assert-MockCalled -CommandName Set-PSResourceRepository -Exactly -Times 1 -Scope It - } - } - } - - Context 'When the configuration should be absent' { - Context 'When the repository do exist' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Present' - Name = $mockRepository.Name - URL = $mockRepository.URL - Priority = $mockRepository.Priority - #InstallationPolicy = $mockRepository.InstallationPolicy - #Trusted = $mockRepository.Trusted - Registered = $mockRepository.Registered - } - } - } - - It 'Should return call the correct mocks' { - $setTargetResourceParameters = @{ - Ensure = 'Absent' - Name = $mockRepositoryName - } - - { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - - Assert-MockCalled -CommandName Register-PSResourceRepository -Exactly -Times 0 -Scope It - Assert-MockCalled -CommandName Unregister-PSResourceRepository -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Set-PSResourceRepository -Exactly -Times 0 -Scope It - } - } - } - } - } - - Describe 'MSFT_PSRepository\Test-TargetResource' -Tag 'Test' { - Context 'When the system is in the desired state' { - Context 'When the configuration is present' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Present' - Name = $mockRepository.Name - URL = $mockRepository.URL - Priority = $mockRepository.Priority - #InstallationPolicy = $mockRepository.InstallationPolicy - #Trusted = $mockRepository.Trusted - Registered = $mockRepository.Registered - } - } - } - - It 'Should return the state as $true' { - $testTargetResourceResult = Test-TargetResource -Name $mockRepositoryName - $testTargetResourceResult | Should -Be $true - - Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It - } - } - - Context 'When the configuration is absent' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Absent' - Name = $mockRepositoryName - URL = $null - Priority = $null - #InstallationPolicy = $null - #Trusted = $false - Registered = $false - } - } - } - - It 'Should return the state as $true' { - $testTargetResourceResult = Test-TargetResource -Ensure 'Absent' -Name $mockRepositoryName - $testTargetResourceResult | Should -Be $true - - Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It - } - } - } - - Context 'When the system is not in the desired state' { - Context 'When the configuration should be present' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Absent' - Name = $mockRepositoryName - URL = $null - Priority = $null - #InstallationPolicy = $null - #Trusted = $false - Registered = $false - } - } - } - - It 'Should return the state as $false' { - $testTargetResourceParameters = @{ - Name = $mockRepository.Name - URL = $mockRepository.URL - Priority = $mockRepository.Priority - #Trusted = $mockRepository.Trusted - #InstallationPolicy = $mockRepository.InstallationPolicy - } - - $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters - $testTargetResourceResult | Should -Be $false - - Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It - } - } - - Context 'When a property is not in desired state' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Present' - Name = $mockRepository.Name - URL = $mockRepository.URL - Priority = $mockRepository.Priority - #InstallationPolicy = $mockRepository.InstallationPolicy - #Trusted = $mockRepository.Trusted - Registered = $mockRepository.Registered - } - } - } - - $defaultTestCase = @{ - URL = $mockRepository.URL - Priority = $mockRepository.Priority - #Trusted = $mockRepository.Trusted - #InstallationPolicy = $mockRepository.InstallationPolicy - } - - $testCaseSourceLocationIsMissing = $defaultTestCase.Clone() - $testCaseSourceLocationIsMissing['TestName'] = 'SourceLocation is missing' - $testCaseSourceLocationIsMissing['URL'] = 'https://www.powershellgallery.com/api/v2' - - - $testCasePriorityIsMissing = $defaultTestCase.Clone() - $testCasePriorityIsMissing['TestName'] = 'Priority is missing' - $testCasePriorityIsMissing['Priority'] = '50' - - - #$testCaseInstallationPolicyIsMissing = $defaultTestCase.Clone() - #$testCaseInstallationPolicyIsMissing['TestName'] = 'InstallationPolicy is missing' - #$testCaseInstallationPolicyIsMissing['Trusted'] = $mockInstallationPolicy_NotTrusted - - $testCases = @( - $testCaseSourceLocationIsMissing - $testCasePriorityIsMissing - #$testCaseInstallationPolicyIsMissing - ) - - It 'Should return the state as $false when the correct ' -TestCases $testCases { - param - ( - $URL, - $Priority - #$Trusted, - #$InstallationPolicy - ) - - $testTargetResourceParameters = @{ - Name = $mockRepositoryName - URL = $URL - Priority = $Priority - #Trusted = $Trusted - #InstallationPolicy = $InstallationPolicy - } - - $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters - $testTargetResourceResult | Should -Be $false - - Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It - } - } - - Context 'When the configuration should be absent' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return @{ - Ensure = 'Present' - Name = $mockRepositoryName - URL = $mockRepository.URL - Priority = $mockRepository.Priority - #Trusted = $mockRepository.Trusted - #InstallationPolicy = $mockRepository.InstallationPolicy - Registered = $mockRepository.Registered - } - } - } - - It 'Should return the state as $false' { - $testTargetResourceResult = Test-TargetResource -Ensure 'Absent' -Name $mockRepositoryName - $testTargetResourceResult | Should -Be $false - - Assert-MockCalled -CommandName Get-TargetResource -Exactly -Times 1 -Scope It - } - } - } - } - } -} -finally { - Invoke-TestCleanup -} diff --git a/DSC/Tests/Unit/PowerShellGet.LocalizationHelper.Tests.ps1 b/DSC/Tests/Unit/PowerShellGet.LocalizationHelper.Tests.ps1 deleted file mode 100644 index 6b9e6eda9..000000000 --- a/DSC/Tests/Unit/PowerShellGet.LocalizationHelper.Tests.ps1 +++ /dev/null @@ -1,206 +0,0 @@ -<# - .SYNOPSIS - Automated unit test for helper functions in module PowerShellGet.ResourceHelper. -#> - - -$script:helperModuleName = 'PowerShellGet.LocalizationHelper' - -Describe "$script:helperModuleName Unit Tests" { - BeforeAll { - $resourceModuleRoot = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent - $dscResourcesFolderFilePath = Join-Path -Path (Join-Path -Path $resourceModuleRoot -ChildPath 'Modules') ` - -ChildPath $script:helperModuleName - - Import-Module -Name (Join-Path -Path $dscResourcesFolderFilePath ` - -ChildPath "$script:helperModuleName.psm1") -Force - } - - InModuleScope $script:helperModuleName { - Describe 'Get-LocalizedData' { - $mockTestPath = { - return $mockTestPathReturnValue - } - - $mockImportLocalizedData = { - $BaseDirectory | Should -Be $mockExpectedLanguagePath - } - - BeforeEach { - Mock -CommandName Test-Path -MockWith $mockTestPath -Verifiable - Mock -CommandName Import-LocalizedData -MockWith $mockImportLocalizedData -Verifiable - } - - Context 'When loading localized data for Swedish' { - $mockExpectedLanguagePath = 'sv-SE' - $mockTestPathReturnValue = $true - - It 'Should call Import-LocalizedData with sv-SE language' { - Mock -CommandName Join-Path -MockWith { - return 'sv-SE' - } -Verifiable - - { Get-LocalizedData -ResourceName 'DummyResource' } | Should -Not -Throw - - Assert-MockCalled -CommandName Join-Path -Exactly -Times 2 -Scope It - Assert-MockCalled -CommandName Test-Path -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Import-LocalizedData -Exactly -Times 1 -Scope It - } - - $mockExpectedLanguagePath = 'en-US' - $mockTestPathReturnValue = $false - - It 'Should call Import-LocalizedData and fallback to en-US if sv-SE language does not exist' { - Mock -CommandName Join-Path -MockWith { - return $ChildPath - } -Verifiable - - { Get-LocalizedData -ResourceName 'DummyResource' } | Should -Not -Throw - - Assert-MockCalled -CommandName Join-Path -Exactly -Times 3 -Scope It - Assert-MockCalled -CommandName Test-Path -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Import-LocalizedData -Exactly -Times 1 -Scope It - } - - Context 'When $ScriptRoot is set to a path' { - $mockExpectedLanguagePath = 'sv-SE' - $mockTestPathReturnValue = $true - - It 'Should call Import-LocalizedData with sv-SE language' { - Mock -CommandName Join-Path -MockWith { - return 'sv-SE' - } -Verifiable - - { Get-LocalizedData -ResourceName 'DummyResource' -ScriptRoot '.' } | Should -Not -Throw - - Assert-MockCalled -CommandName Join-Path -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Test-Path -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Import-LocalizedData -Exactly -Times 1 -Scope It - } - - $mockExpectedLanguagePath = 'en-US' - $mockTestPathReturnValue = $false - - It 'Should call Import-LocalizedData and fallback to en-US if sv-SE language does not exist' { - Mock -CommandName Join-Path -MockWith { - return $ChildPath - } -Verifiable - - { Get-LocalizedData -ResourceName 'DummyResource' -ScriptRoot '.' } | Should -Not -Throw - - Assert-MockCalled -CommandName Join-Path -Exactly -Times 2 -Scope It - Assert-MockCalled -CommandName Test-Path -Exactly -Times 1 -Scope It - Assert-MockCalled -CommandName Import-LocalizedData -Exactly -Times 1 -Scope It - } - } - } - - Context 'When loading localized data for English' { - Mock -CommandName Join-Path -MockWith { - return 'en-US' - } -Verifiable - - $mockExpectedLanguagePath = 'en-US' - $mockTestPathReturnValue = $true - - It 'Should call Import-LocalizedData with en-US language' { - { Get-LocalizedData -ResourceName 'DummyResource' } | Should -Not -Throw - } - } - - Assert-VerifiableMock - } - - Describe 'New-InvalidResultException' { - Context 'When calling with Message parameter only' { - It 'Should throw the correct error' { - $mockErrorMessage = 'Mocked error' - - { New-InvalidResultException -Message $mockErrorMessage } | Should -Throw $mockErrorMessage - } - } - - Context 'When calling with both the Message and ErrorRecord parameter' { - It 'Should throw the correct error' { - $mockErrorMessage = 'Mocked error' - $mockExceptionErrorMessage = 'Mocked exception error message' - - $mockException = New-Object -TypeName System.Exception -ArgumentList $mockExceptionErrorMessage - $mockErrorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList $mockException, $null, 'InvalidResult', $null - - $exception = { New-InvalidResultException -Message $mockErrorMessage -ErrorRecord $mockErrorRecord -ErrorAction SilentlyContinue} - $exception | Should -Throw -PassThru $_ | Should -Match ('System.Exception: {0}' -f $mockErrorMessage) - $exception | Should -Throw -PassThru $_ | Should -Match ('System.Exception: {0}' -f $mockExceptionErrorMessage) - } - } - - Assert-VerifiableMock - } - - Describe 'New-ObjectNotFoundException' { - Context 'When calling with Message parameter only' { - It 'Should throw the correct error' { - $mockErrorMessage = 'Mocked error' - - { New-ObjectNotFoundException -Message $mockErrorMessage } | Should -Throw $mockErrorMessage - } - } - - Context 'When calling with both the Message and ErrorRecord parameter' { - It 'Should throw the correct error' { - $mockErrorMessage = 'Mocked error' - $mockExceptionErrorMessage = 'Mocked exception error message' - - $mockException = New-Object -TypeName System.Exception -ArgumentList $mockExceptionErrorMessage - $mockErrorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList $mockException, $null, 'InvalidResult', $null - - $exception = { New-ObjectNotFoundException -Message $mockErrorMessage -ErrorRecord $mockErrorRecord } - $exception | Should -Throw -PassThru $_ | Should -Match ('System.Exception: {0}' -f $mockErrorMessage) - $exception | Should -Throw -PassThru $_ | Should -Match ('System.Exception: {0}' -f $mockExceptionErrorMessage) - } - } - - Assert-VerifiableMock - } - - Describe 'New-InvalidOperationException' { - Context 'When calling with Message parameter only' { - It 'Should throw the correct error' { - $mockErrorMessage = 'Mocked error' - - { New-InvalidOperationException -Message $mockErrorMessage } | Should -Throw $mockErrorMessage - } - } - - Context 'When calling with both the Message and ErrorRecord parameter' { - It 'Should throw the correct error' { - $mockErrorMessage = 'Mocked error' - $mockExceptionErrorMessage = 'Mocked exception error message' - - $mockException = New-Object -TypeName System.Exception -ArgumentList $mockExceptionErrorMessage - $mockErrorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList $mockException, $null, 'InvalidResult', $null - - $exception = { New-InvalidOperationException -Message $mockErrorMessage -ErrorRecord $mockErrorRecord } - $exception | Should -Throw -PassThru $_ | Should -Match ('System.InvalidOperationException: {0}' -f $mockErrorMessage) - $exception | Should -Throw -PassThru $_ | Should -Match ('System.Exception: {0}' -f $mockExceptionErrorMessage) - } - } - - Assert-VerifiableMock - } - - Describe 'New-InvalidArgumentException' { - Context 'When calling with both the Message and ArgumentName parameter' { - It 'Should throw the correct error' { - $mockErrorMessage = 'Mocked error' - $mockArgumentName = 'MockArgument' - - $exception = { New-InvalidArgumentException -Message $mockErrorMessage -ArgumentName $mockArgumentName } - $exception | Should -Throw -PassThru $_ | Should -Match ("Parameter '{0}'" -f $mockArgumentName) - } - } - - Assert-VerifiableMock - } - } -} diff --git a/DSC/Tests/Unit/PowerShellGet.ResourceHelper.Tests.ps1 b/DSC/Tests/Unit/PowerShellGet.ResourceHelper.Tests.ps1 deleted file mode 100644 index ead1d4da8..000000000 --- a/DSC/Tests/Unit/PowerShellGet.ResourceHelper.Tests.ps1 +++ /dev/null @@ -1,504 +0,0 @@ -<# - .SYNOPSIS - Automated unit test for helper functions in module PowerShellGet.ResourceHelper. -#> - - -$script:helperModuleName = 'PowerShellGet.ResourceHelper' - -$resourceModuleRoot = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent -$dscResourcesFolderFilePath = Join-Path -Path (Join-Path -Path $resourceModuleRoot -ChildPath 'Modules') ` - -ChildPath $script:helperModuleName - -Import-Module -Name (Join-Path -Path $dscResourcesFolderFilePath ` - -ChildPath "$script:helperModuleName.psm1") -Force - -InModuleScope $script:helperModuleName { - Describe 'New-SplatParameterHashTable' { - Context 'When specific parameters should be returned' { - It 'Should return a hashtable with the correct values' { - $mockPSBoundParameters = @{ - Property1 = '1' - Property2 = '2' - Property3 = '3' - Property4 = '4' - } - - $extractArgumentsResult = New-SplatParameterHashTable ` - -FunctionBoundParameters $mockPSBoundParameters ` - -ArgumentNames @('Property2', 'Property3') - - $extractArgumentsResult | Should -BeOfType [System.Collections.Hashtable] - $extractArgumentsResult.Count | Should -Be 2 - $extractArgumentsResult.ContainsKey('Property2') | Should -BeTrue - $extractArgumentsResult.ContainsKey('Property3') | Should -BeTrue - $extractArgumentsResult.Property2 | Should -Be '2' - $extractArgumentsResult.Property3 | Should -Be '3' - } - } - - Context 'When the specific parameters to be returned does not exist' { - It 'Should return an empty hashtable' { - $mockPSBoundParameters = @{ - Property1 = '1' - } - - $extractArgumentsResult = New-SplatParameterHashTable ` - -FunctionBoundParameters $mockPSBoundParameters ` - -ArgumentNames @('Property2', 'Property3') - - $extractArgumentsResult | Should -BeOfType [System.Collections.Hashtable] - $extractArgumentsResult.Count | Should -Be 0 - } - } - - Context 'When and empty hashtable is passed in the parameter FunctionBoundParameters' { - It 'Should return an empty hashtable' { - $mockPSBoundParameters = @{ - } - - $extractArgumentsResult = New-SplatParameterHashTable ` - -FunctionBoundParameters $mockPSBoundParameters ` - -ArgumentNames @('Property2', 'Property3') - - $extractArgumentsResult | Should -BeOfType [System.Collections.Hashtable] - $extractArgumentsResult.Count | Should -Be 0 - } - } - } - - Describe 'Test-ParameterValue' { - BeforeAll { - $mockProviderName = 'PowerShellGet' - } - - Context 'When passing a correct uri as ''Value'' and type is ''SourceUri''' { - It 'Should not throw an error' { - { - Test-ParameterValue ` - -Value 'https://mocked.uri' ` - -Type 'SourceUri' ` - -ProviderName $mockProviderName - } | Should -Not -Throw - } - } - - Context 'When passing an invalid uri as ''Value'' and type is ''SourceUri''' { - It 'Should throw the correct error' { - $mockParameterName = 'mocked.uri' - - { - Test-ParameterValue ` - -Value $mockParameterName ` - -Type 'SourceUri' ` - -ProviderName $mockProviderName - } | Should -Throw ($LocalizedData.InValidUri -f $mockParameterName) - } - } - - Context 'When passing a correct path as ''Value'' and type is ''DestinationPath''' { - It 'Should not throw an error' { - { - Test-ParameterValue ` - -Value 'TestDrive:\' ` - -Type 'DestinationPath' ` - -ProviderName $mockProviderName - } | Should -Not -Throw - } - } - - Context 'When passing an invalid path as ''Value'' and type is ''DestinationPath''' { - It 'Should throw the correct error' { - $mockParameterName = 'TestDrive:\NonExistentPath' - - { - Test-ParameterValue ` - -Value $mockParameterName ` - -Type 'DestinationPath' ` - -ProviderName $mockProviderName - } | Should -Throw ($LocalizedData.PathDoesNotExist -f $mockParameterName) - } - } - - #Context 'When passing a correct uri as ''Value'' and type is ''PackageSource''' { - # It 'Should not throw an error' { - # { - # Test-ParameterValue ` - # -Value 'https://mocked.uri' - #-Type 'PackageSource' ` - #-ProviderName $mockProviderName - # } | Should -Not -Throw - # } - # } - - #Context 'When passing an correct package source as ''Value'' and type is ''PackageSource''' { - # BeforeAll { - # $mockParameterName = 'PSGallery' - - # Mock -CommandName Get-PackageSource -MockWith { - # return New-Object -TypeName Object | - # Add-Member -Name 'Name' -MemberType NoteProperty -Value $mockParameterName -PassThru - # } - # } - #} - - # Context 'When passing type is ''PackageSource'' and passing a package source that does not exist' { - # BeforeAll { - # $mockParameterName = 'PSGallery' - - # Mock -CommandName Get-PackageSource - # } - # } - - Context 'When passing invalid type in parameter ''Type''' { - BeforeAll { - $mockType = 'UnknownType' - } - - It 'Should throw the correct error' { - { - Test-ParameterValue ` - -Value 'AnyArgument' ` - -Type $mockType ` - -ProviderName $mockProviderName - } | Should -Throw ($LocalizedData.UnexpectedArgument -f $mockType) - } - } - } - - Describe 'Test-VersionParameter' { - Context 'When not passing in any parameters (using default values)' { - It 'Should return true' { - Test-VersionParameter | Should -BeTrue - } - } - - Context 'When only ''RequiredVersion'' are passed' { - It 'Should return true' { - #Test-VersionParameter -RequiredVersion '3.0.0.0' | Should -BeTrue - } - } -<# - Context 'When ''MinimumVersion'' has a lower version than ''MaximumVersion''' { - It 'Should throw the correct error' { - { - Test-VersionParameter ` - -MinimumVersion '2.0.0.0' ` - -MaximumVersion '1.0.0.0' - } | Should -Throw $LocalizedData.VersionError - } - } - - Context 'When ''MinimumVersion'' has a lower version than ''MaximumVersion''' { - It 'Should throw the correct error' { - { - Test-VersionParameter ` - -MinimumVersion '2.0.0.0' ` - -MaximumVersion '1.0.0.0' - } | Should -Throw $LocalizedData.VersionError - } - } - - Context 'When ''RequiredVersion'', ''MinimumVersion'', and ''MaximumVersion'' are passed' { - It 'Should throw the correct error' { - { - Test-VersionParameter ` - -RequiredVersion '3.0.0.0' ` - -MinimumVersion '2.0.0.0' ` - -MaximumVersion '1.0.0.0' - } | Should -Throw $LocalizedData.VersionError - } - } - #> - } - - - Describe 'Testing Test-DscParameterState' -Tag TestDscParameterState { - Context -Name 'When passing values' -Fixture { - It 'Should return true for two identical tables' { - $mockDesiredValues = @{ Example = 'test' } - - $testParameters = @{ - CurrentValues = $mockDesiredValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $true - } - - It 'Should return false when a value is different for [System.String]' { - $mockCurrentValues = @{ Example = [System.String]'something' } - $mockDesiredValues = @{ Example = [System.String]'test' } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $false - } - - It 'Should return false when a value is different for [System.Int32]' { - $mockCurrentValues = @{ Example = [System.Int32]1 } - $mockDesiredValues = @{ Example = [System.Int32]2 } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $false - } - - It 'Should return false when a value is different for [Int16]' { - $mockCurrentValues = @{ Example = [System.Int16]1 } - $mockDesiredValues = @{ Example = [System.Int16]2 } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $false - } - - It 'Should return false when a value is different for [UInt16]' { - $mockCurrentValues = @{ Example = [System.UInt16]1 } - $mockDesiredValues = @{ Example = [System.UInt16]2 } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $false - } - - It 'Should return false when a value is missing' { - $mockCurrentValues = @{ } - $mockDesiredValues = @{ Example = 'test' } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $false - } - - It 'Should return true when only a specified value matches, but other non-listed values do not' { - $mockCurrentValues = @{ Example = 'test'; SecondExample = 'true' } - $mockDesiredValues = @{ Example = 'test'; SecondExample = 'false' } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - ValuesToCheck = @('Example') - } - - Test-DscParameterState @testParameters | Should -Be $true - } - - It 'Should return false when only specified values do not match, but other non-listed values do ' { - $mockCurrentValues = @{ Example = 'test'; SecondExample = 'true' } - $mockDesiredValues = @{ Example = 'test'; SecondExample = 'false' } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - ValuesToCheck = @('SecondExample') - } - - Test-DscParameterState @testParameters | Should -Be $false - } - - It 'Should return false when an empty hash table is used in the current values' { - $mockCurrentValues = @{ } - $mockDesiredValues = @{ Example = 'test'; SecondExample = 'false' } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $false - } - - It 'Should return true when evaluating a table against a CimInstance' { - $mockCurrentValues = @{ Handle = '0'; ProcessId = '1000' } - - $mockWin32ProcessProperties = @{ - Handle = 0 - ProcessId = 1000 - } - - $mockNewCimInstanceParameters = @{ - ClassName = 'Win32_Process' - Property = $mockWin32ProcessProperties - Key = 'Handle' - ClientOnly = $true - } - - $mockDesiredValues = New-CimInstance @mockNewCimInstanceParameters - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - ValuesToCheck = @('Handle', 'ProcessId') - } - - Test-DscParameterState @testParameters | Should -Be $true - } - - It 'Should return false when evaluating a table against a CimInstance and a value is wrong' { - $mockCurrentValues = @{ Handle = '1'; ProcessId = '1000' } - - $mockWin32ProcessProperties = @{ - Handle = 0 - ProcessId = 1000 - } - - $mockNewCimInstanceParameters = @{ - ClassName = 'Win32_Process' - Property = $mockWin32ProcessProperties - Key = 'Handle' - ClientOnly = $true - } - - $mockDesiredValues = New-CimInstance @mockNewCimInstanceParameters - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - ValuesToCheck = @('Handle', 'ProcessId') - } - - Test-DscParameterState @testParameters | Should -Be $false - } - - It 'Should return true when evaluating a hash table containing an array' { - $mockCurrentValues = @{ Example = 'test'; SecondExample = @('1', '2') } - $mockDesiredValues = @{ Example = 'test'; SecondExample = @('1', '2') } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $true - } - - It 'Should return false when evaluating a hash table containing an array with wrong values' { - $mockCurrentValues = @{ Example = 'test'; SecondExample = @('A', 'B') } - $mockDesiredValues = @{ Example = 'test'; SecondExample = @('1', '2') } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $false - } - - It 'Should return false when evaluating a hash table containing an array, but the CurrentValues are missing an array' { - $mockCurrentValues = @{ Example = 'test' } - $mockDesiredValues = @{ Example = 'test'; SecondExample = @('1', '2') } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $false - } - - It 'Should return false when evaluating a hash table containing an array, but the property i CurrentValues is $null' { - $mockCurrentValues = @{ Example = 'test'; SecondExample = $null } - $mockDesiredValues = @{ Example = 'test'; SecondExample = @('1', '2') } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $false - } - } - - Context -Name 'When passing invalid types for DesiredValues' -Fixture { - It 'Should throw the correct error when DesiredValues is of wrong type' { - $mockCurrentValues = @{ Example = 'something' } - $mockDesiredValues = 'NotHashTable' - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - $mockCorrectErrorMessage = ($script:localizedData.PropertyTypeInvalidForDesiredValues -f $testParameters.DesiredValues.GetType().Name) - { Test-DscParameterState @testParameters } | Should -Throw $mockCorrectErrorMessage - } - - It 'Should write a warning when DesiredValues contain an unsupported type' { - Mock -CommandName Write-Warning -Verifiable - - # This is a dummy type to test with a type that could never be a correct one. - class MockUnknownType { - [ValidateNotNullOrEmpty()] - [System.String] - $Property1 - - [ValidateNotNullOrEmpty()] - [System.String] - $Property2 - - MockUnknownType() { - } - } - - $mockCurrentValues = @{ Example = New-Object -TypeName MockUnknownType } - $mockDesiredValues = @{ Example = New-Object -TypeName MockUnknownType } - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - } - - Test-DscParameterState @testParameters | Should -Be $false - - Assert-MockCalled -CommandName Write-Warning -Exactly -Times 1 - } - } - - Context -Name 'When passing an CimInstance as DesiredValue and ValuesToCheck is $null' -Fixture { - It 'Should throw the correct error' { - $mockCurrentValues = @{ Example = 'something' } - - $mockWin32ProcessProperties = @{ - Handle = 0 - ProcessId = 1000 - } - - $mockNewCimInstanceParameters = @{ - ClassName = 'Win32_Process' - Property = $mockWin32ProcessProperties - Key = 'Handle' - ClientOnly = $true - } - - $mockDesiredValues = New-CimInstance @mockNewCimInstanceParameters - - $testParameters = @{ - CurrentValues = $mockCurrentValues - DesiredValues = $mockDesiredValues - ValuesToCheck = $null - } - - $mockCorrectErrorMessage = $script:localizedData.PropertyTypeInvalidForValuesToCheck - { Test-DscParameterState @testParameters } | Should -Throw $mockCorrectErrorMessage - } - } - - Assert-VerifiableMock - } -} diff --git a/build.ps1 b/build.ps1 index ff1f68b1a..26ea93c7b 100644 --- a/build.ps1 +++ b/build.ps1 @@ -52,7 +52,6 @@ $script:SrcPath = $config.SourcePath $script:OutDirectory = $config.BuildOutputPath $script:SignedDirectory = $config.SignedOutputPath $script:TestPath = $config.TestPath -$script:DSCModulePath = "DSC" $script:ModuleRoot = $PSScriptRoot $script:Culture = $config.Culture diff --git a/doBuild.ps1 b/doBuild.ps1 index ee7d99785..a2a3f7044 100644 --- a/doBuild.ps1 +++ b/doBuild.ps1 @@ -44,20 +44,6 @@ function DoBuild Write-Verbose -Verbose -Message "Copying ThirdPartyNotices.txt to '$BuildOutPath'" Copy-Item -Path "./Notice.txt" -Dest "$BuildOutPath" - # - # Copy DSC resources - # TODO: This should not be part of PowerShellGet build/publish and should be moved to its own project - # - Write-Verbose -Verbose -Message "Copying DSC resources to '$BuildOutPath" - Copy-Item -Path "${DSCModulePath}/DscResources" -Dest "$BuildOutPath" -Recurse -Force - - # - # Copy Localization and Resources helper modules - # TODO: This should not be part of PowerShellGet build/publish and should be moved to its own project - # - Write-Verbose -Verbose -Message "Copying DSC resources to '$BuildOutPath" - Copy-Item -Path "${DSCModulePath}/Modules" -Dest "$BuildOutPath" -Recurse -Force - # Build and place binaries if ( Test-Path "${SrcPath}/code" ) { Write-Verbose -Verbose -Message "Building assembly and copying to '$BuildOutPath'"