Skip to content

Commit

Permalink
Merge pull request #163 from JPRuskin/148-Pester5
Browse files Browse the repository at this point in the history
(GH-148) Updates Tests to be compatible with Pester 5
  • Loading branch information
corbob authored Jul 7, 2023
2 parents 210c34a + effdd1a commit 69e2587
Show file tree
Hide file tree
Showing 17 changed files with 639 additions and 525 deletions.
4 changes: 2 additions & 2 deletions AppVeyor/AppVeyorInstall.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ Write-Host "Installed NuGet version '$($pkg.version)'"
#---------------------------------#
# Install Modules #
#---------------------------------#
[version]$ScriptAnalyzerVersion = '1.8.1'
[version]$PesterVersion = '4.10.1'
[version]$ScriptAnalyzerVersion = '1.21.0'
[version]$PesterVersion = '5.99.99'
Install-Module -Name 'PSScriptAnalyzer' -Repository PSGallery -Force -ErrorAction Stop -MaximumVersion $ScriptAnalyzerVersion
Install-Module -Name 'Pester' -SkipPublisherCheck -Repository PSGallery -Force -ErrorAction Stop -MaximumVersion $PesterVersion
Install-Module -Name 'xDSCResourceDesigner' -Repository PSGallery -Force -ErrorAction Stop
Expand Down
21 changes: 18 additions & 3 deletions AppVeyor/AppVeyorTest.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,27 @@ Write-Host "Current working directory: $pwd"
# Run Pester Tests #
#---------------------------------#
$resultsFile = '.\TestsResults.xml'
$testFiles = Get-ChildItem "$pwd\tests" | Where-Object {$_.FullName -match 'Tests.ps1$'} | Select-Object -ExpandProperty FullName
$results = Invoke-Pester -Script $testFiles -OutputFormat NUnitXml -OutputFile $resultsFile -PassThru
$PesterConfiguration = New-PesterConfiguration @{
Run = @{
Path = "$PSScriptRoot\..\tests"
PassThru = $true
}
TestResult = @{
Enabled = $true
OutputFormat = "NUnitXml"
OutputPath = $resultsFile
}
Output = @{
Verbosity = "Detailed"
}
}
$results = Invoke-Pester -Configuration $PesterConfiguration

Write-Host 'Uploading results'
try {
(New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path $resultsFile))
if ($env:APPVEYOR_JOB_ID) {
(New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path $resultsFile))
}
} catch {
throw "Upload failed."
}
Expand Down
3 changes: 1 addition & 2 deletions DSCResources/cChocoConfig/cChocoConfig.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,11 @@ function Set-TargetResource
choco config unset --name "'$ConfigName'"
}
}

}

<#
.Description
Performs the test for cChocoFeature.
Performs the test for cChocoConfig.
.Example
Test-TargetResource -ConfigName cacheLocation -Ensure 'Present' -Value 'c:\temp\choco'
Expand Down
9 changes: 3 additions & 6 deletions DSCResources/cChocoFeature/cChocoFeature.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ function Set-TargetResource
Write-Verbose "Enabling choco feature $FeatureName."
choco feature enable -n $FeatureName
}
else
else
{
Write-Verbose "Disabling choco feature $FeatureName."
choco feature disable -n $FeatureName
Expand Down Expand Up @@ -131,18 +131,15 @@ function Test-TargetResource
.Description
Query chocolatey features.
#>
function Get-ChocoFeature
function Get-ChocoFeature
{
[OutputType([PSCustomObject])]
param(
[string]
$FeatureName
)
choco feature -r | ConvertFrom-Csv -Delimiter "|" -Header Name, State, Description | Where-Object {$_.Name -eq $FeatureName}
choco feature -r | ConvertFrom-Csv -Delimiter "|" -Header Name, State, Description | Where-Object Name -eq $FeatureName
}




Export-ModuleMember -Function *-TargetResource

6 changes: 6 additions & 0 deletions DSCResources/cChocoInstaller/cChocoInstaller.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
function Get-TargetResource
{
[OutputType([hashtable])]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "InstallDir")]
param
(
[parameter(Mandatory)]
Expand Down Expand Up @@ -61,6 +62,7 @@ function Set-TargetResource
function Test-TargetResource
{
[OutputType([bool])]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "ChocoInstallScriptUrl")]
param
(
[parameter(Mandatory)]
Expand Down Expand Up @@ -124,6 +126,10 @@ Function Test-Command
#region - chocolately installer work arounds. Main issue is use of write-host
function global:Write-Host
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalFunctions", "")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "NoNewLine")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "ForegroundColor")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "BackgroundColor")]
Param(
[Parameter(Mandatory,Position = 0)]
$Object,
Expand Down
26 changes: 16 additions & 10 deletions DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
function Get-TargetResource
{
[OutputType([hashtable])]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "MinimumVersion")]
param
(
[parameter(Mandatory)]
Expand Down Expand Up @@ -283,7 +284,7 @@ function InstallPackage
if ($cParams) {
$chocoParams += " $cParams"
}
# Check if Chocolatey version is Greater than 0.10.4, and add --no-progress
# Check if Chocolatey version is Greater than 0.10.4, and add --no-progress
if ((Get-ChocoVersion) -ge [System.Version]('0.10.4')){
$chocoParams += " --no-progress"
}
Expand Down Expand Up @@ -319,7 +320,7 @@ function UninstallPackage
if ($pVersion) {
$chocoParams += " --version=`"$pVersion`""
}
# Check if Chocolatey version is Greater than 0.10.4, and add --no-progress
# Check if Chocolatey version is Greater than 0.10.4, and add --no-progress
if ((Get-ChocoVersion) -ge [System.Version]('0.10.4')){
$chocoParams += " --no-progress"
}
Expand All @@ -344,10 +345,10 @@ function IsPackageInstalled
param(
[Parameter(Position=0, Mandatory)]
[string]$pName,

[Parameter(ParameterSetName = 'RequiredVersion')]
[string]$pVersion,

[Parameter(ParameterSetName = 'MinimumVersion')]
[string]$pMinimumVersion
)
Expand Down Expand Up @@ -426,7 +427,11 @@ Function Test-LatestVersionInstalled {
##attempting to work around the issues with Chocolatey calling Write-host in its scripts.
function global:Write-Host
{
Param(
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalFunctions", "")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "NoNewLine")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "ForegroundColor")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "BackgroundColor")]
param(
[Parameter(Mandatory, Position = 0)]
[Object]
$Object,
Expand All @@ -436,7 +441,6 @@ function global:Write-Host
$ForegroundColor,
[ConsoleColor]
$BackgroundColor

)

#Override default Write-Host...
Expand Down Expand Up @@ -470,7 +474,7 @@ Function Upgrade-Package {
if ($cParams) {
$chocoParams += " $cParams"
}
# Check if Chocolatey version is Greater than 0.10.4, and add --no-progress
# Check if Chocolatey version is Greater than 0.10.4, and add --no-progress
if ((Get-ChocoVersion) -ge [System.Version]('0.10.4')){
$chocoParams += " --no-progress"
}
Expand Down Expand Up @@ -522,12 +526,12 @@ function Get-ChocoInstalledPackage {
}

function Get-ChocoVersion {
[OutputType([System.Version])]
[CmdletBinding()]
param (
[switch]$Purge,
[switch]$NoCache
)

$chocoInstallCache = Join-Path -Path $env:ChocolateyInstall -ChildPath 'cache'
if ( -not (Test-Path $chocoInstallCache)){
New-Item -Name 'cache' -Path $env:ChocolateyInstall -ItemType Directory | Out-Null
Expand All @@ -544,10 +548,12 @@ function Get-ChocoVersion {
} else {
$cmd = choco -v
$res = [System.Version]($cmd.Split('-')[0])
$res | Export-Clixml -Path $chocoVersion
if (-not $NoCache) {
$res | Export-Clixml -Path $chocoVersion
}
}
}
Return $res
return $res
}

Export-ModuleMember -Function *-TargetResource
141 changes: 141 additions & 0 deletions Tests/cChocoConfig.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# Copyright (c) 2017 Chocolatey Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

#---------------------------------#
# Pester tests for cChocoConfig #
#---------------------------------#
Describe "Testing cChocoConfig" {
BeforeAll {
$ModuleUnderTest = "cChocoConfig"

Import-Module $PSScriptRoot\..\DSCResources\$($ModuleUnderTest)\$($ModuleUnderTest).psm1 -Force

if (-not $env:ChocolateyInstall) {
# Chocolatey doesn't need to be installed for these tests, but the resource tests for it
$env:ChocolateyInstall = "C:\ProgramData\chocolatey"
}

if (-not (Get-Command choco -ErrorAction SilentlyContinue)) {
function global:choco {}
}

Mock Get-Item -ModuleName $ModuleUnderTest -ParameterFilter {
$Path.StartsWith($env:ChocolateyInstall)
} -MockWith {
$true
}

Mock Get-ChildItem -ModuleName $ModuleUnderTest -ParameterFilter {
$Path -eq (Join-Path $env:ChocolateyInstall "config")
} -MockWith {
@{
Name = "chocolatey.config"
FullName = Join-Path $env:ChocolateyInstall "config/chocolatey.config"
}
}
}

AfterAll {
Remove-Module $ModuleUnderTest
}

Context "Test-TargetResource" {
BeforeAll {
Mock Get-Content -ModuleName $ModuleUnderTest -ParameterFilter {
$Path.EndsWith('chocolatey.config')
} -MockWith {
'<?xml version="1.0" encoding="utf-8"?>
<chocolatey xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<config>
<add key="commandExecutionTimeoutSeconds" value="1339" description="Default timeout for command execution. for infinite (starting in 0.10.4)." />
<add key="proxy" value="" description="Explicit proxy location. Available in 0.9.9.9+." />
</config>
<sources>
<source id="chocolatey" value="https://chocolatey.org/api/v2/" disabled="false" bypassProxy="false" selfService="false" adminOnly="false" priority="0" />
</sources>
</chocolatey>'
}
}

It 'Test-TargetResource returns true when Present and Configured.' {
Test-TargetResource -ConfigName 'commandExecutionTimeoutSeconds' -Ensure 'Present' -Value '1339' | Should -Be $true
}

It 'Test-TargetResource returns false when Present and Not configured' {
Test-TargetResource -ConfigName 'proxy' -Ensure 'Present' -Value 'http://myproxy.url' | Should -Be $false
}

It 'Test-TargetResource returns false when Present and Unknown' {
Test-TargetResource -ConfigName 'MyParam' -Ensure 'Present' -Value 'MyValue' | Should -Be $false
}

It 'Test-TargetResource throws when Present and no value' {
{ Test-TargetResource -ConfigName 'MyParam' -Ensure 'Present' } | Should -Throw "Missing parameter 'Value' when ensuring config is present!"
}

It 'Test-TargetResource throws when Present and no value' {
{ Test-TargetResource -ConfigName 'MyParam' -Ensure 'Present' -Value '' } | Should -Throw "Missing parameter 'Value' when ensuring config is present!"
}

It 'Test-TargetResource throws when Present and no value' {
{ Test-TargetResource -ConfigName 'MyParam' -Ensure 'Present' -Value $null } | Should -Throw "Missing parameter 'Value' when ensuring config is present!"
}

It 'Test-TargetResource returns false when Absent and Configured' {
Test-TargetResource -ConfigName 'commandExecutionTimeoutSeconds' -Ensure 'Absent' | Should -Be $false
}

It 'Test-TargetResource returns true when Absent and Not configured' {
Test-TargetResource -ConfigName 'proxy' -Ensure 'Absent' | Should -Be $true
}

It 'Test-TargetResource returns true when Absent and Unknown' {
Test-TargetResource -ConfigName 'MyParam' -Ensure 'Absent' | Should -Be $true
}
}

Context "Set-TargetResource" {
BeforeAll {
Mock choco -ModuleName $ModuleUnderTest
}

Context "Setting a config value when Present" {
BeforeAll {
Set-TargetResource -ConfigName "TestConfig" -Ensure "Present" -Value "MyValue"
}

It "Present - Should have called choco, to set the specified ConfigName with the specified Value" {
Assert-MockCalled choco -ModuleName $ModuleUnderTest -ParameterFilter {
$args[0] -eq 'config' -and
$args -match "\bset\b" -and
$args -match "'MyValue'"
} -Scope Context
}
}

Context "Removing a config value when Absent" {
BeforeAll {
Set-TargetResource -ConfigName "TestConfig" -Ensure "Absent"
}

It "Absent - Should have called choco, to unset the specified ConfigName" {
Assert-MockCalled choco -ModuleName $ModuleUnderTest -ParameterFilter {
$args[0] -eq "config" -and
$args -match "\bunset\b" -and
$args -match "'TestConfig'"
} -Scope Context
}
}
}
}
Loading

0 comments on commit 69e2587

Please sign in to comment.