diff --git a/.vscode/settings.json b/.vscode/settings.json index f8efa407..42fa48b4 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -36,7 +36,14 @@ "keepachangelog", "notin", "pscmdlet", - "steppable" + "steppable", + "contoso", + "fabrikam", + "fourthcoffee", + "Lbfo", + "HKLM", + "HKCU", + "RDMA" ], "cSpell.ignorePaths": [ ".git" diff --git a/CHANGELOG.md b/CHANGELOG.md index 39401b0d..590bd5d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Updated pipeline files to match current DSC Community patterns - fixes [Issue #528](https://github.com/dsccommunity/NetworkingDsc/issues/528). - Updated HQRM and build steps to use windows-latest image. - Update build pieline to pin GitVersion v5. +- Tests + - Update to use Pester 5. ## [9.0.0] - 2022-05-30 diff --git a/RequiredModules.psd1 b/RequiredModules.psd1 index 46f9d35f..a352f062 100644 --- a/RequiredModules.psd1 +++ b/RequiredModules.psd1 @@ -1,5 +1,5 @@ @{ - PSDependOptions = @{ + PSDependOptions = @{ AddToPath = $true Target = 'output\RequiredModules' Parameters = @{ @@ -7,18 +7,18 @@ } } - InvokeBuild = 'latest' - PSScriptAnalyzer = 'latest' - Pester = '4.10.1' - Plaster = 'latest' - ModuleBuilder = 'latest' - ChangelogManagement = 'latest' - Sampler = 'latest' - 'Sampler.GitHubTasks' = 'latest' - MarkdownLinkCheck = 'latest' - 'DscResource.Test' = 'latest' - xDscResourceDesigner = 'latest' - LoopbackAdapter = 'latest' + InvokeBuild = 'latest' + PSScriptAnalyzer = 'latest' + Pester = 'latest' + Plaster = 'latest' + ModuleBuilder = 'latest' + ChangelogManagement = 'latest' + Sampler = 'latest' + 'Sampler.GitHubTasks' = 'latest' + MarkdownLinkCheck = 'latest' + 'DscResource.Test' = 'latest' + xDscResourceDesigner = 'latest' + LoopbackAdapter = 'latest' # Build dependencies needed for using the module 'DscResource.Common' = 'latest' diff --git a/build.yaml b/build.yaml index 60779fd0..87d240d0 100644 --- a/build.yaml +++ b/build.yaml @@ -26,17 +26,17 @@ BuildWorkflow: - package_module_nupkg hqrmtest: - - DscResource_Tests_Stop_On_Fail + - Invoke_HQRM_Tests_Stop_On_Fail test: - Pester_Tests_Stop_On_Fail + - Convert_Pester_Coverage - Pester_If_Code_Coverage_Under_Threshold publish: - publish_module_to_gallery - Publish_Release_To_GitHub - Publish_GitHub_Wiki_Content - - Create_ChangeLog_GitHub_PR #################################################### # ModuleBuilder Configuration # @@ -44,11 +44,8 @@ BuildWorkflow: CopyPaths: - en-US - DSCResources - - Modules Prefix: prefix.ps1 -Suffix: suffix.ps1 Encoding: UTF8 -VersionedOutputDirectory: true BuiltModuleSubdirectory: builtModule ModuleBuildTasks: @@ -87,16 +84,6 @@ NestedModule: #################################################### Pester: - # Pester 4 configuration - Script: - - tests/Unit - ExcludeTag: - Tag: - CodeCoverageOutputFile: JaCoCo_coverage.xml - CodeCoverageOutputFileEncoding: ascii - CodeCoverageThreshold: 80 - - # Pester 5 configuration Configuration: Run: Path: @@ -120,14 +107,26 @@ Pester: # Pester Configuration (DscResource.Test) # #################################################### DscTest: - OutputFormat: NUnitXML - ExcludeTag: - - 'Common Tests - New Error-Level Script Analyzer Rules' - ExcludeSourceFile: - - output - ExcludeModuleFile: - - Modules/DscResource.Common - MainGitBranch: main + Pester: + Configuration: + Filter: + ExcludeTag: + - 'Common Tests - New Error-Level Script Analyzer Rules' + Output: + Verbosity: Detailed + CIFormat: Auto + TestResult: + Enabled: true + OutputFormat: NUnitXML + OutputEncoding: ascii + OutputPath: ./output/testResults/NUnitXml_HQRM_Tests.xml + Script: + ExcludeSourceFile: + - output + ExcludeModuleFile: + - Modules/DscResource.Common + - NetworkingDsc.ps1 + MainGitBranch: main #################################################### # PSDepend Configuration # @@ -163,7 +162,7 @@ DscResource.DocGenerator: - '\*(.+?)\*' # Match Italic (asterisk) Publish_GitHub_Wiki_Content: Debug: false - Generate_Wiki_Content: + Generate_Markdown_For_DSC_Resources: MofResourceMetadata: Type: MofResource Category: Resources @@ -174,5 +173,5 @@ DscResource.DocGenerator: Type: CompositeResource Category: Resources Generate_Wiki_Sidebar: - Debug: false - AlwaysOverwrite: true + Debug: false + AlwaysOverwrite: true diff --git a/source/Build.psd1 b/source/Build.psd1 deleted file mode 100644 index 8977e456..00000000 --- a/source/Build.psd1 +++ /dev/null @@ -1,5 +0,0 @@ -@{ - Path = 'NetworkingDsc.psd1' -} -# Waiting for ModuleBuilder to do away with this file -# when all parameters are provided to the function diff --git a/source/DSCResources/DSC_DefaultGatewayAddress/DSC_DefaultGatewayAddress.psm1 b/source/DSCResources/DSC_DefaultGatewayAddress/DSC_DefaultGatewayAddress.psm1 index d1034729..ccf8ce58 100644 --- a/source/DSCResources/DSC_DefaultGatewayAddress/DSC_DefaultGatewayAddress.psm1 +++ b/source/DSCResources/DSC_DefaultGatewayAddress/DSC_DefaultGatewayAddress.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -48,9 +43,6 @@ function Get-TargetResource $($script:localizedData.GettingDefaultGatewayAddressMessage) ) -join '' ) - $destinationPrefix = Get-NetDefaultGatewayDestinationPrefix ` - -AddressFamily $AddressFamily - $defaultRoutes = Get-NetDefaultRoute ` -InterfaceAlias $InterfaceAlias ` -AddressFamily $AddressFamily @@ -118,8 +110,8 @@ function Set-TargetResource ) -join '' ) $defaultRoutes = @(Get-NetDefaultRoute ` - -InterfaceAlias $InterfaceAlias ` - -AddressFamily $AddressFamily) + -InterfaceAlias $InterfaceAlias ` + -AddressFamily $AddressFamily) # Remove any existing default routes foreach ($defaultRoute in $defaultRoutes) @@ -203,8 +195,8 @@ function Test-TargetResource Assert-ResourceProperty @PSBoundParameters $defaultRoutes = @(Get-NetDefaultRoute ` - -InterfaceAlias $InterfaceAlias ` - -AddressFamily $AddressFamily) + -InterfaceAlias $InterfaceAlias ` + -AddressFamily $AddressFamily) # Test if the Default Gateway passed is equal to the current default gateway if ($Address) @@ -212,8 +204,8 @@ function Test-TargetResource if ($defaultRoutes) { $nextHopRoute = $defaultRoutes.Where( { - $_.NextHop -eq $Address - } ) + $_.NextHop -eq $Address + } ) if ($nextHopRoute) { @@ -302,7 +294,7 @@ function Assert-ResourceProperty { Assert-IPAddress -Address $Address -AddressFamily $AddressFamily } -} # Assert-ResourceProperty +} <# .SYNOPSIS @@ -333,7 +325,7 @@ function Get-NetDefaultGatewayDestinationPrefix } return $destinationPrefix -} # Get-NetDefaultGatewayDestinationPrefix +} <# .SYNOPSIS @@ -366,11 +358,9 @@ function Get-NetDefaultRoute -AddressFamily $AddressFamily return @(Get-NetRoute ` - -InterfaceAlias $InterfaceAlias ` - -AddressFamily $AddressFamily ` - -ErrorAction Stop).Where({ + -InterfaceAlias $InterfaceAlias ` + -AddressFamily $AddressFamily ` + -ErrorAction Stop).Where({ $_.DestinationPrefix -eq $destinationPrefix }) -} # Get-NetDefaultRoute - -Export-ModuleMember -function *-TargetResource +} diff --git a/source/DSCResources/DSC_DnsClientGlobalSetting/DSC_DnsClientGlobalSetting.psm1 b/source/DSCResources/DSC_DnsClientGlobalSetting/DSC_DnsClientGlobalSetting.psm1 index fc86745a..88d09449 100644 --- a/source/DSCResources/DSC_DnsClientGlobalSetting/DSC_DnsClientGlobalSetting.psm1 +++ b/source/DSCResources/DSC_DnsClientGlobalSetting/DSC_DnsClientGlobalSetting.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -130,7 +125,7 @@ function Set-TargetResource Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " $($script:localizedData.DnsClientGlobalSettingUpdateParameterMessage) ` - -f $parameter.Name,($parameterNewValue -join ',') + -f $parameter.Name, ($parameterNewValue -join ',') ) -join '' ) } # if } # foreach @@ -263,5 +258,3 @@ function Test-TargetResource return $desiredConfigurationMatch } # Test-TargetResource - -Export-ModuleMember -Function *-TargetResource diff --git a/source/DSCResources/DSC_DnsConnectionSuffix/DSC_DnsConnectionSuffix.psm1 b/source/DSCResources/DSC_DnsConnectionSuffix/DSC_DnsConnectionSuffix.psm1 index f89526b2..2ce39976 100644 --- a/source/DSCResources/DSC_DnsConnectionSuffix/DSC_DnsConnectionSuffix.psm1 +++ b/source/DSCResources/DSC_DnsConnectionSuffix/DSC_DnsConnectionSuffix.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -266,5 +261,3 @@ function Test-TargetResource return $inDesiredState } - -Export-ModuleMember -function *-TargetResource diff --git a/source/DSCResources/DSC_DnsServerAddress/DSC_DnsServerAddress.psm1 b/source/DSCResources/DSC_DnsServerAddress/DSC_DnsServerAddress.psm1 index 57ef9903..b387c5fd 100644 --- a/source/DSCResources/DSC_DnsServerAddress/DSC_DnsServerAddress.psm1 +++ b/source/DSCResources/DSC_DnsServerAddress/DSC_DnsServerAddress.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -46,7 +41,7 @@ function Get-TargetResource ) Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " - $($script:localizedData.GettingDnsServerAddressesMessage) + $($script:localizedData.GettingDnsServerAddressesMessage) ) -join '') # Remove the parameters we don't want to splat @@ -110,7 +105,7 @@ function Set-TargetResource ) Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.ApplyingDnsServerAddressesMessage -f $AddressFamily, ($Address -join ','), $InterfaceAlias) + $($script:localizedData.ApplyingDnsServerAddressesMessage -f $AddressFamily, ($Address -join ','), $InterfaceAlias) ) -join '') $dnsServerAddressSplat = @{ @@ -140,7 +135,7 @@ function Set-TargetResource -ErrorAction Stop Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " - $($script:localizedData.DNSServersHaveBeenSetCorrectlyMessage) + $($script:localizedData.DNSServersHaveBeenSetCorrectlyMessage) ) -join '' ) } catch [Microsoft.Management.Infrastructure.CimException] @@ -203,7 +198,7 @@ function Test-TargetResource $desiredConfigurationMatch = $true Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " - $($script:localizedData.CheckingDnsServerAddressesMessage) + $($script:localizedData.CheckingDnsServerAddressesMessage) ) -join '' ) # Validate the Address passed or set to empty array if not passed @@ -228,29 +223,29 @@ function Test-TargetResource # Get the current DNS Server Addresses based on the parameters given. [String[]] $currentAddress = @(Get-DnsClientServerStaticAddress ` - @PSBoundParameters ` - -ErrorAction Stop) + @PSBoundParameters ` + -ErrorAction Stop) # Check if the Server addresses are the same as the desired addresses. [Boolean] $addressDifferent = (@(Compare-Object ` - -ReferenceObject $currentAddress ` - -DifferenceObject $Address ` - -SyncWindow 0).Length -gt 0) + -ReferenceObject $currentAddress ` + -DifferenceObject $Address ` + -SyncWindow 0).Length -gt 0) if ($addressDifferent) { $desiredConfigurationMatch = $false Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " - $($script:localizedData.DNSServersNotCorrectMessage) ` - -f ($Address -join ','),($currentAddress -join ',') + $($script:localizedData.DNSServersNotCorrectMessage) ` + -f ($Address -join ','), ($currentAddress -join ',') ) -join '' ) } else { # Test will return true in this case Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " - $($script:localizedData.DNSServersSetCorrectlyMessage) + $($script:localizedData.DNSServersSetCorrectlyMessage) ) -join '' ) } return $desiredConfigurationMatch @@ -300,5 +295,3 @@ function Assert-ResourceProperty Assert-IPAddress -Address $Address -AddressFamily $AddressFamily } # Assert-ResourceProperty - -Export-ModuleMember -function *-TargetResource diff --git a/source/DSCResources/DSC_Firewall/DSC_Firewall.psm1 b/source/DSCResources/DSC_Firewall/DSC_Firewall.psm1 index f5dd463d..f33fddb4 100644 --- a/source/DSCResources/DSC_Firewall/DSC_Firewall.psm1 +++ b/source/DSCResources/DSC_Firewall/DSC_Firewall.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -1371,7 +1366,5 @@ function ConvertTo-FirewallRuleNameEscapedString $Name ) - return $Name.Replace('[','`[').Replace(']','`]').Replace('*','`*') + return $Name.Replace('[', '`[').Replace(']', '`]').Replace('*', '`*') } - -Export-ModuleMember -Function *-TargetResource diff --git a/source/DSCResources/DSC_FirewallProfile/DSC_FirewallProfile.psm1 b/source/DSCResources/DSC_FirewallProfile/DSC_FirewallProfile.psm1 index 1a05d3a9..91fcf227 100644 --- a/source/DSCResources/DSC_FirewallProfile/DSC_FirewallProfile.psm1 +++ b/source/DSCResources/DSC_FirewallProfile/DSC_FirewallProfile.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -469,5 +464,3 @@ function Test-TargetResource return $desiredConfigurationMatch } # Test-TargetResource - -Export-ModuleMember -Function *-TargetResource diff --git a/source/DSCResources/DSC_HostsFile/DSC_HostsFile.psm1 b/source/DSCResources/DSC_HostsFile/DSC_HostsFile.psm1 index 279af660..afe0825b 100644 --- a/source/DSCResources/DSC_HostsFile/DSC_HostsFile.psm1 +++ b/source/DSCResources/DSC_HostsFile/DSC_HostsFile.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -105,7 +100,7 @@ function Set-TargetResource if ($Ensure -eq 'Present' -and $PSBoundParameters.ContainsKey('IPAddress') -eq $false) { New-InvalidArgumentException ` - -Message $($($script:localizedData.UnableToEnsureWithoutIP) -f $Address, $AddressFamily) ` + -Message $script:localizedData.UnableToEnsureWithoutIP ` -ArgumentName 'IPAddress' } diff --git a/source/DSCResources/DSC_IPAddress/DSC_IPAddress.psm1 b/source/DSCResources/DSC_IPAddress/DSC_IPAddress.psm1 index 18bd8dc1..b2791d61 100644 --- a/source/DSCResources/DSC_IPAddress/DSC_IPAddress.psm1 +++ b/source/DSCResources/DSC_IPAddress/DSC_IPAddress.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -129,7 +124,6 @@ function Set-TargetResource if ($AddressFamily -eq 'IPv6') { $destinationPrefix = '::/0' - $prefixLength = 64 } # Get all the default routes - this has to be done in case the IP Address is being Removed @@ -507,5 +501,3 @@ function Assert-ResourceProperty } } } # Assert-ResourceProperty - -Export-ModuleMember -function *-TargetResource diff --git a/source/DSCResources/DSC_IPAddressOption/DSC_IPAddressOption.psm1 b/source/DSCResources/DSC_IPAddressOption/DSC_IPAddressOption.psm1 index 06203372..e242b5ca 100644 --- a/source/DSCResources/DSC_IPAddressOption/DSC_IPAddressOption.psm1 +++ b/source/DSCResources/DSC_IPAddressOption/DSC_IPAddressOption.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -129,5 +124,3 @@ function Test-TargetResource return $desiredConfigurationMatch } - -Export-ModuleMember -function *-TargetResource diff --git a/source/DSCResources/DSC_NetAdapterAdvancedProperty/DSC_NetAdapterAdvancedProperty.psm1 b/source/DSCResources/DSC_NetAdapterAdvancedProperty/DSC_NetAdapterAdvancedProperty.psm1 index b9034af5..f3b6d9bf 100644 --- a/source/DSCResources/DSC_NetAdapterAdvancedProperty/DSC_NetAdapterAdvancedProperty.psm1 +++ b/source/DSCResources/DSC_NetAdapterAdvancedProperty/DSC_NetAdapterAdvancedProperty.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings diff --git a/source/DSCResources/DSC_NetAdapterBinding/DSC_NetAdapterBinding.psm1 b/source/DSCResources/DSC_NetAdapterBinding/DSC_NetAdapterBinding.psm1 index b57d30d4..d9bdf17f 100644 --- a/source/DSCResources/DSC_NetAdapterBinding/DSC_NetAdapterBinding.psm1 +++ b/source/DSCResources/DSC_NetAdapterBinding/DSC_NetAdapterBinding.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -274,5 +269,3 @@ function Get-Binding return $binding } # Get-Binding - -Export-ModuleMember -function *-TargetResource diff --git a/source/DSCResources/DSC_NetAdapterLso/DSC_NetAdapterLso.psm1 b/source/DSCResources/DSC_NetAdapterLso/DSC_NetAdapterLso.psm1 index c8feece8..60cb7c85 100644 --- a/source/DSCResources/DSC_NetAdapterLso/DSC_NetAdapterLso.psm1 +++ b/source/DSCResources/DSC_NetAdapterLso/DSC_NetAdapterLso.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings diff --git a/source/DSCResources/DSC_NetAdapterName/DSC_NetAdapterName.psm1 b/source/DSCResources/DSC_NetAdapterName/DSC_NetAdapterName.psm1 index bab3ad79..895d4491 100644 --- a/source/DSCResources/DSC_NetAdapterName/DSC_NetAdapterName.psm1 +++ b/source/DSCResources/DSC_NetAdapterName/DSC_NetAdapterName.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -365,7 +360,7 @@ function Test-TargetResource # Can an adapter be found with the new name? $adapterWithNewName = Find-NetworkAdapter ` -Name $NewName ` - -Verbose:$Verbose ` + -Verbose:$VerbosePreference ` -ErrorAction SilentlyContinue if ($adapterWithNewName) @@ -396,5 +391,3 @@ function Test-TargetResource return $false } # if } # Test-TargetResource - -Export-ModuleMember -function *-TargetResource diff --git a/source/DSCResources/DSC_NetAdapterRdma/DSC_NetAdapterRdma.psm1 b/source/DSCResources/DSC_NetAdapterRdma/DSC_NetAdapterRdma.psm1 index bde6e762..9ac88e66 100644 --- a/source/DSCResources/DSC_NetAdapterRdma/DSC_NetAdapterRdma.psm1 +++ b/source/DSCResources/DSC_NetAdapterRdma/DSC_NetAdapterRdma.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings diff --git a/source/DSCResources/DSC_NetAdapterRsc/DSC_NetAdapterRsc.psm1 b/source/DSCResources/DSC_NetAdapterRsc/DSC_NetAdapterRsc.psm1 index 3bb5e429..d04b46ed 100644 --- a/source/DSCResources/DSC_NetAdapterRsc/DSC_NetAdapterRsc.psm1 +++ b/source/DSCResources/DSC_NetAdapterRsc/DSC_NetAdapterRsc.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings diff --git a/source/DSCResources/DSC_NetAdapterRss/DSC_NetAdapterRss.psm1 b/source/DSCResources/DSC_NetAdapterRss/DSC_NetAdapterRss.psm1 index 3e5508c0..fafeb1a4 100644 --- a/source/DSCResources/DSC_NetAdapterRss/DSC_NetAdapterRss.psm1 +++ b/source/DSCResources/DSC_NetAdapterRss/DSC_NetAdapterRss.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings diff --git a/source/DSCResources/DSC_NetAdapterState/DSC_NetAdapterState.psm1 b/source/DSCResources/DSC_NetAdapterState/DSC_NetAdapterState.psm1 index 9f8f5645..387e07a1 100644 --- a/source/DSCResources/DSC_NetAdapterState/DSC_NetAdapterState.psm1 +++ b/source/DSCResources/DSC_NetAdapterState/DSC_NetAdapterState.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -42,6 +37,8 @@ function Get-TargetResource $script:localizedData.CheckingNetAdapterMessage ) -join '') + $netAdapter = $null + try { $netAdapter = Get-NetAdapter ` @@ -115,6 +112,8 @@ function Set-TargetResource $script:localizedData.CheckingNetAdapterMessage ) -join '') + $netAdapter = $null + try { $netAdapter = Get-NetAdapter ` diff --git a/source/DSCResources/DSC_NetBios/DSC_NetBios.psm1 b/source/DSCResources/DSC_NetBios/DSC_NetBios.psm1 index a0966063..fabbdfdc 100644 --- a/source/DSCResources/DSC_NetBios/DSC_NetBios.psm1 +++ b/source/DSCResources/DSC_NetBios/DSC_NetBios.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -196,8 +191,8 @@ function Set-TargetResource Write-Verbose -Message ($script:localizedData.SetNetBiosMessage -f $netAdapter.NetConnectionID, $Setting) $netAdapterConfig = $netAdapter | Get-CimAssociatedInstance ` - -ResultClassName Win32_NetworkAdapterConfiguration ` - -ErrorAction Stop + -ResultClassName Win32_NetworkAdapterConfiguration ` + -ErrorAction Stop Set-NetAdapterNetbiosOptions ` -NetworkAdapterObject $netAdapterConfig ` @@ -263,12 +258,12 @@ function Get-NetAdapterNetbiosOptionsFromRegistry param ( [Parameter(Mandatory = $true)] - [ValidatePattern("^\{[a-zA-Z0-9]{8}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{12}\}$")] + [ValidatePattern('^\{[a-zA-Z0-9]{8}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{12}\}$')] [System.String] $NetworkAdapterGUID, [Parameter(Mandatory = $true)] - [ValidateSet('Default','Enable','Disable')] + [ValidateSet('Default', 'Enable', 'Disable')] [System.String] $Setting ) @@ -308,7 +303,7 @@ function Get-NetAdapterNetbiosOptionsFromRegistry default { # Unknown value. Returning invalid setting to trigger Set-TargetResource - [System.String[]] $invalidSetting = 'Default','Enable','Disable' | Where-Object -FilterScript { + [System.String[]] $invalidSetting = 'Default', 'Enable', 'Disable' | Where-Object -FilterScript { $_ -ne $Setting } @@ -352,7 +347,7 @@ function Set-NetAdapterNetbiosOptions $InterfaceAlias, [Parameter(Mandatory = $true)] - [ValidateSet('Default','Enable','Disable')] + [ValidateSet('Default', 'Enable', 'Disable')] [System.String] $Setting ) @@ -368,7 +363,7 @@ function Set-NetAdapterNetbiosOptions -ErrorAction Stop ` -Arguments @{ TcpipNetbiosOptions = [uint32][NetBiosSetting]::$Setting.value__ - } + } if ($result.ReturnValue -ne 0) { @@ -390,5 +385,3 @@ function Set-NetAdapterNetbiosOptions $null = Set-ItemProperty @setItemPropertyParameters } } # end function Set-NetAdapterNetbiosOptions - -Export-ModuleMember -Function *-TargetResource diff --git a/source/DSCResources/DSC_NetConnectionProfile/DSC_NetConnectionProfile.psm1 b/source/DSCResources/DSC_NetConnectionProfile/DSC_NetConnectionProfile.psm1 index cef402d1..e594aa81 100644 --- a/source/DSCResources/DSC_NetConnectionProfile/DSC_NetConnectionProfile.psm1 +++ b/source/DSCResources/DSC_NetConnectionProfile/DSC_NetConnectionProfile.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings diff --git a/source/DSCResources/DSC_NetIPInterface/DSC_NetIPInterface.psm1 b/source/DSCResources/DSC_NetIPInterface/DSC_NetIPInterface.psm1 index 6ed8ba67..27b5fc69 100644 --- a/source/DSCResources/DSC_NetIPInterface/DSC_NetIPInterface.psm1 +++ b/source/DSCResources/DSC_NetIPInterface/DSC_NetIPInterface.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -228,7 +223,7 @@ function Set-TargetResource $getTargetResourceParameters = @{ InterfaceAlias = $InterfaceAlias - AddressFamily = $AddressFamily + AddressFamily = $AddressFamily } $currentState = Get-TargetResource @getTargetResourceParameters @@ -242,7 +237,7 @@ function Set-TargetResource $parameterUpdated = $false $setNetIPInterfaceParameters = @{ InterfaceAlias = $InterfaceAlias - AddressFamily = $AddressFamily + AddressFamily = $AddressFamily } foreach ($parameter in $script:parameterList) @@ -439,7 +434,7 @@ function Test-TargetResource $getTargetResourceParameters = @{ InterfaceAlias = $InterfaceAlias - AddressFamily = $AddressFamily + AddressFamily = $AddressFamily } $currentState = Get-TargetResource @getTargetResourceParameters @@ -500,7 +495,7 @@ function Get-NetworkIPInterface #> $networkIPInterface = @{ InterfaceAlias = $InterfaceAlias - AddressFamily = $AddressFamily + AddressFamily = $AddressFamily } foreach ($parameter in $script:parameterList) @@ -516,5 +511,3 @@ function Get-NetworkIPInterface return $networkIPInterface } - -Export-ModuleMember -Function *-TargetResource diff --git a/source/DSCResources/DSC_NetworkTeam/DSC_NetworkTeam.psm1 b/source/DSCResources/DSC_NetworkTeam/DSC_NetworkTeam.psm1 index a33653ff..6ba8cab5 100644 --- a/source/DSCResources/DSC_NetworkTeam/DSC_NetworkTeam.psm1 +++ b/source/DSCResources/DSC_NetworkTeam/DSC_NetworkTeam.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -137,6 +132,8 @@ function Set-TargetResource Name = $Name } + $isNetModifyRequired = $false + if ($networkTeam.loadBalancingAlgorithm -ne $LoadBalancingAlgorithm) { Write-Verbose -Message ($script:localizedData.LoadBalancingAlgorithmDifferent -f $LoadBalancingAlgorithm) diff --git a/source/DSCResources/DSC_NetworkTeamInterface/DSC_NetworkTeamInterface.psm1 b/source/DSCResources/DSC_NetworkTeamInterface/DSC_NetworkTeamInterface.psm1 index 7495e667..31e75f72 100644 --- a/source/DSCResources/DSC_NetworkTeamInterface/DSC_NetworkTeamInterface.psm1 +++ b/source/DSCResources/DSC_NetworkTeamInterface/DSC_NetworkTeamInterface.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -303,5 +298,3 @@ function Test-TargetResource } } } - -Export-ModuleMember -Function *-TargetResource diff --git a/source/DSCResources/DSC_ProxySettings/DSC_ProxySettings.psm1 b/source/DSCResources/DSC_ProxySettings/DSC_ProxySettings.psm1 index 2c24e690..a8dca99b 100644 --- a/source/DSCResources/DSC_ProxySettings/DSC_ProxySettings.psm1 +++ b/source/DSCResources/DSC_ProxySettings/DSC_ProxySettings.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -24,13 +19,13 @@ function Get-TargetResource param ( [Parameter(Mandatory = $true)] - [ValidateSet('LocalMachine','CurrentUser')] + [ValidateSet('LocalMachine', 'CurrentUser')] [System.String] $Target ) Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.GettingProxySettingsMessage -f $Target) + $($script:localizedData.GettingProxySettingsMessage -f $Target) ) -join '') $proxySettingsPath = Get-ProxySettingsRegistryKeyPath ` @@ -57,22 +52,22 @@ function Get-TargetResource if ($proxySettingsRegistryBinary) { - $returnValue.Add('Ensure','Present') + $returnValue.Add('Ensure', 'Present') $proxySettings = ConvertFrom-ProxySettingsBinary ` -ProxySettings $proxySettingsRegistryBinary - $returnValue.Add('EnableManualProxy',$proxySettings.EnableManualProxy) - $returnValue.Add('EnableAutoConfiguration',$proxySettings.EnableAutoConfiguration) - $returnValue.Add('EnableAutoDetection',$proxySettings.EnableAutoDetection) - $returnValue.Add('ProxyServer',$proxySettings.ProxyServer) - $returnValue.Add('ProxyServerBypassLocal',$proxySettings.ProxyServerBypassLocal) - $returnValue.Add('ProxyServerExceptions',$proxySettings.ProxyServerExceptions) - $returnValue.Add('AutoConfigURL',$proxySettings.AutoConfigURL) + $returnValue.Add('EnableManualProxy', $proxySettings.EnableManualProxy) + $returnValue.Add('EnableAutoConfiguration', $proxySettings.EnableAutoConfiguration) + $returnValue.Add('EnableAutoDetection', $proxySettings.EnableAutoDetection) + $returnValue.Add('ProxyServer', $proxySettings.ProxyServer) + $returnValue.Add('ProxyServerBypassLocal', $proxySettings.ProxyServerBypassLocal) + $returnValue.Add('ProxyServerExceptions', $proxySettings.ProxyServerExceptions) + $returnValue.Add('AutoConfigURL', $proxySettings.AutoConfigURL) } else { - $returnValue.Add('Ensure','Absent') + $returnValue.Add('Ensure', 'Absent') } return $returnValue @@ -128,17 +123,17 @@ function Set-TargetResource param ( [Parameter(Mandatory = $true)] - [ValidateSet('LocalMachine','CurrentUser')] + [ValidateSet('LocalMachine', 'CurrentUser')] [System.String] $Target, [Parameter()] - [ValidateSet('Present','Absent')] + [ValidateSet('Present', 'Absent')] [System.String] $Ensure = 'Present', [Parameter()] - [ValidateSet('All','Default','Legacy')] + [ValidateSet('All', 'Default', 'Legacy')] [System.String] $ConnectionType = 'All', @@ -172,7 +167,7 @@ function Set-TargetResource ) Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.ApplyingProxySettingsMessage -f $Target, $Ensure) + $($script:localizedData.ApplyingProxySettingsMessage -f $Target, $Ensure) ) -join '') $proxySettingsPath = Get-ProxySettingsRegistryKeyPath ` @@ -182,10 +177,10 @@ function Set-TargetResource { # Remove all the Proxy Settings Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.DisablingProxyMessage -f $Target) + $($script:localizedData.DisablingProxyMessage -f $Target) ) -join '') - if ($ConnectionType -in ('All','Default')) + if ($ConnectionType -in ('All', 'Default')) { Remove-ItemProperty ` -Path $proxySettingsPath ` @@ -193,7 +188,7 @@ function Set-TargetResource -ErrorAction SilentlyContinue } - if ($ConnectionType -in ('All','Legacy')) + if ($ConnectionType -in ('All', 'Legacy')) { Remove-ItemProperty ` -Path $proxySettingsPath ` @@ -204,7 +199,7 @@ function Set-TargetResource else { Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.EnablingProxyMessage -f $Target) + $($script:localizedData.EnablingProxyMessage -f $Target) ) -join '') # Generate the Proxy Settings binary value @@ -216,10 +211,10 @@ function Set-TargetResource $proxySettings = ConvertTo-ProxySettingsBinary @convertToProxySettingsBinaryParameters - if ($ConnectionType -in ('All','Default')) + if ($ConnectionType -in ('All', 'Default')) { Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.WritingProxyBinarySettingsMessage -f $Target, 'DefaultConnectionSettings',($proxySettings -join ',')) + $($script:localizedData.WritingProxyBinarySettingsMessage -f $Target, 'DefaultConnectionSettings', ($proxySettings -join ',')) ) -join '') Set-BinaryRegistryValue ` @@ -228,10 +223,10 @@ function Set-TargetResource -Value $proxySettings } - if ($ConnectionType -in ('All','Legacy')) + if ($ConnectionType -in ('All', 'Legacy')) { Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.WritingProxyBinarySettingsMessage -f $Target, 'SavedLegacySettings',($proxySettings -join ',')) + $($script:localizedData.WritingProxyBinarySettingsMessage -f $Target, 'SavedLegacySettings', ($proxySettings -join ',')) ) -join '') Set-BinaryRegistryValue ` @@ -293,17 +288,17 @@ function Test-TargetResource param ( [Parameter(Mandatory = $true)] - [ValidateSet('LocalMachine','CurrentUser')] + [ValidateSet('LocalMachine', 'CurrentUser')] [System.String] $Target, [Parameter()] - [ValidateSet('Present','Absent')] + [ValidateSet('Present', 'Absent')] [System.String] $Ensure = 'Present', [Parameter()] - [ValidateSet('All','Default','Legacy')] + [ValidateSet('All', 'Default', 'Legacy')] [System.String] $ConnectionType = 'All', @@ -337,7 +332,7 @@ function Test-TargetResource ) Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.CheckingProxySettingsMessage -f $Target, $Ensure) + $($script:localizedData.CheckingProxySettingsMessage -f $Target, $Ensure) ) -join '') $desiredConfigurationMatch = $true @@ -352,13 +347,13 @@ function Test-TargetResource if ($Ensure -eq 'Absent') { # Check if any of the Proxy Settings need to be removed - if ($ConnectionType -in ('All','Default')) + if ($ConnectionType -in ('All', 'Default')) { # Does the Default Connection Settings need to be removed? if ($connectionsRegistryValues.DefaultConnectionSettings) { Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.ProxyBinarySettingsRequiresRemovalMessage -f $Target, 'DefaultConnectionSettings') + $($script:localizedData.ProxyBinarySettingsRequiresRemovalMessage -f $Target, 'DefaultConnectionSettings') ) -join '') $desiredConfigurationMatch = $false @@ -366,12 +361,12 @@ function Test-TargetResource } # Does the Saved Legacy Settings need to be removed? - if ($ConnectionType -in ('All','Legacy')) + if ($ConnectionType -in ('All', 'Legacy')) { if ($connectionsRegistryValues.SavedLegacySettings) { Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.ProxyBinarySettingsRequiresRemovalMessage -f $Target, 'SavedLegacySettings') + $($script:localizedData.ProxyBinarySettingsRequiresRemovalMessage -f $Target, 'SavedLegacySettings') ) -join '') $desiredConfigurationMatch = $false @@ -386,11 +381,11 @@ function Test-TargetResource $desiredValues.Remove('Ensure') $desiredValues.Remove('ConnectionType') - if ($ConnectionType -in ('All','Default')) + if ($ConnectionType -in ('All', 'Default')) { # Check if the Default Connection proxy settings are in the desired state Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.CheckingProxyBinarySettingsMessage -f $Target, 'DefaultConnectionSettings') + $($script:localizedData.CheckingProxyBinarySettingsMessage -f $Target, 'DefaultConnectionSettings') ) -join '') if ($connectionsRegistryValues.DefaultConnectionSettings) @@ -410,18 +405,18 @@ function Test-TargetResource if (-not $inDesiredState) { Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.ProxyBinarySettingsNoMatchMessage -f $Target, 'DefaultConnectionSettings') + $($script:localizedData.ProxyBinarySettingsNoMatchMessage -f $Target, 'DefaultConnectionSettings') ) -join '') $desiredConfigurationMatch = $false } } - if ($ConnectionType -in ('All','Legacy')) + if ($ConnectionType -in ('All', 'Legacy')) { # Check if the Saved Legacy proxy settings are in the desired state Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.CheckingProxyBinarySettingsMessage -f $Target, 'SavedLegacySettings') + $($script:localizedData.CheckingProxyBinarySettingsMessage -f $Target, 'SavedLegacySettings') ) -join '') if ($connectionsRegistryValues.SavedLegacySettings) @@ -441,7 +436,7 @@ function Test-TargetResource if (-not $inDesiredState) { Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.ProxyBinarySettingsNoMatchMessage -f $Target, 'SavedLegacySettings') + $($script:localizedData.ProxyBinarySettingsNoMatchMessage -f $Target, 'SavedLegacySettings') ) -join '') $desiredConfigurationMatch = $false @@ -530,7 +525,7 @@ function Test-ProxySettings if ($DesiredValues.ContainsKey($proxySetting) -and ($DesiredValues.$proxySetting -ne $CurrentValues.$proxySetting)) { Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.ProxySettingMismatchMessage -f $proxySetting,$CurrentValues.$proxySetting,$DesiredValues.$proxySetting) + $($script:localizedData.ProxySettingMismatchMessage -f $proxySetting, $CurrentValues.$proxySetting, $DesiredValues.$proxySetting) ) -join '') $inState = $false @@ -539,13 +534,13 @@ function Test-ProxySettings # Test the array value if ($DesiredValues.ContainsKey('ProxyServerExceptions') ` - -and $CurrentValues.ProxyServerExceptions ` - -and @(Compare-Object ` - -ReferenceObject $DesiredValues.ProxyServerExceptions ` - -DifferenceObject $CurrentValues.ProxyServerExceptions).Count -gt 0) + -and $CurrentValues.ProxyServerExceptions ` + -and @(Compare-Object ` + -ReferenceObject $DesiredValues.ProxyServerExceptions ` + -DifferenceObject $CurrentValues.ProxyServerExceptions).Count -gt 0) { Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.ProxySettingMismatchMessage -f 'ProxyServerExceptions',($CurrentValues.ProxyServerExceptions -join ';'),($DesiredValues.ProxyServerExceptions -join ';')) + $($script:localizedData.ProxySettingMismatchMessage -f 'ProxyServerExceptions', ($CurrentValues.ProxyServerExceptions -join ';'), ($DesiredValues.ProxyServerExceptions -join ';')) ) -join '') $inState = $false @@ -576,10 +571,10 @@ function Get-StringLengthInHexBytes $hex = '{0:x8}' -f $Value.Length $stringLength = @() - $stringLength += @('0x' + $hex.Substring(6,2)) - $stringLength += @('0x' + $hex.Substring(4,2)) - $stringLength += @('0x' + $hex.Substring(2,2)) - $stringLength += @('0x' + $hex.Substring(0,2)) + $stringLength += @('0x' + $hex.Substring(6, 2)) + $stringLength += @('0x' + $hex.Substring(4, 2)) + $stringLength += @('0x' + $hex.Substring(2, 2)) + $stringLength += @('0x' + $hex.Substring(0, 2)) return $stringLength } @@ -793,9 +788,9 @@ function ConvertFrom-ProxySettingsBinary $enableAutoDetection = $true } - $proxyParameters.Add('EnableManualProxy',$enableManualProxy) - $proxyParameters.Add('EnableAutoConfiguration',$enableAutoConfiguration) - $proxyParameters.Add('EnableAutoDetection',$enableAutoDetection) + $proxyParameters.Add('EnableManualProxy', $enableManualProxy) + $proxyParameters.Add('EnableAutoConfiguration', $enableAutoConfiguration) + $proxyParameters.Add('EnableAutoDetection', $enableAutoDetection) $stringPointer = 12 @@ -809,12 +804,12 @@ function ConvertFrom-ProxySettingsBinary if ($stringLength -gt 0) { $stringBytes = New-Object -TypeName Byte[] -ArgumentList $stringLength - $null = [System.Buffer]::BlockCopy($ProxySettings,$stringPointer,$stringBytes,0,$stringLength) + $null = [System.Buffer]::BlockCopy($ProxySettings, $stringPointer, $stringBytes, 0, $stringLength) $proxyServer = [System.Text.Encoding]::ASCII.GetString($stringBytes) $stringPointer += $stringLength } - $proxyParameters.Add('ProxyServer',$proxyServer) + $proxyParameters.Add('ProxyServer', $proxyServer) # Extract the Proxy Server Exceptions string $proxyServerExceptions = @() @@ -826,7 +821,7 @@ function ConvertFrom-ProxySettingsBinary if ($stringLength -gt 0) { $stringBytes = New-Object -TypeName Byte[] -ArgumentList $stringLength - $null = [System.Buffer]::BlockCopy($ProxySettings,$stringPointer,$stringBytes,0,$stringLength) + $null = [System.Buffer]::BlockCopy($ProxySettings, $stringPointer, $stringBytes, 0, $stringLength) $proxyServerExceptionsString = [System.Text.Encoding]::ASCII.GetString($stringBytes) $stringPointer += $stringLength $proxyServerExceptions = [System.String[]] ($proxyServerExceptionsString -split ';') @@ -835,14 +830,14 @@ function ConvertFrom-ProxySettingsBinary if ($proxyServerExceptions.Contains('')) { $proxyServerExceptions = $proxyServerExceptions | Where-Object -FilterScript { $_ -ne '' } - $proxyParameters.Add('ProxyServerBypassLocal',$true) + $proxyParameters.Add('ProxyServerBypassLocal', $true) } else { - $proxyParameters.Add('ProxyServerBypassLocal',$false) + $proxyParameters.Add('ProxyServerBypassLocal', $false) } - $proxyParameters.Add('ProxyServerExceptions',$proxyServerExceptions) + $proxyParameters.Add('ProxyServerExceptions', $proxyServerExceptions) # Extract the Auto Config URL string $autoConfigURL = '' @@ -852,12 +847,12 @@ function ConvertFrom-ProxySettingsBinary if ($stringLength -gt 0) { $stringBytes = New-Object -TypeName Byte[] -ArgumentList $stringLength - $null = [System.Buffer]::BlockCopy($ProxySettings,$stringPointer,$stringBytes,0,$stringLength) + $null = [System.Buffer]::BlockCopy($ProxySettings, $stringPointer, $stringBytes, 0, $stringLength) $autoConfigURL = [System.Text.Encoding]::ASCII.GetString($stringBytes) $stringPointer += $stringLength } - $proxyParameters.Add('AutoConfigURL',$autoConfigURL) + $proxyParameters.Add('AutoConfigURL', $autoConfigURL) } return [PSObject] $proxyParameters @@ -880,7 +875,7 @@ function Get-ProxySettingsRegistryKeyPath param ( [Parameter()] - [ValidateSet('LocalMachine','CurrentUser')] + [ValidateSet('LocalMachine', 'CurrentUser')] [System.String] $Target = 'LocalMachine' ) @@ -922,10 +917,8 @@ function ConvertTo-Win32RegistryPath ) # Translate the registry key from PS - $Path = $Path -replace '^HKLM:\\','HKEY_LOCAL_MACHINE\' - $Path = $Path -replace '^HKCU:\\','HKEY_CURRENT_USER\' + $Path = $Path -replace '^HKLM:\\', 'HKEY_LOCAL_MACHINE\' + $Path = $Path -replace '^HKCU:\\', 'HKEY_CURRENT_USER\' return $Path } - -Export-ModuleMember -function *-TargetResource diff --git a/source/DSCResources/DSC_Route/DSC_Route.psm1 b/source/DSCResources/DSC_Route/DSC_Route.psm1 index fbdc1c24..c1e1701c 100644 --- a/source/DSCResources/DSC_Route/DSC_Route.psm1 +++ b/source/DSCResources/DSC_Route/DSC_Route.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -629,5 +624,3 @@ function Assert-ResourceProperty # Validate the NextHop Parameter Assert-IPAddress -Address $NextHop -AddressFamily $AddressFamily } - -Export-ModuleMember -Function *-TargetResource diff --git a/source/DSCResources/DSC_WaitForNetworkTeam/DSC_WaitForNetworkTeam.psm1 b/source/DSCResources/DSC_WaitForNetworkTeam/DSC_WaitForNetworkTeam.psm1 index 7e2ce408..8520ceab 100644 --- a/source/DSCResources/DSC_WaitForNetworkTeam/DSC_WaitForNetworkTeam.psm1 +++ b/source/DSCResources/DSC_WaitForNetworkTeam/DSC_WaitForNetworkTeam.psm1 @@ -5,11 +5,6 @@ param () $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -180,7 +175,7 @@ function Test-TargetResource <# .SYNOPSIS Returns the current status of a network team. - 'Up' indicates that the network team is acive. + 'Up' indicates that the network team is active. 'Degraded' indicates that the network team is not yet available. If the network team does not exist an exception will be @@ -219,5 +214,3 @@ function Get-NetLbfoTeamStatus return $lbfoTeam.Status } - -Export-ModuleMember -Function *-TargetResource diff --git a/source/DSCResources/DSC_WinsServerAddress/DSC_WinsServerAddress.psm1 b/source/DSCResources/DSC_WinsServerAddress/DSC_WinsServerAddress.psm1 index 6951523d..44a0bdb8 100644 --- a/source/DSCResources/DSC_WinsServerAddress/DSC_WinsServerAddress.psm1 +++ b/source/DSCResources/DSC_WinsServerAddress/DSC_WinsServerAddress.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -167,5 +162,3 @@ function Assert-ResourceProperty } } } - -Export-ModuleMember -Function *-TargetResource diff --git a/source/DSCResources/DSC_WinsSetting/DSC_WinsSetting.psm1 b/source/DSCResources/DSC_WinsSetting/DSC_WinsSetting.psm1 index 2dd213f0..859cc8e4 100644 --- a/source/DSCResources/DSC_WinsSetting/DSC_WinsSetting.psm1 +++ b/source/DSCResources/DSC_WinsSetting/DSC_WinsSetting.psm1 @@ -1,10 +1,5 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' -# Import the Networking Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) - Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') # Import Localization Strings @@ -182,5 +177,3 @@ function Test-TargetResource return Test-DscParameterState -CurrentValues $currentState -DesiredValues $PSBoundParameters } # Test-TargetResource - -Export-ModuleMember -Function *-TargetResource diff --git a/source/Modules/NetworkingDsc.Common/NetworkingDsc.Common.psm1 b/source/Modules/NetworkingDsc.Common/NetworkingDsc.Common.psm1 deleted file mode 100644 index 0b71bc8e..00000000 --- a/source/Modules/NetworkingDsc.Common/NetworkingDsc.Common.psm1 +++ /dev/null @@ -1,586 +0,0 @@ -$modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' - -Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common') - -# Import Localization Strings -$script:localizedData = Get-LocalizedData -DefaultUICulture 'en-US' - -<# - .SYNOPSIS - Converts any IP Addresses containing CIDR notation filters in an array to use Subnet Mask - notation. - - .PARAMETER Address - The array of addresses to that need to be converted. -#> -function Convert-CIDRToSubhetMask -{ - [CmdletBinding()] - [OutputType([ Microsoft.Management.Infrastructure.CimInstance])] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String[]] - $Address - ) - - $results = @() - - foreach ($entry in $Address) - { - if (-not $entry.Contains(':') -and -not $entry.Contains('-')) - { - $entrySplit = $entry -split '/' - - if (-not [String]::IsNullOrEmpty($entrySplit[1])) - { - # There was a / so this contains a Subnet Mask or CIDR - $prefix = $entrySplit[0] - $postfix = $entrySplit[1] - - if ($postfix -match '^[0-9]*$') - { - # The postfix contains CIDR notation so convert this to Subnet Mask - $cidr = [System.Int32] $postfix - $subnetMaskInt64 = ([convert]::ToInt64(('1' * $cidr + '0' * (32 - $cidr)), 2)) - $subnetMask = @( - ([math]::Truncate($subnetMaskInt64 / 16777216)) - ([math]::Truncate(($subnetMaskInt64 % 16777216) / 65536)) - ([math]::Truncate(($subnetMaskInt64 % 65536) / 256)) - ([math]::Truncate($subnetMaskInt64 % 256)) - ) - } - else - { - $subnetMask = $postfix -split '\.' - } - - <# - Apply the Subnet Mast to the IP Address so that we end up with a correctly - masked IP Address that will match what the Firewall rule returns. - #> - $maskedIp = $prefix -split '\.' - - for ([System.Int32] $Octet = 0; $octet -lt 4; $octet++) - { - $maskedIp[$Octet] = $maskedIp[$octet] -band $SubnetMask[$octet] - } - - $entry = '{0}/{1}' -f ($maskedIp -join '.'), ($subnetMask -join '.') - } - } - - $results += $entry - } - - return $results -} # Convert-CIDRToSubhetMask - -<# - .SYNOPSIS - This function will find a network adapter based on the provided - search parameters. - - .PARAMETER Name - This is the name of network adapter to find. - - .PARAMETER PhysicalMediaType - This is the media type of the network adapter to find. - - .PARAMETER Status - This is the status of the network adapter to find. - - .PARAMETER MacAddress - This is the MAC address of the network adapter to find. - - .PARAMETER InterfaceDescription - This is the interface description of the network adapter to find. - - .PARAMETER InterfaceIndex - This is the interface index of the network adapter to find. - - .PARAMETER InterfaceGuid - This is the interface GUID of the network adapter to find. - - .PARAMETER DriverDescription - This is the driver description of the network adapter. - - .PARAMETER InterfaceNumber - This is the interface number of the network adapter if more than one - are returned by the parameters. - - .PARAMETER IgnoreMultipleMatchingAdapters - This switch will suppress an error occurring if more than one matching - adapter matches the parameters passed. -#> -function Find-NetworkAdapter -{ - [CmdletBinding()] - [OutputType([System.Collections.Hashtable])] - param - ( - [Parameter()] - [System.String] - $Name, - - [Parameter()] - [System.String] - $PhysicalMediaType, - - [Parameter()] - [ValidateNotNullOrEmpty()] - [ValidateSet('Up', 'Disconnected', 'Disabled')] - [System.String] - $Status = 'Up', - - [Parameter()] - [System.String] - $MacAddress, - - [Parameter()] - [System.String] - $InterfaceDescription, - - [Parameter()] - [System.UInt32] - $InterfaceIndex, - - [Parameter()] - [System.String] - $InterfaceGuid, - - [Parameter()] - [System.String] - $DriverDescription, - - [Parameter()] - [System.UInt32] - $InterfaceNumber = 1, - - [Parameter()] - [System.Boolean] - $IgnoreMultipleMatchingAdapters = $false - ) - - Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.FindingNetAdapterMessage) - ) -join '') - - $adapterFilters = @() - - if ($PSBoundParameters.ContainsKey('Name')) - { - $adapterFilters += @('($_.Name -eq $Name)') - } # if - - if ($PSBoundParameters.ContainsKey('PhysicalMediaType')) - { - $adapterFilters += @('($_.PhysicalMediaType -eq $PhysicalMediaType)') - } # if - - if ($PSBoundParameters.ContainsKey('Status')) - { - $adapterFilters += @('($_.Status -eq $Status)') - } # if - - if ($PSBoundParameters.ContainsKey('MacAddress')) - { - $adapterFilters += @('($_.MacAddress -eq $MacAddress)') - } # if - - if ($PSBoundParameters.ContainsKey('InterfaceDescription')) - { - $adapterFilters += @('($_.InterfaceDescription -eq $InterfaceDescription)') - } # if - - if ($PSBoundParameters.ContainsKey('InterfaceIndex')) - { - $adapterFilters += @('($_.InterfaceIndex -eq $InterfaceIndex)') - } # if - - if ($PSBoundParameters.ContainsKey('InterfaceGuid')) - { - $adapterFilters += @('($_.InterfaceGuid -eq $InterfaceGuid)') - } # if - - if ($PSBoundParameters.ContainsKey('DriverDescription')) - { - $adapterFilters += @('($_.DriverDescription -eq $DriverDescription)') - } # if - - if ($adapterFilters.Count -eq 0) - { - Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.AllNetAdaptersFoundMessage) - ) -join '') - - $matchingAdapters = @(Get-NetAdapter) - } - else - { - # Join all the filters together - $adapterFilterScript = '(' + ($adapterFilters -join ' -and ') + ')' - $matchingAdapters = @(Get-NetAdapter | - Where-Object -FilterScript ([ScriptBlock]::Create($adapterFilterScript))) - } - - # Were any adapters found matching the criteria? - if ($matchingAdapters.Count -eq 0) - { - New-InvalidOperationException ` - -Message ($script:localizedData.NetAdapterNotFoundError) - - # Return a null so that ErrorAction SilentlyContinue works correctly - return $null - } - else - { - Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.NetAdapterFoundMessage -f $matchingAdapters.Count) - ) -join '') - - if ($matchingAdapters.Count -gt 1) - { - if ($IgnoreMultipleMatchingAdapters) - { - # Was the number of matching adapters found matching the adapter number? - if (($InterfaceNumber -gt 1) -and ($InterfaceNumber -gt $matchingAdapters.Count)) - { - New-InvalidOperationException ` - -Message ($script:localizedData.InvalidNetAdapterNumberError ` - -f $matchingAdapters.Count, $InterfaceNumber) - - # Return a null so that ErrorAction SilentlyContinue works correctly - return $null - } # if - } - else - { - New-InvalidOperationException ` - -Message ($script:localizedData.MultipleMatchingNetAdapterFound ` - -f $matchingAdapters.Count) - - # Return a null so that ErrorAction SilentlyContinue works correctly - return $null - } # if - } # if - } # if - - # Identify the exact adapter from the adapters that match - $exactAdapter = $matchingAdapters[$InterfaceNumber - 1] - - $returnValue = [PSCustomObject] @{ - Name = $exactAdapter.Name - PhysicalMediaType = $exactAdapter.PhysicalMediaType - Status = $exactAdapter.Status - MacAddress = $exactAdapter.MacAddress - InterfaceDescription = $exactAdapter.InterfaceDescription - InterfaceIndex = $exactAdapter.InterfaceIndex - InterfaceGuid = $exactAdapter.InterfaceGuid - MatchingAdapterCount = $matchingAdapters.Count - } - - return $returnValue -} # Find-NetworkAdapter - -<# - .SYNOPSIS - Returns the DNS Client Server static address that are assigned to a network - adapter. This is required because Get-DnsClientServerAddress always returns - the currently assigned server addresses whether regardless if they were - assigned as static or by DHCP. - - The only way that could be found to do this is to query the registry. - - .PARAMETER InterfaceAlias - Alias of the network interface to get the static DNS Server addresses from. - - .PARAMETER AddressFamily - IP address family. -#> -function Get-DnsClientServerStaticAddress -{ - [CmdletBinding()] - [OutputType([System.String[]])] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $InterfaceAlias, - - [Parameter(Mandatory = $true)] - [ValidateSet('IPv4', 'IPv6')] - [System.String] - $AddressFamily - ) - - Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.GettingDNSServerStaticAddressMessage) -f $AddressFamily, $InterfaceAlias - ) -join '') - - # Look up the interface Guid - $adapter = Get-NetAdapter ` - -InterfaceAlias $InterfaceAlias ` - -ErrorAction SilentlyContinue - - if (-not $adapter) - { - New-InvalidOperationException ` - -Message ($script:localizedData.InterfaceAliasNotFoundError ` - -f $InterfaceAlias) - - # Return null to support ErrorAction Silently Continue - return $null - } # if - - $interfaceGuid = $adapter.InterfaceGuid.ToLower() - - if ($AddressFamily -eq 'IPv4') - { - $interfaceRegKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\$interfaceGuid\" - } - else - { - $interfaceRegKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces\$interfaceGuid\" - } # if - - $interfaceInformation = Get-ItemProperty ` - -Path $interfaceRegKeyPath ` - -ErrorAction SilentlyContinue - $nameServerAddressString = $interfaceInformation.NameServer - - # Are any statically assigned addresses for this adapter? - if ([System.String]::IsNullOrWhiteSpace($nameServerAddressString)) - { - # Static DNS Server addresses not found so return empty array - Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.DNSServerStaticAddressNotSetMessage) -f $AddressFamily, $InterfaceAlias - ) -join '') - - return @() - } - else - { - # Static DNS Server addresses found so split them into an array using comma - Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($script:localizedData.DNSServerStaticAddressFoundMessage) -f $AddressFamily, $InterfaceAlias, $nameServerAddressString - ) -join '') - - return @($nameServerAddressString -split ',') - } # if -} # Get-DnsClientServerStaticAddress - -<# - .SYNOPSIS - Returns the WINS Client Server static address that are assigned to a network - adapter. The CIM class Win32_NetworkAdapterConfiguration unfortunately only supports - the primary and secondary WINS server. The registry gives more flexibility. - - .PARAMETER InterfaceAlias - Alias of the network interface to get the static WINS Server addresses from. -#> -function Get-WinsClientServerStaticAddress -{ - [CmdletBinding()] - [OutputType([System.String[]])] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $InterfaceAlias - ) - - Write-Verbose -Message ("$($MyInvocation.MyCommand): $($script:localizedData.GettingWinsServerStaticAddressMessage -f $InterfaceAlias)") - - # Look up the interface Guid - $adapter = Get-NetAdapter ` - -InterfaceAlias $InterfaceAlias ` - -ErrorAction SilentlyContinue - - if (-not $adapter) - { - New-InvalidOperationException -Message ($script:localizedData.InterfaceAliasNotFoundError -f $InterfaceAlias) - - # Return null to support ErrorAction Silently Continue - return $null - } - - $interfaceGuid = $adapter.InterfaceGuid.ToLower() - - $interfaceRegKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters\Interfaces\Tcpip_$interfaceGuid\" - - $interfaceInformation = Get-ItemProperty -Path $interfaceRegKeyPath -ErrorAction SilentlyContinue - $nameServerAddressString = $interfaceInformation.NameServerList - - # Are any statically assigned addresses for this adapter? - if (-not $nameServerAddressString) - { - # Static DNS Server addresses not found so return empty array - Write-Verbose -Message ("$($MyInvocation.MyCommand): $($script:localizedData.WinsServerStaticAddressNotSetMessage -f $InterfaceAlias)") - return $null - } - else - { - # Static DNS Server addresses found so split them into an array using comma - Write-Verbose -Message ("$($MyInvocation.MyCommand): $($script:localizedData.WinsServerStaticAddressFoundMessage -f - $InterfaceAlias, ($nameServerAddressString -join ','))") - - return $nameServerAddressString - } -} # Get-WinsClientServerStaticAddress - -<# - .SYNOPSIS - Sets the WINS Client Server static address on a network adapter. The CIM class - Win32_NetworkAdapterConfiguration unfortunately only supports the primary and - secondary WINS server. The registry gives more flexibility. - - .PARAMETER InterfaceAlias - Alias of the network interface to set the static WINS Server addresses on. -#> -function Set-WinsClientServerStaticAddress -{ - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $InterfaceAlias, - - [Parameter(Mandatory = $true)] - [AllowEmptyCollection()] - [System.String[]] - $Address - ) - - Write-Verbose -Message ("$($MyInvocation.MyCommand): $($script:localizedData.SettingWinsServerStaticAddressMessage -f $InterfaceAlias, ($Address -join ', '))") - - # Look up the interface Guid - $adapter = Get-NetAdapter ` - -InterfaceAlias $InterfaceAlias ` - -ErrorAction SilentlyContinue - - if (-not $adapter) - { - New-InvalidOperationException -Message ($script:localizedData.InterfaceAliasNotFoundError -f $InterfaceAlias) - } - - $interfaceGuid = $adapter.InterfaceGuid.ToLower() - - $interfaceRegKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters\Interfaces\Tcpip_$interfaceGuid\" - - Set-ItemProperty -Path $interfaceRegKeyPath -Name NameServerList -Value $Address - -} # Set-WinsClientServerStaticAddress - -<# - .SYNOPSIS - Gets the IP Address prefix from a provided IP Address in CIDR notation. - - .PARAMETER IPAddress - IP Address to get prefix for, can be in CIDR notation. - - .PARAMETER AddressFamily - Address family for provided IP Address, defaults to IPv4. - -#> -function Get-IPAddressPrefix -{ - [cmdletbinding()] - param - ( - [Parameter(Mandatory = $true, - ValueFromPipeline)] - [System.String[]] - $IPAddress, - - [Parameter()] - [ValidateSet('IPv4', 'IPv6')] - [System.String] - $AddressFamily = 'IPv4' - ) - - process - { - foreach ($singleIP in $IPAddress) - { - $prefixLength = ($singleIP -split '/')[1] - - if (-not ($prefixLength) -and $AddressFamily -eq 'IPv4') - { - if ($singleIP.split('.')[0] -in (0..127)) - { - $prefixLength = 8 - } - elseif ($singleIP.split('.')[0] -in (128..191)) - { - $prefixLength = 16 - } - elseif ($singleIP.split('.')[0] -in (192..223)) - { - $prefixLength = 24 - } - } - elseif (-not ($prefixLength) -and $AddressFamily -eq 'IPv6') - { - $prefixLength = 64 - } - - [PSCustomObject]@{ - IPAddress = $singleIP.split('/')[0] - prefixLength = $prefixLength - } - } - } -} - -<# -.SYNOPSIS - Returns a filter string for the net adapter CIM instances. Wildcards supported. - -.PARAMETER InterfaceAlias - Specifies the alias of a network interface. Supports the use of '*' or '%'. -#> -function Format-Win32NetworkAdapterFilterByNetConnectionId -{ - [CmdletBinding()] - [OutputType([System.String])] - param - ( - [Parameter(Mandatory = $true)] - [System.String] - $InterfaceAlias - ) - - if ($InterfaceAlias.Contains('*')) - { - $InterfaceAlias = $InterfaceAlias.Replace('*','%') - } - - if ($InterfaceAlias.Contains('%')) - { - $operator = ' LIKE ' - } - else - { - $operator = '=' - } - - $returnNetAdapaterFilter = 'NetConnectionID{0}"{1}"' -f $operator, $InterfaceAlias - - return $returnNetAdapaterFilter -} - -Export-ModuleMember -Function @( - 'Convert-CIDRToSubhetMask' - 'Find-NetworkAdapter' - 'Get-DnsClientServerStaticAddress' - 'Get-WinsClientServerStaticAddress' - 'Set-WinsClientServerStaticAddress' - 'Get-IPAddressPrefix' - 'Format-Win32NetworkAdapterFilterByNetConnectionId' -) diff --git a/source/Modules/NetworkingDsc.Common/en-US/NetworkingDsc.Common.strings.psd1 b/source/Modules/NetworkingDsc.Common/en-US/NetworkingDsc.Common.strings.psd1 deleted file mode 100644 index 3c8b51d5..00000000 --- a/source/Modules/NetworkingDsc.Common/en-US/NetworkingDsc.Common.strings.psd1 +++ /dev/null @@ -1,16 +0,0 @@ -ConvertFrom-StringData @' - FindingNetAdapterMessage = Finding network adapters matching the parameters. - AllNetAdaptersFoundMessage = Found all network adapters because no filter parameters provided. - NetAdapterFoundMessage = {0} network adapters were found matching the parameters. - NetAdapterNotFoundError = A network adapter matching the parameters was not found. Please correct the properties and try again. - InterfaceAliasNotFoundError = A network adapter with the alias '{0}' could not be found. - MultipleMatchingNetAdapterFound = Please adjust the parameters or specify IgnoreMultipleMatchingAdapters to only use the first and try again. - InvalidNetAdapterNumberError = network adapter interface number {0} was specified but only {1} was found. Please correct the interface number and try again. - GettingDNSServerStaticAddressMessage = Getting staticly assigned DNS server {0} address for interface alias '{1}'. - GettingWinsServerStaticAddressMessage = Getting staticly assigned WINS server address for interface alias '{0}'. - SettingWinsServerStaticAddressMessage = Setting staticly assigned WINS server address for interface alias '{0}' to '{1}'. - DNSServerStaticAddressNotSetMessage = Statically assigned DNS server {0} address for interface alias '{1}' is not set. - WinsServerStaticAddressNotSetMessage = Statically assigned WINS server address for interface alias '{0}' is not set. - DNSServerStaticAddressFoundMessage = Statically assigned DNS server {0} address for interface alias '{1}' is '{2}'. - WinsServerStaticAddressFoundMessage = Statically assigned WINS server address for interface alias '{0}' is '{1}'. -'@ diff --git a/source/NetworkingDsc.psd1 b/source/NetworkingDsc.psd1 index 51c2971b..53a2c17f 100644 --- a/source/NetworkingDsc.psd1 +++ b/source/NetworkingDsc.psd1 @@ -1,4 +1,7 @@ @{ + # Script module or binary module file associated with this manifest. + RootModule = 'NetworkingDsc.psm1' + # Version number of this module. moduleVersion = '0.0.1' @@ -36,33 +39,7 @@ AliasesToExport = @() # DSC resources to export from this module - DscResourcesToExport = @( - 'DefaultGatewayAddress', - 'DnsClientGlobalSetting', - 'DnsConnectionSuffix', - 'DNSServerAddress', - 'Firewall', - 'FirewallProfile', - 'HostsFile', - 'IPAddress', - 'IPAddressOption', - 'NetAdapterAdvancedProperty', - 'NetAdapterBinding', - 'NetAdapterLso', - 'NetAdapterName', - 'NetAdapterRDMA', - 'NetAdapterRsc', - 'NetAdapterRss', - 'NetAdapterState', - 'NetBIOS', - 'NetConnectionProfile', - 'NetIPInterface', - 'NetworkTeam', - 'NetworkTeamInterface', - 'ProxySettings', - 'Route', - 'WINSSetting' - ) + DscResourcesToExport = @() # 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 = @{ diff --git a/source/Public/Convert-CIDRToSubnetMask.ps1 b/source/Public/Convert-CIDRToSubnetMask.ps1 new file mode 100644 index 00000000..b9d9e349 --- /dev/null +++ b/source/Public/Convert-CIDRToSubnetMask.ps1 @@ -0,0 +1,71 @@ +<# + .SYNOPSIS + Converts any IP Addresses containing CIDR notation filters in an array to use Subnet Mask + notation. + + .PARAMETER Address + The array of addresses to that need to be converted. +#> +function Convert-CIDRToSubnetMask +{ + [CmdletBinding()] + [OutputType([ Microsoft.Management.Infrastructure.CimInstance])] + param + ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [System.String[]] + $Address + ) + + $results = @() + + foreach ($entry in $Address) + { + if (-not $entry.Contains(':') -and -not $entry.Contains('-')) + { + $entrySplit = $entry -split '/' + + if (-not [String]::IsNullOrEmpty($entrySplit[1])) + { + # There was a / so this contains a Subnet Mask or CIDR + $prefix = $entrySplit[0] + $postfix = $entrySplit[1] + + if ($postfix -match '^[0-9]*$') + { + # The postfix contains CIDR notation so convert this to Subnet Mask + $cidr = [System.Int32] $postfix + $subnetMaskInt64 = ([convert]::ToInt64(('1' * $cidr + '0' * (32 - $cidr)), 2)) + $subnetMask = @( + ([math]::Truncate($subnetMaskInt64 / 16777216)) + ([math]::Truncate(($subnetMaskInt64 % 16777216) / 65536)) + ([math]::Truncate(($subnetMaskInt64 % 65536) / 256)) + ([math]::Truncate($subnetMaskInt64 % 256)) + ) + } + else + { + $subnetMask = $postfix -split '\.' + } + + <# + Apply the Subnet Mast to the IP Address so that we end up with a correctly + masked IP Address that will match what the Firewall rule returns. + #> + $maskedIp = $prefix -split '\.' + + for ([System.Int32] $Octet = 0; $octet -lt 4; $octet++) + { + $maskedIp[$Octet] = $maskedIp[$octet] -band $SubnetMask[$octet] + } + + $entry = '{0}/{1}' -f ($maskedIp -join '.'), ($subnetMask -join '.') + } + } + + $results += $entry + } + + return $results +} diff --git a/source/Public/Find-NetworkAdapter.ps1 b/source/Public/Find-NetworkAdapter.ps1 new file mode 100644 index 00000000..c2597dd7 --- /dev/null +++ b/source/Public/Find-NetworkAdapter.ps1 @@ -0,0 +1,206 @@ +<# + .SYNOPSIS + This function will find a network adapter based on the provided + search parameters. + + .PARAMETER Name + This is the name of network adapter to find. + + .PARAMETER PhysicalMediaType + This is the media type of the network adapter to find. + + .PARAMETER Status + This is the status of the network adapter to find. + + .PARAMETER MacAddress + This is the MAC address of the network adapter to find. + + .PARAMETER InterfaceDescription + This is the interface description of the network adapter to find. + + .PARAMETER InterfaceIndex + This is the interface index of the network adapter to find. + + .PARAMETER InterfaceGuid + This is the interface GUID of the network adapter to find. + + .PARAMETER DriverDescription + This is the driver description of the network adapter. + + .PARAMETER InterfaceNumber + This is the interface number of the network adapter if more than one + are returned by the parameters. + + .PARAMETER IgnoreMultipleMatchingAdapters + This switch will suppress an error occurring if more than one matching + adapter matches the parameters passed. +#> +function Find-NetworkAdapter +{ + [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] + param + ( + [Parameter()] + [System.String] + $Name, + + [Parameter()] + [System.String] + $PhysicalMediaType, + + [Parameter()] + [ValidateNotNullOrEmpty()] + [ValidateSet('Up', 'Disconnected', 'Disabled')] + [System.String] + $Status = 'Up', + + [Parameter()] + [System.String] + $MacAddress, + + [Parameter()] + [System.String] + $InterfaceDescription, + + [Parameter()] + [System.UInt32] + $InterfaceIndex, + + [Parameter()] + [System.String] + $InterfaceGuid, + + [Parameter()] + [System.String] + $DriverDescription, + + [Parameter()] + [System.UInt32] + $InterfaceNumber = 1, + + [Parameter()] + [System.Boolean] + $IgnoreMultipleMatchingAdapters = $false + ) + + Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " + $($script:localizedData.FindingNetAdapterMessage) + ) -join '') + + $adapterFilters = @() + + if ($PSBoundParameters.ContainsKey('Name')) + { + $adapterFilters += @('($_.Name -eq $Name)') + } # if + + if ($PSBoundParameters.ContainsKey('PhysicalMediaType')) + { + $adapterFilters += @('($_.PhysicalMediaType -eq $PhysicalMediaType)') + } # if + + if ($PSBoundParameters.ContainsKey('Status')) + { + $adapterFilters += @('($_.Status -eq $Status)') + } # if + + if ($PSBoundParameters.ContainsKey('MacAddress')) + { + $adapterFilters += @('($_.MacAddress -eq $MacAddress)') + } # if + + if ($PSBoundParameters.ContainsKey('InterfaceDescription')) + { + $adapterFilters += @('($_.InterfaceDescription -eq $InterfaceDescription)') + } # if + + if ($PSBoundParameters.ContainsKey('InterfaceIndex')) + { + $adapterFilters += @('($_.InterfaceIndex -eq $InterfaceIndex)') + } # if + + if ($PSBoundParameters.ContainsKey('InterfaceGuid')) + { + $adapterFilters += @('($_.InterfaceGuid -eq $InterfaceGuid)') + } # if + + if ($PSBoundParameters.ContainsKey('DriverDescription')) + { + $adapterFilters += @('($_.DriverDescription -eq $DriverDescription)') + } # if + + if ($adapterFilters.Count -eq 0) + { + Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " + $($script:localizedData.AllNetAdaptersFoundMessage) + ) -join '') + + $matchingAdapters = @(Get-NetAdapter) + } + else + { + # Join all the filters together + $adapterFilterScript = '(' + ($adapterFilters -join ' -and ') + ')' + $matchingAdapters = @(Get-NetAdapter | + Where-Object -FilterScript ([ScriptBlock]::Create($adapterFilterScript))) + } + + # Were any adapters found matching the criteria? + if ($matchingAdapters.Count -eq 0) + { + New-InvalidOperationException ` + -Message ($script:localizedData.NetAdapterNotFoundError) + + # Return a null so that ErrorAction SilentlyContinue works correctly + return $null + } + else + { + Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " + $($script:localizedData.NetAdapterFoundMessage -f $matchingAdapters.Count) + ) -join '') + + if ($matchingAdapters.Count -gt 1) + { + if ($IgnoreMultipleMatchingAdapters) + { + # Was the number of matching adapters found matching the adapter number? + if (($InterfaceNumber -gt 1) -and ($InterfaceNumber -gt $matchingAdapters.Count)) + { + New-InvalidOperationException ` + -Message ($script:localizedData.InvalidNetAdapterNumberError ` + -f $matchingAdapters.Count, $InterfaceNumber) + + # Return a null so that ErrorAction SilentlyContinue works correctly + return $null + } # if + } + else + { + New-InvalidOperationException ` + -Message ($script:localizedData.MultipleMatchingNetAdapterFound ` + -f $matchingAdapters.Count) + + # Return a null so that ErrorAction SilentlyContinue works correctly + return $null + } # if + } # if + } # if + + # Identify the exact adapter from the adapters that match + $exactAdapter = $matchingAdapters[$InterfaceNumber - 1] + + $returnValue = [PSCustomObject] @{ + Name = $exactAdapter.Name + PhysicalMediaType = $exactAdapter.PhysicalMediaType + Status = $exactAdapter.Status + MacAddress = $exactAdapter.MacAddress + InterfaceDescription = $exactAdapter.InterfaceDescription + InterfaceIndex = $exactAdapter.InterfaceIndex + InterfaceGuid = $exactAdapter.InterfaceGuid + MatchingAdapterCount = $matchingAdapters.Count + } + + return $returnValue +} diff --git a/source/Public/Format-Win32NetworkAdapterFilterByNetConnectionId.ps1 b/source/Public/Format-Win32NetworkAdapterFilterByNetConnectionId.ps1 new file mode 100644 index 00000000..c707b999 --- /dev/null +++ b/source/Public/Format-Win32NetworkAdapterFilterByNetConnectionId.ps1 @@ -0,0 +1,36 @@ +<# +.SYNOPSIS + Returns a filter string for the net adapter CIM instances. Wildcards supported. + +.PARAMETER InterfaceAlias + Specifies the alias of a network interface. Supports the use of '*' or '%'. +#> +function Format-Win32NetworkAdapterFilterByNetConnectionId +{ + [CmdletBinding()] + [OutputType([System.String])] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $InterfaceAlias + ) + + if ($InterfaceAlias.Contains('*')) + { + $InterfaceAlias = $InterfaceAlias.Replace('*','%') + } + + if ($InterfaceAlias.Contains('%')) + { + $operator = ' LIKE ' + } + else + { + $operator = '=' + } + + $returnNetAdapaterFilter = 'NetConnectionID{0}"{1}"' -f $operator, $InterfaceAlias + + return $returnNetAdapaterFilter +} diff --git a/source/Public/Get-DnsClientServerStaticAddress.ps1 b/source/Public/Get-DnsClientServerStaticAddress.ps1 new file mode 100644 index 00000000..9b1cf502 --- /dev/null +++ b/source/Public/Get-DnsClientServerStaticAddress.ps1 @@ -0,0 +1,87 @@ +<# + .SYNOPSIS + Returns the DNS Client Server static address that are assigned to a network + adapter. This is required because Get-DnsClientServerAddress always returns + the currently assigned server addresses whether regardless if they were + assigned as static or by DHCP. + + The only way that could be found to do this is to query the registry. + + .PARAMETER InterfaceAlias + Alias of the network interface to get the static DNS Server addresses from. + + .PARAMETER AddressFamily + IP address family. +#> +function Get-DnsClientServerStaticAddress +{ + [CmdletBinding()] + [OutputType([System.Object[]])] + param + ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [System.String] + $InterfaceAlias, + + [Parameter(Mandatory = $true)] + [ValidateSet('IPv4', 'IPv6')] + [System.String] + $AddressFamily + ) + + Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " + $($script:localizedData.GettingDNSServerStaticAddressMessage) -f $AddressFamily, $InterfaceAlias + ) -join '') + + # Look up the interface Guid + $adapter = Get-NetAdapter ` + -InterfaceAlias $InterfaceAlias ` + -ErrorAction SilentlyContinue + + if (-not $adapter) + { + New-InvalidOperationException ` + -Message ($script:localizedData.InterfaceAliasNotFoundError ` + -f $InterfaceAlias) + + # Return null to support ErrorAction Silently Continue + return $null + } # if + + $interfaceGuid = $adapter.InterfaceGuid.ToLower() + + if ($AddressFamily -eq 'IPv4') + { + $interfaceRegKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\$interfaceGuid\" + } + else + { + $interfaceRegKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces\$interfaceGuid\" + } # if + + $interfaceInformation = Get-ItemProperty ` + -Path $interfaceRegKeyPath ` + -ErrorAction SilentlyContinue + $nameServerAddressString = $interfaceInformation.NameServer + + # Are any statically assigned addresses for this adapter? + if ([System.String]::IsNullOrWhiteSpace($nameServerAddressString)) + { + # Static DNS Server addresses not found so return empty array + Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " + $($script:localizedData.DNSServerStaticAddressNotSetMessage) -f $AddressFamily, $InterfaceAlias + ) -join '') + + return @() + } + else + { + # Static DNS Server addresses found so split them into an array using comma + Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " + $($script:localizedData.DNSServerStaticAddressFoundMessage) -f $AddressFamily, $InterfaceAlias, $nameServerAddressString + ) -join '') + + return @($nameServerAddressString -split ',') + } # if +} diff --git a/source/Public/Get-IPAddressPrefix.ps1 b/source/Public/Get-IPAddressPrefix.ps1 new file mode 100644 index 00000000..6f76f50a --- /dev/null +++ b/source/Public/Get-IPAddressPrefix.ps1 @@ -0,0 +1,60 @@ +<# + .SYNOPSIS + Gets the IP Address prefix from a provided IP Address in CIDR notation. + + .PARAMETER IPAddress + IP Address to get prefix for, can be in CIDR notation. + + .PARAMETER AddressFamily + Address family for provided IP Address, defaults to IPv4. + +#> +function Get-IPAddressPrefix +{ + [cmdletbinding()] + param + ( + [Parameter(Mandatory = $true, + ValueFromPipeline)] + [System.String[]] + $IPAddress, + + [Parameter()] + [ValidateSet('IPv4', 'IPv6')] + [System.String] + $AddressFamily = 'IPv4' + ) + + process + { + foreach ($singleIP in $IPAddress) + { + $prefixLength = ($singleIP -split '/')[1] + + if (-not ($prefixLength) -and $AddressFamily -eq 'IPv4') + { + if ($singleIP.split('.')[0] -in (0..127)) + { + $prefixLength = 8 + } + elseif ($singleIP.split('.')[0] -in (128..191)) + { + $prefixLength = 16 + } + elseif ($singleIP.split('.')[0] -in (192..223)) + { + $prefixLength = 24 + } + } + elseif (-not ($prefixLength) -and $AddressFamily -eq 'IPv6') + { + $prefixLength = 64 + } + + [PSCustomObject]@{ + IPAddress = $singleIP.split('/')[0] + prefixLength = $prefixLength + } + } + } +} diff --git a/source/Public/Get-WinsClientServerStaticAddress.ps1 b/source/Public/Get-WinsClientServerStaticAddress.ps1 new file mode 100644 index 00000000..22a2eb46 --- /dev/null +++ b/source/Public/Get-WinsClientServerStaticAddress.ps1 @@ -0,0 +1,59 @@ +<# + .SYNOPSIS + Returns the WINS Client Server static address that are assigned to a network + adapter. The CIM class Win32_NetworkAdapterConfiguration unfortunately only supports + the primary and secondary WINS server. The registry gives more flexibility. + + .PARAMETER InterfaceAlias + Alias of the network interface to get the static WINS Server addresses from. +#> +function Get-WinsClientServerStaticAddress +{ + [CmdletBinding()] + [OutputType([System.String[]])] + param + ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [System.String] + $InterfaceAlias + ) + + Write-Verbose -Message ("$($MyInvocation.MyCommand): $($script:localizedData.GettingWinsServerStaticAddressMessage -f $InterfaceAlias)") + + # Look up the interface Guid + $adapter = Get-NetAdapter ` + -InterfaceAlias $InterfaceAlias ` + -ErrorAction SilentlyContinue + + if (-not $adapter) + { + New-InvalidOperationException -Message ($script:localizedData.InterfaceAliasNotFoundError -f $InterfaceAlias) + + # Return null to support ErrorAction Silently Continue + return $null + } + + $interfaceGuid = $adapter.InterfaceGuid.ToLower() + + $interfaceRegKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters\Interfaces\Tcpip_$interfaceGuid\" + + $interfaceInformation = Get-ItemProperty -Path $interfaceRegKeyPath -ErrorAction SilentlyContinue + $nameServerAddressString = $interfaceInformation.NameServerList + + # Are any statically assigned addresses for this adapter? + if (-not $nameServerAddressString) + { + # Static DNS Server addresses not found so return empty array + Write-Verbose -Message ("$($MyInvocation.MyCommand): $($script:localizedData.WinsServerStaticAddressNotSetMessage -f $InterfaceAlias)") + return $null + } + else + { + # Static DNS Server addresses found so split them into an array using comma + Write-Verbose -Message ("$($MyInvocation.MyCommand): $($script:localizedData.WinsServerStaticAddressFoundMessage -f + $InterfaceAlias, ($nameServerAddressString -join ','))") + + return $nameServerAddressString + } +} diff --git a/source/Public/Set-WinsClientServerStaticAddress.ps1 b/source/Public/Set-WinsClientServerStaticAddress.ps1 new file mode 100644 index 00000000..7570b70b --- /dev/null +++ b/source/Public/Set-WinsClientServerStaticAddress.ps1 @@ -0,0 +1,44 @@ +<# + .SYNOPSIS + Sets the WINS Client Server static address on a network adapter. The CIM class + Win32_NetworkAdapterConfiguration unfortunately only supports the primary and + secondary WINS server. The registry gives more flexibility. + + .PARAMETER InterfaceAlias + Alias of the network interface to set the static WINS Server addresses on. +#> +function Set-WinsClientServerStaticAddress +{ + [CmdletBinding()] + param + ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [System.String] + $InterfaceAlias, + + [Parameter(Mandatory = $true)] + [AllowEmptyCollection()] + [System.String[]] + $Address + ) + + Write-Verbose -Message ("$($MyInvocation.MyCommand): $($script:localizedData.SettingWinsServerStaticAddressMessage -f $InterfaceAlias, ($Address -join ', '))") + + # Look up the interface Guid + $adapter = Get-NetAdapter ` + -InterfaceAlias $InterfaceAlias ` + -ErrorAction SilentlyContinue + + if (-not $adapter) + { + New-InvalidOperationException -Message ($script:localizedData.InterfaceAliasNotFoundError -f $InterfaceAlias) + } + + $interfaceGuid = $adapter.InterfaceGuid.ToLower() + + $interfaceRegKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters\Interfaces\Tcpip_$interfaceGuid\" + + Set-ItemProperty -Path $interfaceRegKeyPath -Name NameServerList -Value $Address + +} diff --git a/source/en-US/NetworkingDsc.strings.psd1 b/source/en-US/NetworkingDsc.strings.psd1 new file mode 100644 index 00000000..5907469d --- /dev/null +++ b/source/en-US/NetworkingDsc.strings.psd1 @@ -0,0 +1,25 @@ +# Localized resources for NetworkingDsc + +ConvertFrom-StringData @' + # Find-NetworkAdapter + AllNetAdaptersFoundMessage = Found all network adapters because no filter parameters provided. (NET0002) + FindingNetAdapterMessage = Finding network adapters matching the parameters. (NET0001) + NetAdapterNotFoundError = A network adapter matching the parameters was not found. Please correct the properties and try again. (NET0004) + NetAdapterFoundMessage = {0} network adapters were found matching the parameters. (NET0003) + InvalidNetAdapterNumberError = network adapter interface number {0} was specified but only {1} was found. Please correct the interface number and try again. (NET0007) + MultipleMatchingNetAdapterFound = Please adjust the parameters or specify IgnoreMultipleMatchingAdapters to only use the first and try again. (NET0006) + + # Get-DnsClientServerStaticAddress + GettingDNSServerStaticAddressMessage = Getting statically assigned DNS server {0} address for interface alias '{1}'. (NET0008) + InterfaceAliasNotFoundError = A network adapter with the alias '{0}' could not be found. (NET0005) + DNSServerStaticAddressNotSetMessage = Statically assigned DNS server {0} address for interface alias '{1}' is not set. (NET0011) + DNSServerStaticAddressFoundMessage = Statically assigned DNS server {0} address for interface alias '{1}' is '{2}'. (NET0013) + + # Get-WinsClientServerStaticAddress + GettingWinsServerStaticAddressMessage = Getting statically assigned WINS server address for interface alias '{0}'. (NET0009) + WinsServerStaticAddressNotSetMessage = Statically assigned WINS server address for interface alias '{0}' is not set. (NET0012) + WinsServerStaticAddressFoundMessage = Statically assigned WINS server address for interface alias '{0}' is '{1}'. (NET0014) + + # Set-WinsClientServerStaticAddress + SettingWinsServerStaticAddressMessage = Setting statically assigned WINS server address for interface alias '{0}' to '{1}'. (NET0010) +'@ diff --git a/source/prefix.ps1 b/source/prefix.ps1 new file mode 100644 index 00000000..e142f8f6 --- /dev/null +++ b/source/prefix.ps1 @@ -0,0 +1,5 @@ +# Import nested, 'DscResource.Common' module +$script:dscResourceCommonModulePath = Join-Path -Path $PSScriptRoot -ChildPath 'Modules\DscResource.Common' +Import-Module -Name $script:dscResourceCommonModulePath + +$script:localizedData = Get-LocalizedData -DefaultUICulture 'en-US' diff --git a/tests/Integration/DSC_DNSConnectionSuffix.Integration.Tests.ps1 b/tests/Integration/DSC_DNSConnectionSuffix.Integration.Tests.ps1 index 92d4eebe..fdd83876 100644 --- a/tests/Integration/DSC_DNSConnectionSuffix.Integration.Tests.ps1 +++ b/tests/Integration/DSC_DNSConnectionSuffix.Integration.Tests.ps1 @@ -1,66 +1,100 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_DnsConnectionSuffix' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'DnsConnectionSuffix' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'DnsConnectionSuffix' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'DnsConnectionSuffix Integration Tests' { +Describe 'DnsConnectionSuffix Integration Tests' { + BeforeAll { # Configure Loopback Adapter New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop + . $configFile + } - Describe "$($script:dscResourceName)_Integration" { - It 'Should compile without throwing' { - { - & "$($script:dscResourceName)_Config" -OutputPath $TestDrive - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force - } | Should -Not -Throw - } + AfterAll { + # Remove Loopback Adapter + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' + } - It 'should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + Describe "$($script:dscResourceName)_Integration" { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile without throwing' { + { + & "$($script:dscResourceName)_Config" -OutputPath $TestDrive + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $current.InterfaceAlias | Should -Be $TestDnsConnectionSuffix.InterfaceAlias - $current.ConnectionSpecificSuffix | Should -Be $TestDnsConnectionSuffix.ConnectionSpecificSuffix - $current.RegisterThisConnectionsAddress | Should -Be $TestDnsConnectionSuffix.RegisterThisConnectionsAddress - $current.Ensure | Should -Be $TestDnsConnectionSuffix.Ensure + It 'should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + $current.InterfaceAlias | Should -Be $TestDnsConnectionSuffix.InterfaceAlias + $current.ConnectionSpecificSuffix | Should -Be $TestDnsConnectionSuffix.ConnectionSpecificSuffix + $current.RegisterThisConnectionsAddress | Should -Be $TestDnsConnectionSuffix.RegisterThisConnectionsAddress + $current.Ensure | Should -Be $TestDnsConnectionSuffix.Ensure } } } -finally -{ - # Remove Loopback Adapter - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_DefaultGatewayAddress.Integration.Tests.ps1 b/tests/Integration/DSC_DefaultGatewayAddress.Integration.Tests.ps1 index b725b0fa..cd9cc18b 100644 --- a/tests/Integration/DSC_DefaultGatewayAddress.Integration.Tests.ps1 +++ b/tests/Integration/DSC_DefaultGatewayAddress.Integration.Tests.ps1 @@ -1,65 +1,99 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_DefaultGatewayAddress' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'DefaultGatewayAddress' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'DefaultGatewayAddress' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'DefaultGatewayAddress Integration Tests' { +Describe 'DefaultGatewayAddress Integration Tests' { + BeforeAll { # Configure Loopback Adapter New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop + . $configFile + } - Describe "$($script:dscResourceName)_Integration" { - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" -OutputPath $TestDrive - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force - } | Should -Not -Throw - } + AfterAll { + # Remove Loopback Adapter + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + Describe "$($script:dscResourceName)_Integration" { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" -OutputPath $TestDrive + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $current.InterfaceAlias | Should -Be $TestDefaultGatewayAddress.InterfaceAlias - $current.AddressFamily | Should -Be $TestDefaultGatewayAddress.AddressFamily - $current.Address | Should -Be $TestDefaultGatewayAddress.Address + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + $current.InterfaceAlias | Should -Be $TestDefaultGatewayAddress.InterfaceAlias + $current.AddressFamily | Should -Be $TestDefaultGatewayAddress.AddressFamily + $current.Address | Should -Be $TestDefaultGatewayAddress.Address } } } -finally -{ - # Remove Loopback Adapter - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_DnsClientGlobalSetting.Integration.Tests.ps1 b/tests/Integration/DSC_DnsClientGlobalSetting.Integration.Tests.ps1 index 4a4c7b0f..e1e6c118 100644 --- a/tests/Integration/DSC_DnsClientGlobalSetting.Integration.Tests.ps1 +++ b/tests/Integration/DSC_DnsClientGlobalSetting.Integration.Tests.ps1 @@ -1,35 +1,59 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_DnsClientGlobalSetting' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' -} -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'DnsClientGlobalSetting' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'DnsClientGlobalSetting' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' -# Load the parameter List from the data file -$moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) -$resourceData = Import-LocalizedData ` - -BaseDirectory (Join-Path -Path $moduleRoot -ChildPath 'Source\DscResources\DSC_DnsClientGlobalSetting') ` - -FileName 'DSC_DnsClientGlobalSetting.data.psd1' + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +} -$parameterList = $resourceData.ParameterList | Where-Object -Property IntTest -eq $True +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -# Begin Testing -try -{ - Describe 'DnsClientGlobalSetting Integration Tests' { + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} + +Describe 'DnsClientGlobalSetting Integration Tests' { + BeforeAll { # Backup the existing settings $script:currentDnsClientGlobalSetting = Get-DnsClientGlobalSetting @@ -52,49 +76,55 @@ try $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" . $configFile + } - Describe "$($script:dscResourceName)_Integration" { - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force - } | Should -Not -Throw - } + AfterAll { + # Clean up + Set-DnsClientGlobalSetting ` + -SuffixSearchList $script:currentDnsClientGlobalSetting.SuffixSearchList ` + -UseDevolution $script:currentDnsClientGlobalSetting.UseDevolution ` + -DevolutionLevel $script:currentDnsClientGlobalSetting.DevolutionLevel + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + Describe "$($script:dscResourceName)_Integration" { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - # Get the DNS Client Global Settings details - $dnsClientGlobalSettingNew = Get-DnsClientGlobalSetting + Context 'When testing each of the parameter values' { + BeforeAll { + # Get the DNS Client Global Settings details + $dnsClientGlobalSettingNew = Get-DnsClientGlobalSetting + } - # Use the Parameters List to perform these tests - foreach ($parameter in $parameterList) - { - $parameterCurrentValue = (Get-Variable -Name 'dnsClientGlobalSettingNew').value.$($parameter.name) - $parameterNewValue = (Get-Variable -Name configData).Value.AllNodes[0].$($parameter.Name) + It 'Should have the correct value for <_>' -ForEach @( + 'SuffixSearchList', + 'UseDevolution', + 'DevolutionLevel' + ) { + $parameterCurrentValue = (Get-Variable -Name dnsClientGlobalSettingNew).value.$_ + $parameterNewValue = (Get-Variable -Name configData).Value.AllNodes[0].$_ - It "Should have set the '$parameterName' to '$parameterNewValue'" { - $parameterCurrentValue | Should -Be $parameterNewValue - } + $parameterCurrentValue | Should -Be $parameterNewValue } } } } -finally -{ - # Clean up - Set-DnsClientGlobalSetting ` - -SuffixSearchList $script:currentDnsClientGlobalSetting.SuffixSearchList ` - -UseDevolution $script:currentDnsClientGlobalSetting.UseDevolution ` - -DevolutionLevel $script:currentDnsClientGlobalSetting.DevolutionLevel - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_DnsServerAddress.Integration.Tests.ps1 b/tests/Integration/DSC_DnsServerAddress.Integration.Tests.ps1 index 77b7b301..7cdc20d3 100644 --- a/tests/Integration/DSC_DnsServerAddress.Integration.Tests.ps1 +++ b/tests/Integration/DSC_DnsServerAddress.Integration.Tests.ps1 @@ -1,165 +1,212 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_DnsServerAddress' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'DnsServerAddress' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'DnsServerAddress' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'DnsServerAddress Integration Tests' { +Describe 'DnsServerAddress Integration Tests' { + BeforeAll { # Configure Loopback Adapter New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_Static.config.ps1" - . $configFile -Verbose -ErrorAction Stop - - Describe "$($script:dscResourceName)_Integration using single address" { - It 'Should compile and apply the MOF without throwing' { - { - # This is to pass to the Config - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - InterfaceAlias = 'NetworkingDscLBA' - AddressFamily = 'IPv4' - Address = '10.139.17.99' - Validate = $False - } - ) - } - - & "$($script:dscResourceName)_Config_Static" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration -Path $TestDrive ` - -ComputerName localhost -Wait -Verbose -Force - } | Should -Not -Throw - } + . $configFile + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + AfterAll { + # Remove Loopback Adapter + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' + } + + Describe "$($script:dscResourceName)_Integration using single address" { + AfterEach { + Wait-ForIdleLcm + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Static" + It 'Should compile and apply the MOF without throwing' { + { + # This is to pass to the Config + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = 'NetworkingDscLBA' + AddressFamily = 'IPv4' + Address = '10.139.17.99' + Validate = $False + } + ) } - $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' - $current.AddressFamily | Should -Be 'IPv4' - $current.Address.Count | Should -Be 1 - $current.Address | Should -Be '10.139.17.99' - } + + & "$($script:dscResourceName)_Config_Static" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration -Path $TestDrive ` + -ComputerName localhost -Wait -Verbose -Force + } | Should -Not -Throw } - Describe "$($script:dscResourceName)_Integration using two addresses" { - It 'Should compile and apply the MOF without throwing' { - { - # This is to pass to the Config - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - InterfaceAlias = 'NetworkingDscLBA' - AddressFamily = 'IPv4' - Address = @('10.139.17.99','10.139.17.100') - Validate = $False - } - ) - } - - & "$($script:dscResourceName)_Config_Static" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force - } | Should -Not -Throw - } + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Static" } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Static" + $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' + $current.AddressFamily | Should -Be 'IPv4' + $current.Address.Count | Should -Be 1 + $current.Address | Should -Be '10.139.17.99' + } + } + + Describe "$($script:dscResourceName)_Integration using two addresses" { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + # This is to pass to the Config + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = 'NetworkingDscLBA' + AddressFamily = 'IPv4' + Address = @('10.139.17.99', '10.139.17.100') + Validate = $False + } + ) } - $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' - $current.AddressFamily | Should -Be 'IPv4' - $current.Address.Count | Should -Be 2 - $current.Address[0] | Should -Be '10.139.17.99' - $current.Address[1] | Should -Be '10.139.17.100' - } + + & "$($script:dscResourceName)_Config_Static" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force + } | Should -Not -Throw } - $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_DHCP.config.ps1" - . $configFile -Verbose -ErrorAction Stop - - Describe "$($script:dscResourceName)_Integration using no addresses" { - It 'Should compile and apply the MOF without throwing' { - { - # This is to pass to the Config - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - InterfaceAlias = 'NetworkingDscLBA' - AddressFamily = 'IPv4' - } - ) - } - - & "$($script:dscResourceName)_Config_DHCP" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force - } | Should -Not -Throw - } + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Static" } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config_DHCP" + $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' + $current.AddressFamily | Should -Be 'IPv4' + $current.Address.Count | Should -Be 2 + $current.Address[0] | Should -Be '10.139.17.99' + $current.Address[1] | Should -Be '10.139.17.100' + } + } + + Describe "$($script:dscResourceName)_Integration using no addresses" { + BeforeAll { + $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_DHCP.config.ps1" + . $configFile -Verbose -ErrorAction Stop + } + + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + # This is to pass to the Config + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = 'NetworkingDscLBA' + AddressFamily = 'IPv4' + } + ) } - $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' - $current.AddressFamily | Should -Be 'IPv4' - $current.Address.Count | Should -Be 0 - $current.Address | Should -BeNullOrEmpty + + & "$($script:dscResourceName)_Config_DHCP" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config_DHCP" } + + $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' + $current.AddressFamily | Should -Be 'IPv4' + $current.Address.Count | Should -Be 0 + $current.Address | Should -BeNullOrEmpty } } } -finally -{ - # Remove Loopback Adapter - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_Firewall.Integration.Tests.ps1 b/tests/Integration/DSC_Firewall.Integration.Tests.ps1 index bbfa9782..c0474415 100644 --- a/tests/Integration/DSC_Firewall.Integration.Tests.ps1 +++ b/tests/Integration/DSC_Firewall.Integration.Tests.ps1 @@ -1,35 +1,59 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_Firewall' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' -} -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'Firewall' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'Firewall' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +} -# Load the parameter List from the data file -$moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) -$resourceData = Import-LocalizedData ` - -BaseDirectory (Join-Path -Path $moduleRoot -ChildPath 'Source\DscResources\DSC_DnsClientGlobalSetting') ` - -FileName 'DSC_DnsClientGlobalSetting.data.psd1' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -$parameterList = $resourceData.ParameterList | Where-Object -Property IntTest -eq $True + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'Firewall Integration Tests' { +Describe 'Firewall Integration Tests' { + BeforeAll { # Create a config data object to pass to the Add Rule Config $script:ruleNameGuid = [Guid]::NewGuid().ToString() $script:ruleName = $script:ruleNameGuid + '[]*' @@ -77,65 +101,157 @@ try $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_add.config.ps1" . $configFile + } - Describe "$($script:dscResourceName)_Add_Integration" { - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Add_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw + AfterAll { + if (Get-NetFirewallRule -Name $script:ruleNameEscaped -ErrorAction SilentlyContinue) + { + Remove-NetFirewallRule -Name $script:ruleNameEscaped + } + } + + Describe "$($script:dscResourceName)_Add_Integration" { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Add_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { $script:current = Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + Context 'DSC resource state' { + BeforeDiscovery { + $arrayTestCases = @( + @{ Name = 'Profile'; Variable = 'FirewallRule'; Type = 'Array'; Delimiter = ', ' } + @{ Name = 'RemotePort'; Variable = 'properties'; Property = 'PortFilters'; Type = 'Array' } + @{ Name = 'LocalPort'; Variable = 'properties'; Property = 'PortFilters'; Type = 'Array' } + @{ Name = 'InterfaceAlias'; Variable = 'properties'; Property = 'InterfaceFilters'; Type = 'Array' } + @{ Name = 'Platform'; Variable = 'FirewallRule'; Type = 'Array' } + @{ Name = 'IcmpType'; Variable = 'properties'; Property = 'PortFilters'; Type = 'Array' } + ) + + $arrayIpTestCases = @( + @{ Name = 'LocalAddress'; Variable = 'properties'; Property = 'AddressFilters'; Type = 'ArrayIP' } + @{ Name = 'RemoteAddress'; Variable = 'properties'; Property = 'AddressFilters'; Type = 'ArrayIP' } + ) + + $remainingTestCases = @( + @{ Name = 'DisplayName'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'Group'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'DisplayGroup'; Variable = 'FirewallRule'; Type = '' } + @{ Name = 'Enabled'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'Action'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'Direction'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'Description'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'Protocol'; Variable = 'properties'; Property = 'PortFilters'; Type = 'String' } + @{ Name = 'Program'; Variable = 'properties'; Property = 'ApplicationFilters'; Type = 'String' } + @{ Name = 'Service'; Variable = 'properties'; Property = 'ServiceFilters'; Type = 'String' } + @{ Name = 'Authentication'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'String' } + @{ Name = 'Encryption'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'String' } + @{ Name = 'InterfaceType'; Variable = 'properties'; Property = 'InterfaceTypeFilters'; Type = 'String' } + @{ Name = 'LocalUser'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'String' } + @{ Name = 'Package'; Variable = 'properties'; Property = 'ApplicationFilters'; Type = 'String' } + @{ Name = 'RemoteMachine'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'String' } + @{ Name = 'RemoteUser'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'String' } + @{ Name = 'DynamicTransport'; Variable = 'properties'; Property = 'PortFilters'; Type = 'String' } + @{ Name = 'EdgeTraversalPolicy'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'LocalOnlyMapping'; Variable = 'FirewallRule'; Type = 'Boolean' } + @{ Name = 'LooseSourceMapping'; Variable = 'FirewallRule'; Type = 'Boolean' } + @{ Name = 'OverrideBlockRules'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'Boolean' } + @{ Name = 'Owner'; Variable = 'FirewallRule'; Type = 'String' } + ) } - It 'Should be able to call Get-DscConfiguration without throwing' { - { $script:current = Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + # Array + It 'Should have set the parameter ''''' -ForEach $arrayTestCases { + $parameterValue = $Current.$Name + + $parameterNew = (Get-Variable -Name configData).Value.AllNodes[0].$Name + + $parameterValue | Should -Be $parameterNew } - Context 'DSC resource state' { - # Use the Parameters List to perform these tests - foreach ($parameter in $parameterList) + # ArrayIP + It "Should have set the '' array item correctly" -ForEach $arrayIpTestCases { + $parameterValue = $Current.$Name + + $parameterNew = (Get-Variable -Name configData).Value.AllNodes[0].$Name + + for ([int] $entry = 0; $entry -lt $parameterNew.Count; $entry++) { - $parameterName = $parameter.Name - - if ($parameterName -ne 'Name') - { - $parameterValue = $Current.$($parameter.Name) - - $parameterNew = (Get-Variable -Name configData).Value.AllNodes[0].$($parameter.Name) - - if ($parameter.Type -eq 'Array' -and $parameter.Delimiter) - { - It "Should have set the '$parameterName' to '$parameterNew'" { - $parameterValue | Should -Be $parameterNew - } - } - elseif ($parameter.Type -eq 'ArrayIP') - { - for ([int] $entry = 0; $entry -lt $parameterNew.Count; $entry++) - { - It "Should have set the '$parameterName' arry item $entry to '$($parameterNew[$entry])'" { - $parameterValue[$entry] | Should -Be (Convert-CIDRToSubhetMask -Address $parameterNew[$entry]) - } - } - } - else - { - It "Should have set the '$parameterName' to '$parameterNew'" { - $parameterValue | Should -Be $parameterNew - } - } - } + $parameterValue[$entry] | Should -Be (Convert-CIDRToSubnetMask -Address $parameterNew[$entry]) } } - Context 'The current firewall rule state' { + # Other + It 'Should have set the parameter ''''' -ForEach $remainingTestCases { + $parameterValue = $Current.$Name + + $parameterNew = (Get-Variable -Name configData).Value.AllNodes[0].$Name + + $parameterValue | Should -Be $parameterNew + } + } + + Context 'The current firewall rule state' { + BeforeDiscovery { + $arrayTestCases = @( + @{ Name = 'Profile'; Variable = 'FirewallRule'; Type = 'Array'; Delimiter = ', ' } + @{ Name = 'RemotePort'; Variable = 'properties'; Property = 'PortFilters'; Type = 'Array' } + @{ Name = 'LocalPort'; Variable = 'properties'; Property = 'PortFilters'; Type = 'Array' } + @{ Name = 'InterfaceAlias'; Variable = 'properties'; Property = 'InterfaceFilters'; Type = 'Array' } + @{ Name = 'Platform'; Variable = 'FirewallRule'; Type = 'Array' } + @{ Name = 'IcmpType'; Variable = 'properties'; Property = 'PortFilters'; Type = 'Array' } + ) + + $arrayIpTestCases = @( + @{ Name = 'LocalAddress'; Variable = 'properties'; Property = 'AddressFilters'; Type = 'ArrayIP' } + @{ Name = 'RemoteAddress'; Variable = 'properties'; Property = 'AddressFilters'; Type = 'ArrayIP' } + ) + + $remainingTestCases = @( + @{ Name = 'DisplayName'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'Group'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'DisplayGroup'; Variable = 'FirewallRule'; Type = '' } + @{ Name = 'Enabled'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'Action'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'Direction'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'Description'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'Protocol'; Variable = 'properties'; Property = 'PortFilters'; Type = 'String' } + @{ Name = 'Program'; Variable = 'properties'; Property = 'ApplicationFilters'; Type = 'String' } + @{ Name = 'Service'; Variable = 'properties'; Property = 'ServiceFilters'; Type = 'String' } + @{ Name = 'Authentication'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'String' } + @{ Name = 'Encryption'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'String' } + @{ Name = 'InterfaceType'; Variable = 'properties'; Property = 'InterfaceTypeFilters'; Type = 'String' } + @{ Name = 'LocalUser'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'String' } + @{ Name = 'Package'; Variable = 'properties'; Property = 'ApplicationFilters'; Type = 'String' } + @{ Name = 'RemoteMachine'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'String' } + @{ Name = 'RemoteUser'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'String' } + @{ Name = 'DynamicTransport'; Variable = 'properties'; Property = 'PortFilters'; Type = 'String' } + @{ Name = 'EdgeTraversalPolicy'; Variable = 'FirewallRule'; Type = 'String' } + @{ Name = 'LocalOnlyMapping'; Variable = 'FirewallRule'; Type = 'Boolean' } + @{ Name = 'LooseSourceMapping'; Variable = 'FirewallRule'; Type = 'Boolean' } + @{ Name = 'OverrideBlockRules'; Variable = 'properties'; Property = 'SecurityFilters'; Type = 'Boolean' } + @{ Name = 'Owner'; Variable = 'FirewallRule'; Type = 'String' } + ) + } + + BeforeAll { # Get the Rule details $firewallRule = Get-NetFireWallRule -Name $script:ruleNameEscaped @@ -149,101 +265,110 @@ try SecurityFilters = @(Get-NetFirewallSecurityFilter -AssociatedNetFirewallRule $FirewallRule) ServiceFilters = @(Get-NetFirewallServiceFilter -AssociatedNetFirewallRule $FirewallRule) } + } + + # Array Test + It "Should have set the '' property correctly" -ForEach $arrayTestCases { + if ($Property) + { + $parameterValue = (Get-Variable -Name $Variable).value.$Property.$Name + } + else + { + $parameterValue = (Get-Variable -Name $Variable).value.$Name + } - # Use the Parameters List to perform these tests - foreach ($parameter in $parameterList) + $parameterNew = (Get-Variable -Name configData).Value.AllNodes[0].$Name + + if ($Delimiter) { - $parameterName = $parameter.Name - - if ($parameterName -ne 'Name') - { - if ($parameter.Property) - { - $parameterValue = (Get-Variable -Name ($parameter.Variable)).value.$($parameter.Property).$($parameter.Name) - } - else - { - $parameterValue = (Get-Variable -Name ($parameter.Variable)).value.$($parameter.Name) - } - - $parameterNew = (Get-Variable -Name configData).Value.AllNodes[0].$($parameter.Name) - - if ($parameter.Type -eq 'Array' -and $parameter.Delimiter) - { - $parameterNew = $parameterNew -join $parameter.Delimiter - - It "Should have set the '$parameterName' to '$parameterNew'" { - $parameterValue | Should -Be $parameterNew - } - } - elseif ($parameter.Type -eq 'ArrayIP') - { - for ([int] $entry = 0; $entry -lt $parameterNew.Count; $entry++) - { - It "Should have set the '$parameterName' arry item $entry to '$($parameterNew[$entry])'" { - $parameterValue[$entry] | Should -Be (Convert-CIDRToSubhetMask -Address $parameterNew[$entry]) - } - } - } - else - { - It "Should have set the '$parameterName' to '$parameterNew'" { - $parameterValue | Should -Be $parameterNew - } - } - } + $parameterNew = $parameterNew -join $Delimiter } + + $parameterValue | Should -Be $parameterNew } - } - # Modify the config data object to pass to the Remove Rule Config - $configData.AllNodes[0].Ensure = 'Absent' + # ArrayIP + It "Should have set the '' property correctly" -ForEach $arrayIpTestCases { + if ($Property) + { + $parameterValue = (Get-Variable -Name $Variable).value.$Property.$Name + } + else + { + $parameterValue = (Get-Variable -Name $Variable).value.$Name + } - $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_remove.config.ps1" - . $configFile + $parameterNew = (Get-Variable -Name configData).Value.AllNodes[0].$Name - Describe "$($script:dscResourceName)_Remove_Integration" { - It 'Should compile and apply the MOF without throwing' { + for ([int] $entry = 0; $entry -lt $parameterNew.Count; $entry++) { - & "$($script:dscResourceName)_Remove_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw + $parameterValue[$entry] | Should -Be (Convert-CIDRToSubnetMask -Address $parameterNew[$entry]) + } } - It 'Should be able to call Get-DscConfiguration without throwing' { - { $script:current = Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + # Other + It "Should have set the '' property correctly" -ForEach $remainingTestCases { + if ($Property) + { + $parameterValue = (Get-Variable -Name $Variable).value.$Property.$Name + } + else + { + $parameterValue = (Get-Variable -Name $Variable).value.$Name + } + + $parameterNew = (Get-Variable -Name configData).Value.AllNodes[0].$Name + + $parameterValue | Should -Be $parameterNew } + } + } - Context 'DSC resource state' { - It 'Should return the expected values' { - $script:current.Ensure | Should -Be 'Absent' - } + Describe "$($script:dscResourceName)_Remove_Integration" { + BeforeAll { + # Modify the config data object to pass to the Remove Rule Config + $configData.AllNodes[0].Ensure = 'Absent' + + $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_remove.config.ps1" + . $configFile + } + + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Remove_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { $script:current = Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + Context 'DSC resource state' { + It 'Should return the expected values' { + $script:current.Ensure | Should -Be 'Absent' } + } - Context 'The current firewall rule state' { - It 'Should have deleted the rule' { - # Get the Rule details - $firewallRule = Get-NetFireWallRule -Name $script:ruleNameEscaped -ErrorAction SilentlyContinue - $firewallRule | Should -BeNullOrEmpty - } + Context 'The current firewall rule state' { + It 'Should have deleted the rule' { + # Get the Rule details + $firewallRule = Get-NetFireWallRule -Name $script:ruleNameEscaped -ErrorAction SilentlyContinue + $firewallRule | Should -BeNullOrEmpty } } } } -finally -{ - if (Get-NetFirewallRule -Name $script:ruleNameEscaped -ErrorAction SilentlyContinue) - { - Remove-NetFirewallRule -Name $script:ruleNameEscaped - } - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_FirewallProfile.Integration.Tests.ps1 b/tests/Integration/DSC_FirewallProfile.Integration.Tests.ps1 index af00776c..b1e0f37d 100644 --- a/tests/Integration/DSC_FirewallProfile.Integration.Tests.ps1 +++ b/tests/Integration/DSC_FirewallProfile.Integration.Tests.ps1 @@ -1,35 +1,59 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_FirewallProfile' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' -} -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'FirewallProfile' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'FirewallProfile' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' -# Load the parameter List from the data file -$moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) -$resourceData = Import-LocalizedData ` - -BaseDirectory (Join-Path -Path $moduleRoot -ChildPath 'Source\DscResources\DSC_FirewallProfile') ` - -FileName 'DSC_FirewallProfile.data.psd1' + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +} -$parameterList = $resourceData.ParameterList | Where-Object -Property IntTest -eq $True +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -# Begin Testing -try -{ - Describe 'FirewallProfile Integration Tests' { + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} + +Describe 'FirewallProfile Integration Tests' { + BeforeAll { # Backup the existing settings $script:firewallProfileName = 'Public' $script:currentFirewallProfile = Get-NetFirewallProfile -Name $script:firewallProfileName @@ -88,64 +112,87 @@ try $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" . $configFile + } - Describe "$($script:dscResourceName)_Integration" { - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration ` - -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force - } | Should -Not -Throw - } + AfterAll { + # Clean up + Set-NetFirewallProfile ` + -Name $script:firewallProfileName ` + -Enabled $script:currentFirewallProfile.Enabled ` + -DefaultInboundAction $script:currentFirewallProfile.DefaultInboundAction ` + -DefaultOutboundAction $script:currentFirewallProfile.DefaultOutboundAction ` + -AllowInboundRules $script:currentFirewallProfile.AllowInboundRules ` + -AllowLocalFirewallRules $script:currentFirewallProfile.AllowLocalFirewallRules ` + -AllowLocalIPsecRules $script:currentFirewallProfile.AllowLocalIPsecRules ` + -AllowUserApps $script:currentFirewallProfile.AllowUserApps ` + -AllowUserPorts $script:currentFirewallProfile.AllowUserPorts ` + -AllowUnicastResponseToMulticast $script:currentFirewallProfile.AllowUnicastResponseToMulticast ` + -NotifyOnListen $script:currentFirewallProfile.NotifyOnListen ` + -EnableStealthModeForIPsec $script:currentFirewallProfile.EnableStealthModeForIPsec ` + -LogFileName $script:currentFirewallProfile.LogFileName ` + -LogMaxSizeKilobytes $script:currentFirewallProfile.LogMaxSizeKilobytes ` + -LogAllowed $script:currentFirewallProfile.LogAllowed ` + -LogBlocked $script:currentFirewallProfile.LogBlocked ` + -LogIgnored $script:currentFirewallProfile.LogIgnored ` + -DisabledInterfaceAliases $script:currentFirewallProfile.DisabledInterfaceAliases + + # Remove Loopback Adapter + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' + } + + Describe "$($script:dscResourceName)_Integration" { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration ` + -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + Context 'When checking the parameters' { + BeforeDiscovery { + $testCases = @( + 'AllowInboundRules', + 'AllowLocalFirewallRules', + 'AllowLocalIPsecRules', + 'AllowUnicastResponseToMulticast', + 'AllowUserApps', + 'AllowUserPorts', + 'DefaultInboundAction', + 'DefaultOutboundAction', + 'DisabledInterfaceAliases', + 'Enabled', + 'EnableStealthModeForIPsec', + 'LogAllowed', + 'LogBlocked', + 'LogFileName', + 'LogIgnored', + 'LogMaxSizeKilobytes', + 'NotifyOnListen' + ) } - # Get the DNS Client Global Settings details - $firewallProfileNew = Get-NetFirewallProfile -Name $script:firewallProfileName + BeforeAll { + # Get the DNS Client Global Settings details + $firewallProfileNew = Get-NetFirewallProfile -Name $script:firewallProfileName + } - # Use the Parameters List to perform these tests - foreach ($parameter in $parameterList) - { - $parameterName = $parameter.name - $parameterCurrentValue = (Get-Variable -Name 'firewallProfileNew').value.$($parameter.name) - $parameterNewValue = (Get-Variable -Name configData).Value.AllNodes[0].$($parameter.Name) + It 'Should have set parameter <_> correctly' -ForEach $testCases { + $parameterCurrentValue = (Get-Variable -Name 'firewallProfileNew').value.$_ + $parameterNewValue = (Get-Variable -Name configData).Value.AllNodes[0].$_ - It "Should have set the '$parameterName' to '$parameterNewValue'" { - $parameterCurrentValue | Should -Be $parameterNewValue - } + $parameterCurrentValue | Should -Be $parameterNewValue } } } } -finally -{ - # Clean up - Set-NetFirewallProfile ` - -Name $script:firewallProfileName ` - -Enabled $script:currentFirewallProfile.Enabled ` - -DefaultInboundAction $script:currentFirewallProfile.DefaultInboundAction ` - -DefaultOutboundAction $script:currentFirewallProfile.DefaultOutboundAction ` - -AllowInboundRules $script:currentFirewallProfile.AllowInboundRules ` - -AllowLocalFirewallRules $script:currentFirewallProfile.AllowLocalFirewallRules ` - -AllowLocalIPsecRules $script:currentFirewallProfile.AllowLocalIPsecRules ` - -AllowUserApps $script:currentFirewallProfile.AllowUserApps ` - -AllowUserPorts $script:currentFirewallProfile.AllowUserPorts ` - -AllowUnicastResponseToMulticast $script:currentFirewallProfile.AllowUnicastResponseToMulticast ` - -NotifyOnListen $script:currentFirewallProfile.NotifyOnListen ` - -EnableStealthModeForIPsec $script:currentFirewallProfile.EnableStealthModeForIPsec ` - -LogFileName $script:currentFirewallProfile.LogFileName ` - -LogMaxSizeKilobytes $script:currentFirewallProfile.LogMaxSizeKilobytes ` - -LogAllowed $script:currentFirewallProfile.LogAllowed ` - -LogBlocked $script:currentFirewallProfile.LogBlocked ` - -LogIgnored $script:currentFirewallProfile.LogIgnored ` - -DisabledInterfaceAliases $script:currentFirewallProfile.DisabledInterfaceAliases - - # Remove Loopback Adapter - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_HostsFile.Integration.Tests.ps1 b/tests/Integration/DSC_HostsFile.Integration.Tests.ps1 index 20d5e621..4cd0b926 100644 --- a/tests/Integration/DSC_HostsFile.Integration.Tests.ps1 +++ b/tests/Integration/DSC_HostsFile.Integration.Tests.ps1 @@ -1,30 +1,72 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_HostsFile' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'HostsFile' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'HostsFile' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +Describe 'HostsFile Integration Tests' { + BeforeAll { + $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" + . $configFile -# Begin Testing -try -{ - Describe 'HostsFile Integration Tests' { Copy-Item -Path "${env:SystemRoot}\System32\Drivers\Etc\Hosts" -Destination "${env:Temp}\Hosts" -Force + } + + AfterAll { + # Restore unmodified hosts file + Copy-Item "${env:Temp}\Hosts" "${env:SystemRoot}\System32\Drivers\Etc\Hosts" -Force + } - Describe "$($script:dscResourceName)_Integration - Add Single Line" { + Describe "$($script:dscResourceName)_Integration - Add Single Line" { + BeforeAll { $configData = @{ AllNodes = @( @{ @@ -35,35 +77,39 @@ try } ) } + } - $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop - - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration ` - -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force - } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration ` + -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $result.Ensure | Should -Be $configData.AllNodes[0].Ensure - $result.HostName | Should -Be $configData.AllNodes[0].HostName - $result.IPAddress | Should -Be $configData.AllNodes[0].IPAddress + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $result.Ensure | Should -Be $configData.AllNodes[0].Ensure + $result.HostName | Should -Be $configData.AllNodes[0].HostName + $result.IPAddress | Should -Be $configData.AllNodes[0].IPAddress } + } - Describe "$($script:dscResourceName)_Integration - Add Multiple Line" { + Describe "$($script:dscResourceName)_Integration - Add Multiple Line" { + BeforeAll { $configData = @{ AllNodes = @( @{ @@ -74,35 +120,39 @@ try } ) } + } - $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop - - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration ` - -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force - } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration ` + -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $result.Ensure | Should -Be $configData.AllNodes[0].Ensure - $result.HostName | Should -Be $configData.AllNodes[0].HostName - $result.IPAddress | Should -Be $configData.AllNodes[0].IPAddress + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $result.Ensure | Should -Be $configData.AllNodes[0].Ensure + $result.HostName | Should -Be $configData.AllNodes[0].HostName + $result.IPAddress | Should -Be $configData.AllNodes[0].IPAddress } + } - Describe "$($script:dscResourceName)_Integration - Remove Single Line" { + Describe "$($script:dscResourceName)_Integration - Remove Single Line" { + BeforeAll { $configData = @{ AllNodes = @( @{ @@ -113,39 +163,34 @@ try } ) } + } - $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop - - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration ` - -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force - } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration ` + -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $result.Ensure | Should -Be $configData.AllNodes[0].Ensure - $result.HostName | Should -Be $configData.AllNodes[0].HostName - $result.IPAddress | Should -BeNullOrEmpty + It 'Should have set the resource and all the parameters should match' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $result.Ensure | Should -Be $configData.AllNodes[0].Ensure + $result.HostName | Should -Be $configData.AllNodes[0].HostName + $result.IPAddress | Should -BeNullOrEmpty } } } -finally -{ - # Restore unmodified hosts file - Copy-Item "${env:Temp}\Hosts" "${env:SystemRoot}\System32\Drivers\Etc\Hosts" -Force - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_IPAddress.Integration.Tests.ps1 b/tests/Integration/DSC_IPAddress.Integration.Tests.ps1 index a319cc92..e4ad1020 100644 --- a/tests/Integration/DSC_IPAddress.Integration.Tests.ps1 +++ b/tests/Integration/DSC_IPAddress.Integration.Tests.ps1 @@ -1,42 +1,74 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_IPAddress' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' -} -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'IPAddress' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'IPAddress' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' -# Begin Testing -try -{ - Describe 'IPAddress Integration Tests' { - $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +} - BeforeAll { - New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA1' - New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA2' - } +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force - AfterAll { - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA1' - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA2' - } + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} + +Describe 'HostsFile Integration Tests' { + BeforeAll { + New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA1' + New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA2' + + $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" + . $configFile + } - Describe "$($script:dscResourceName)_Integration" { - Context 'When a single IP address is specified' { + AfterAll { + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA1' + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA2' + } + + Describe "$($script:dscResourceName)_Integration" { + Context 'When a single IP address is specified' { + BeforeAll { # This is to pass to the Config $configData = @{ AllNodes = @( @@ -48,49 +80,60 @@ try } ) } + } - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $current[0].InterfaceAlias | Should -Be $configData.AllNodes[0].InterfaceAlias - $current[0].AddressFamily | Should -Be $configData.AllNodes[0].AddressFamily - $current[0].IPAddress | Should -Be $configData.AllNodes[0].IPAddress + It 'should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $current[0].InterfaceAlias | Should -Be $configData.AllNodes[0].InterfaceAlias + $current[0].AddressFamily | Should -Be $configData.AllNodes[0].AddressFamily + $current[0].IPAddress | Should -Be $configData.AllNodes[0].IPAddress } } Context 'When a two IP addresses are specified' { - # This is to pass to the Config - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - InterfaceAlias = 'NetworkingDscLBA2' - AddressFamily = 'IPv4' - IPAddress = @('10.12.13.14/16', '10.13.14.16/32') - } - ) + BeforeAll { + # This is to pass to the Config + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = 'NetworkingDscLBA2' + AddressFamily = 'IPv4' + IPAddress = @('10.12.13.14/16', '10.13.14.16/32') + } + ) + } + } + + AfterEach { + Wait-ForIdleLcm } It 'Should compile and apply the MOF without throwing' { @@ -117,6 +160,7 @@ try $current = Get-DscConfiguration | Where-Object -FilterScript { $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + $current[0].InterfaceAlias | Should -Be $configData.AllNodes[0].InterfaceAlias $current[0].AddressFamily | Should -Be $configData.AllNodes[0].AddressFamily $current[0].IPAddress | Should -Contain $configData.AllNodes[0].IPAddress[0] @@ -125,7 +169,3 @@ try } } } -finally -{ - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_IPAddressOption.Integration.Tests.ps1 b/tests/Integration/DSC_IPAddressOption.Integration.Tests.ps1 index e299c64a..5634342f 100644 --- a/tests/Integration/DSC_IPAddressOption.Integration.Tests.ps1 +++ b/tests/Integration/DSC_IPAddressOption.Integration.Tests.ps1 @@ -1,68 +1,102 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_IPAddressOption' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'IPAddressOption' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'IPAddressOption' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'IPAddressOption Integration Tests' { +Describe 'IPAddressOption Integration Tests' { + BeforeAll { New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop + . $configFile + } - Describe "$($script:dscResourceName)_Integration" { - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" -OutputPath $TestDrive + AfterAll { + # Remove Loopback Adapter + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' + } - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + Describe "$($script:dscResourceName)_Integration" { + AfterEach { + Wait-ForIdleLcm + } - It 'should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" -OutputPath $TestDrive + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $current[0].InterfaceAlias | Should -Be $TestIPAddress.InterfaceAlias - $current[0].AddressFamily | Should -Be $TestIPAddress.AddressFamily - $current[0].IPAddress | Should -Be $TestIPAddress.IPAddress - $current[1].IPAddress | Should -Be $TestIPAddressOption.IPAddress - $current[1].SkipAsSource | Should -Be $TestIPAddressOption.SkipAsSource + It 'should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $current[0].InterfaceAlias | Should -Be $TestIPAddress.InterfaceAlias + $current[0].AddressFamily | Should -Be $TestIPAddress.AddressFamily + $current[0].IPAddress | Should -Be $TestIPAddress.IPAddress + $current[1].IPAddress | Should -Be $TestIPAddressOption.IPAddress + $current[1].SkipAsSource | Should -Be $TestIPAddressOption.SkipAsSource } } } -finally -{ - # Remove Loopback Adapter - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_NetAdapterBinding.Integration.Tests.ps1 b/tests/Integration/DSC_NetAdapterBinding.Integration.Tests.ps1 index ffc2b386..9c180a99 100644 --- a/tests/Integration/DSC_NetAdapterBinding.Integration.Tests.ps1 +++ b/tests/Integration/DSC_NetAdapterBinding.Integration.Tests.ps1 @@ -1,66 +1,100 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterBinding' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'NetAdapterBinding' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'NetAdapterBinding' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'NetAdapterBinding Integration Tests' { +Describe 'NetAdapterBinding Integration Tests' { + BeforeAll { New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop - - Describe "$($script:dscResourceName)_Integration" { - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" -OutputPath $TestDrive - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + . $configFile + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + AfterAll { + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' + } + + Describe "$($script:dscResourceName)_Integration" { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" -OutputPath $TestDrive + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $current.InterfaceAlias | Should -Be $TestDisableIPv4.InterfaceAlias - $current.ComponentId | Should -Be $TestDisableIPv4.ComponentId - $current.State | Should -Be $TestDisableIPv4.State + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $current.InterfaceAlias | Should -Be $TestDisableIPv4.InterfaceAlias + $current.ComponentId | Should -Be $TestDisableIPv4.ComponentId + $current.State | Should -Be $TestDisableIPv4.State } } } -finally -{ - # Remove Loopback Adapter - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_NetAdapterLso.Integration.Tests.ps1 b/tests/Integration/DSC_NetAdapterLso.Integration.Tests.ps1 index c5a1e90c..36e41d29 100644 --- a/tests/Integration/DSC_NetAdapterLso.Integration.Tests.ps1 +++ b/tests/Integration/DSC_NetAdapterLso.Integration.Tests.ps1 @@ -1,96 +1,135 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterLso' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' -} -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' -} +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'NetAdapterLso' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" -<# + <# To run these tests a network adapter that has NDIS version of 6 or greater. If this is not available then the tests will be skipped. -#> -$script:netAdapter = Get-NetAdapter | Where-Object -FilterScript { - $_.NdisVersion -ge 6 -} | Select-Object -First 1 - -if (-not $script:netAdapter) -{ - Write-Verbose -Message ('A network adapter with NDIS version of 6 or greater is required to run these tests. Integration tests will be skipped.') - return + #> + $script:netAdapter = Get-NetAdapter | Where-Object -FilterScript { + $_.NdisVersion -ge 6 + } | Select-Object -First 1 + + if (-not $script:netAdapter) + { + $script:skip = $true + } } -# Begin Testing -try -{ - Describe 'NetAdapterLso Integration Tests' { - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - Name = $script:netAdapter.Name - Protocol = 'IPv6' - State = $true - } - ) - } +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'NetAdapterLso' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + +} + +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} + +Describe 'NetAdapterLso Integration Tests' { + BeforeAll { + $script:netAdapter = Get-NetAdapter | Where-Object -FilterScript { + $_.NdisVersion -ge 6 + } | Select-Object -First 1 $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop - - Describe "$($script:dscResourceName)_Integration" { - It 'Should compile without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + . $configFile + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + Describe "$($script:dscResourceName)_Integration" { + BeforeAll { + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + Name = $script:netAdapter.Name + Protocol = 'IPv6' + State = $true + } + ) } + } - It 'Should be able to call Test-DscConfiguration without throwing' { - { $script:currentState = Test-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'Should report that DSC is in state' { - $script:currentState | Should -BeTrue - } + It 'Should compile without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $current.Name | Should -Be $configData.AllNodes[0].Name - $current.Protocol | Should -Be $configData.AllNodes[0].Protocol - $current.State | Should -Be $configData.AllNodes[0].State + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should be able to call Test-DscConfiguration without throwing' { + { $script:currentState = Test-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should report that DSC is in state' { + $script:currentState | Should -BeTrue + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $current.Name | Should -Be $configData.AllNodes[0].Name + $current.Protocol | Should -Be $configData.AllNodes[0].Protocol + $current.State | Should -Be $configData.AllNodes[0].State } } } -finally -{ - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_NetAdapterName.Integration.Tests.ps1 b/tests/Integration/DSC_NetAdapterName.Integration.Tests.ps1 index 5a854ee2..7a79f2ee 100644 --- a/tests/Integration/DSC_NetAdapterName.Integration.Tests.ps1 +++ b/tests/Integration/DSC_NetAdapterName.Integration.Tests.ps1 @@ -1,171 +1,202 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterName' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'NetAdapterName' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'NetAdapterName' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'NetAdapterName Integration Tests' { - Describe "$($script:dscResourceName)_Integration using all parameters" { - $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_all.config.ps1" - . $configFile -Verbose -ErrorAction Stop - BeforeAll { - New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - $adapter = Get-NetAdapter -Name 'NetworkingDscLBA' - } +Describe 'NetAdapterName Integration Tests' { + BeforeAll { + New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - AfterAll { - # Remove Loopback Adapter - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBANew' - } + $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_all.config.ps1" + . $configFile + } - It 'Should compile and apply the MOF without throwing' { - { - # This is to pass to the Config - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - NewName = 'NetworkingDscLBANew' - Name = $adapter.Name - PhysicalMediaType = $adapter.PhysicalMediaType - Status = $adapter.Status - MacAddress = $adapter.MacAddress - InterfaceDescription = $adapter.InterfaceDescription - InterfaceIndex = $adapter.InterfaceIndex - InterfaceGuid = $adapter.InterfaceGuid - } - ) - } - - & "$($script:dscResourceName)_Config_All" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + AfterAll { + # Remove Loopback Adapter + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBANew' + } - It 'Should reapply the MOF without throwing' { - { - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + Describe "$($script:dscResourceName)_Integration using all parameters" { + BeforeAll { + $adapter = Get-NetAdapter -Name 'NetworkingDscLBA' + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { - Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config_All" + It 'Should compile and apply the MOF without throwing' { + { + # This is to pass to the Config + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + NewName = 'NetworkingDscLBANew' + Name = $adapter.Name + PhysicalMediaType = $adapter.PhysicalMediaType + Status = $adapter.Status + MacAddress = $adapter.MacAddress + InterfaceDescription = $adapter.InterfaceDescription + InterfaceIndex = $adapter.InterfaceIndex + InterfaceGuid = $adapter.InterfaceGuid + } + ) } - $current.Name | Should -Be 'NetworkingDscLBANew' + + & "$($script:dscResourceName)_Config_All" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should reapply the MOF without throwing' { + { + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { + Get-DscConfiguration -Verbose -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config_All" } + + $current.Name | Should -Be 'NetworkingDscLBANew' } + } - Describe "$($script:dscResourceName)_Integration using name parameter only" { + Describe "$($script:dscResourceName)_Integration using name parameter only" { + BeforeAll { $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_nameonly.config.ps1" . $configFile -Verbose -ErrorAction Stop + } - BeforeAll { - New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - $adapter = Get-NetAdapter -Name 'NetworkingDscLBA' - } + AfterEach { + Wait-ForIdleLcm + } - AfterAll { - # Remove Loopback Adapter - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBANew' - } + It 'Should compile and apply the MOF without throwing' { + { + # This is to pass to the Config + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + NewName = 'NetworkingDscLBANew' + Name = $adapter.Name + } + ) + } - It 'Should compile and apply the MOF without throwing' { - { - # This is to pass to the Config - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - NewName = 'NetworkingDscLBANew' - Name = $adapter.Name - } - ) - } - - & "$($script:dscResourceName)_Config_NameOnly" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + & "$($script:dscResourceName)_Config_NameOnly" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } - It 'Should reapply the MOF without throwing' { - { - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + It 'Should reapply the MOF without throwing' { + { + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { - Get-DscConfiguration -Verbose -ErrorAction Stop - } | Should -Not -Throw - } + It 'Should be able to call Get-DscConfiguration without throwing' { + { + Get-DscConfiguration -Verbose -ErrorAction Stop + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config_NameOnly" - } - $current.Name | Should -Be 'NetworkingDscLBANew' + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config_NameOnly" } + + $current.Name | Should -Be 'NetworkingDscLBANew' } } } -finally -{ - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_NetAdapterRdma.Integration.Tests.ps1 b/tests/Integration/DSC_NetAdapterRdma.Integration.Tests.ps1 index 7822cda3..c927af96 100644 --- a/tests/Integration/DSC_NetAdapterRdma.Integration.Tests.ps1 +++ b/tests/Integration/DSC_NetAdapterRdma.Integration.Tests.ps1 @@ -11,97 +11,140 @@ testing, so do not specify an adapter used for connectivity to the test client. This is why these tests can not be executed in AppVeyor. #> -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterRdma' -$script:AdapterName = 'vEthernet (Default Switch)' -# Check the adapter selected for use in testing is RDMA compatible and preserve state -$script:adapterRDMAStatus = Get-NetAdapterRdma -Name $script:AdapterName -ErrorAction SilentlyContinue +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } -if (-not $script:adapterRDMAStatus) -{ - Write-Verbose -Message ('The network adapter selected for RDMA integration testing is not RDMA compatible. Integration tests will be skipped.') - return -} + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } -# Make sure RDMA is disabled on the selected adapter before running tests -Set-NetAdapterRdma -Name $script:AdapterName -Enabled $false + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'NetAdapterRdma' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + $AdapterName = 'vEthernet (Default Switch)' + + # Check the adapter selected for use in testing is RDMA compatible and preserve state + $adapterRDMAStatus = Get-NetAdapterRdma -Name $AdapterName -ErrorAction SilentlyContinue + + if (-not $adapterRDMAStatus) + { + $script:Skip = $true + } } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'NetAdapterRdma' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'NetAdapterName Integration Tests' { +Describe 'NetAdapterName Integration Tests' -Skip:$script:Skip { + BeforeAll { $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop - - # This is to pass to the Config - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - Name = $script:AdapterName - Enabled = $true - } - ) - } + . $configFile - Describe "$($script:dscResourceName)_Integration" { - AfterAll { - Set-NetAdapterRdma ` - -Name $configData.AllNodes[0].Name ` - -Enabled $false - } + $AdapterName = 'vEthernet (Default Switch)' - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + # Check the adapter selected for use in testing is RDMA compatible and preserve state + $adapterRDMAStatus = Get-NetAdapterRdma -Name $AdapterName -ErrorAction SilentlyContinue - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + # Make sure RDMA is disabled on the selected adapter before running tests + Set-NetAdapterRdma -Name $AdapterName -Enabled $false + } + + AfterAll { + Set-NetAdapterRdma -Name $AdapterName -Enabled $adapterRDMAStatus.Enabled + } + + Describe "$($script:dscResourceName)_Integration" { + BeforeAll { + # This is to pass to the Config + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + Name = $AdapterName + Enabled = $true + } + ) } + } + + AfterAll { + Set-NetAdapterRdma ` + -Name $configData.AllNodes[0].Name ` + -Enabled $false + } + + AfterEach { + Wait-ForIdleLcm + } - It 'Should have set the resource and all the parameters should match' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $result.Name | Should -Be $configData.AllNodes[0].Name - $result.Enabled | Should -Be $configData.AllNodes[0].Enabled + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $result.Name | Should -Be $configData.AllNodes[0].Name + $result.Enabled | Should -Be $configData.AllNodes[0].Enabled } } } -finally -{ - Set-NetAdapterRdma -Name $script:AdapterName -Enabled $script:adapterRDMAStatus.Enabled - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_NetAdapterState.Integration.Tests.ps1 b/tests/Integration/DSC_NetAdapterState.Integration.Tests.ps1 index 2e338322..b0904a0b 100644 --- a/tests/Integration/DSC_NetAdapterState.Integration.Tests.ps1 +++ b/tests/Integration/DSC_NetAdapterState.Integration.Tests.ps1 @@ -1,64 +1,99 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterState' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'NetAdapterState' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'NetAdapterState' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'NetAdapterState Integration Tests' { +Describe 'NetAdapterState Integration Tests' { + BeforeAll { New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop - - Describe "$($script:dscResourceName)_Integration" { - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" -OutputPath $TestDrive - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + . $configFile + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + AfterAll { + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' + } + + Describe "$($script:dscResourceName)_Integration" { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" -OutputPath $TestDrive + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $current.Name | Should -Be $TestNetAdapterState.Name - $current.State | Should -Be $TestNetAdapterState.State + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $current.Name | Should -Be $TestNetAdapterState.Name + $current.State | Should -Be $TestNetAdapterState.State } } } -finally -{ - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_NetBios.Integration.Tests.ps1 b/tests/Integration/DSC_NetBios.Integration.Tests.ps1 index f4a625cc..154f8301 100644 --- a/tests/Integration/DSC_NetBios.Integration.Tests.ps1 +++ b/tests/Integration/DSC_NetBios.Integration.Tests.ps1 @@ -1,34 +1,59 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetBios' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' -} -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'NetBios' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'NetBios' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' -# Begin Testing -try -{ - Describe 'NetBios Integration Tests' { - # Configure Loopback Adapters - New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA1' - New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA2' + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +} - $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} +Describe 'NetBios Integration Tests' { + BeforeAll { # Check NetBiosSetting enum loaded, if not load try { @@ -46,92 +71,152 @@ public enum NetBiosSetting '@ } -function Invoke-NetBiosIntegrationTest -{ - param ( - [Parameter()] - [System.String] - $InterfaceAlias, - - [Parameter()] - [System.String] - $Setting = 'Disable' - ) - - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - InterfaceAlias = $InterfaceAlias - Setting = $Setting - } - ) - } + # Configure Loopback Adapters + New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA1' + New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA2' - It 'Should compile and apply the MOF without throwing' { - { - & "DSC_NetBios_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw + $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" + . $configFile } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + AfterAll { + # Remove Loopback Adapters + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA2' + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA1' } - It 'Should have set the resource and all setting should match current state' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "DSC_NetBios_Config" - } - $result.Setting | Should -Be $Setting - } -} + Describe "$($script:dscResourceName)_Integration" { + Context 'When applying to a single network adapter' { + BeforeDiscovery { + $testCases = @( + @{ + InterfaceAlias = 'NetworkingDscLBA1' + Setting = 'Disable' + } + @{ + InterfaceAlias = 'NetworkingDscLBA1' + Setting = 'Enable' + } + @{ + InterfaceAlias = 'NetworkingDscLBA1' + Setting = 'Default' + } + ) + } + + Context 'When setting NetBios over TCP/IP to ' -ForEach $testCases { + BeforeAll { + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = $InterfaceAlias + Setting = $Setting + } + ) + } + } - Describe "$($script:dscResourceName)_Integration" { - Context 'When applying to a single network adapter' { - Context 'When setting NetBios over TCP/IP to Disable' { - Invoke-NetBiosIntegrationTest -InterfaceAlias 'NetworkingDscLBA1' -Setting 'Disable' + AfterEach { + Wait-ForIdleLcm } - Context 'When setting NetBios over TCP/IP to Enable' { - Invoke-NetBiosIntegrationTest -InterfaceAlias 'NetworkingDscLBA1' -Setting 'Enable' + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw } - Context 'When setting NetBios over TCP/IP to Default' { - Invoke-NetBiosIntegrationTest -InterfaceAlias 'NetworkingDscLBA1' -Setting 'Default' + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all setting should match current state' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" + } + + $result.Setting | Should -Be $Setting } } + } + + Context 'When applying to a all network adapters' { + BeforeDiscovery { + $testCases = @( + @{ + InterfaceAlias = 'NetworkingDscLBA*' + Setting = 'Disable' + } + @{ + InterfaceAlias = 'NetworkingDscLBA*' + Setting = 'Enable' + } + @{ + InterfaceAlias = 'NetworkingDscLBA*' + Setting = 'Default' + } + ) + } + + Context 'When setting NetBios over TCP/IP to ' -ForEach $testCases { + BeforeAll { + # Fix intermittent test failures + Wait-ForIdleLcm -Clear + + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = $InterfaceAlias + Setting = $Setting + } + ) + } + } + + AfterEach { + Wait-ForIdleLcm + } - Context 'When applying to a all network adapters' { - Context 'When setting NetBios over TCP/IP to Disable' { - Invoke-NetBiosIntegrationTest -InterfaceAlias 'NetworkingDscLBA*' -Setting 'Disable' + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw } - Context 'When setting NetBios over TCP/IP to Enable' { - Invoke-NetBiosIntegrationTest -InterfaceAlias 'NetworkingDscLBA*' -Setting 'Enable' + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw } - Context 'When setting NetBios over TCP/IP to Default' { - Invoke-NetBiosIntegrationTest -InterfaceAlias 'NetworkingDscLBA*' -Setting 'Default' + It 'Should have set the resource and all setting should match current state' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" + } + + $result.Setting | Should -Be $Setting } } } } } -finally -{ - # Remove Loopback Adapters - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA2' - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA1' - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_NetConnectionProfile.Integration.Tests.ps1 b/tests/Integration/DSC_NetConnectionProfile.Integration.Tests.ps1 index 5bec1fe7..3ccee0fc 100644 --- a/tests/Integration/DSC_NetConnectionProfile.Integration.Tests.ps1 +++ b/tests/Integration/DSC_NetConnectionProfile.Integration.Tests.ps1 @@ -1,55 +1,87 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetConnectionProfile' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'NetConnectionProfile' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'NetConnectionProfile' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'NetConnectionProfile Integration Tests' { +Describe 'NetConnectionProfile Integration Tests' { + BeforeAll { $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop - - Describe "$($script:dscResourceName)_Integration" { - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" -OutputPath $TestDrive - Start-DscConfiguration -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force - } | Should -Not -Throw - } + . $configFile + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + Describe "$($script:dscResourceName)_Integration" { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" -OutputPath $TestDrive + Start-DscConfiguration -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object {$_.ConfigurationName -eq "$($script:dscResourceName)_Config"} - $rule.InterfaceAlias | Should -Be $current.InterfaceAlias - $rule.NetworkCategory | Should -Be $current.NetworkCategory - $rule.IPv4Connectivity | Should -Be $current.IPv4Connectivity - $rule.IPv6Connectivity | Should -Be $current.IPv6Connectivity - $rule.Address | Should -Be $current.Address - $rule.AddressFamily | Should -Be $current.AddressFamily - } + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object { $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + $rule.InterfaceAlias | Should -Be $current.InterfaceAlias + $rule.NetworkCategory | Should -Be $current.NetworkCategory + $rule.IPv4Connectivity | Should -Be $current.IPv4Connectivity + $rule.IPv6Connectivity | Should -Be $current.IPv6Connectivity + $rule.Address | Should -Be $current.Address + $rule.AddressFamily | Should -Be $current.AddressFamily } } } -finally -{ - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_NetIPInterface.Integration.Tests.ps1 b/tests/Integration/DSC_NetIPInterface.Integration.Tests.ps1 index 6db33275..8758221a 100644 --- a/tests/Integration/DSC_NetIPInterface.Integration.Tests.ps1 +++ b/tests/Integration/DSC_NetIPInterface.Integration.Tests.ps1 @@ -1,27 +1,59 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetIPInterface' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'NetIPInterface' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'NetIPInterface' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'NetIPInterface Integration Tests' { +Describe 'NetIPInterface Integration Tests' { + BeforeAll { New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' <# @@ -51,15 +83,23 @@ try WeakHostReceive = 'Disabled' WeakHostSend = 'Disabled' } + Set-NetIPInterface @setNetIPInterfaceParameters $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop + . $configFile + } + + AfterAll { + # Remove Loopback Adapter + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' + } - Describe "$($script:dscResourceName)_Integration" { - Context 'When all settings are enabled' { + Describe "$($script:dscResourceName)_Integration" { + Context 'When all settings are enabled' { + BeforeAll { # This is to pass to the Config - $script:configData = @{ + $configData = @{ AllNodes = @( @{ NodeName = 'localhost' @@ -83,53 +123,60 @@ try } ) } + } - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config_Enabled" ` - -OutputPath $TestDrive ` - -ConfigurationData $script:configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config_Enabled" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Enabled" - } - $current.InterfaceAlias | Should -Be $script:configData.AllNodes[0].InterfaceAlias - $current.AddressFamily | Should -Be $script:configData.AllNodes[0].AddressFamily - $current.AdvertiseDefaultRoute | Should -Be $script:configData.AllNodes[0].AdvertiseDefaultRoute - $current.AutomaticMetric | Should -Be $script:configData.AllNodes[0].AutomaticMetric - $current.Dhcp | Should -Be $script:configData.AllNodes[0].Dhcp - $current.DirectedMacWolPattern | Should -Be $script:configData.AllNodes[0].DirectedMacWolPattern - $current.EcnMarking | Should -Be $script:configData.AllNodes[0].EcnMarking - $current.ForceArpNdWolPattern | Should -Be $script:configData.AllNodes[0].ForceArpNdWolPattern - $current.Forwarding | Should -Be $script:configData.AllNodes[0].Forwarding - $current.IgnoreDefaultRoutes | Should -Be $script:configData.AllNodes[0].IgnoreDefaultRoutes - $current.ManagedAddressConfiguration | Should -Be $script:configData.AllNodes[0].ManagedAddressConfiguration - $current.NeighborUnreachabilityDetection | Should -Be $script:configData.AllNodes[0].NeighborUnreachabilityDetection - $current.OtherStatefulConfiguration | Should -Be $script:configData.AllNodes[0].OtherStatefulConfiguration - $current.RouterDiscovery | Should -Be $script:configData.AllNodes[0].RouterDiscovery - $current.WeakHostReceive | Should -Be $script:configData.AllNodes[0].WeakHostReceive - $current.WeakHostSend | Should -Be $script:configData.AllNodes[0].WeakHostSend + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Enabled" } + + $current.InterfaceAlias | Should -Be $configData.AllNodes[0].InterfaceAlias + $current.AddressFamily | Should -Be $configData.AllNodes[0].AddressFamily + $current.AdvertiseDefaultRoute | Should -Be $configData.AllNodes[0].AdvertiseDefaultRoute + $current.AutomaticMetric | Should -Be $configData.AllNodes[0].AutomaticMetric + $current.Dhcp | Should -Be $configData.AllNodes[0].Dhcp + $current.DirectedMacWolPattern | Should -Be $configData.AllNodes[0].DirectedMacWolPattern + $current.EcnMarking | Should -Be $configData.AllNodes[0].EcnMarking + $current.ForceArpNdWolPattern | Should -Be $configData.AllNodes[0].ForceArpNdWolPattern + $current.Forwarding | Should -Be $configData.AllNodes[0].Forwarding + $current.IgnoreDefaultRoutes | Should -Be $configData.AllNodes[0].IgnoreDefaultRoutes + $current.ManagedAddressConfiguration | Should -Be $configData.AllNodes[0].ManagedAddressConfiguration + $current.NeighborUnreachabilityDetection | Should -Be $configData.AllNodes[0].NeighborUnreachabilityDetection + $current.OtherStatefulConfiguration | Should -Be $configData.AllNodes[0].OtherStatefulConfiguration + $current.RouterDiscovery | Should -Be $configData.AllNodes[0].RouterDiscovery + $current.WeakHostReceive | Should -Be $configData.AllNodes[0].WeakHostReceive + $current.WeakHostSend | Should -Be $configData.AllNodes[0].WeakHostSend } + } - Context 'When all settings are disabled' { + Context 'When all settings are disabled' { + BeforeAll { # This is to pass to the Config - $script:configData = @{ + $configData = @{ AllNodes = @( @{ NodeName = 'localhost' @@ -153,57 +200,55 @@ try } ) } + } - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config_Disabled" ` - -OutputPath $TestDrive ` - -ConfigurationData $script:configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config_Disabled" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Disabled" - } - $current.InterfaceAlias | Should -Be $script:configData.AllNodes[0].InterfaceAlias - $current.AddressFamily | Should -Be $script:configData.AllNodes[0].AddressFamily - $current.AdvertiseDefaultRoute | Should -Be $script:configData.AllNodes[0].AdvertiseDefaultRoute - $current.AutomaticMetric | Should -Be $script:configData.AllNodes[0].AutomaticMetric - $current.Dhcp | Should -Be $script:configData.AllNodes[0].Dhcp - $current.DirectedMacWolPattern | Should -Be $script:configData.AllNodes[0].DirectedMacWolPattern - $current.EcnMarking | Should -Be $script:configData.AllNodes[0].EcnMarking - $current.ForceArpNdWolPattern | Should -Be $script:configData.AllNodes[0].ForceArpNdWolPattern - $current.Forwarding | Should -Be $script:configData.AllNodes[0].Forwarding - $current.IgnoreDefaultRoutes | Should -Be $script:configData.AllNodes[0].IgnoreDefaultRoutes - $current.ManagedAddressConfiguration | Should -Be $script:configData.AllNodes[0].ManagedAddressConfiguration - $current.OtherStatefulConfiguration | Should -Be $script:configData.AllNodes[0].OtherStatefulConfiguration - $current.RouterDiscovery | Should -Be $script:configData.AllNodes[0].RouterDiscovery - $current.WeakHostReceive | Should -Be $script:configData.AllNodes[0].WeakHostReceive - $current.WeakHostSend | Should -Be $script:configData.AllNodes[0].WeakHostSend - $current.NlMtu | Should -Be $script:configData.AllNodes[0].NlMtu - $current.InterfaceMetric | Should -Be $script:configData.AllNodes[0].InterfaceMetric + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Disabled" } + + $current.InterfaceAlias | Should -Be $configData.AllNodes[0].InterfaceAlias + $current.AddressFamily | Should -Be $configData.AllNodes[0].AddressFamily + $current.AdvertiseDefaultRoute | Should -Be $configData.AllNodes[0].AdvertiseDefaultRoute + $current.AutomaticMetric | Should -Be $configData.AllNodes[0].AutomaticMetric + $current.Dhcp | Should -Be $configData.AllNodes[0].Dhcp + $current.DirectedMacWolPattern | Should -Be $configData.AllNodes[0].DirectedMacWolPattern + $current.EcnMarking | Should -Be $configData.AllNodes[0].EcnMarking + $current.ForceArpNdWolPattern | Should -Be $configData.AllNodes[0].ForceArpNdWolPattern + $current.Forwarding | Should -Be $configData.AllNodes[0].Forwarding + $current.IgnoreDefaultRoutes | Should -Be $configData.AllNodes[0].IgnoreDefaultRoutes + $current.ManagedAddressConfiguration | Should -Be $configData.AllNodes[0].ManagedAddressConfiguration + $current.OtherStatefulConfiguration | Should -Be $configData.AllNodes[0].OtherStatefulConfiguration + $current.RouterDiscovery | Should -Be $configData.AllNodes[0].RouterDiscovery + $current.WeakHostReceive | Should -Be $configData.AllNodes[0].WeakHostReceive + $current.WeakHostSend | Should -Be $configData.AllNodes[0].WeakHostSend + $current.NlMtu | Should -Be $configData.AllNodes[0].NlMtu + $current.InterfaceMetric | Should -Be $configData.AllNodes[0].InterfaceMetric } } } } -finally -{ - # Remove Loopback Adapter - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_NetworkTeam.Integration.Tests.ps1 b/tests/Integration/DSC_NetworkTeam.Integration.Tests.ps1 index bfdeed9a..99170b18 100644 --- a/tests/Integration/DSC_NetworkTeam.Integration.Tests.ps1 +++ b/tests/Integration/DSC_NetworkTeam.Integration.Tests.ps1 @@ -13,42 +13,90 @@ for testing into the $script:NetworkTeamMembers array below. E.g. $script:NetworkTeamMembers = @('Ethernet','Ethernet 2') #> -$script:NetworkTeamMembers = @() -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetworkTeam' -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } -# Check if integration tests can be run -if (-not (Test-NetworkTeamIntegrationEnvironment -NetworkAdapters $script:NetworkTeamMembers)) -{ - Write-Warning -Message 'Integration tests will be skipped.' - return -} + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'NetworkTeam' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + # Import to allow check to run in Discovery + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + $script:NetworkTeamMembers = @() + + # Check if integration tests can be run + if (-not (Test-NetworkTeamIntegrationEnvironment -NetworkAdapters $script:NetworkTeamMembers)) + { + $script:Skip = $true + } } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'NetworkTeam' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $script:NetworkTeamMembers = @() } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'NetworkTeam Integration Tests' { +Describe 'NetworkTeam Integration Tests' -Skip:$script:Skip { + BeforeAll { $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop + . $configFile + } + + AfterAll { + # Remove the team just in case it wasn't removed correctly + Remove-NetLbfoTeam ` + -Name 'TestTeam' ` + -Confirm:$false ` + -ErrorAction SilentlyContinue + } - Describe "$($script:dscResourceName)_Integration" { + Describe "$($script:dscResourceName)_Integration" { + BeforeAll { $configurationData = @{ AllNodes = @( @{ @@ -61,110 +109,109 @@ try } ) } + } - Context 'When the network team is created' { - It 'Should compile and apply the MOF without throwing' { + Context 'When the network team is created' { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configurationData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + + # Wait for up to 60 seconds for the team to be created + $count = 0 + While (-not (Get-NetLbfoTeam -Name 'TestTeam' -ErrorAction SilentlyContinue)) { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configurationData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - - # Wait for up to 60 seconds for the team to be created - $count = 0 - While (-not (Get-NetLbfoTeam -Name 'TestTeam' -ErrorAction SilentlyContinue)) + Start-Sleep -Seconds 1 + + if ($count -ge 60) { - Start-Sleep -Seconds 1 + break + } - if ($count -ge 60) - { - break - } + $count++ + } + } | Should -Not -Throw + } - $count++ - } - } | Should -Not -Throw - } + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + It 'Should have set the resource and all the parameters should match' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } - It 'Should have set the resource and all the parameters should match' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $result.Ensure | Should -Be $configurationData.AllNodes[0].Ensure - $result.Name | Should -Be $configurationData.AllNodes[0].Name - $result.TeamMembers | Should -Be $configurationData.AllNodes[0].Members - $result.LoadBalancingAlgorithm | Should -Be $configurationData.AllNodes[0].LoadBalancingAlgorithm - $result.TeamingMode | Should -Be $configurationData.AllNodes[0].TeamingMode - } + $result.Ensure | Should -Be $configurationData.AllNodes[0].Ensure + $result.Name | Should -Be $configurationData.AllNodes[0].Name + $result.TeamMembers | Should -Be $configurationData.AllNodes[0].Members + $result.LoadBalancingAlgorithm | Should -Be $configurationData.AllNodes[0].LoadBalancingAlgorithm + $result.TeamingMode | Should -Be $configurationData.AllNodes[0].TeamingMode } + } - $configurationData.AllNodes[0].Ensure = 'Absent' + Context 'When the network team is deleted' { + AfterEach { + Wait-ForIdleLcm + } - Context 'When the network team is deleted' { - It 'Should compile and apply the MOF without throwing' { + It 'Should compile and apply the MOF without throwing' { + $configurationData.AllNodes[0].Ensure = 'Absent' + + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configurationData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + + # Wait for up to 60 seconds for the team to be removed + $count = 0 + While (Get-NetLbfoTeam -Name 'TestTeam' -ErrorAction SilentlyContinue) { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configurationData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - - # Wait for up to 60 seconds for the team to be removed - $count = 0 - While (Get-NetLbfoTeam -Name 'TestTeam' -ErrorAction SilentlyContinue) - { - Start-Sleep -Seconds 1 + Start-Sleep -Seconds 1 - if ($count -ge 60) - { - break - } - - $count++ + if ($count -ge 60) + { + break } - } | Should -Not -Throw - } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } - - It 'Should have set the resource and all the parameters should match' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" + $count++ } - $result.Ensure | Should -Be $configurationData.AllNodes[0].Ensure - $result.Name | Should -Be $configurationData.AllNodes[0].Name - $result.TeamMembers | Should -Be $configurationData.AllNodes[0].Members + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + $result.Ensure | Should -Be $configurationData.AllNodes[0].Ensure + $result.Name | Should -Be $configurationData.AllNodes[0].Name + $result.TeamMembers | Should -Be $configurationData.AllNodes[0].Members } } } } -finally -{ - # Remove the team just in case it wasn't removed correctly - Remove-NetLbfoTeam ` - -Name 'TestTeam' ` - -Confirm:$false ` - -ErrorAction SilentlyContinue - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_NetworkTeamInterface.Integration.Tests.ps1 b/tests/Integration/DSC_NetworkTeamInterface.Integration.Tests.ps1 index f3f334ca..548c5c7f 100644 --- a/tests/Integration/DSC_NetworkTeamInterface.Integration.Tests.ps1 +++ b/tests/Integration/DSC_NetworkTeamInterface.Integration.Tests.ps1 @@ -13,175 +13,221 @@ for testing into the $script:NetworkTeamMembers array below. E.g. $script:NetworkTeamMembers = @('Ethernet','Ethernet 2') #> -$script:NetworkTeamMembers = @() -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetworkTeam' -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } -# Check if integration tests can be run -if (-not (Test-NetworkTeamIntegrationEnvironment -NetworkAdapters $script:NetworkTeamMembers)) -{ - Write-Warning -Message 'Integration tests will be skipped.' - return -} + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'NetworkTeam' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + # Import to allow check to run in discovery + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $script:NetworkTeamMembers = @() + + # Check if integration tests can be run + if (-not (Test-NetworkTeamIntegrationEnvironment -NetworkAdapters $script:NetworkTeamMembers)) + { + $script:Skip = $true + } } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'NetworkTeam' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + $script:NetworkTeamMembers = @() + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'NetworkTeamInterface Integration Tests' { +Describe 'NetworkTeamInterface Integration Tests' -Skip:$script:Skip { + BeforeAll { $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop - - Describe "$($script:dscResourceName)_Integration" { - $configurationData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - TeamName = 'TestTeam' - Members = $script:NetworkTeamMembers - LoadBalancingAlgorithm = 'MacAddresses' - TeamingMode = 'SwitchIndependent' - Ensure = 'Present' - InterfaceName = 'TestInterface' - VlanId = 100 - } - ) + . $configFile + } + + AfterAll { + # Remove the team just in case it wasn't removed correctly + Remove-NetLbfoTeamNic ` + -Team 'TestTeam' ` + -VlanId 100 ` + -Confirm:$false ` + -ErrorAction SilentlyContinue + + Remove-NetLbfoTeam ` + -Name 'TestTeam' ` + -Confirm:$false ` + -ErrorAction SilentlyContinue + } + + Describe "$($script:dscResourceName)_Integration" { + $configurationData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + TeamName = 'TestTeam' + Members = $script:NetworkTeamMembers + LoadBalancingAlgorithm = 'MacAddresses' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' + InterfaceName = 'TestInterface' + VlanId = 100 + } + ) + } + + Context 'When the network team is created and the TestInterface is added' { + AfterEach { + Wait-ForIdleLcm } - Context 'When the network team is created and the TestInterface is added' { - It 'Should compile and apply the MOF without throwing' { + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configurationData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + + # Wait for up to 60 seconds for the team interface to be created + $count = 0 + While (-not (Get-NetLbfoTeamNic -Name 'TestInterface' -Team 'TestTeam' -ErrorAction SilentlyContinue)) { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configurationData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - - # Wait for up to 60 seconds for the team interface to be created - $count = 0 - While (-not (Get-NetLbfoTeamNic -Name 'TestInterface' -Team 'TestTeam' -ErrorAction SilentlyContinue)) + Start-Sleep -Seconds 1 + + if ($count -ge 60) { - Start-Sleep -Seconds 1 + break + } - if ($count -ge 60) - { - break - } + $count++ + } + } | Should -Not -Throw + } - $count++ - } - } | Should -Not -Throw - } + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + It 'Should have set the resource and all the parameters should match' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } - It 'Should have set the resource and all the parameters should match' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $result[0].Ensure | Should -Be 'Present' - $result[0].Name | Should -Be $configurationData.AllNodes[0].TeamName - $result[0].TeamMembers | Should -Be $configurationData.AllNodes[0].Members - $result[0].LoadBalancingAlgorithm | Should -Be $configurationData.AllNodes[0].LoadBalancingAlgorithm - $result[0].TeamingMode | Should -Be $configurationData.AllNodes[0].TeamingMode - $result[1].Ensure | Should -Be $configurationData.AllNodes[0].Ensure - $result[1].Name | Should -Be $configurationData.AllNodes[0].InterfaceName - $result[1].TeamName | Should -Be $configurationData.AllNodes[0].TeamName - $result[1].VlanId | Should -Be $configurationData.AllNodes[0].VlanId - } + $result[0].Ensure | Should -Be 'Present' + $result[0].Name | Should -Be $configurationData.AllNodes[0].TeamName + $result[0].TeamMembers | Should -Be $configurationData.AllNodes[0].Members + $result[0].LoadBalancingAlgorithm | Should -Be $configurationData.AllNodes[0].LoadBalancingAlgorithm + $result[0].TeamingMode | Should -Be $configurationData.AllNodes[0].TeamingMode + $result[1].Ensure | Should -Be $configurationData.AllNodes[0].Ensure + $result[1].Name | Should -Be $configurationData.AllNodes[0].InterfaceName + $result[1].TeamName | Should -Be $configurationData.AllNodes[0].TeamName + $result[1].VlanId | Should -Be $configurationData.AllNodes[0].VlanId } + } - $configurationData.AllNodes[0].Ensure = 'Absent' + Context 'When the network team is created and the TestInterface is removed' { + AfterEach { + Wait-ForIdleLcm + } - Context 'When the network team is created and the TestInterface is removed' { - It 'Should compile and apply the MOF without throwing' { + It 'Should compile and apply the MOF without throwing' { + { + $configurationData.AllNodes[0].Ensure = 'Absent' + + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configurationData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + + # Wait for up to 60 seconds for the team interface to be created + $count = 0 + While (Get-NetLbfoTeamNic -Name 'TestInterface' -Team 'TestTeam' -ErrorAction SilentlyContinue) { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configurationData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - - # Wait for up to 60 seconds for the team interface to be created - $count = 0 - While (Get-NetLbfoTeamNic -Name 'TestInterface' -Team 'TestTeam' -ErrorAction SilentlyContinue) + Start-Sleep -Seconds 1 + + if ($count -ge 60) { - Start-Sleep -Seconds 1 + break + } - if ($count -ge 60) - { - break - } + $count++ + } + } | Should -Not -Throw + } - $count++ - } - } | Should -Not -Throw - } + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + It 'Should have set the resource and all the parameters should match' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } - It 'Should have set the resource and all the parameters should match' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $result[0].Ensure | Should -Be 'Present' - $result[0].Name | Should -Be $configurationData.AllNodes[0].TeamName - $result[0].TeamMembers | Should -Be $configurationData.AllNodes[0].Members - $result[0].LoadBalancingAlgorithm | Should -Be $configurationData.AllNodes[0].LoadBalancingAlgorithm - $result[0].TeamingMode | Should -Be $configurationData.AllNodes[0].TeamingMode - $result[1].Ensure | Should -Be $configurationData.AllNodes[0].Ensure - $result[1].Name | Should -Be $configurationData.AllNodes[0].InterfaceName - $result[1].TeamName | Should -Be $configurationData.AllNodes[0].TeamName - } + $result[0].Ensure | Should -Be 'Present' + $result[0].Name | Should -Be $configurationData.AllNodes[0].TeamName + $result[0].TeamMembers | Should -Be $configurationData.AllNodes[0].Members + $result[0].LoadBalancingAlgorithm | Should -Be $configurationData.AllNodes[0].LoadBalancingAlgorithm + $result[0].TeamingMode | Should -Be $configurationData.AllNodes[0].TeamingMode + $result[1].Ensure | Should -Be $configurationData.AllNodes[0].Ensure + $result[1].Name | Should -Be $configurationData.AllNodes[0].InterfaceName + $result[1].TeamName | Should -Be $configurationData.AllNodes[0].TeamName } } } } -finally -{ - # Remove the team just in case it wasn't removed correctly - Remove-NetLbfoTeamNic ` - -Team 'TestTeam' ` - -VlanId 100 ` - -Confirm:$false ` - -ErrorAction SilentlyContinue - - Remove-NetLbfoTeam ` - -Name 'TestTeam' ` - -Confirm:$false ` - -ErrorAction SilentlyContinue - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_ProxySettings.Integration.Tests.ps1 b/tests/Integration/DSC_ProxySettings.Integration.Tests.ps1 index 4c68d76d..b97e4539 100644 --- a/tests/Integration/DSC_ProxySettings.Integration.Tests.ps1 +++ b/tests/Integration/DSC_ProxySettings.Integration.Tests.ps1 @@ -1,165 +1,206 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_ProxySettings' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'ProxySettings' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'ProxySettings' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} + +Describe 'ProxySettings Integration Tests' { + BeforeAll { + $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" + . $configFile -# Begin Testing -try -{ - Describe 'ProxySettings Integration Tests' { # Create a config data object to pass to the DSC Config $testProxyServer = 'testproxy:8888' $testProxyExceptions = 1..20 | Foreach-Object -Process { "exception$_.contoso.com" } $testAutoConfigURL = 'http://wpad.contoso.com/test.wpad' + } - $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop + AfterAll { + # Clean up any proxy settings in case the tests fail + $connectionsRegistryKeyPath = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections' - foreach ($target in @('LocalMachine','CurrentUser')) - { - Context "When Target is '$Target'" { - Context "When Ensure is 'Present'" { - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - Target = $Target - EnableAutoDetection = $True - EnableAutoConfiguration = $True - EnableManualProxy = $True - ProxyServer = $testProxyServer - ProxyServerExceptions = $testProxyExceptions - ProxyServerBypassLocal = $True - AutoConfigURL = $testAutoConfigURL - } - ) - } - - It 'Should compile without throwing' { - { - & "$($script:dscResourceName)_Present_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } - - It 'Should be able to call Test-DscConfiguration without throwing' { - { $script:currentState = Test-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } - - It 'Should report that DSC is in state' { - $script:currentState | Should -BeTrue - } - - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object { - $_.ConfigurationName -eq "$($script:dscResourceName)_Present_Config" + Remove-ItemProperty ` + -Path "HKLM:\$($connectionsRegistryKeyPath)" ` + -Name 'DefaultConnectionSettings' ` + -ErrorAction SilentlyContinue + + Remove-ItemProperty ` + -Path "HKLM:\$($connectionsRegistryKeyPath)" ` + -Name 'SavedLegacySettings' ` + -ErrorAction SilentlyContinue + } + + Context 'When Target is <_>' -ForEach @('LocalMachine', 'CurrentUser') { + Context "When Ensure is 'Present'" { + BeforeAll { + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + Target = $_ + EnableAutoDetection = $True + EnableAutoConfiguration = $True + EnableManualProxy = $True + ProxyServer = $testProxyServer + ProxyServerExceptions = $testProxyExceptions + ProxyServerBypassLocal = $True + AutoConfigURL = $testAutoConfigURL } - $current.Ensure | Should -Be 'Present' - $current.Target | Should -Be $configData.AllNodes[0].Target - $current.EnableAutoDetection | Should -Be $configData.AllNodes[0].EnableAutoDetection - $current.EnableAutoConfiguration | Should -Be $configData.AllNodes[0].EnableAutoConfiguration - $current.EnableManualProxy | Should -Be $configData.AllNodes[0].EnableManualProxy - $current.ProxyServer | Should -Be $configData.AllNodes[0].ProxyServer - $current.ProxyServerExceptions | Should -Be $configData.AllNodes[0].ProxyServerExceptions - $current.ProxyServerBypassLocal | Should -Be $configData.AllNodes[0].ProxyServerBypassLocal - $current.AutoConfigURL | Should -Be $configData.AllNodes[0].AutoConfigURL - } + ) } + } - Context "When Ensure is 'Absent'" { - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - Target = $Target - } - ) - } - - It 'Should compile without throwing' { - { - & "$($script:dscResourceName)_Absent_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } - - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } - - It 'Should be able to call Test-DscConfiguration without throwing' { - { $script:currentState = Test-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } - - It 'Should report that DSC is in state' { - $script:currentState | Should -BeTrue - } - - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object { - $_.ConfigurationName -eq "$($script:dscResourceName)_Absent_Config" - } - $current.Ensure | Should -Be 'Absent' - $current.Target | Should -Be $configData.AllNodes[0].Target - } + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile without throwing' { + { + & "$($script:dscResourceName)_Present_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should be able to call Test-DscConfiguration without throwing' { + { $script:currentState = Test-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should report that DSC is in state' { + $script:currentState | Should -BeTrue + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object { + $_.ConfigurationName -eq "$($script:dscResourceName)_Present_Config" } + + $current.Ensure | Should -Be 'Present' + $current.Target | Should -Be $configData.AllNodes[0].Target + $current.EnableAutoDetection | Should -Be $configData.AllNodes[0].EnableAutoDetection + $current.EnableAutoConfiguration | Should -Be $configData.AllNodes[0].EnableAutoConfiguration + $current.EnableManualProxy | Should -Be $configData.AllNodes[0].EnableManualProxy + $current.ProxyServer | Should -Be $configData.AllNodes[0].ProxyServer + $current.ProxyServerExceptions | Should -Be $configData.AllNodes[0].ProxyServerExceptions + $current.ProxyServerBypassLocal | Should -Be $configData.AllNodes[0].ProxyServerBypassLocal + $current.AutoConfigURL | Should -Be $configData.AllNodes[0].AutoConfigURL } } - } -} -finally -{ - # Clean up any proxy settings in case the tests fail - $connectionsRegistryKeyPath = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections' - Remove-ItemProperty ` - -Path "HKLM:\$($connectionsRegistryKeyPath)" ` - -Name 'DefaultConnectionSettings' ` - -ErrorAction SilentlyContinue + Context "When Ensure is 'Absent'" { + BeforeAll { + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + Target = $_ + } + ) + } + } - Remove-ItemProperty ` - -Path "HKLM:\$($connectionsRegistryKeyPath)" ` - -Name 'SavedLegacySettings' ` - -ErrorAction SilentlyContinue + AfterEach { + Wait-ForIdleLcm + } - Restore-TestEnvironment -TestEnvironment $script:testEnvironment + It 'Should compile without throwing' { + { + & "$($script:dscResourceName)_Absent_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should be able to call Test-DscConfiguration without throwing' { + { $script:currentState = Test-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should report that DSC is in state' { + $script:currentState | Should -BeTrue + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object { + $_.ConfigurationName -eq "$($script:dscResourceName)_Absent_Config" + } + + $current.Ensure | Should -Be 'Absent' + $current.Target | Should -Be $configData.AllNodes[0].Target + } + } + } } diff --git a/tests/Integration/DSC_Route.Integration.Tests.ps1 b/tests/Integration/DSC_Route.Integration.Tests.ps1 index c5bbe3f4..02563fa5 100644 --- a/tests/Integration/DSC_Route.Integration.Tests.ps1 +++ b/tests/Integration/DSC_Route.Integration.Tests.ps1 @@ -1,27 +1,59 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_Route' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'Route' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'Route' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'Route Integration Tests' { +Describe 'Route Integration Tests' { + BeforeAll { $script:interfaceAlias = (Get-NetAdapter -Physical | Select-Object -First 1).Name $script:dummyRoute = [PSObject] @{ @@ -33,9 +65,18 @@ try } $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop + . $configFile + } - Describe "$($script:dscResourceName)_Add_Integration" { + AfterAll { + # Clean up any created routes just in case the integration tests fail + $null = Remove-NetRoute @dummyRoute ` + -Confirm:$false ` + -ErrorAction SilentlyContinue + } + + Describe "$($script:dscResourceName)_Add_Integration" { + BeforeAll { $configData = @{ AllNodes = @( @{ @@ -50,47 +91,53 @@ try } ) } + } - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - - $current.InterfaceAlias | Should -Be $configData.AllNodes[0].InterfaceAlias - $current.AddressFamily | Should -Be $configData.AllNodes[0].AddressFamily - $current.DestinationPrefix | Should -Be $configData.AllNodes[0].DestinationPrefix - $current.NextHop | Should -Be $configData.AllNodes[0].NextHop - $current.Ensure | Should -Be $configData.AllNodes[0].Ensure - $current.RouteMetric | Should -Be $configData.AllNodes[0].RouteMetric - $current.Publish | Should -Be $configData.AllNodes[0].Publish - } + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should have created the route' { - Get-NetRoute @dummyRoute -ErrorAction SilentlyContinue | Should -Not -BeNullOrEmpty + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $current.InterfaceAlias | Should -Be $configData.AllNodes[0].InterfaceAlias + $current.AddressFamily | Should -Be $configData.AllNodes[0].AddressFamily + $current.DestinationPrefix | Should -Be $configData.AllNodes[0].DestinationPrefix + $current.NextHop | Should -Be $configData.AllNodes[0].NextHop + $current.Ensure | Should -Be $configData.AllNodes[0].Ensure + $current.RouteMetric | Should -Be $configData.AllNodes[0].RouteMetric + $current.Publish | Should -Be $configData.AllNodes[0].Publish } - Describe "$($script:dscResourceName)_Remove_Integration" { + It 'Should have created the route' { + Get-NetRoute @dummyRoute -ErrorAction SilentlyContinue | Should -Not -BeNullOrEmpty + } + } + + Describe "$($script:dscResourceName)_Remove_Integration" { + BeforeAll { $configData = @{ AllNodes = @( @{ @@ -105,51 +152,46 @@ try } ) } + } - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - $current.InterfaceAlias | Should -Be $configData.AllNodes[0].InterfaceAlias - $current.AddressFamily | Should -Be $configData.AllNodes[0].AddressFamily - $current.DestinationPrefix | Should -Be $configData.AllNodes[0].DestinationPrefix - $current.NextHop | Should -Be $configData.AllNodes[0].NextHop - $current.Ensure | Should -Be $configData.AllNodes[0].Ensure + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } - It 'Should have deleted the route' { - Get-NetRoute @dummyRoute -ErrorAction SilentlyContinue | Should -BeNullOrEmpty - } + $current.InterfaceAlias | Should -Be $configData.AllNodes[0].InterfaceAlias + $current.AddressFamily | Should -Be $configData.AllNodes[0].AddressFamily + $current.DestinationPrefix | Should -Be $configData.AllNodes[0].DestinationPrefix + $current.NextHop | Should -Be $configData.AllNodes[0].NextHop + $current.Ensure | Should -Be $configData.AllNodes[0].Ensure } - } -} -finally -{ - # Clean up any created routes just in case the integration tests fail - $null = Remove-NetRoute @dummyRoute ` - -Confirm:$false ` - -ErrorAction SilentlyContinue - Restore-TestEnvironment -TestEnvironment $script:testEnvironment + It 'Should have deleted the route' { + Get-NetRoute @dummyRoute -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } + } } diff --git a/tests/Integration/DSC_WaitForNetworkTeam.Integration.Tests.ps1 b/tests/Integration/DSC_WaitForNetworkTeam.Integration.Tests.ps1 index 035585f4..4ade013f 100644 --- a/tests/Integration/DSC_WaitForNetworkTeam.Integration.Tests.ps1 +++ b/tests/Integration/DSC_WaitForNetworkTeam.Integration.Tests.ps1 @@ -13,99 +13,139 @@ for testing into the $script:NetworkTeamMembers array below. E.g. $script:NetworkTeamMembers = @('Ethernet','Ethernet 2') #> -$script:NetworkTeamMembers = @() -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_WaitForNetworkTeam' -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -# Check if integration tests can be run -if (-not (Test-NetworkTeamIntegrationEnvironment -NetworkAdapters $script:NetworkTeamMembers)) -{ - Write-Warning -Message 'Integration tests will be skipped.' - return +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } + + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'WaitForNetworkTeam' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $script:NetworkTeamMembers = @() + + # Check if integration tests can be run + if (-not (Test-NetworkTeamIntegrationEnvironment -NetworkAdapters $script:NetworkTeamMembers)) + { + $script:Skip = $true + } } -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'WaitForNetworkTeam' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + Restore-TestEnvironment -TestEnvironment $script:testEnvironment } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' - -# Begin Testing -try -{ - Describe 'WaitForNetworkTeam Integration Tests' { - $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile -Verbose -ErrorAction Stop - - Describe "$($script:dscResourceName)_Integration" { - $null = New-NetLbfoTeam ` - -Name 'TestTeam' ` - -TeamMembers $script:NetworkTeamMembers ` - -LoadBalancingAlgorithm 'MacAddresses' ` - -TeamingMode 'SwitchIndependent' ` - -Confirm:$false +Describe 'WaitForNetworkTeam Integration Tests' -Skip:$script:Skip { + BeforeAll { + $null = New-NetLbfoTeam ` + -Name 'TestTeam' ` + -TeamMembers $script:NetworkTeamMembers ` + -LoadBalancingAlgorithm 'MacAddresses' ` + -TeamingMode 'SwitchIndependent' ` + -Confirm:$false + $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" + . $configFile + } + + AfterAll { + # Remove the team just in case it wasn't removed correctly + Remove-NetLbfoTeam ` + -Name 'TestTeam' ` + -Confirm:$false ` + -ErrorAction SilentlyContinue + } + + Describe "$($script:dscResourceName)_Integration" { + BeforeAll { $configurationData = @{ AllNodes = @( @{ - NodeName = 'localhost' - Name = 'TestTeam' - RetryIntervalSec = 2 - RetryCount = 30 + NodeName = 'localhost' + Name = 'TestTeam' + RetryIntervalSec = 2 + RetryCount = 30 } ) } + } - Context 'When the network team has been created' { - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configurationData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + Context 'When the network team has been created' { + AfterEach { + Wait-ForIdleLcm + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configurationData - It 'Should have set the resource and all the parameters should match' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $result.Ensure | Should -Be $configurationData.AllNodes[0].Ensure - $result.Name | Should -Be $configurationData.AllNodes[0].Name + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $result.Ensure | Should -Be $configurationData.AllNodes[0].Ensure + $result.Name | Should -Be $configurationData.AllNodes[0].Name } } } } -finally -{ - # Remove the team just in case it wasn't removed correctly - Remove-NetLbfoTeam ` - -Name 'TestTeam' ` - -Confirm:$false ` - -ErrorAction SilentlyContinue - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_WinsServerAddress.Integration.Tests.ps1 b/tests/Integration/DSC_WinsServerAddress.Integration.Tests.ps1 index 93f05265..e6ae1a26 100644 --- a/tests/Integration/DSC_WinsServerAddress.Integration.Tests.ps1 +++ b/tests/Integration/DSC_WinsServerAddress.Integration.Tests.ps1 @@ -1,145 +1,190 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_WinsServerAddress' +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'WinsServerAddress' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" } -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'WinsServerAddress' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} -# Begin Testing -try -{ - Describe 'WinsServerAddress Integration Tests' { +Describe 'WinsServerAddress Integration Tests' { + BeforeAll { New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_Configured.config.ps1" - . $configFile -Verbose -ErrorAction Stop - - Describe "$($script:dscResourceName)_Integration using single address" { - It 'Should compile and apply the MOF without throwing' { - { - # This is to pass to the Config - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - InterfaceAlias = 'NetworkingDscLBA' - Address = '10.139.17.99' - } - ) - } - - & "$($script:dscResourceName)_Config_Configured" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration -Path $TestDrive ` - -ComputerName localhost -Wait -Verbose -Force - } | Should -Not -Throw - } + . $configFile + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + AfterAll { + # Remove Loopback Adapter + Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' + } + + Describe "$($script:dscResourceName)_Integration using single address" { + AfterEach { + Wait-ForIdleLcm + } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Configured" + It 'Should compile and apply the MOF without throwing' { + { + # This is to pass to the Config + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = 'NetworkingDscLBA' + Address = '10.139.17.99' + } + ) } - $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' - $current.Address.Count | Should -Be 1 - $current.Address | Should -Be '10.139.17.99' - } + + & "$($script:dscResourceName)_Config_Configured" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration -Path $TestDrive ` + -ComputerName localhost -Wait -Verbose -Force + } | Should -Not -Throw } - Describe "$($script:dscResourceName)_Integration using two addresses" { - It 'Should compile and apply the MOF without throwing' { - { - # This is to pass to the Config - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - InterfaceAlias = 'NetworkingDscLBA' - Address = '10.139.17.99', '10.139.17.100' - } - ) - } - - & "$($script:dscResourceName)_Config_Configured" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration -Path $TestDrive ` - -ComputerName localhost -Wait -Verbose -Force - } | Should -Not -Throw - } + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Configured" } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Configured" + $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' + $current.Address.Count | Should -Be 1 + $current.Address | Should -Be '10.139.17.99' + } + } + + Describe "$($script:dscResourceName)_Integration using two addresses" { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + # This is to pass to the Config + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = 'NetworkingDscLBA' + Address = '10.139.17.99', '10.139.17.100' + } + ) } - $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' - $current.Address.Count | Should -Be 2 - $current.Address[0] | Should -Be '10.139.17.99' - $current.Address[1] | Should -Be '10.139.17.100' - } + + & "$($script:dscResourceName)_Config_Configured" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration -Path $TestDrive ` + -ComputerName localhost -Wait -Verbose -Force + } | Should -Not -Throw } - Describe "$($script:dscResourceName)_Integration using no addresses" { - It 'Should compile and apply the MOF without throwing' { - { - # This is to pass to the Config - $configData = @{ - AllNodes = @( - @{ - NodeName = 'localhost' - InterfaceAlias = 'NetworkingDscLBA' - Address = @() - } - ) - } - - & "$($script:dscResourceName)_Config_Configured" ` - -OutputPath $TestDrive ` - -ConfigurationData $configData - Start-DscConfiguration -Path $TestDrive ` - -ComputerName localhost -Wait -Verbose -Force - } | Should -Not -Throw - } + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Configured" } - It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Configured" + $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' + $current.Address.Count | Should -Be 2 + $current.Address[0] | Should -Be '10.139.17.99' + $current.Address[1] | Should -Be '10.139.17.100' + } + } + + Describe "$($script:dscResourceName)_Integration using no addresses" { + AfterEach { + Wait-ForIdleLcm + } + + It 'Should compile and apply the MOF without throwing' { + { + # This is to pass to the Config + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = 'NetworkingDscLBA' + Address = @() + } + ) } - $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' - $current.Address | Should -BeNullOrEmpty + + & "$($script:dscResourceName)_Config_Configured" ` + -OutputPath $TestDrive ` + -ConfigurationData $configData + Start-DscConfiguration -Path $TestDrive ` + -ComputerName localhost -Wait -Verbose -Force + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config_Configured" } + + $current.InterfaceAlias | Should -Be 'NetworkingDscLBA' + $current.Address | Should -BeNullOrEmpty } } } -finally -{ - # Remove Loopback Adapter - Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA' - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/Integration/DSC_WinsSetting.Integration.Tests.ps1 b/tests/Integration/DSC_WinsSetting.Integration.Tests.ps1 index 561339ec..a3005c7a 100644 --- a/tests/Integration/DSC_WinsSetting.Integration.Tests.ps1 +++ b/tests/Integration/DSC_WinsSetting.Integration.Tests.ps1 @@ -1,61 +1,85 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_WinsSetting' - -# Find an adapter we can test with. It needs to be enabled and have IP enabled. -$netAdapter = $null -$netAdapterConfig = $null -$netAdapterEnabled = Get-CimInstance -ClassName Win32_NetworkAdapter -Filter 'NetEnabled="True"' - -if (-not $netAdapterEnabled) -{ - Write-Verbose -Message ('There are no enabled network adapters in this system. Integration tests will be skipped.') -Verbose - return -} +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] +param () -foreach ($netAdapter in $netAdapterEnabled) -{ - $netAdapterConfig = $netAdapter | - Get-CimAssociatedInstance -ResultClassName Win32_NetworkAdapterConfiguration | - Where-Object -FilterScript { $_.IPEnabled -eq $True } +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } - if ($netAdapterConfig) + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] { - break + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } -} -if (-not $netAdapterConfig) -{ - Write-Verbose -Message ('There are no enabled network adapters with IP enabled in this system. Integration tests will be skipped.') -Verbose - return -} + <# + Need to define that variables here to be used in the Pester Discover to + build the ForEach-blocks. + #> + $script:dscResourceFriendlyName = 'WinsSetting' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" -Write-Verbose -Message ('A network adapter ({0}) was found in this system that meets requirements for integration testing.' -f $netAdapter.Name) -Verbose + # Find an adapter we can test with. It needs to be enabled and have IP enabled. + $netAdapterConfig = $null + $netAdapterEnabled = Get-CimInstance -ClassName Win32_NetworkAdapter -Filter 'NetEnabled="True"' -try -{ - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' -} -catch [System.IO.FileNotFoundException] -{ - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + if (-not $netAdapterEnabled) + { + $script:skip = $true + } + + foreach ($netAdapter in $netAdapterEnabled) + { + $netAdapterConfig = $netAdapter | + Get-CimAssociatedInstance -ResultClassName Win32_NetworkAdapterConfiguration | + Where-Object -FilterScript { $_.IPEnabled -eq $True } + + if ($netAdapterConfig) + { + break + } + } + + if (-not $netAdapterConfig) + { + $script:Skip = $true + } } -$script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Integration' +BeforeAll { + # Need to define the variables here which will be used in Pester Run. + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceFriendlyName = 'WinsSetting' + $script:dscResourceName = "DSC_$($script:dscResourceFriendlyName)" -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Integration' -# Begin Testing -try -{ - Describe 'WinsSetting Integration Tests' { - $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" - . $configFile + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +} + +AfterAll { + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + Restore-TestEnvironment -TestEnvironment $script:testEnvironment +} + +Describe 'WinsSetting Integration Tests' -Skip:$script:skip { + BeforeAll { # Store the current WINS settings $enableDnsRegistryKey = Get-ItemProperty ` -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' ` @@ -84,12 +108,28 @@ try -ClassName Win32_NetworkAdapterConfiguration ` -MethodName EnableWins ` -Arguments @{ - DNSEnabledForWINSResolution = $true - WINSEnableLMHostsLookup = $true - } + DNSEnabledForWINSResolution = $true + WINSEnableLMHostsLookup = $true + } + + $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1" + . $configFile + } + + AfterAll { + # Restore the WINS settings + $null = Invoke-CimMethod ` + -ClassName Win32_NetworkAdapterConfiguration ` + -MethodName EnableWins ` + -Arguments @{ + DNSEnabledForWINSResolution = $currentEnableDns + WINSEnableLMHostsLookup = $currentEnableLmHosts + } + } - Describe "$($script:dscResourceName)_Integration" { - Context 'Disable all settings' { + Describe "$($script:dscResourceName)_Integration" { + Context 'Disable all settings' { + BeforeAll { $configurationData = @{ AllNodes = @( @{ @@ -99,37 +139,44 @@ try } ) } + } - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configurationData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configurationData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } - It 'Should have set the resource and all setting should match current state' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $result.EnableLmHosts | Should -Be $false - $result.EnableDns | Should -Be $false + It 'Should have set the resource and all setting should match current state' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + + $result.EnableLmHosts | Should -BeFalse + $result.EnableDns | Should -BeFalse } + } - Context 'Enable all settings' { + Context 'Enable all settings' { + BeforeAll { $configurationData = @{ AllNodes = @( @{ @@ -139,48 +186,39 @@ try } ) } + } - It 'Should compile and apply the MOF without throwing' { - { - & "$($script:dscResourceName)_Config" ` - -OutputPath $TestDrive ` - -ConfigurationData $configurationData - - Start-DscConfiguration ` - -Path $TestDrive ` - -ComputerName localhost ` - -Wait ` - -Verbose ` - -Force ` - -ErrorAction Stop - } | Should -Not -Throw - } + AfterEach { + Wait-ForIdleLcm + } - It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw - } + It 'Should compile and apply the MOF without throwing' { + { + & "$($script:dscResourceName)_Config" ` + -OutputPath $TestDrive ` + -ConfigurationData $configurationData + + Start-DscConfiguration ` + -Path $TestDrive ` + -ComputerName localhost ` + -Wait ` + -Verbose ` + -Force ` + -ErrorAction Stop + } | Should -Not -Throw + } - It 'Should have set the resource and all setting should match current state' { - $result = Get-DscConfiguration | Where-Object -FilterScript { - $_.ConfigurationName -eq "$($script:dscResourceName)_Config" - } - $result.EnableLmHosts | Should -Be $true - $result.EnableDns | Should -Be $true + It 'Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw + } + + It 'Should have set the resource and all setting should match current state' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:dscResourceName)_Config" } + $result.EnableLmHosts | Should -BeTrue + $result.EnableDns | Should -BeTrue } } } } -finally -{ - # Restore the WINS settings - $null = Invoke-CimMethod ` - -ClassName Win32_NetworkAdapterConfiguration ` - -MethodName EnableWins ` - -Arguments @{ - DNSEnabledForWINSResolution = $currentEnableDns - WINSEnableLMHostsLookup = $currentEnableLmHosts - } - - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} diff --git a/tests/TestHelpers/CommonTestHelper.psm1 b/tests/TestHelpers/CommonTestHelper.psm1 index c5c1a6d1..6c3c00ef 100644 --- a/tests/TestHelpers/CommonTestHelper.psm1 +++ b/tests/TestHelpers/CommonTestHelper.psm1 @@ -27,62 +27,12 @@ function Get-InvalidArgumentRecord $argumentException = New-Object -TypeName 'ArgumentException' -ArgumentList @( $Message, $ArgumentName ) $newObjectParams = @{ - TypeName = 'System.Management.Automation.ErrorRecord' + TypeName = 'System.Management.Automation.ErrorRecord' ArgumentList = @( $argumentException, $ArgumentName, 'InvalidArgument', $null ) } return New-Object @newObjectParams } -<# - .SYNOPSIS - Returns an invalid operation exception object - - .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 Get-InvalidOperationRecord -{ - [CmdletBinding()] - param - ( - [Parameter()] - [ValidateNotNullOrEmpty()] - [String] - $Message, - - [Parameter()] - [ValidateNotNull()] - [System.Management.Automation.ErrorRecord] - $ErrorRecord - ) - - if ($null -eq $Message) - { - $invalidOperationException = New-Object -TypeName 'InvalidOperationException' - } - elseif ($null -eq $ErrorRecord) - { - $invalidOperationException = - New-Object -TypeName 'InvalidOperationException' -ArgumentList @( $Message ) - } - else - { - $invalidOperationException = - New-Object -TypeName 'InvalidOperationException' -ArgumentList @( $Message, - $ErrorRecord.Exception ) - } - - $newObjectParams = @{ - TypeName = 'System.Management.Automation.ErrorRecord' - ArgumentList = @( $invalidOperationException.ToString(), 'MachineStateIncorrect', - 'InvalidOperation', $null ) - } - return New-Object @newObjectParams -} - <# .SYNOPSIS Determines if Network Team integration tests can be executed. @@ -112,11 +62,11 @@ function Test-NetworkTeamIntegrationEnvironment if ($NetworkAdapters.Count -lt 2) { Write-Warning -Message (@( - 'Performing Network Teaming integration tests requires at least two compatible' - 'network adapters to be specified.' - 'Please see the comment based help in the header of the integration tests for' - 'instruction on how to specify the network adapters to use.' - ) -join ' ') + 'Performing Network Teaming integration tests requires at least two compatible' + 'network adapters to be specified.' + 'Please see the comment based help in the header of the integration tests for' + 'instruction on how to specify the network adapters to use.' + ) -join ' ') $executeTests = $false } @@ -202,9 +152,8 @@ function Remove-IntegrationLoopbackAdapter } # function Remove-IntegrationLoopbackAdapter -Export-ModuleMember -Function ` - Get-InvalidArgumentRecord, ` - Get-InvalidOperationRecord, ` - Test-NetworkTeamIntegrationEnvironment, ` - New-IntegrationLoopbackAdapter, ` - Remove-IntegrationLoopbackAdapter +# Export-ModuleMember -Function ` +# Get-InvalidArgumentRecord, ` +# Test-NetworkTeamIntegrationEnvironment, ` +# New-IntegrationLoopbackAdapter, ` +# Remove-IntegrationLoopbackAdapter diff --git a/tests/Unit/DSC_DefaultGatewayAddress.Tests.ps1 b/tests/Unit/DSC_DefaultGatewayAddress.Tests.ps1 index 2f203ba4..343c7710 100644 --- a/tests/Unit/DSC_DefaultGatewayAddress.Tests.ps1 +++ b/tests/Unit/DSC_DefaultGatewayAddress.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_DefaultGatewayAddress' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_DefaultGatewayAddress' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,315 +35,444 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} -Invoke-TestSetup + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - $getNetRouteIpv4_Mock = { - [PSCustomObject] @{ - NextHop = '192.168.0.1' - DestinationPrefix = '0.0.0.0/0' - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - AddressFamily = 'IPv4' + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} + +Describe 'DSC_DefaultGatewayAddress\Get-TargetResource' -Tag 'Get' { + Context 'When interface has a default gateway set' { + BeforeAll { + Mock -CommandName Get-NetDefaultRoute -MockWith { + @{ + NextHop = '192.168.0.1' + DestinationPrefix = '0.0.0.0/0' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + AddressFamily = 'IPv4' + } } } - Describe 'DSC_DefaultGatewayAddress\Get-TargetResource' -Tag 'Get' { - Context 'When interface has a default gateway set' { - Mock -CommandName Get-NetRoute -MockWith $getNetRouteIpv4_Mock + It 'Should return current default gateway' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return current default gateway' { - $getTargetResourceParameters = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + $getTargetResourceParameters = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + } - $result = Get-TargetResource @getTargetResourceParameters + $result = Get-TargetResource @getTargetResourceParameters - $result.Address | Should -Be '192.168.0.1' - } + $result.Address | Should -Be '192.168.0.1' } - Context 'When interface has no default gateway set' { - Mock -CommandName Get-NetRoute + Should -Invoke -CommandName Get-NetDefaultRoute -Exactly -Times 1 -Scope Context + } + } - It 'Should return no default gateway' { - $getTargetResourceParameters = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'When interface has no default gateway set' { + BeforeAll { + Mock -CommandName Get-NetDefaultRoute + } - $result = Get-TargetResource @getTargetResourceParameters + It 'Should return no default gateway' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $result.Address | Should -BeNullOrEmpty + $getTargetResourceParameters = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Get-TargetResource @getTargetResourceParameters + + $result.Address | Should -BeNullOrEmpty } + + Should -Invoke -CommandName Get-NetDefaultRoute -Exactly -Times 1 -Scope Context } + } +} - Describe 'DSC_DefaultGatewayAddress\Set-TargetResource' -Tag 'Set' { - BeforeEach { - Mock -CommandName Get-NetRoute -MockWith $getNetRouteIpv4_Mock - Mock -CommandName Remove-NetRoute - Mock -CommandName New-NetRoute +Describe 'DSC_DefaultGatewayAddress\Set-TargetResource' -Tag 'Set' { + BeforeEach { + Mock -CommandName Get-NetDefaultRoute -MockWith { + @{ + NextHop = '192.168.0.1' + DestinationPrefix = '0.0.0.0/0' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + AddressFamily = 'IPv4' } + } - Context 'When invoking with no Default Gateway Address' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Mock -CommandName Get-NetDefaultGatewayDestinationPrefix -MockWith { + '0.0.0.0/0' + } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw + Mock -CommandName Remove-NetRoute + Mock -CommandName New-NetRoute + } - $result | Should -BeNullOrEmpty - } + Context 'When invoking with no Default Gateway Address' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-NetRoute -Exactly 1 - Assert-MockCalled -commandName Remove-NetRoute -Exactly 1 - Assert-MockCalled -commandName New-NetRoute -Exactly 0 + $setTargetResourceParameters = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } + } - Context 'When invoking with valid Default Gateway Address' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetDefaultRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetRoute -Exactly -Times 0 -Scope Context + } + } - { - $result = Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw + Context 'When invoking with valid Default Gateway Address' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $result | Should -BeNullOrEmpty + $setTargetResourceParameters = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-NetRoute -Exactly 1 - Assert-MockCalled -commandName Remove-NetRoute -Exactly 1 - Assert-MockCalled -commandName New-NetRoute -Exactly 1 - } + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } } - Describe 'DSC_DefaultGatewayAddress\Test-TargetResource' -Tag 'Test' { - BeforeEach { - Mock -CommandName Get-NetAdapter -MockWith { - [PSObject] @{ - Name = 'Ethernet' - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetDefaultRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetDefaultGatewayDestinationPrefix -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetRoute -Exactly -Times 1 -Scope Context + } + } +} + +Describe 'DSC_DefaultGatewayAddress\Test-TargetResource' -Tag 'Test' { + Context 'When checking return with default gateway that matches currently set one' { + BeforeAll { + Mock -CommandName Assert-ResourceProperty + Mock -CommandName Get-NetDefaultRoute -MockWith { + @{ + NextHop = '192.168.0.1' + DestinationPrefix = '0.0.0.0/0' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + AddressFamily = 'IPv4' } } + } - Context 'When checking return with default gateway that matches currently set one' { - Mock -CommandName Get-NetRoute -MockWith $getNetRouteIpv4_Mock - - It 'Should return true' { - $testTargetResourceParameters = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Test-TargetResource @testTargetResourceParameters | Should -Be $true + $testTargetResourceParameters = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - } - Context 'Checking return with no gateway but one is currently set' { - Mock -CommandName Get-NetRoute -MockWith $getNetRouteIpv4_Mock + Test-TargetResource @testTargetResourceParameters | Should -BeTrue + } - It 'Should return false' { - $testTargetResourceParameters = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Should -Invoke Assert-ResourceProperty -Exactly -Times 1 -Scope It + Should -Invoke Get-NetDefaultRoute -Exactly -Times 1 -Scope It + } + } - Test-TargetResource @testTargetResourceParameters | Should -Be $False + Context 'Checking return with no gateway but one is currently set' { + BeforeAll { + Mock -CommandName Assert-ResourceProperty + Mock -CommandName Get-NetDefaultRoute -MockWith { + @{ + NextHop = '192.168.0.1' + DestinationPrefix = '0.0.0.0/0' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + AddressFamily = 'IPv4' } } + } - Context 'Checking return with default gateway but none are currently set' { - Mock -CommandName Get-NetRoute - - It 'Should return false' { - $testTargetResourceParameters = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Test-TargetResource @testTargetResourceParameters | Should -Be $False + $testTargetResourceParameters = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } - Context 'Checking return with no gateway and none are currently set' { - Mock -CommandName Get-NetRoute + Should -Invoke Assert-ResourceProperty -Exactly -Times 1 -Scope It + Should -Invoke Get-NetDefaultRoute -Exactly -Times 1 -Scope It + } + } + + Context 'Checking return with default gateway but none are currently set' { + BeforeAll { + Mock -CommandName Assert-ResourceProperty + Mock -CommandName Get-NetDefaultRoute + } - It 'Should return true' { - $testTargetResourceParameters = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Test-TargetResource @testTargetResourceParameters | Should -Be $true + $testTargetResourceParameters = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } + + Should -Invoke Assert-ResourceProperty -Exactly -Times 1 -Scope It + Should -Invoke Get-NetDefaultRoute -Exactly -Times 1 -Scope It + } + } + + Context 'Checking return with no gateway and none are currently set' { + BeforeAll { + Mock -CommandName Assert-ResourceProperty + Mock -CommandName Get-NetDefaultRoute } - Describe 'DSC_DefaultGatewayAddress\Assert-ResourceProperty' { - BeforeEach { - Mock -CommandName Get-NetAdapter -MockWith { - [PSObject] @{ - Name = 'Ethernet' - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testTargetResourceParameters = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } - Context 'When invoking with bad interface alias' { - It 'Should throw an InterfaceNotAvailable error' { - $assertResourcePropertyParameters = @{ - Address = '192.168.0.1' - InterfaceAlias = 'NotReal' - AddressFamily = 'IPv4' - } + Should -Invoke Assert-ResourceProperty -Exactly -Times 1 -Scope It + Should -Invoke Get-NetDefaultRoute -Exactly -Times 1 -Scope It + } + } +} + +Describe 'DSC_DefaultGatewayAddress\Assert-ResourceProperty' -Tag 'Private' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + } + } + } - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.InterfaceNotAvailableError -f $assertResourcePropertyParameters.InterfaceAlias) + Context 'When invoking with bad interface alias' { + It 'Should throw an InterfaceNotAvailable error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw $ErrorRecord + $assertResourcePropertyParameters = @{ + Address = '192.168.0.1' + InterfaceAlias = 'NotReal' + AddressFamily = 'IPv4' } + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.InterfaceNotAvailableError -f $assertResourcePropertyParameters.InterfaceAlias) + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw -ExpectedMessage $ErrorRecord } + } + } - Context 'When invoking with invalid IP Address' { - It 'Should throw an exception' { - $assertResourcePropertyParameters = @{ - Address = 'NotReal' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'When invoking with invalid IP Address' { + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw + $assertResourcePropertyParameters = @{ + Address = 'NotReal' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw } + } + } - Context 'When invoking with IPv4 Address and family mismatch' { - It 'Should throw an exception' { - $assertResourcePropertyParameters = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + Context 'When invoking with IPv4 Address and family mismatch' { + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw + $assertResourcePropertyParameters = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw } + } + } - Context 'When invoking with IPv6 Address and family mismatch' { - It 'Should throw an exception' { - $assertResourcePropertyParameters = @{ - Address = 'fe80::' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'When invoking with IPv6 Address and family mismatch' { + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw + $assertResourcePropertyParameters = @{ + Address = 'fe80::' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw } + } + } - Context 'When invoking with valid IPv4 Address' { - It 'Should not throw an error' { - $assertResourcePropertyParameters = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'When invoking with valid IPv4 Address' { + It 'Should not throw an error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw + $assertResourcePropertyParameters = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw } + } + } - Context 'When invoking with valid IPv6 Address' { - It 'Should not throw an error' { - $assertResourcePropertyParameters = @{ - Address = 'fe80:ab04:30F5:002b::1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + Context 'When invoking with valid IPv6 Address' { + It 'Should not throw an error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw + $assertResourcePropertyParameters = @{ + Address = 'fe80:ab04:30F5:002b::1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw } } + } +} - Describe 'DSC_DefaultGatewayAddress\Get-NetDefaultGatewayDestinationPrefix' { - Context 'When the AddressFamily is IPv4' { - It 'Should return current default gateway' { - Get-NetDefaultGatewayDestinationPrefix -AddressFamily 'IPv4' | Should -Be '0.0.0.0/0' - } +Describe 'DSC_DefaultGatewayAddress\Get-NetDefaultGatewayDestinationPrefix' -Tag 'Private' { + Context 'When the AddressFamily is IPv4' { + It 'Should return current default gateway' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Get-NetDefaultGatewayDestinationPrefix -AddressFamily 'IPv4' | Should -Be '0.0.0.0/0' } + } + } - Context 'When the AddressFamily is IPv6' { - It 'Should return current default gateway' { - Get-NetDefaultGatewayDestinationPrefix -AddressFamily 'IPv6' | Should -Be '::/0' - } + Context 'When the AddressFamily is IPv6' { + It 'Should return current default gateway' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Get-NetDefaultGatewayDestinationPrefix -AddressFamily 'IPv6' | Should -Be '::/0' } } + } +} - Describe 'DSC_DefaultGatewayAddress\Get-NetDefaultRoute' { - Context 'When interface has a default gateway set' { - Mock -CommandName Get-NetRoute -MockWith { - [PSCustomObject] @{ - NextHop = '192.168.0.1' - DestinationPrefix = '0.0.0.0/0' - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - AddressFamily = 'IPv4' - } +Describe 'DSC_DefaultGatewayAddress\Get-NetDefaultRoute' -Tag 'Private' { + Context 'When interface has a default gateway set' { + BeforeAll { + Mock -CommandName Get-NetRoute -MockWith { + @{ + NextHop = '192.168.0.1' + DestinationPrefix = '0.0.0.0/0' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + AddressFamily = 'IPv4' } + } + } - It 'Should return current default gateway' { - $GetNetDefaultRouteParameters = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } - - $result = Get-NetDefaultRoute @GetNetDefaultRouteParameters + It 'Should return current default gateway' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $result.NextHop | Should -Be '192.168.0.1' + $GetNetDefaultRouteParameters = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - } - Context 'When interface has no default gateway set' { - Mock -CommandName Get-NetRoute + $result = Get-NetDefaultRoute @GetNetDefaultRouteParameters + + $result.NextHop | Should -Be '192.168.0.1' + } + } + } - It 'Should return no default gateway' { - $GetNetDefaultRouteParameters = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'When interface has no default gateway set' { + BeforeAll { + Mock -CommandName Get-NetRoute + } - $result = Get-NetDefaultRoute @GetNetDefaultRouteParameters + It 'Should return no default gateway' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $result | Should -BeNullOrEmpty + $GetNetDefaultRouteParameters = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Get-NetDefaultRoute @GetNetDefaultRouteParameters + + $result | Should -BeNullOrEmpty } } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_DnsClientGlobalSetting.Tests.ps1 b/tests/Unit/DSC_DnsClientGlobalSetting.Tests.ps1 index 679d7523..73d1e9ee 100644 --- a/tests/Unit/DSC_DnsClientGlobalSetting.Tests.ps1 +++ b/tests/Unit/DSC_DnsClientGlobalSetting.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_DnsClientGlobalSetting' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_DnsClientGlobalSetting' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,325 +35,509 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} -Invoke-TestSetup + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - # Create the Mock Objects that will be used for running tests - $dnsClientGlobalSettings = [PSObject] @{ - SuffixSearchList = 'contoso.com' - DevolutionLevel = 1 - UseDevolution = $true +Describe 'DSC_DnsClientGlobalSetting\Get-TargetResource' -Tag 'Get' { + BeforeEach { + Mock -CommandName Get-DnsClientGlobalSetting -MockWith { + @{ + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true + } } + } + + Context 'DNS Client Global Settings Exists' { + It 'Should return correct DNS Client Global Settings values' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $getTargetResourceParameters = Get-TargetResource -IsSingleInstance 'Yes' - $dnsClientGlobalMultiSuffixSettings = [PSObject]@{ - SuffixSearchList = @('fabrikam.com', 'fourthcoffee.com') - DevolutionLevel = 1 - UseDevolution = $true + $getTargetResourceParameters.SuffixSearchList | Should -Be 'contoso.com' + $getTargetResourceParameters.DevolutionLevel | Should -Be 1 + $getTargetResourceParameters.UseDevolution | Should -BeTrue + } } - $dnsClientGlobalEmptyArraySuffixSettings = [PSObject]@{ - SuffixSearchList = @() - DevolutionLevel = 1 - UseDevolution = $true + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context } + } +} - $dnsClientGlobalEmptyStringSuffixSettings = [PSObject]@{ - SuffixSearchList = '' - DevolutionLevel = 1 - UseDevolution = $true +Describe 'DSC_DnsClientGlobalSetting\Set-TargetResource' -Tag 'Set' { + BeforeEach { + Mock -CommandName Get-DnsClientGlobalSetting -MockWith { + @{ + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true + } } + } - $dnsClientGlobalSettingsSplat = [PSObject]@{ - IsSingleInstance = 'Yes' - SuffixSearchList = $dnsClientGlobalSettings.SuffixSearchList - DevolutionLevel = $dnsClientGlobalSettings.DevolutionLevel - UseDevolution = $dnsClientGlobalSettings.UseDevolution + Context 'DNS Client Global Settings all parameters are the same' { + BeforeAll { + Mock -CommandName Set-DnsClientGlobalSetting } - Describe 'DSC_DnsClientGlobalSetting\Get-TargetResource' -Tag 'Get' { - BeforeEach { - Mock -CommandName Get-DnsClientGlobalSetting -MockWith { $dnsClientGlobalSettings } - } + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'DNS Client Global Settings Exists' { - It 'Should return correct DNS Client Global Settings values' { - $getTargetResourceParameters = Get-TargetResource -IsSingleInstance 'Yes' - $getTargetResourceParameters.SuffixSearchList | Should -Be $dnsClientGlobalSettings.SuffixSearchList - $getTargetResourceParameters.DevolutionLevel | Should -Be $dnsClientGlobalSettings.DevolutionLevel - $getTargetResourceParameters.UseDevolution | Should -Be $dnsClientGlobalSettings.UseDevolution + $setTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 - } + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } } - Describe 'DSC_DnsClientGlobalSetting\Set-TargetResource' -Tag 'Set' { - BeforeEach { - Mock -CommandName Get-DnsClientGlobalSetting -MockWith { $dnsClientGlobalSettings } - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-DnsClientGlobalSetting -Exactly -Times 0 -Scope Context + } + } - Context 'DNS Client Global Settings all parameters are the same' { - Mock -CommandName Set-DnsClientGlobalSetting + Context 'DNS Client Global Settings SuffixSearchList is different' { + BeforeAll { + Mock -CommandName Set-DnsClientGlobalSetting + } - It 'Should not throw error' { - { - $setTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 - Assert-MockCalled -commandName Set-DnsClientGlobalSetting -Exactly -Times 0 + $setTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } - } - Context 'DNS Client Global Settings SuffixSearchList is different' { - Mock -CommandName Set-DnsClientGlobalSetting + $setTargetResourceParameters.SuffixSearchList = 'fabrikam.com' - It 'Should not throw error' { - { - $setTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $setTargetResourceParameters.SuffixSearchList = 'fabrikam.com' - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } - - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 - Assert-MockCalled -commandName Set-DnsClientGlobalSetting -Exactly -Times 1 - } + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } + } - Context 'DNS Client Global Settings SuffixSearchList Array is different' { - $suffixSearchListArray = @('fabrikam.com', 'fourthcoffee.com') + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } + + Context 'DNS Client Global Settings SuffixSearchList Array is different' { + BeforeAll { + $suffixSearchListArray = @('fabrikam.com', 'fourthcoffee.com') - $setDnsClientGlobalMockParameterFilter = { + $setDnsClientGlobalMockParameterFilter = { (Compare-Object -ReferenceObject $suffixSearchList -DifferenceObject $suffixSearchListArray -SyncWindow 0).Length -eq 0 - } + } - Mock -CommandName Set-DnsClientGlobalSetting -ParameterFilter $setDnsClientGlobalMockParameterFilter + Mock -CommandName Set-DnsClientGlobalSetting -ParameterFilter $setDnsClientGlobalMockParameterFilter + } - It 'Should not throw error' { - { - $setTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $setTargetResourceParameters.SuffixSearchList = $suffixSearchListArray - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 - Assert-MockCalled -commandName Set-DnsClientGlobalSetting -ParameterFilter $setDnsClientGlobalMockParameterFilter -Exactly -Times 1 + $setTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $setTargetResourceParameters.SuffixSearchList = @('fabrikam.com', 'fourthcoffee.com') + + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } + } - Context 'DNS Client Global Settings DevolutionLevel is different' { - Mock -CommandName Set-DnsClientGlobalSetting + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-DnsClientGlobalSetting -ParameterFilter $setDnsClientGlobalMockParameterFilter -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw error' { - { - $setTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $setTargetResourceParameters.DevolutionLevel = $setTargetResourceParameters.DevolutionLevel + 1 - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } + Context 'DNS Client Global Settings DevolutionLevel is different' { + BeforeAll { + Mock -CommandName Set-DnsClientGlobalSetting + } - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 - Assert-MockCalled -commandName Set-DnsClientGlobalSetting -Exactly -Times 1 + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $setTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $setTargetResourceParameters.DevolutionLevel = $setTargetResourceParameters.DevolutionLevel + 1 + + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } + } - Context 'DNS Client Global Settings UseDevolution is different' { - Mock -CommandName Set-DnsClientGlobalSetting + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw error' { - { - $setTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $setTargetResourceParameters.UseDevolution = -not $setTargetResourceParameters.UseDevolution - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } + Context 'DNS Client Global Settings UseDevolution is different' { + BeforeAll { + Mock -CommandName Set-DnsClientGlobalSetting + } + + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 - Assert-MockCalled -commandName Set-DnsClientGlobalSetting -Exactly -Times 1 + $setTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $setTargetResourceParameters.UseDevolution = -not $setTargetResourceParameters.UseDevolution + + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } } - Describe 'DSC_DnsClientGlobalSetting\Test-TargetResource' -Tag 'Test' { - Context 'Single suffix is in the search list' { - BeforeEach { - Mock -CommandName Get-DnsClientGlobalSetting -MockWith { $dnsClientGlobalSettings } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } +} + +Describe 'DSC_DnsClientGlobalSetting\Test-TargetResource' -Tag 'Test' { + Context 'Single suffix is in the search list' { + BeforeEach { + Mock -CommandName Get-DnsClientGlobalSetting -MockWith { + @{ + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + } + } - Context 'DNS Client Global Settings all parameters are the same' { - It 'Should return true' { - $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - Test-TargetResource @testTargetResourceParameters | Should -Be $true - } + Context 'DNS Client Global Settings all parameters are the same' { + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 + $testTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } + } - Context 'DNS Client Global Settings SuffixSearchList is different' { - It 'Should return false' { - $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $testTargetResourceParameters.SuffixSearchList = 'fabrikam.com' - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 + Context 'DNS Client Global Settings SuffixSearchList is different' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $testTargetResourceParameters.SuffixSearchList = 'fabrikam.com' + + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } + } - Context 'DNS Client Global Settings DevolutionLevel is different' { - It 'Should return false' { - $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $testTargetResourceParameters.DevolutionLevel = $testTargetResourceParameters.DevolutionLevel + 1 - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 + Context 'DNS Client Global Settings DevolutionLevel is different' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $testTargetResourceParameters.DevolutionLevel = $testTargetResourceParameters.DevolutionLevel + 1 + + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } + } - Context 'DNS Client Global Settings UseDevolution is different' { - It 'Should return false' { - $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $testTargetResourceParameters.UseDevolution = -not $testTargetResourceParameters.UseDevolution - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } + + Context 'DNS Client Global Settings UseDevolution is different' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 + $testTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $testTargetResourceParameters.UseDevolution = -not $testTargetResourceParameters.UseDevolution + + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } } - Context 'Mulitple suffixes are in the search list' { - BeforeEach { - Mock -CommandName Get-DnsClientGlobalSetting -MockWith { $dnsClientGlobalMultiSuffixSettings } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } + } + + Context 'Mulitple suffixes are in the search list' { + BeforeEach { + Mock -CommandName Get-DnsClientGlobalSetting -MockWith { + @{ + SuffixSearchList = @('fabrikam.com', 'fourthcoffee.com') + DevolutionLevel = 1 + UseDevolution = $true } + } + } - Context 'DNS Client Global Settings SuffixSearchList Array is different' { - It 'Should return false' { - $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $testTargetResourceParameters.SuffixSearchList = @('fabrikam.com', 'contoso.com') - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } + Context 'DNS Client Global Settings SuffixSearchList Array is different' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 + $testTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $testTargetResourceParameters.SuffixSearchList = @('fabrikam.com', 'contoso.com') + + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } + } - Context 'DNS Client Global Settings SuffixSearchList Array Order is same' { - It 'Should return true' { - $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $testTargetResourceParameters.SuffixSearchList = @('fabrikam.com', 'fourthcoffee.com') - Test-TargetResource @testTargetResourceParameters | Should -Be $true - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } + + Context 'DNS Client Global Settings SuffixSearchList Array Order is same' { + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 + $testTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $testTargetResourceParameters.SuffixSearchList = @('fabrikam.com', 'fourthcoffee.com') + + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } + } - Context 'DNS Client Global Settings SuffixSearchList Array Order is different' { - It 'Should return false' { - $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $testTargetResourceParameters.SuffixSearchList = @('fourthcoffee.com', 'fabrikam.com') - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } + + Context 'DNS Client Global Settings SuffixSearchList Array Order is different' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 + $testTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $testTargetResourceParameters.SuffixSearchList = @('fourthcoffee.com', 'fabrikam.com') + + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } } - Context 'When the search list is an empty array' { - BeforeEach { - Mock -CommandName Get-DnsClientGlobalSetting -MockWith { $dnsClientGlobalEmptyArraySuffixSettings } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } + } + + Context 'When the search list is an empty array' { + BeforeEach { + Mock -CommandName Get-DnsClientGlobalSetting -MockWith { + @{ + SuffixSearchList = @() + DevolutionLevel = 1 + UseDevolution = $true } + } + } - Context 'When the DNS Client Global Settings SuffixSearchList Array is different' { - It 'Should return false' { - $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $testTargetResourceParameters.SuffixSearchList = @('fabrikam.com') - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } + Context 'When the DNS Client Global Settings SuffixSearchList Array is different' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 + $testTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $testTargetResourceParameters.SuffixSearchList = @('fabrikam.com') + + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } + } - Context 'When the DNS Client Global Settings SuffixSearchList is same' { - It 'Should return true' { - $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $testTargetResourceParameters.SuffixSearchList = @() - Test-TargetResource @testTargetResourceParameters | Should -Be $true - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } + + Context 'When the DNS Client Global Settings SuffixSearchList is same' { + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 + $testTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $testTargetResourceParameters.SuffixSearchList = @() + + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } - Context 'When the search list is an empty string' { - BeforeEach { - Mock -CommandName Get-DnsClientGlobalSetting -MockWith { $dnsClientGlobalEmptyStringSuffixSettings } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } + } + + Context 'When the search list is an empty string' { + BeforeEach { + Mock -CommandName Get-DnsClientGlobalSetting -MockWith { + @{ + SuffixSearchList = '' + DevolutionLevel = 1 + UseDevolution = $true } + } + } - Context 'When the DNS Client Global Settings SuffixSearchList Array is different' { - It 'Should return false' { - $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $testTargetResourceParameters.SuffixSearchList = @('fabrikam.com') - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } + Context 'When the DNS Client Global Settings SuffixSearchList Array is different' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 + $testTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $testTargetResourceParameters.SuffixSearchList = @('fabrikam.com') + + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } + } - Context 'When the DNS Client Global Settings SuffixSearchList is same' { - It 'Should return true' { - $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - $testTargetResourceParameters.SuffixSearchList = @() - Test-TargetResource @testTargetResourceParameters | Should -Be $true - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-DnsClientGlobalSetting -Exactly -Times 1 + Context 'When the DNS Client Global Settings SuffixSearchList is same' { + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testTargetResourceParameters = @{ + IsSingleInstance = 'Yes' + SuffixSearchList = 'contoso.com' + DevolutionLevel = 1 + UseDevolution = $true } + + $testTargetResourceParameters.SuffixSearchList = @() + + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-DnsClientGlobalSetting -Exactly -Times 1 -Scope Context + } } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_DnsConnectionSuffix.Tests.ps1 b/tests/Unit/DSC_DnsConnectionSuffix.Tests.ps1 index 14c7f056..e3a78c47 100644 --- a/tests/Unit/DSC_DnsConnectionSuffix.Tests.ps1 +++ b/tests/Unit/DSC_DnsConnectionSuffix.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_DnsConnectionSuffix' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_DnsConnectionSuffix' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,192 +35,379 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup - -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - $testDnsSuffix = 'example.local' - $testInterfaceAlias = 'Ethernet' - $testDnsSuffixParams = @{ - InterfaceAlias = $testInterfaceAlias - ConnectionSpecificSuffix = $testDnsSuffix - } +Describe 'DSC_DnsConnectionSuffix\Get-TargetResource' -Tag 'Get' { + Context 'Validates "Get-TargetResource" method' { + Context 'When the Dns Suffix does match' { + BeforeAll { + Mock -CommandName Get-DnsClient -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + RegisterThisConnectionsAddress = $true + UseSuffixWhenRegistering = $false + } + } + } - $fakeDnsSuffixPresent = @{ - InterfaceAlias = $testInterfaceAlias - ConnectionSpecificSuffix = $testDnsSuffix - RegisterThisConnectionsAddress = $true - UseSuffixWhenRegistering = $false - } + It 'Should return a "System.Collections.Hashtable" object type' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $fakeDnsSuffixMismatch = $fakeDnsSuffixPresent.Clone() - $fakeDnsSuffixMismatch['ConnectionSpecificSuffix'] = 'mismatch.local' + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + } - $fakeDnsSuffixAbsent = $fakeDnsSuffixPresent.Clone() - $fakeDnsSuffixAbsent['ConnectionSpecificSuffix'] = '' + $targetResource = Get-TargetResource @testDnsSuffixParams + $targetResource -is [System.Collections.Hashtable] | Should -BeTrue + } + } - Describe 'DSC_DnsConnectionSuffix\Get-TargetResource' -Tag 'Get' { - Context 'Validates "Get-TargetResource" method' { - It 'Should return a "System.Collections.Hashtable" object type' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixPresent } + It 'Should return "Present" when DNS suffix matches and "Ensure" = "Present"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + } $targetResource = Get-TargetResource @testDnsSuffixParams - $targetResource -is [System.Collections.Hashtable] | Should -Be $true + $targetResource.Ensure | Should -Be 'Present' } + } + + It 'Should return "Present" when DNS suffix is defined and "Ensure" = "Absent"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return "Present" when DNS suffix matches and "Ensure" = "Present"' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixPresent } + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + Ensure = 'Absent' + } $targetResource = Get-TargetResource @testDnsSuffixParams $targetResource.Ensure | Should -Be 'Present' } + } + } + + Context 'When the Dns Suffix is blank' { + BeforeAll { + Mock -CommandName Get-DnsClient -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = '' + RegisterThisConnectionsAddress = $true + UseSuffixWhenRegistering = $false + } + } + } + + It 'Should return "Absent" when no DNS suffix is defined and "Ensure" = "Present"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return "Absent" when DNS suffix does not match and "Ensure" = "Present"' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixMismatch } + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + } $targetResource = Get-TargetResource @testDnsSuffixParams $targetResource.Ensure | Should -Be 'Absent' } + } - It 'Should return "Absent" when no DNS suffix is defined and "Ensure" = "Present"' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixAbsent } + It 'Should return "Absent" when no DNS suffix is defined and "Ensure" = "Absent"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + Ensure = 'Absent' + } $targetResource = Get-TargetResource @testDnsSuffixParams $targetResource.Ensure | Should -Be 'Absent' } + } + } - It 'Should return "Absent" when no DNS suffix is defined and "Ensure" = "Absent"' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixAbsent } + Context 'When the Dns Suffix does not match' { + It 'Should return "Absent" when DNS suffix does not match and "Ensure" = "Present"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $targetResource = Get-TargetResource @testDnsSuffixParams -Ensure Absent + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + } + + $targetResource = Get-TargetResource @testDnsSuffixParams $targetResource.Ensure | Should -Be 'Absent' } + } + } + } +} - It 'Should return "Present" when DNS suffix is defined and "Ensure" = "Absent"' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixPresent } +Describe 'DSC_DnsConnectionSuffix\Test-TargetResource' -Tag 'Test' { + Context 'Validates "Test-TargetResource" method' { + Context 'When the Dns Suffix is present' { + BeforeAll { + Mock -CommandName Get-DnsClient -MockWith { @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + RegisterThisConnectionsAddress = $true + UseSuffixWhenRegistering = $false + } + } + } - $targetResource = Get-TargetResource @testDnsSuffixParams -Ensure Absent + It 'Should pass when all properties match and "Ensure" = "Present"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $targetResource.Ensure | Should -Be 'Present' + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + } + + $targetResource = Test-TargetResource @testDnsSuffixParams + + $targetResource | Should -BeTrue } + } - } #end Context 'Validates "Get-TargetResource" method' - } + It 'Should pass when "RegisterThisConnectionsAddress" setting is correct' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Describe 'DSC_DnsConnectionSuffix\Test-TargetResource' -Tag 'Test' { - Context 'Validates "Test-TargetResource" method' { - It 'Should pass when all properties match and "Ensure" = "Present"' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixPresent } + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + RegisterThisConnectionsAddress = $true + } $targetResource = Test-TargetResource @testDnsSuffixParams - $targetResource | Should -Be $true + $targetResource | Should -BeTrue } + } - It 'Should pass when no DNS suffix is registered and "Ensure" = "Absent"' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixAbsent } + It 'Should pass when "UseSuffixWhenRegistering" setting is correct' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $targetResource = Test-TargetResource @testDnsSuffixParams -Ensure Absent + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + UseSuffixWhenRegistering = $false + } + + $targetResource = Test-TargetResource @testDnsSuffixParams - $targetResource | Should -Be $true + $targetResource | Should -BeTrue } + } - It 'Should pass when "RegisterThisConnectionsAddress" setting is correct' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixPresent } + It 'Should fail when a DNS suffix is registered and "Ensure" = "Absent"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $targetResource = Test-TargetResource @testDnsSuffixParams -RegisterThisConnectionsAddress $true + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + Ensure = 'Absent' + } - $targetResource | Should -Be $true + $targetResource = Test-TargetResource @testDnsSuffixParams + + $targetResource | Should -BeFalse } + } - It 'Should pass when "UseSuffixWhenRegistering" setting is correct' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixPresent } + It 'Should fail when "RegisterThisConnectionsAddress" setting is incorrect' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $targetResource = Test-TargetResource @testDnsSuffixParams -UseSuffixWhenRegistering $false + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + RegisterThisConnectionsAddress = $false + } + + $targetResource = Test-TargetResource @testDnsSuffixParams - $targetResource | Should -Be $true + $targetResource | Should -BeFalse } + } + It 'Should fail when "UseSuffixWhenRegistering" setting is incorrect' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should fail when no DNS suffix is registered and "Ensure" = "Present"' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixAbsent } + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + UseSuffixWhenRegistering = $true + } $targetResource = Test-TargetResource @testDnsSuffixParams - $targetResource | Should -Be $false + $targetResource | Should -BeFalse } + } + } + + Context 'When the Dns Suffix is Absent' { + BeforeAll { + Mock -CommandName Get-DnsClient -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = '' + RegisterThisConnectionsAddress = $true + UseSuffixWhenRegistering = $false + } + } + } + + It 'Should pass when no DNS suffix is registered and "Ensure" = "Absent"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should fail when the registered DNS suffix is incorrect and "Ensure" = "Present"' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixMismatch } + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + Ensure = 'Absent' + } $targetResource = Test-TargetResource @testDnsSuffixParams - $targetResource | Should -Be $false + $targetResource | Should -BeTrue } + } - It 'Should fail when a DNS suffix is registered and "Ensure" = "Absent"' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixPresent } + It 'Should fail when no DNS suffix is registered and "Ensure" = "Present"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $targetResource = Test-TargetResource @testDnsSuffixParams -Ensure Absent + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + } - $targetResource | Should -Be $false - } + $targetResource = Test-TargetResource @testDnsSuffixParams - It 'Should fail when "RegisterThisConnectionsAddress" setting is incorrect' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixPresent } + $targetResource | Should -BeFalse + } + } - $targetResource = Test-TargetResource @testDnsSuffixParams -RegisterThisConnectionsAddress $false + } - $targetResource | Should -Be $false + Context 'When the Dns Suffix is blank' { + BeforeAll { + Mock -CommandName Get-DnsClient -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'mismatch.local' + RegisterThisConnectionsAddress = $true + UseSuffixWhenRegistering = $false + } } + } + + It 'Should fail when the registered DNS suffix is incorrect and "Ensure" = "Present"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should fail when "UseSuffixWhenRegistering" setting is incorrect' { - Mock Get-DnsClient { return [PSCustomObject] $fakeDnsSuffixPresent } + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + } - $targetResource = Test-TargetResource @testDnsSuffixParams -UseSuffixWhenRegistering $true + $targetResource = Test-TargetResource @testDnsSuffixParams - $targetResource | Should -Be $false + $targetResource | Should -BeFalse } - } #end Context 'Validates "Test-TargetResource" method' + } } + } +} - Describe 'DSC_DnsConnectionSuffix\Set-TargetResource' -Tag 'Set' { - Context 'Validates "Set-TargetResource" method' { - It 'Should call "Set-DnsClient" with specified DNS suffix when "Ensure" = "Present"' { - Mock Set-DnsClient -ParameterFilter { $InterfaceAlias -eq $testInterfaceAlias -and $ConnectionSpecificSuffix -eq $testDnsSuffix } { } +Describe 'DSC_DnsConnectionSuffix\Set-TargetResource' -Tag 'Set' { + Context 'Validates "Set-TargetResource" method' { + Context 'When Dns Suffix should be added' { + BeforeAll { + Mock -CommandName Set-DnsClient + } - Set-TargetResource @testDnsSuffixParams + It 'Should call "Set-DnsClient" with specified DNS suffix when "Ensure" = "Present"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + } - Assert-MockCalled Set-DnsClient -ParameterFilter { $InterfaceAlias -eq $testInterfaceAlias -and $ConnectionSpecificSuffix -eq $testDnsSuffix } -Scope It + Set-TargetResource @testDnsSuffixParams } - It 'Should call "Set-DnsClient" with no DNS suffix when "Ensure" = "Absent"' { - Mock Set-DnsClient -ParameterFilter { $InterfaceAlias -eq $testInterfaceAlias -and $ConnectionSpecificSuffix -eq '' } { } + Should -Invoke -CommandName Set-DnsClient -ParameterFilter { $ConnectionSpecificSuffix -eq 'example.local' } ` + -Exactly -Times 1 -Scope It + } + } + + Context 'When Dns suffix should be removed' { + BeforeAll { + Mock -CommandName Set-DnsClient + } + + It 'Should call "Set-DnsClient" with no DNS suffix when "Ensure" = "Absent"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Set-TargetResource @testDnsSuffixParams -Ensure Absent + $testDnsSuffixParams = @{ + InterfaceAlias = 'Ethernet' + ConnectionSpecificSuffix = 'example.local' + Ensure = 'Absent' + } - Assert-MockCalled Set-DnsClient -ParameterFilter { $InterfaceAlias -eq $testInterfaceAlias -and $ConnectionSpecificSuffix -eq '' } -Scope It + Set-TargetResource @testDnsSuffixParams } - } #end Context 'Validates "Set-TargetResource" method' + + Should -Invoke -CommandName Set-DnsClient -ParameterFilter { $ConnectionSpecificSuffix -eq '' } ` + -Exactly -Times 1 -Scope It + } } - } #end InModuleScope $DSCResourceName -} -finally -{ - Invoke-TestCleanup + } #end Context 'Validates "Set-TargetResource" method' } diff --git a/tests/Unit/DSC_DnsServerAddress.Tests.ps1 b/tests/Unit/DSC_DnsServerAddress.Tests.ps1 index ac9d3bd0..51a72329 100644 --- a/tests/Unit/DSC_DnsServerAddress.Tests.ps1 +++ b/tests/Unit/DSC_DnsServerAddress.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_DnsServerAddress' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_DnsServerAddress' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,653 +35,766 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup - -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - Describe 'DSC_DnsServerAddress\Get-TargetResource' -Tag 'Get' { - Context 'Test IPv4' { - Context 'Invoking with an IPv4 address and one address is currently set' { - Mock Get-DnsClientServerStaticAddress -MockWith { '192.168.0.1' } - - It 'Should return true' { - $getTargetResourceSplat = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } - - $Result = Get-TargetResource @getTargetResourceSplat - $Result.Address | Should -Be '192.168.0.1' - } +Describe 'DSC_DnsServerAddress\Get-TargetResource' -Tag 'Get' { + Context 'Test IPv4' { + Context 'Invoking with an IPv4 address and one address is currently set' { + BeforeAll { + Mock -CommandName Get-DnsClientServerStaticAddress -MockWith { '192.168.0.1' } + } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $getTargetResourceSplat = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $Result = Get-TargetResource @getTargetResourceSplat + $Result.Address | Should -Be '192.168.0.1' } } - Context 'Test IPv6' { - Context 'Invoking with an IPv6 address and one address is currently set' { - Mock Get-DnsClientServerStaticAddress -MockWith { 'fe80:ab04:30F5:002b::1' } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } + } + } - It 'Should return true' { - $getTargetResourceSplat = @{ - Address = 'fe80:ab04:30F5:002b::1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + Context 'Test IPv6' { + Context 'Invoking with an IPv6 address and one address is currently set' { + BeforeAll { + Mock Get-DnsClientServerStaticAddress -MockWith { 'fe80:ab04:30F5:002b::1' } + } - $Result = Get-TargetResource @getTargetResourceSplat - $Result.Address | Should -Be 'fe80:ab04:30F5:002b::1' - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 + $getTargetResourceSplat = @{ + Address = 'fe80:ab04:30F5:002b::1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + $Result = Get-TargetResource @getTargetResourceSplat + $Result.Address | Should -Be 'fe80:ab04:30F5:002b::1' } } - Context 'Test DHCP' { - Context 'Invoking with an IPv4 address and DHCP is currently set' { - Mock Get-DnsClientServerStaticAddress -MockWith { @() } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } + } + } - It 'Should return true' { - $getTargetResourceSplat = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + Context 'Test DHCP' { + Context 'Invoking with an IPv4 address and DHCP is currently set' { + BeforeAll { + Mock Get-DnsClientServerStaticAddress -MockWith { @() } + } - $Result = Get-TargetResource @getTargetResourceSplat - $Result.Address | Should -BeNullOrEmpty - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 + $getTargetResourceSplat = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $Result = Get-TargetResource @getTargetResourceSplat + $Result.Address | Should -BeNullOrEmpty } } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } } + } +} - Describe 'DSC_DnsServerAddress\Set-TargetResource' -Tag 'Set' { - Context 'Test IPv4' { - BeforeEach { - Mock Get-DnsClientServerStaticAddress -MockWith { '192.168.0.1' } - Mock Set-DnsClientServerAddress -ParameterFilter { $Validate -eq $true } - Mock Set-DnsClientServerAddress -ParameterFilter { $Validate -eq $false } - Mock Set-DnsClientServerAddress -ParameterFilter { $ResetServerAddresses -eq $true } - } +Describe 'DSC_DnsServerAddress\Set-TargetResource' -Tag 'Set' { + Context 'Test IPv4' { + BeforeAll { + Mock Get-DnsClientServerStaticAddress -MockWith { '192.168.0.1' } + Mock Set-DnsClientServerAddress -ParameterFilter { $Validate -eq $true } + Mock Set-DnsClientServerAddress -ParameterFilter { $Validate -eq $false } + Mock Set-DnsClientServerAddress -ParameterFilter { $ResetServerAddresses -eq $true } + } - Context 'Invoking with single IPv4 server address that is the same as current' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + Context 'Invoking with single IPv4 server address that is the same as current' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw + $setTargetResourceSplat = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $ResetServerAddresses -eq $true } - } + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } - Context 'Invoking with single IPv4 server address that is different to current' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = '192.168.0.99' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw - } + Context 'Invoking with single IPv4 server address that is different to current' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $ResetServerAddresses -eq $true } + $setTargetResourceSplat = @{ + Address = '192.168.0.99' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } - Context 'Invoking with single IPv4 server address that is different to current and validate true' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = '192.168.0.99' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Validate = $true - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw - } + Context 'Invoking with single IPv4 server address that is different to current and validate true' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $ResetServerAddresses -eq $true } + $setTargetResourceSplat = @{ + Address = '192.168.0.99' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + Validate = $true } + + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } - Context 'Invoking with multiple IPv4 server addresses that are different to current' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = @( '192.168.0.99', '192.168.0.100' ) - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + Context 'Invoking with multiple IPv4 server addresses that are different to current' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw + $setTargetResourceSplat = @{ + Address = @( '192.168.0.99', '192.168.0.100' ) + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $ResetServerAddresses -eq $true } - } + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } - Context 'Invoking with IPv4 server addresses set to DHCP but one address is currently assigned' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw - } + Context 'Invoking with IPv4 server addresses set to DHCP but one address is currently assigned' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $ResetServerAddresses -eq $true } + $setTargetResourceSplat = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } - Context 'Invoking with multiple IPv4 server addresses when there are different ones currently assigned' { - Mock -commandName Get-DnsClientServerStaticAddress -MockWith { @( '192.168.0.1', '192.168.0.2' ) } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = @( '192.168.0.3', '192.168.0.4' ) - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + Context 'Invoking with multiple IPv4 server addresses when there are different ones currently assigned' { + BeforeAll { + Mock -CommandName Get-DnsClientServerStaticAddress -MockWith { @( '192.168.0.1', '192.168.0.2' ) } + } - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw - } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $ResetServerAddresses -eq $true } + $setTargetResourceSplat = @{ + Address = @( '192.168.0.3', '192.168.0.4' ) + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } - Context 'Invoking with multiple IPv4 server addresses when DHCP is currently set' { - Mock -commandName Get-DnsClientServerStaticAddress -MockWith { @() } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = @( '192.168.0.2', '192.168.0.3' ) - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + Context 'Invoking with multiple IPv4 server addresses when DHCP is currently set' { + BeforeAll { + Mock -CommandName Get-DnsClientServerStaticAddress -MockWith { @() } + } - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw - } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $ResetServerAddresses -eq $true } + $setTargetResourceSplat = @{ + Address = @( '192.168.0.2', '192.168.0.3' ) + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } } - Context 'Test IPv6' { - BeforeEach { - Mock Get-DnsClientServerStaticAddress -MockWith { 'fe80:ab04:30F5:002b::1' } - Mock Set-DnsClientServerAddress -ParameterFilter { $Validate -eq $true } - Mock Set-DnsClientServerAddress -ParameterFilter { $Validate -eq $false } - Mock Set-DnsClientServerAddress -ParameterFilter { $ResetServerAddresses -eq $true } - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } + } - Context 'Invoking with single IPv6 server address that is the same as current' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = 'fe80:ab04:30F5:002b::1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + Context 'Test IPv6' { + BeforeAll { + Mock Get-DnsClientServerStaticAddress -MockWith { 'fe80:ab04:30F5:002b::1' } + Mock Set-DnsClientServerAddress -ParameterFilter { $Validate -eq $true } + Mock Set-DnsClientServerAddress -ParameterFilter { $Validate -eq $false } + Mock Set-DnsClientServerAddress -ParameterFilter { $ResetServerAddresses -eq $true } + } - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw - } + Context 'Invoking with single IPv6 server address that is the same as current' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $ResetServerAddresses -eq $true } + $setTargetResourceSplat = @{ + Address = 'fe80:ab04:30F5:002b::1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } - Context 'Invoking with single IPv6 server address that is different to current' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = 'fe80:ab04:30F5:002b::2' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + Context 'Invoking with single IPv6 server address that is different to current' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw + $setTargetResourceSplat = @{ + Address = 'fe80:ab04:30F5:002b::2' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $ResetServerAddresses -eq $true } - } + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } - Context 'Invoking with single IPv6 server address that is different to current and validate true' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = 'fe80:ab04:30F5:002b::2' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Validate = $true - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw - } + Context 'Invoking with single IPv6 server address that is different to current and validate true' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $ResetServerAddresses -eq $true } + $setTargetResourceSplat = @{ + Address = 'fe80:ab04:30F5:002b::2' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' + Validate = $true } + + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } - Context 'Invoking with multiple IPv6 server addresses that are different to current' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = @( 'fe80:ab04:30F5:002b::1', 'fe80:ab04:30F5:002b::2' ) - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw - } + Context 'Invoking with multiple IPv6 server addresses that are different to current' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $ResetServerAddresses -eq $true } + $setTargetResourceSplat = @{ + Address = @( 'fe80:ab04:30F5:002b::1', 'fe80:ab04:30F5:002b::2' ) + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } - Context 'Invoking with IPv6 server addresses set to DHCP but one address is currently assigned' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + Context 'Invoking with IPv6 server addresses set to DHCP but one address is currently assigned' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw + $setTargetResourceSplat = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $ResetServerAddresses -eq $true } - } + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } - Context 'Invoking with multiple IPv6 server addresses when DHCP is currently set' { - Mock Get-DnsClientServerStaticAddress -MockWith { @() } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } + } - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = @( 'fe80:ab04:30F5:002b::1', 'fe80:ab04:30F5:002b::1' ) - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + Context 'Invoking with multiple IPv6 server addresses when DHCP is currently set' { + BeforeAll { + Mock Get-DnsClientServerStaticAddress -MockWith { @() } + } - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw - } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 0 - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $Validate -eq $true } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 1 -ParameterFilter { $Validate -eq $false } - Assert-MockCalled -commandName Set-DnsClientServerAddress -Exactly 0 -ParameterFilter { $ResetServerAddresses -eq $true } + $setTargetResourceSplat = @{ + Address = @( 'fe80:ab04:30F5:002b::1', 'fe80:ab04:30F5:002b::1' ) + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $Validate -eq $true } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 1 -Scope Context -ParameterFilter { $Validate -eq $false } + Should -Invoke -CommandName Set-DnsClientServerAddress -Exactly -Times 0 -Scope Context -ParameterFilter { $ResetServerAddresses -eq $true } + } } + } +} - Describe 'DSC_DnsServerAddress\Test-TargetResource' -Tag 'Test' { - Context 'Test IPv4' { - BeforeEach { - Mock Get-NetAdapter -MockWith { [PSObject]@{ Name = 'Ethernet' } } - Mock Get-DnsClientServerStaticAddress -MockWith { '192.168.0.1' } - } +Describe 'DSC_DnsServerAddress\Test-TargetResource' -Tag 'Test' { + Context 'Test IPv4' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { @{ Name = 'Ethernet' } } + Mock -CommandName Get-DnsClientServerStaticAddress -MockWith { '192.168.0.1' } + } - Context 'Invoking with single IPv4 server address that is the same as current' { - It 'Should return true' { - $testTargetResourceSplat = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + Context 'Invoking with single IPv4 server address that is the same as current' { + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Test-TargetResource @testTargetResourceSplat | Should -Be $true + $testTargetResourceSplat = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 - } + Test-TargetResource @testTargetResourceSplat | Should -BeTrue } + } - Context 'Invoking with single IPv4 server address that is different to current' { - It 'Should return false' { - $testTargetResourceSplat = @{ - Address = '192.168.0.2' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } + } - Test-TargetResource @testTargetResourceSplat | Should -Be $False - } + Context 'Invoking with single IPv4 server address that is different to current' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 + $testTargetResourceSplat = @{ + Address = '192.168.0.2' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } + } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } + } - Context 'Invoking with multiple IPv4 server addresses that are different to current' { - It 'Should return false' { - $testTargetResourceSplat = @{ - Address = @( '192.168.0.2', '192.168.0.3' ) - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + Context 'Invoking with multiple IPv4 server addresses that are different to current' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Test-TargetResource @testTargetResourceSplat | Should -Be $False + $testTargetResourceSplat = @{ + Address = @( '192.168.0.2', '192.168.0.3' ) + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 - } + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } + } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } + } - Context 'Invoking with IPv4 server addresses set to DHCP but one address is currently assigned' { - It 'Should return false' { - $testTargetResourceSplat = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + Context 'Invoking with IPv4 server addresses set to DHCP but one address is currently assigned' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Test-TargetResource @testTargetResourceSplat | Should -Be $False + $testTargetResourceSplat = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 - } + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } + } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } + } - Context 'Invoking with multiple IPv4 server addresses but DHCP is currently enabled' { - Mock Get-NetAdapter -MockWith { [PSObject]@{ Name = 'Ethernet' } } - Mock Get-DnsClientServerStaticAddress -MockWith { $null } + Context 'Invoking with multiple IPv4 server addresses but DHCP is currently enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { @{ Name = 'Ethernet' } } + Mock -CommandName Get-DnsClientServerStaticAddress + } - It 'Should return false' { - $testTargetResourceSplat = @{ - Address = @( '192.168.0.2', '192.168.0.3' ) - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Test-TargetResource @testTargetResourceSplat | Should -Be $False + $testTargetResourceSplat = @{ + Address = @( '192.168.0.2', '192.168.0.3' ) + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 - } + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } } - Context 'Test IPv6' { - BeforeEach { - Mock Get-NetAdapter -MockWith { [PSObject]@{ Name = 'Ethernet' } } - Mock Get-DnsClientServerStaticAddress -MockWith { 'fe80:ab04:30F5:002b::1' } - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } + } + } - Context 'Invoking with single IPv6 server address that is the same as current' { - It 'Should return true' { - $testTargetResourceSplat = @{ - Address = 'fe80:ab04:30F5:002b::1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + Context 'Test IPv6' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { @{ Name = 'Ethernet' } } + Mock -CommandName Get-DnsClientServerStaticAddress -MockWith { 'fe80:ab04:30F5:002b::1' } + } - Test-TargetResource @testTargetResourceSplat | Should -Be $true - } + Context 'Invoking with single IPv6 server address that is the same as current' { + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 + $testTargetResourceSplat = @{ + Address = 'fe80:ab04:30F5:002b::1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + Test-TargetResource @testTargetResourceSplat | Should -BeTrue } + } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } + } - Context 'Invoking with single IPv6 server address that is different to current' { - It 'Should return false' { - $testTargetResourceSplat = @{ - Address = 'fe80:ab04:30F5:002b::2' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + Context 'Invoking with single IPv6 server address that is different to current' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Test-TargetResource @testTargetResourceSplat | Should -Be $False + $testTargetResourceSplat = @{ + Address = 'fe80:ab04:30F5:002b::2' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 - } + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } + } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } + } - Context 'Invoking with multiple IPv6 server addresses that are different to current' { - It 'Should return false' { - $testTargetResourceSplat = @{ - Address = @( 'fe80:ab04:30F5:002b::1', 'fe80:ab04:30F5:002b::2' ) - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + Context 'Invoking with multiple IPv6 server addresses that are different to current' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Test-TargetResource @testTargetResourceSplat | Should -Be $False + $testTargetResourceSplat = @{ + Address = @( 'fe80:ab04:30F5:002b::1', 'fe80:ab04:30F5:002b::2' ) + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 - } + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } + } - Context 'Invoking with IPv6 server addresses set to DHCP but one address is currently assigned' { - It 'Should return false' { - $testTargetResourceSplat = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } + } - Test-TargetResource @testTargetResourceSplat | Should -Be $False - } + Context 'Invoking with IPv6 server addresses set to DHCP but one address is currently assigned' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 + $testTargetResourceSplat = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } + } - Context 'Invoking with multiple IPv6 server addresses but DHCP is currently enabled' { - Mock Get-NetAdapter -MockWith { [PSObject]@{ Name = 'Ethernet' } } - Mock Get-DnsClientServerStaticAddress -MockWith { $null } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - $testTargetResourceSplat = @{ - Address = @( 'fe80:ab04:30F5:002b::1', 'fe80:ab04:30F5:002b::2' ) - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + Context 'Invoking with multiple IPv6 server addresses but DHCP is currently enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { @{ Name = 'Ethernet' } } + Mock -CommandName Get-DnsClientServerStaticAddress + } - Test-TargetResource @testTargetResourceSplat | Should -Be $False - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Get-DnsClientServerStaticAddress -Exactly 1 + $testTargetResourceSplat = @{ + Address = @( 'fe80:ab04:30F5:002b::1', 'fe80:ab04:30F5:002b::2' ) + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } } - } - Describe 'DSC_DnsServerAddress\Assert-ResourceProperty' { - BeforeEach { - Mock Get-NetAdapter -MockWith { [PSObject]@{ Name = 'Ethernet' } } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-DnsClientServerStaticAddress -Exactly -Times 1 -Scope Context } + } + } +} - Context 'Invoking with bad interface alias' { - It 'Should throw the expected exception' { - $assertResourcePropertySplat = @{ - Address = '192.168.0.1' - InterfaceAlias = 'NotReal' - AddressFamily = 'IPv4' - Verbose = $true - } +Describe 'DSC_DnsServerAddress\Assert-ResourceProperty' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { @{ Name = 'Ethernet' } } + } - $errorRecord = Get-InvalidArgumentRecord ` - -Message ($script:localizedData.InterfaceNotAvailableError -f $assertResourcePropertySplat.InterfaceAlias) ` - -ArgumentName 'InterfaceAlias' + Context 'Invoking with bad interface alias' { + It 'Should throw the expected exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Throw $ErrorRecord + $assertResourcePropertySplat = @{ + Address = '192.168.0.1' + InterfaceAlias = 'NotReal' + AddressFamily = 'IPv4' } + + $errorRecord = Get-InvalidArgumentRecord ` + -Message ($script:localizedData.InterfaceNotAvailableError -f $assertResourcePropertySplat.InterfaceAlias) ` + -ArgumentName 'InterfaceAlias' + + { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Throw $ErrorRecord } + } + } - Context 'Invoking with invalid IP Address' { - It 'Should throw an exception' { - $assertResourcePropertySplat = @{ - Address = 'NotReal' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + Context 'Invoking with invalid IP Address' { + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Throw + $assertResourcePropertySplat = @{ + Address = 'NotReal' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Throw } + } + } - Context 'Invoking with IPv4 Address and family mismatch' { - It 'Should throw an exception' { - $assertResourcePropertySplat = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + Context 'Invoking with IPv4 Address and family mismatch' { + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Throw + $assertResourcePropertySplat = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Throw } + } + } - Context 'Invoking with IPv6 Address and family mismatch' { - It 'Should throw an exception' { - $assertResourcePropertySplat = @{ - Address = 'fe80::' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + Context 'Invoking with IPv6 Address and family mismatch' { + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Throw + $assertResourcePropertySplat = @{ + Address = 'fe80::' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Throw } + } + } - Context 'Invoking with valid IPv4 Addresses' { - It 'Should not throw an error' { - $assertResourcePropertySplat = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true - } + Context 'Invoking with valid IPv4 Addresses' { + It 'Should not throw an error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Not -Throw + $assertResourcePropertySplat = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Not -Throw } + } + } - Context 'Invoking with valid IPv6 Addresses' { - It 'Should not throw an error' { - $assertResourcePropertySplat = @{ - Address = 'fe80:ab04:30F5:002b::1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - Verbose = $true - } + Context 'Invoking with valid IPv6 Addresses' { + It 'Should not throw an error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Not -Throw + $assertResourcePropertySplat = @{ + Address = 'fe80:ab04:30F5:002b::1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + { Assert-ResourceProperty @assertResourcePropertySplat } | Should -Not -Throw } } - } #end InModuleScope $DSCResourceName -} -finally -{ - Invoke-TestCleanup + } } diff --git a/tests/Unit/DSC_Firewall.Tests.ps1 b/tests/Unit/DSC_Firewall.Tests.ps1 index d1950ecd..2125b439 100644 --- a/tests/Unit/DSC_Firewall.Tests.ps1 +++ b/tests/Unit/DSC_Firewall.Tests.ps1 @@ -1,1374 +1,1374 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_Firewall' - -function Invoke-TestSetup -{ - try - { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' - } - catch [System.IO.FileNotFoundException] - { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' - } - - $script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Unit' - - Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') -} - -function Invoke-TestCleanup -{ - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} - -Invoke-TestSetup - -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - # Get the rule that will be used for testing - $firewallRule = Get-NetFirewallRule | - Sort-Object -Property Name | - Where-Object { - $_.DisplayGroup -ne $null - } | - Select-Object -First 1 - $firewallRuleName = $firewallRule.Name - $properties = Get-FirewallRuleProperty -FirewallRule $firewallRule - - # Pull two rules to use testing that error is thrown when this occurs - $firewallRules = Get-NetFirewallRule | - Sort-Object -Property Name | - Where-Object -FilterScript { - $_.DisplayGroup -ne $null - } | - Select-Object -First 2 - - Describe 'DSC_Firewall\Get-TargetResource' -Tag 'Get' { - Context 'Absent should return correctly' { - Mock -CommandName Get-NetFirewallRule - - It "Should return absent on firewall rule $($firewallRule.Name)" { - $result = Get-TargetResource -Name 'FirewallRule' - $result.Name | Should -Be 'FirewallRule' - $result.Ensure | Should -Be 'Absent' - } - } - - Context 'Present should return correctly' { - $result = Get-TargetResource -Name $firewallRule.Name - - # Looping these tests - foreach ($parameter in $ParameterList) - { - if ($parameter.Property) - { - $parameterValue = (Get-Variable ` - -Name ($parameter.Variable)).value.$($parameter.Property).$($parameter.Name) - } - else - { - $parameterValue = (Get-Variable ` - -Name ($parameter.Variable)).value.$($parameter.Name) - } - - $parameterNew = (Get-Variable -Name 'Result').Value.$($parameter.Name) - - It "Should have the correct $($parameter.Name) on firewall rule $($firewallRule.Name)" { - if ($parameter.Delimiter) - { - $parameterNew = $parameterNew -join ',' - } - - $parameterNew | Should -Be $parameterValue - } - } - } - } - - Describe 'DSC_Firewall\Test-TargetResource' -Tag 'Test' { - Context 'Ensure is Absent and the Firewall is not Present' { - Mock -CommandName Get-FirewallRule - - It "Should return $true on firewall rule $($firewallRule.Name)" { - $result = Test-TargetResource -Name 'FirewallRule' -Ensure 'Absent' - $result | Should -BeTrue - } - } - - Context 'Ensure is Absent and the Firewall is Present' { - Mock -CommandName Test-RuleProperties - - It "Should return $false on firewall rule $($firewallRule.Name)" { - $result = Test-TargetResource -Name $firewallRule.Name -Ensure 'Absent' - $result | Should -BeFalse - } - } - - Context 'Ensure is Present and the Firewall is Present and properties match' { - Mock -CommandName Test-RuleProperties -MockWith { return $true } - - It "Should return $true on firewall rule $($firewallRule.Name)" { - $result = Test-TargetResource -Name $firewallRule.Name - $result | Should -BeTrue - } - } - - Context 'Ensure is Present and the Firewall is Present and properties are different' { - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - It "Should return $false on firewall rule $($firewallRule.Name)" { - $result = Test-TargetResource -Name $firewallRule.Name - $result | Should -BeFalse - } - } - - Context 'Ensure is Present and the Firewall is Absent' { - Mock -CommandName Get-FirewallRule - It "Should return $false on firewall rule $($firewallRule.Name)" { - $result = Test-TargetResource -Name $firewallRule.Name - $result | Should -BeFalse - } - } - } - - Describe 'DSC_Firewall\Set-TargetResource' -Tag 'Set' { - BeforeEach { - # To speed up all these tests create Mocks so that these functions are not repeatedly called - Mock -CommandName Get-FirewallRule -MockWith { $firewallRule } - Mock -CommandName Get-FirewallRuleProperty -MockWith { $properties } - } - - Context 'Ensure is Absent and Firewall rule exists' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Remove-NetFirewallRule - - Set-TargetResource -Name $firewallRule.Name -Ensure 'Absent' - - Assert-MockCalled -CommandName Remove-NetFirewallRule -Exactly -Times 1 - } - } - - Context 'Ensure is Absent and Firewall rule with wildcard characters in name exists' { - It "Should call expected mocks on firewall rule 'Test [With] Wildcard*'" { - Mock ` - -CommandName Remove-NetFirewallRule ` - -ParameterFilter { - $Name -eq 'Test `[With`] Wildcard`*' - } - - Set-TargetResource -Name 'Test [With] Wildcard*' -Ensure 'Absent' - - Assert-MockCalled ` - -CommandName Remove-NetFirewallRule ` - -ParameterFilter { - $Name -eq 'Test `[With`] Wildcard`*' - } ` - -Exactly -Times 1 - } - } - - Context 'Ensure is Absent and the Firewall rule does not exist' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Get-FirewallRule - Mock -CommandName Remove-NetFirewallRule - - Set-TargetResource -Name $firewallRule.Name -Ensure 'Absent' - - Assert-MockCalled -CommandName Remove-NetFirewallRule -Exactly 0 - } - } - - Context 'Ensure is Present and the Firewall rule does not exist' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Get-FirewallRule - Mock -CommandName New-NetFirewallRule - - Set-TargetResource -Name $firewallRule.Name -Ensure 'Present' - - Assert-MockCalled -CommandName New-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Get-FirewallRule -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different DisplayName' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -DisplayName 'Different' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule with wildcard characters in name does exist but has a different DisplayName' { - It "Should call expected mocks on firewall rule 'Test [With] Wildcard*'" { - Mock ` - -CommandName Set-NetFirewallRule ` - -ParameterFilter { - $Name -eq 'Test `[With`] Wildcard`*' - } - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name 'Test [With] Wildcard*' ` - -DisplayName 'Different' ` - -Ensure 'Present' - - Assert-MockCalled ` - -CommandName Set-NetFirewallRule ` - -ParameterFilter { - $Name -eq 'Test `[With`] Wildcard`*' - } ` - -Exactly -Times 1 - - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Group' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName New-NetFirewallRule - Mock -CommandName Remove-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -DisplayName $firewallRule.DisplayName ` - -Group 'Different' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName New-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist with a specified Group that is unchanged but some other parameter is different' { - It "Should remove Group from parameters before calling Set-NetFirewallRule mock on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - # 1. Group is specified but unchanged - # 2. Some other parameter is different (Description) - Set-TargetResource ` - -Name $firewallRule.Name ` - -Group $firewallRule.Group ` - -Description 'Different' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -ExclusiveFilter { - -not $PSBoundParameters.ContainsKey('Group') - } -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Enabled' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - if ( $firewallRule.Enabled -eq 'True' ) - { - $newEnabled = 'False' - } - else - { - $newEnabled = 'True' - } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Enabled $newEnabled ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Action' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - if ( $firewallRule.Action -eq 'Allow') - { - $NewAction = 'Block' - } - else - { - $NewAction = 'Allow' - } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Action $NewAction ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Profile' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - if ( $firewallRule.Profile -ccontains 'Domain') - { - $NewProfile = @('Public', 'Private') - } - else - { - $NewProfile = @('Domain', 'Public') - } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Profile $NewProfile ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Direction' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - if ( $firewallRule.Direction -eq 'Inbound') - { - $NewDirection = 'Outbound' - } - else - { - $NewDirection = 'Inbound' - } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Direction $NewDirection ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different RemotePort' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -RemotePort 9999 ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different LocalPort' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -LocalPort 9999 ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Protocol' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - if ( $firewallRule.Protocol -eq 'TCP') - { - $NewProtocol = 'UDP' - } - else - { - $NewProtocol = 'TCP' - } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Protocol $NewProtocol ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Description' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Description 'Different' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Program' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Program 'Different' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Service' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Service 'Different' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Authentication' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - if ( $properties.SecurityFilters.Authentication -eq 'Required') - { - $NewAuthentication = 'NotRequired' - } - else - { - $NewAuthentication = 'Required' - } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Authentication $NewAuthentication ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Encryption' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - if ( $properties.SecurityFilters.Encryption -eq 'Required') - { - $NewEncryption = 'NotRequired' - } - else - { - $NewEncryption = 'Required' - } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Encryption $NewEncryption ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different InterfaceAlias' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -InterfaceAlias 'Different' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different InterfaceType' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - if ( $properties.InterfaceTypeFilters.InterfaceType -eq 'Wired') - { - $NewInterfaceType = 'Wireless' - } - else - { - $NewInterfaceType = 'Wired' - } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -InterfaceType $NewInterfaceType ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different LocalAddress' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -LocalAddress @('10.0.0.1/255.0.0.0', '10.1.1.0-10.1.2.0') ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different LocalUser' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -LocalUser 'Different' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Package' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Package 'Different' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Platform' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Platform @('6.1') ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different RemoteAddress' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -RemoteAddress @('10.0.0.1/255.0.0.0', '10.1.1.0-10.1.2.0') ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different RemoteMachine' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -RemoteMachine 'Different' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different RemoteUser' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -RemoteUser 'Different' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different DynamicTransport' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -DynamicTransport 'WifiDirectDisplay' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - Context 'Ensure is Present and the Firewall rule does exist but has a different EdgeTraversalPolicy' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -EdgeTraversalPolicy 'Allow' ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different IcmpType' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -IcmpType @('52', '53') ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different LocalOnlyMapping' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -LocalOnlyMapping $true ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different LooseSourceMapping' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -LooseSourceMapping $true ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different OverrideBlockRules' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -OverrideBlockRules $true ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist but has a different Owner' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $false } - - Set-TargetResource ` - -Name $firewallRule.Name ` - -Owner (Get-CimInstance win32_useraccount | Select-Object -First 1).Sid ` - -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - - Context 'Ensure is Present and the Firewall rule does exist and is the same' { - It "Should call expected mocks on firewall rule $($firewallRule.Name)" { - Mock -CommandName Set-NetFirewallRule - Mock -CommandName Test-RuleProperties -MockWith { return $true } - - Set-TargetResource -Name $firewallRule.Name -Ensure 'Present' - - Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly 0 - Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 - } - } - } - - Describe 'DSC_Firewall\Test-RuleProperties' { - # Make an object that can be splatted onto the function - $testRuleProperties = @{ - Verbose = $true - } - - foreach ($parameter in $ParameterList) - { - if ($parameter.Property) - { - $parameterValue = (Get-Variable ` - -Name ($parameter.Variable)).value.$($parameter.Property).$($parameter.Name) - } - else - { - $parameterValue = (Get-Variable ` - -Name ($parameter.Variable)).value.$($parameter.Name) - } - - if ($parameter.Delimiter) - { - $parameterValue = $parameterValue -split $parameter.Delimiter - } - - $testRuleProperties += @{ $parameter.Name = $parameterValue } - } - - Context 'When testing with a rule that has property differences' { - BeforeEach { - # To speed up all these tests create Mocks so that these functions are not repeatedly called - Mock -CommandName Get-FirewallRule -MockWith { $firewallRule } - Mock -CommandName Get-FirewallRuleProperty -MockWith { $properties } - } - - Context 'When testing with a rule with a different name' { - $compareRule = $testRuleProperties.Clone() - $compareRule.Name = 'Different' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different displayname' { - $compareRule = $testRuleProperties.Clone() - $compareRule.DisplayName = 'Different' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different group' { - $compareRule = $testRuleProperties.Clone() - $compareRule.Group = 'Different' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different enabled' { - $compareRule = $testRuleProperties.Clone() - - if ( $compareRule.Enabled -eq 'True' ) - { - $compareRule.Enabled = 'False' - } - else - { - $compareRule.Enabled = 'True' - } - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different action' { - $compareRule = $testRuleProperties.Clone() - - if ($compareRule.Action -eq 'Allow') - { - $compareRule.Action = 'Block' - } - else - { - $compareRule.Action = 'Allow' - } - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different profile' { - $compareRule = $testRuleProperties.Clone() - - if ( $compareRule.Profile -ccontains 'Domain') - { - $compareRule.Profile = @('Public', 'Private') - } - else - { - $compareRule.Profile = @('Domain', 'Public') - } - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different direction' { - $compareRule = $testRuleProperties.Clone() - - if ($compareRule.Direction -eq 'Inbound') - { - $compareRule.Direction = 'Outbound' - } - else - { - $compareRule.Direction = 'Inbound' - } - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different remote port' { - $compareRule = $testRuleProperties.Clone() - $compareRule.RemotePort = 1 - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different local port' { - $compareRule = $testRuleProperties.Clone() - $compareRule.LocalPort = 1 - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different protocol' { - $compareRule = $testRuleProperties.Clone() - - if ( $compareRule.Protocol -eq 'TCP') - { - $compareRule.Protocol = 'UDP' - } - else - { - $compareRule.Protocol = 'TCP' - } - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different description' { - $compareRule = $testRuleProperties.Clone() - $compareRule.Description = 'Different' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different program' { - $compareRule = $testRuleProperties.Clone() - $compareRule.Program = 'Different' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different service' { - $compareRule = $testRuleProperties.Clone() - $compareRule.Service = 'Different' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different Authentication' { - $compareRule = $testRuleProperties.Clone() - - if ( $compareRule.Authentication -eq 'Required') - { - $compareRule.Authentication = 'NotRequired' - } - else - { - $compareRule.Authentication = 'Required' - } - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different Encryption' { - $compareRule = $testRuleProperties.Clone() - - if ( $compareRule.Encryption -eq 'Required') - { - $compareRule.Encryption = 'NotRequired' - } - else - { - $compareRule.Encryption = 'Required' - } - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different InterfaceAlias' { - $compareRule = $testRuleProperties.Clone() - $compareRule.InterfaceAlias = 'Different' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different InterfaceType' { - $compareRule = $testRuleProperties.Clone() - - if ( $compareRule.InterfaceType -eq 'Wired') - { - $compareRule.InterfaceType = 'Wireless' - } - else - { - $compareRule.InterfaceType = 'Wired' - } - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different LocalAddress' { - $compareRule = $testRuleProperties.Clone() - $compareRule.LocalAddress = @('10.0.0.1/255.0.0.0', '10.1.1.0-10.1.2.0') - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different LocalUser' { - $compareRule = $testRuleProperties.Clone() - $compareRule.LocalUser = 'Different' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different Package' { - $compareRule = $testRuleProperties.Clone() - $compareRule.Package = 'Different' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different Platform' { - $compareRule = $testRuleProperties.Clone() - $compareRule.Platform = @('6.2') - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different RemoteAddress' { - $compareRule = $testRuleProperties.Clone() - $compareRule.RemoteAddress = @('10.0.0.1/255.0.0.0', '10.1.1.0-10.1.2.0') - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different RemoteMachine' { - $compareRule = $testRuleProperties.Clone() - $compareRule.RemoteMachine = 'Different' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different RemoteUser' { - $compareRule = $testRuleProperties.Clone() - $compareRule.RemoteUser = 'Different' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different DynamicTransport' { - $compareRule = $testRuleProperties.Clone() - $compareRule.DynamicTransport = 'WifiDirectDevices' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different EdgeTraversalPolicy' { - $compareRule = $testRuleProperties.Clone() - $compareRule.EdgeTraversalPolicy = 'DeferToApp' - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different IcmpType' { - $compareRule = $testRuleProperties.Clone() - $compareRule.IcmpType = @('53', '54') - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different LocalOnlyMapping' { - $compareRule = $testRuleProperties.Clone() - $compareRule.LocalOnlyMapping = ! $compareRule.LocalOnlyMapping - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different LooseSourceMapping' { - $compareRule = $testRuleProperties.Clone() - $compareRule.LooseSourceMapping = ! $compareRule.LooseSourceMapping - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different OverrideBlockRules' { - $compareRule = $testRuleProperties.Clone() - $compareRule.OverrideBlockRules = ! $compareRule.OverrideBlockRules - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - - Context 'When testing with a rule with a different Owner' { - $compareRule = $testRuleProperties.Clone() - $compareRule.Owner = (Get-CimInstance win32_useraccount | Select-Object -First 1).Sid - - It "Should return False on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeFalse - } - } - } - - Context 'When testing with a rule with no differences' { - Context 'When there are no format differences' { - Mock -CommandName Get-FirewallRule -MockWith { $firewallRule } - Mock -CommandName Get-FirewallRuleProperty -MockWith { $properties } - - $compareRule = $testRuleProperties.Clone() - - It "Should return True on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeTrue - } - } - - Context 'When the LocalAddress subnet mask uses CIDR bits format' { - $localAddressProperties = $properties.Clone() - $localAddressProperties.AddressFilters = [PSCustomObject] @{ - LocalAddress = '10.0.0.0/255.0.0.0' - RemoteAddress = $localAddressProperties.AddressFilters.RemoteAddress - } - - Mock -CommandName Get-FirewallRule -MockWith { $firewallRule } - Mock -CommandName Get-FirewallRuleProperty -MockWith { $localAddressProperties } - - $compareRule = $testRuleProperties.Clone() - $compareRule.LocalAddress = '10.0.0.0/8' - - It "Should return True on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeTrue - } - } - - Context 'When the RemoteAddress subnet mask uses CIDR bits format' { - $remoteAddressProperties = $properties.Clone() - $remoteAddressProperties.AddressFilters = [PSCustomObject] @{ - LocalAddress = $remoteAddressProperties.AddressFilters.LocalAddress - RemoteAddress = '10.0.0.0/255.0.0.0' - } - - Mock -CommandName Get-FirewallRule -MockWith { $firewallRule } - Mock -CommandName Get-FirewallRuleProperty -MockWith { $remoteAddressProperties } - - $compareRule = $testRuleProperties.Clone() - $compareRule.RemoteAddress = '10.0.0.0/8' - - It "Should return True on firewall rule $($firewallRule.Name)" { - $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should -BeTrue - } - } - } - } - - Describe 'DSC_Firewall\Get-FirewallRule' { - Context 'Testing with firewall that exists' { - It "Should return a firewall rule when name is passed on firewall rule $($firewallRule.Name)" { - $result = Get-FirewallRule -Name $firewallRule.Name - $result | Should -Not -BeNullOrEmpty - } - } - - Context 'When testing with firewall that does not exist' { - It "Should not return anything on firewall rule $($firewallRule.Name)" { - $result = Get-FirewallRule -Name 'Does not exist' - $result | Should -BeNullOrEmpty - } - } - - Context 'When testing with firewall that somehow occurs more than once' { - Mock -CommandName Get-NetFirewallRule -MockWith { $firewallRules } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.RuleNotUniqueError -f 2, $firewallRule.Name) - - It "Should throw RuleNotUnique exception on firewall rule $($firewallRule.Name)" { - { $result = Get-FirewallRule -Name $firewallRule.Name } | Should -Throw $errorRecord - } - } - - Context 'When testing with firewall that exists and name contains wildcard characters' { - Mock ` - -CommandName Get-NetFirewallRule ` - -ParameterFilter { - $Name -eq 'Test `[With`] Wildcard`*' - } ` - -MockWith { $firewallRule } - - It 'Should return a firewall rule when name is passed with wildcard characters' { - $result = Get-FirewallRule -Name 'Test [With] Wildcard*' - $result.Name | Should -Be $firewallRule.Name - } - - It 'Should call Get-NetFirewallRule with Name parameter value escaped' { - Assert-MockCalled ` - -CommandName Get-NetFirewallRule ` - -ParameterFilter { - $Name -eq 'Test `[With`] Wildcard`*' - } ` - -Exactly -Times 1 - } - } - } - - Describe 'DSC_Firewall\Get-FirewallRuleProperty' { - Context 'All Properties' { - $result = Get-FirewallRuleProperty -FirewallRule $firewallRule - - It "Should return the right address filter on firewall rule $($firewallRule.Name)" { - $expected = Get-NetFirewallAddressFilter -AssociatedNetFirewallRule $firewallRule - - $($result.AddressFilters | Out-String -Stream) | - Should -Be $($expected | Out-String -Stream) - } - - It "Should return the right application filter on firewall rule $($firewallRule.Name)" { - $expected = Get-NetFirewallApplicationFilter -AssociatedNetFirewallRule $firewallRule - - $($result.ApplicationFilters | Out-String -Stream) | - Should -Be $($expected | Out-String -Stream) - } - - It "Should return the right interface filter on firewall rule $($firewallRule.Name)" { - $expected = Get-NetFirewallInterfaceFilter -AssociatedNetFirewallRule $firewallRule - - $($result.InterfaceFilters | Out-String -Stream) | - Should -Be $($expected | Out-String -Stream) - } - - It "Should return the right interface type filter on firewall rule $($firewallRule.Name)" { - $expected = Get-NetFirewallInterfaceTypeFilter -AssociatedNetFirewallRule $firewallRule - $($result.InterfaceTypeFilters | Out-String -Stream) | - Should -Be $($expected | Out-String -Stream) - } - - It "Should return the right port filter on firewall rule $($firewallRule.Name)" { - $expected = Get-NetFirewallPortFilter -AssociatedNetFirewallRule $firewallRule - $($result.PortFilters | Out-String -Stream) | - Should -Be $($expected | Out-String -Stream) - } - - It "Should return the right Profile on firewall rule $($firewallRule.Name)" { - $expected = Get-NetFirewallProfile -AssociatedNetFirewallRule $firewallRule - $($result.Profile | Out-String -Stream) | - Should -Be $($expected | Out-String -Stream) - } - - It "Should return the right Profile on firewall rule $($firewallRule.Name)" { - $expected = Get-NetFirewallProfile -AssociatedNetFirewallRule $firewallRule - $($result.Profile | Out-String -Stream) | - Should -Be $($expected | Out-String -Stream) - } - - It "Should return the right Security Filters on firewall rule $($firewallRule.Name)" { - $expected = Get-NetFirewallSecurityFilter -AssociatedNetFirewallRule $firewallRule - $($result.SecurityFilters | Out-String -Stream) | - Should -Be $($expected | Out-String -Stream) - } - - It "Should return the right Service Filters on firewall rule $($firewallRule.Name)" { - $expected = Get-NetFirewallServiceFilter -AssociatedNetFirewallRule $firewallRule - $($result.ServiceFilters | Out-String -Stream) | - Should -Be $($expected | Out-String -Stream) - } - } - } - - Describe 'DSC_Firewall\ConvertTo-FirewallRuleNameEscapedString' { - Context 'Rule name that contains no escaped characters' { - It 'Should return the rule name with no backticks added' { - ConvertTo-FirewallRuleNameEscapedString -Name 'No Escaped Characters' | Should -Be 'No Escaped Characters' - } - } - - Context 'Rule name that contains at least one of each escaped characters' { - It 'Should return the rule name with expected backticks added' { - ConvertTo-FirewallRuleNameEscapedString -Name 'Left [ Right ] Asterisk *' | Should -Be 'Left `[ Right `] Asterisk `*' - } - } - } - } #end InModuleScope $DSCResourceName -} -finally -{ - Invoke-TestCleanup -} +# $script:dscModuleName = 'NetworkingDsc' +# $script:dscResourceName = 'DSC_Firewall' + +# function Invoke-TestSetup +# { +# try +# { +# Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' +# } +# catch [System.IO.FileNotFoundException] +# { +# throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' +# } + +# $script:testEnvironment = Initialize-TestEnvironment ` +# -DSCModuleName $script:dscModuleName ` +# -DSCResourceName $script:dscResourceName ` +# -ResourceType 'Mof' ` +# -TestType 'Unit' + +# Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +# } + +# function Invoke-TestCleanup +# { +# Restore-TestEnvironment -TestEnvironment $script:testEnvironment +# } + +# Invoke-TestSetup + +# # Begin Testing +# try +# { +# InModuleScope $script:dscResourceName { +# # Get the rule that will be used for testing +# $firewallRule = Get-NetFirewallRule | +# Sort-Object -Property Name | +# Where-Object { +# $_.DisplayGroup -ne $null +# } | +# Select-Object -First 1 +# $firewallRuleName = $firewallRule.Name +# $properties = Get-FirewallRuleProperty -FirewallRule $firewallRule + +# # Pull two rules to use testing that error is thrown when this occurs +# $firewallRules = Get-NetFirewallRule | +# Sort-Object -Property Name | +# Where-Object -FilterScript { +# $_.DisplayGroup -ne $null +# } | +# Select-Object -First 2 + +# Describe 'DSC_Firewall\Get-TargetResource' -Tag 'Get' { +# Context 'Absent should return correctly' { +# Mock -CommandName Get-NetFirewallRule + +# It "Should return absent on firewall rule $($firewallRule.Name)" { +# $result = Get-TargetResource -Name 'FirewallRule' +# $result.Name | Should -Be 'FirewallRule' +# $result.Ensure | Should -Be 'Absent' +# } +# } + +# Context 'Present should return correctly' { +# $result = Get-TargetResource -Name $firewallRule.Name + +# # Looping these tests +# foreach ($parameter in $ParameterList) +# { +# if ($parameter.Property) +# { +# $parameterValue = (Get-Variable ` +# -Name ($parameter.Variable)).value.$($parameter.Property).$($parameter.Name) +# } +# else +# { +# $parameterValue = (Get-Variable ` +# -Name ($parameter.Variable)).value.$($parameter.Name) +# } + +# $parameterNew = (Get-Variable -Name 'Result').Value.$($parameter.Name) + +# It "Should have the correct $($parameter.Name) on firewall rule $($firewallRule.Name)" { +# if ($parameter.Delimiter) +# { +# $parameterNew = $parameterNew -join ',' +# } + +# $parameterNew | Should -Be $parameterValue +# } +# } +# } +# } + +# Describe 'DSC_Firewall\Test-TargetResource' -Tag 'Test' { +# Context 'Ensure is Absent and the Firewall is not Present' { +# Mock -CommandName Get-FirewallRule + +# It "Should return $true on firewall rule $($firewallRule.Name)" { +# $result = Test-TargetResource -Name 'FirewallRule' -Ensure 'Absent' +# $result | Should -BeTrue +# } +# } + +# Context 'Ensure is Absent and the Firewall is Present' { +# Mock -CommandName Test-RuleProperties + +# It "Should return $false on firewall rule $($firewallRule.Name)" { +# $result = Test-TargetResource -Name $firewallRule.Name -Ensure 'Absent' +# $result | Should -BeFalse +# } +# } + +# Context 'Ensure is Present and the Firewall is Present and properties match' { +# Mock -CommandName Test-RuleProperties -MockWith { return $true } + +# It "Should return $true on firewall rule $($firewallRule.Name)" { +# $result = Test-TargetResource -Name $firewallRule.Name +# $result | Should -BeTrue +# } +# } + +# Context 'Ensure is Present and the Firewall is Present and properties are different' { +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# It "Should return $false on firewall rule $($firewallRule.Name)" { +# $result = Test-TargetResource -Name $firewallRule.Name +# $result | Should -BeFalse +# } +# } + +# Context 'Ensure is Present and the Firewall is Absent' { +# Mock -CommandName Get-FirewallRule +# It "Should return $false on firewall rule $($firewallRule.Name)" { +# $result = Test-TargetResource -Name $firewallRule.Name +# $result | Should -BeFalse +# } +# } +# } + +# Describe 'DSC_Firewall\Set-TargetResource' -Tag 'Set' { +# BeforeEach { +# # To speed up all these tests create Mocks so that these functions are not repeatedly called +# Mock -CommandName Get-FirewallRule -MockWith { $firewallRule } +# Mock -CommandName Get-FirewallRuleProperty -MockWith { $properties } +# } + +# Context 'Ensure is Absent and Firewall rule exists' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Remove-NetFirewallRule + +# Set-TargetResource -Name $firewallRule.Name -Ensure 'Absent' + +# Assert-MockCalled -CommandName Remove-NetFirewallRule -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Absent and Firewall rule with wildcard characters in name exists' { +# It "Should call expected mocks on firewall rule 'Test [With] Wildcard*'" { +# Mock ` +# -CommandName Remove-NetFirewallRule ` +# -ParameterFilter { +# $Name -eq 'Test `[With`] Wildcard`*' +# } + +# Set-TargetResource -Name 'Test [With] Wildcard*' -Ensure 'Absent' + +# Assert-MockCalled ` +# -CommandName Remove-NetFirewallRule ` +# -ParameterFilter { +# $Name -eq 'Test `[With`] Wildcard`*' +# } ` +# -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Absent and the Firewall rule does not exist' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Get-FirewallRule +# Mock -CommandName Remove-NetFirewallRule + +# Set-TargetResource -Name $firewallRule.Name -Ensure 'Absent' + +# Assert-MockCalled -CommandName Remove-NetFirewallRule -Exactly 0 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does not exist' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Get-FirewallRule +# Mock -CommandName New-NetFirewallRule + +# Set-TargetResource -Name $firewallRule.Name -Ensure 'Present' + +# Assert-MockCalled -CommandName New-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-FirewallRule -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different DisplayName' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -DisplayName 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule with wildcard characters in name does exist but has a different DisplayName' { +# It "Should call expected mocks on firewall rule 'Test [With] Wildcard*'" { +# Mock ` +# -CommandName Set-NetFirewallRule ` +# -ParameterFilter { +# $Name -eq 'Test `[With`] Wildcard`*' +# } +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name 'Test [With] Wildcard*' ` +# -DisplayName 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled ` +# -CommandName Set-NetFirewallRule ` +# -ParameterFilter { +# $Name -eq 'Test `[With`] Wildcard`*' +# } ` +# -Exactly -Times 1 + +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Group' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName New-NetFirewallRule +# Mock -CommandName Remove-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -DisplayName $firewallRule.DisplayName ` +# -Group 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName New-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Remove-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist with a specified Group that is unchanged but some other parameter is different' { +# It "Should remove Group from parameters before calling Set-NetFirewallRule mock on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# # 1. Group is specified but unchanged +# # 2. Some other parameter is different (Description) +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Group $firewallRule.Group ` +# -Description 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -ExclusiveFilter { +# -not $PSBoundParameters.ContainsKey('Group') +# } -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Enabled' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# if ( $firewallRule.Enabled -eq 'True' ) +# { +# $newEnabled = 'False' +# } +# else +# { +# $newEnabled = 'True' +# } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Enabled $newEnabled ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Action' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# if ( $firewallRule.Action -eq 'Allow') +# { +# $NewAction = 'Block' +# } +# else +# { +# $NewAction = 'Allow' +# } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Action $NewAction ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Profile' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# if ( $firewallRule.Profile -ccontains 'Domain') +# { +# $NewProfile = @('Public', 'Private') +# } +# else +# { +# $NewProfile = @('Domain', 'Public') +# } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Profile $NewProfile ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Direction' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# if ( $firewallRule.Direction -eq 'Inbound') +# { +# $NewDirection = 'Outbound' +# } +# else +# { +# $NewDirection = 'Inbound' +# } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Direction $NewDirection ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different RemotePort' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -RemotePort 9999 ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different LocalPort' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -LocalPort 9999 ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Protocol' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# if ( $firewallRule.Protocol -eq 'TCP') +# { +# $NewProtocol = 'UDP' +# } +# else +# { +# $NewProtocol = 'TCP' +# } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Protocol $NewProtocol ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Description' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Description 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Program' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Program 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Service' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Service 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Authentication' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# if ( $properties.SecurityFilters.Authentication -eq 'Required') +# { +# $NewAuthentication = 'NotRequired' +# } +# else +# { +# $NewAuthentication = 'Required' +# } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Authentication $NewAuthentication ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Encryption' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# if ( $properties.SecurityFilters.Encryption -eq 'Required') +# { +# $NewEncryption = 'NotRequired' +# } +# else +# { +# $NewEncryption = 'Required' +# } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Encryption $NewEncryption ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different InterfaceAlias' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -InterfaceAlias 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different InterfaceType' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# if ( $properties.InterfaceTypeFilters.InterfaceType -eq 'Wired') +# { +# $NewInterfaceType = 'Wireless' +# } +# else +# { +# $NewInterfaceType = 'Wired' +# } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -InterfaceType $NewInterfaceType ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different LocalAddress' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -LocalAddress @('10.0.0.1/255.0.0.0', '10.1.1.0-10.1.2.0') ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different LocalUser' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -LocalUser 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Package' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Package 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Platform' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Platform @('6.1') ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different RemoteAddress' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -RemoteAddress @('10.0.0.1/255.0.0.0', '10.1.1.0-10.1.2.0') ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different RemoteMachine' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -RemoteMachine 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different RemoteUser' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -RemoteUser 'Different' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different DynamicTransport' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -DynamicTransport 'WifiDirectDisplay' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } +# Context 'Ensure is Present and the Firewall rule does exist but has a different EdgeTraversalPolicy' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -EdgeTraversalPolicy 'Allow' ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different IcmpType' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -IcmpType @('52', '53') ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different LocalOnlyMapping' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -LocalOnlyMapping $true ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different LooseSourceMapping' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -LooseSourceMapping $true ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different OverrideBlockRules' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -OverrideBlockRules $true ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist but has a different Owner' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $false } + +# Set-TargetResource ` +# -Name $firewallRule.Name ` +# -Owner (Get-CimInstance win32_useraccount | Select-Object -First 1).Sid ` +# -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly -Times 1 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } + +# Context 'Ensure is Present and the Firewall rule does exist and is the same' { +# It "Should call expected mocks on firewall rule $($firewallRule.Name)" { +# Mock -CommandName Set-NetFirewallRule +# Mock -CommandName Test-RuleProperties -MockWith { return $true } + +# Set-TargetResource -Name $firewallRule.Name -Ensure 'Present' + +# Assert-MockCalled -CommandName Set-NetFirewallRule -Exactly 0 +# Assert-MockCalled -CommandName Test-RuleProperties -Exactly -Times 1 +# } +# } +# } + +# Describe 'DSC_Firewall\Test-RuleProperties' { +# # Make an object that can be splatted onto the function +# $testRuleProperties = @{ +# Verbose = $true +# } + +# foreach ($parameter in $ParameterList) +# { +# if ($parameter.Property) +# { +# $parameterValue = (Get-Variable ` +# -Name ($parameter.Variable)).value.$($parameter.Property).$($parameter.Name) +# } +# else +# { +# $parameterValue = (Get-Variable ` +# -Name ($parameter.Variable)).value.$($parameter.Name) +# } + +# if ($parameter.Delimiter) +# { +# $parameterValue = $parameterValue -split $parameter.Delimiter +# } + +# $testRuleProperties += @{ $parameter.Name = $parameterValue } +# } + +# Context 'When testing with a rule that has property differences' { +# BeforeEach { +# # To speed up all these tests create Mocks so that these functions are not repeatedly called +# Mock -CommandName Get-FirewallRule -MockWith { $firewallRule } +# Mock -CommandName Get-FirewallRuleProperty -MockWith { $properties } +# } + +# Context 'When testing with a rule with a different name' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.Name = 'Different' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different displayname' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.DisplayName = 'Different' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different group' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.Group = 'Different' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different enabled' { +# $compareRule = $testRuleProperties.Clone() + +# if ( $compareRule.Enabled -eq 'True' ) +# { +# $compareRule.Enabled = 'False' +# } +# else +# { +# $compareRule.Enabled = 'True' +# } + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different action' { +# $compareRule = $testRuleProperties.Clone() + +# if ($compareRule.Action -eq 'Allow') +# { +# $compareRule.Action = 'Block' +# } +# else +# { +# $compareRule.Action = 'Allow' +# } + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different profile' { +# $compareRule = $testRuleProperties.Clone() + +# if ( $compareRule.Profile -ccontains 'Domain') +# { +# $compareRule.Profile = @('Public', 'Private') +# } +# else +# { +# $compareRule.Profile = @('Domain', 'Public') +# } + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different direction' { +# $compareRule = $testRuleProperties.Clone() + +# if ($compareRule.Direction -eq 'Inbound') +# { +# $compareRule.Direction = 'Outbound' +# } +# else +# { +# $compareRule.Direction = 'Inbound' +# } + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different remote port' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.RemotePort = 1 + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different local port' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.LocalPort = 1 + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different protocol' { +# $compareRule = $testRuleProperties.Clone() + +# if ( $compareRule.Protocol -eq 'TCP') +# { +# $compareRule.Protocol = 'UDP' +# } +# else +# { +# $compareRule.Protocol = 'TCP' +# } + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different description' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.Description = 'Different' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different program' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.Program = 'Different' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different service' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.Service = 'Different' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different Authentication' { +# $compareRule = $testRuleProperties.Clone() + +# if ( $compareRule.Authentication -eq 'Required') +# { +# $compareRule.Authentication = 'NotRequired' +# } +# else +# { +# $compareRule.Authentication = 'Required' +# } + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different Encryption' { +# $compareRule = $testRuleProperties.Clone() + +# if ( $compareRule.Encryption -eq 'Required') +# { +# $compareRule.Encryption = 'NotRequired' +# } +# else +# { +# $compareRule.Encryption = 'Required' +# } + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different InterfaceAlias' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.InterfaceAlias = 'Different' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different InterfaceType' { +# $compareRule = $testRuleProperties.Clone() + +# if ( $compareRule.InterfaceType -eq 'Wired') +# { +# $compareRule.InterfaceType = 'Wireless' +# } +# else +# { +# $compareRule.InterfaceType = 'Wired' +# } + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different LocalAddress' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.LocalAddress = @('10.0.0.1/255.0.0.0', '10.1.1.0-10.1.2.0') + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different LocalUser' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.LocalUser = 'Different' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different Package' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.Package = 'Different' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different Platform' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.Platform = @('6.2') + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different RemoteAddress' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.RemoteAddress = @('10.0.0.1/255.0.0.0', '10.1.1.0-10.1.2.0') + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different RemoteMachine' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.RemoteMachine = 'Different' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different RemoteUser' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.RemoteUser = 'Different' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different DynamicTransport' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.DynamicTransport = 'WifiDirectDevices' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different EdgeTraversalPolicy' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.EdgeTraversalPolicy = 'DeferToApp' + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different IcmpType' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.IcmpType = @('53', '54') + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different LocalOnlyMapping' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.LocalOnlyMapping = ! $compareRule.LocalOnlyMapping + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different LooseSourceMapping' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.LooseSourceMapping = ! $compareRule.LooseSourceMapping + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different OverrideBlockRules' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.OverrideBlockRules = ! $compareRule.OverrideBlockRules + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } + +# Context 'When testing with a rule with a different Owner' { +# $compareRule = $testRuleProperties.Clone() +# $compareRule.Owner = (Get-CimInstance win32_useraccount | Select-Object -First 1).Sid + +# It "Should return False on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeFalse +# } +# } +# } + +# Context 'When testing with a rule with no differences' { +# Context 'When there are no format differences' { +# Mock -CommandName Get-FirewallRule -MockWith { $firewallRule } +# Mock -CommandName Get-FirewallRuleProperty -MockWith { $properties } + +# $compareRule = $testRuleProperties.Clone() + +# It "Should return True on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeTrue +# } +# } + +# Context 'When the LocalAddress subnet mask uses CIDR bits format' { +# $localAddressProperties = $properties.Clone() +# $localAddressProperties.AddressFilters = [PSCustomObject] @{ +# LocalAddress = '10.0.0.0/255.0.0.0' +# RemoteAddress = $localAddressProperties.AddressFilters.RemoteAddress +# } + +# Mock -CommandName Get-FirewallRule -MockWith { $firewallRule } +# Mock -CommandName Get-FirewallRuleProperty -MockWith { $localAddressProperties } + +# $compareRule = $testRuleProperties.Clone() +# $compareRule.LocalAddress = '10.0.0.0/8' + +# It "Should return True on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeTrue +# } +# } + +# Context 'When the RemoteAddress subnet mask uses CIDR bits format' { +# $remoteAddressProperties = $properties.Clone() +# $remoteAddressProperties.AddressFilters = [PSCustomObject] @{ +# LocalAddress = $remoteAddressProperties.AddressFilters.LocalAddress +# RemoteAddress = '10.0.0.0/255.0.0.0' +# } + +# Mock -CommandName Get-FirewallRule -MockWith { $firewallRule } +# Mock -CommandName Get-FirewallRuleProperty -MockWith { $remoteAddressProperties } + +# $compareRule = $testRuleProperties.Clone() +# $compareRule.RemoteAddress = '10.0.0.0/8' + +# It "Should return True on firewall rule $($firewallRule.Name)" { +# $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule +# $result | Should -BeTrue +# } +# } +# } +# } + +# Describe 'DSC_Firewall\Get-FirewallRule' { +# Context 'Testing with firewall that exists' { +# It "Should return a firewall rule when name is passed on firewall rule $($firewallRule.Name)" { +# $result = Get-FirewallRule -Name $firewallRule.Name +# $result | Should -Not -BeNullOrEmpty +# } +# } + +# Context 'When testing with firewall that does not exist' { +# It "Should not return anything on firewall rule $($firewallRule.Name)" { +# $result = Get-FirewallRule -Name 'Does not exist' +# $result | Should -BeNullOrEmpty +# } +# } + +# Context 'When testing with firewall that somehow occurs more than once' { +# Mock -CommandName Get-NetFirewallRule -MockWith { $firewallRules } + +# $errorRecord = Get-InvalidOperationRecord ` +# -Message ($script:localizedData.RuleNotUniqueError -f 2, $firewallRule.Name) + +# It "Should throw RuleNotUnique exception on firewall rule $($firewallRule.Name)" { +# { $result = Get-FirewallRule -Name $firewallRule.Name } | Should -Throw $errorRecord +# } +# } + +# Context 'When testing with firewall that exists and name contains wildcard characters' { +# Mock ` +# -CommandName Get-NetFirewallRule ` +# -ParameterFilter { +# $Name -eq 'Test `[With`] Wildcard`*' +# } ` +# -MockWith { $firewallRule } + +# It 'Should return a firewall rule when name is passed with wildcard characters' { +# $result = Get-FirewallRule -Name 'Test [With] Wildcard*' +# $result.Name | Should -Be $firewallRule.Name +# } + +# It 'Should call Get-NetFirewallRule with Name parameter value escaped' { +# Assert-MockCalled ` +# -CommandName Get-NetFirewallRule ` +# -ParameterFilter { +# $Name -eq 'Test `[With`] Wildcard`*' +# } ` +# -Exactly -Times 1 +# } +# } +# } + +# Describe 'DSC_Firewall\Get-FirewallRuleProperty' { +# Context 'All Properties' { +# $result = Get-FirewallRuleProperty -FirewallRule $firewallRule + +# It "Should return the right address filter on firewall rule $($firewallRule.Name)" { +# $expected = Get-NetFirewallAddressFilter -AssociatedNetFirewallRule $firewallRule + +# $($result.AddressFilters | Out-String -Stream) | +# Should -Be $($expected | Out-String -Stream) +# } + +# It "Should return the right application filter on firewall rule $($firewallRule.Name)" { +# $expected = Get-NetFirewallApplicationFilter -AssociatedNetFirewallRule $firewallRule + +# $($result.ApplicationFilters | Out-String -Stream) | +# Should -Be $($expected | Out-String -Stream) +# } + +# It "Should return the right interface filter on firewall rule $($firewallRule.Name)" { +# $expected = Get-NetFirewallInterfaceFilter -AssociatedNetFirewallRule $firewallRule + +# $($result.InterfaceFilters | Out-String -Stream) | +# Should -Be $($expected | Out-String -Stream) +# } + +# It "Should return the right interface type filter on firewall rule $($firewallRule.Name)" { +# $expected = Get-NetFirewallInterfaceTypeFilter -AssociatedNetFirewallRule $firewallRule +# $($result.InterfaceTypeFilters | Out-String -Stream) | +# Should -Be $($expected | Out-String -Stream) +# } + +# It "Should return the right port filter on firewall rule $($firewallRule.Name)" { +# $expected = Get-NetFirewallPortFilter -AssociatedNetFirewallRule $firewallRule +# $($result.PortFilters | Out-String -Stream) | +# Should -Be $($expected | Out-String -Stream) +# } + +# It "Should return the right Profile on firewall rule $($firewallRule.Name)" { +# $expected = Get-NetFirewallProfile -AssociatedNetFirewallRule $firewallRule +# $($result.Profile | Out-String -Stream) | +# Should -Be $($expected | Out-String -Stream) +# } + +# It "Should return the right Profile on firewall rule $($firewallRule.Name)" { +# $expected = Get-NetFirewallProfile -AssociatedNetFirewallRule $firewallRule +# $($result.Profile | Out-String -Stream) | +# Should -Be $($expected | Out-String -Stream) +# } + +# It "Should return the right Security Filters on firewall rule $($firewallRule.Name)" { +# $expected = Get-NetFirewallSecurityFilter -AssociatedNetFirewallRule $firewallRule +# $($result.SecurityFilters | Out-String -Stream) | +# Should -Be $($expected | Out-String -Stream) +# } + +# It "Should return the right Service Filters on firewall rule $($firewallRule.Name)" { +# $expected = Get-NetFirewallServiceFilter -AssociatedNetFirewallRule $firewallRule +# $($result.ServiceFilters | Out-String -Stream) | +# Should -Be $($expected | Out-String -Stream) +# } +# } +# } + +# Describe 'DSC_Firewall\ConvertTo-FirewallRuleNameEscapedString' { +# Context 'Rule name that contains no escaped characters' { +# It 'Should return the rule name with no backticks added' { +# ConvertTo-FirewallRuleNameEscapedString -Name 'No Escaped Characters' | Should -Be 'No Escaped Characters' +# } +# } + +# Context 'Rule name that contains at least one of each escaped characters' { +# It 'Should return the rule name with expected backticks added' { +# ConvertTo-FirewallRuleNameEscapedString -Name 'Left [ Right ] Asterisk *' | Should -Be 'Left `[ Right `] Asterisk `*' +# } +# } +# } +# } #end InModuleScope $DSCResourceName +# } +# finally +# { +# Invoke-TestCleanup +# } diff --git a/tests/Unit/DSC_FirewallProfile.Tests.ps1 b/tests/Unit/DSC_FirewallProfile.Tests.ps1 index 964abb09..d52654e0 100644 --- a/tests/Unit/DSC_FirewallProfile.Tests.ps1 +++ b/tests/Unit/DSC_FirewallProfile.Tests.ps1 @@ -1,318 +1,318 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_FirewallProfile' - -function Invoke-TestSetup -{ - try - { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' - } - catch [System.IO.FileNotFoundException] - { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' - } - - $script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Unit' - - Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') -} - -function Invoke-TestCleanup -{ - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} - -Invoke-TestSetup - -# Load the parameter List from the data file -$moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) -$resourceData = Import-LocalizedData ` - -BaseDirectory (Join-Path -Path $moduleRoot -ChildPath 'source\DscResources\DSC_FirewallProfile') ` - -FileName 'DSC_FirewallProfile.data.psd1' - -$script:parameterList = $resourceData.ParameterList - -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - # Create the Mock Objects that will be used for running tests - $firewallProfile = [PSObject] @{ - Name = 'Private' - Enabled = 'False' - DefaultInboundAction = 'Block' - DefaultOutboundAction = 'Block' - AllowInboundRules = 'False' - AllowLocalFirewallRules = 'False' - AllowLocalIPsecRules = 'False' - AllowUserApps = 'False' - AllowUserPorts = 'False' - AllowUnicastResponseToMulticast = 'False' - NotifyOnListen = 'False' - EnableStealthModeForIPsec = 'False' - LogFileName = '%systemroot%\system32\LogFiles\Firewall\pfirewall.log' - LogMaxSizeKilobytes = 32767 - LogAllowed = 'False' - LogBlocked = 'False' - LogIgnored = 'False' - DisabledInterfaceAliases = 'Ethernet' - } - - $firewallProfileSplat = [PSObject] @{ - Name = $firewallProfile.Name - Enabled = $firewallProfile.Enabled - DefaultInboundAction = $firewallProfile.DefaultInboundAction - DefaultOutboundAction = $firewallProfile.DefaultOutboundAction - AllowInboundRules = $firewallProfile.AllowInboundRules - AllowLocalFirewallRules = $firewallProfile.AllowLocalFirewallRules - AllowLocalIPsecRules = $firewallProfile.AllowLocalIPsecRules - AllowUserApps = $firewallProfile.AllowUserApps - AllowUserPorts = $firewallProfile.AllowUserPorts - AllowUnicastResponseToMulticast = $firewallProfile.AllowUnicastResponseToMulticast - NotifyOnListen = $firewallProfile.NotifyOnListen - EnableStealthModeForIPsec = $firewallProfile.EnableStealthModeForIPsec - LogFileName = $firewallProfile.LogFileName - LogMaxSizeKilobytes = $firewallProfile.LogMaxSizeKilobytes - LogAllowed = $firewallProfile.LogAllowed - LogBlocked = $firewallProfile.LogBlocked - LogIgnored = $firewallProfile.LogIgnored - DisabledInterfaceAliases = $firewallProfile.DisabledInterfaceAliases - } - - $gpoTypeParameters = $script:parameterList | Where-Object -FilterScript { - $_.Name -in @( - 'AllowInboundRules' - 'AllowLocalFirewallRules' - 'AllowLocalIPsecRules' - 'AllowUnicastResponseToMulticast' - 'AllowUserApps' - 'AllowUserPorts' - 'Enabled' - 'EnableStealthModeForIPsec' - 'LogAllowed' - 'LogBlocked' - 'LogIgnored' - 'NotifyOnListen' - ) - } - $actionTypeParameters = $script:parameterList | Where-Object -FilterScript { - $_.Name -in @( - 'DefaultInboundAction' - 'DefaultOutboundAction' - ) - } - - Describe 'DSC_FirewallProfile\Get-TargetResource' -Tag 'Get' { - BeforeEach { - Mock -CommandName Get-NetFirewallProfile -MockWith { $firewallProfile } - } - - Context 'Firewall Profile Exists' { - It 'Should return correct Firewall Profile values' { - $getTargetResourceParameters = Get-TargetResource -Name 'Private' - $getTargetResourceParameters.Name | Should -Be $firewallProfile.Name - $getTargetResourceParameters.Enabled | Should -Be $firewallProfile.Enabled - $getTargetResourceParameters.DefaultInboundAction | Should -Be $firewallProfile.DefaultInboundAction - $getTargetResourceParameters.DefaultOutboundAction | Should -Be $firewallProfile.DefaultOutboundAction - $getTargetResourceParameters.AllowInboundRules | Should -Be $firewallProfile.AllowInboundRules - $getTargetResourceParameters.AllowLocalFirewallRules | Should -Be $firewallProfile.AllowLocalFirewallRules - $getTargetResourceParameters.AllowLocalIPsecRules | Should -Be $firewallProfile.AllowLocalIPsecRules - $getTargetResourceParameters.AllowUserApps | Should -Be $firewallProfile.AllowUserApps - $getTargetResourceParameters.AllowUserPorts | Should -Be $firewallProfile.AllowUserPorts - $getTargetResourceParameters.AllowUnicastResponseToMulticast | Should -Be $firewallProfile.AllowUnicastResponseToMulticast - $getTargetResourceParameters.NotifyOnListen | Should -Be $firewallProfile.NotifyOnListen - $getTargetResourceParameters.EnableStealthModeForIPsec | Should -Be $firewallProfile.EnableStealthModeForIPsec - $getTargetResourceParameters.LogFileName | Should -Be $firewallProfile.LogFileName - $getTargetResourceParameters.LogMaxSizeKilobytes | Should -Be $firewallProfile.LogMaxSizeKilobytes - $getTargetResourceParameters.LogAllowed | Should -Be $firewallProfile.LogAllowed - $getTargetResourceParameters.LogBlocked | Should -Be $firewallProfile.LogBlocked - $getTargetResourceParameters.LogIgnored | Should -Be $firewallProfile.LogIgnored - $getTargetResourceParameters.DisabledInterfaceAliases | Should -Be $firewallProfile.DisabledInterfaceAliases - } - - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetFirewallProfile -Exactly -Times 1 - } - } - } - - Describe 'DSC_FirewallProfile\Set-TargetResource' -Tag 'Set' { - BeforeEach { - Mock -CommandName Get-NetFirewallProfile -MockWith { $firewallProfile } - } - - Context 'Firewall Profile all parameters are the same' { - Mock -CommandName Set-NetFirewallProfile - - It 'Should not throw error' { - { - $setTargetResourceParameters = $firewallProfileSplat.Clone() - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } - - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 - Assert-MockCalled -commandName Set-NetFirewallProfile -Exactly -Times 0 - } - } - - foreach ($parameter in $gpoTypeParameters) - { - $parameterName = $parameter.Name - Context "Firewall Profile $parameterName is different" { - Mock -CommandName Set-NetFirewallProfile - - It 'Should not throw error' { - { - $setTargetResourceParameters = $firewallProfileSplat.Clone() - $setTargetResourceParameters.$parameterName = 'True' - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } - - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 - Assert-MockCalled -commandName Set-NetFirewallProfile -Exactly -Times 1 - } - } - } - - foreach ($parameter in $actionTypeParameters) - { - $parameterName = $parameter.Name - Context "Firewall Profile $parameterName is different" { - Mock -CommandName Set-NetFirewallProfile - - It 'Should not throw error' { - { - $setTargetResourceParameters = $firewallProfileSplat.Clone() - $setTargetResourceParameters.$parameterName = 'Allow' - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } - - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 - Assert-MockCalled -commandName Set-NetFirewallProfile -Exactly -Times 1 - } - } - } - - Context 'Firewall Profile LogFileName is different' { - Mock -CommandName Set-NetFirewallProfile - - It 'Should not throw error' { - { - $setTargetResourceParameters = $firewallProfileSplat.Clone() - $setTargetResourceParameters.LogFileName = 'c:\differentfile.txt' - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } - - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 - Assert-MockCalled -commandName Set-NetFirewallProfile -Exactly -Times 1 - } - } - - Context 'Firewall Profile DisabledInterfaceAliases is different' { - Mock -CommandName Set-NetFirewallProfile - - It 'Should not throw error' { - { - $setTargetResourceParameters = $firewallProfileSplat.Clone() - $setTargetResourceParameters.DisabledInterfaceAliases = 'DifferentInterface' - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } - - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 - Assert-MockCalled -commandName Set-NetFirewallProfile -Exactly -Times 1 - } - } - } - - Describe 'DSC_FirewallProfile\Test-TargetResource' -Tag 'Test' { - BeforeEach { - Mock -CommandName Get-NetFirewallProfile -MockWith { $firewallProfile } - } - - Context 'Firewall Profile all parameters are the same' { - It 'Should return true' { - $testTargetResourceParameters = $firewallProfileSplat.Clone() - Test-TargetResource @testTargetResourceParameters | Should -Be $true - } - - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 - } - } - - foreach ($parameter in $gpoTypeParameters) - { - $parameterName = $parameter.Name - Context "Firewall Profile $parameterName is different" { - It 'Should return false' { - $testTargetResourceParameters = $firewallProfileSplat.Clone() - $testTargetResourceParameters.$parameterName = 'True' - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } - - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 - } - } - } - - foreach ($parameter in $actionTypeParameters) - { - $parameterName = $parameter.Name - Context "Firewall Profile $parameterName is different" { - It 'Should return false' { - $testTargetResourceParameters = $firewallProfileSplat.Clone() - $testTargetResourceParameters.$parameterName = 'Allow' - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } - - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 - } - } - } - - Context 'Firewall Profile LogFileName is different' { - It 'Should return false' { - $testTargetResourceParameters = $firewallProfileSplat.Clone() - $testTargetResourceParameters.LogFileName = 'c:\differentfile.txt' - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } - - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 - } - } - - Context 'Firewall Profile DisabledInterfaceAliases is different' { - It 'Should return false' { - $testTargetResourceParameters = $firewallProfileSplat.Clone() - $testTargetResourceParameters.DisabledInterfaceAliases = 'DifferentInterface' - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } - - It 'Should call expected Mocks' { - Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 - } - } - } - } -} -finally -{ - Invoke-TestCleanup -} +# $script:dscModuleName = 'NetworkingDsc' +# $script:dscResourceName = 'DSC_FirewallProfile' + +# function Invoke-TestSetup +# { +# try +# { +# Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' +# } +# catch [System.IO.FileNotFoundException] +# { +# throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' +# } + +# $script:testEnvironment = Initialize-TestEnvironment ` +# -DSCModuleName $script:dscModuleName ` +# -DSCResourceName $script:dscResourceName ` +# -ResourceType 'Mof' ` +# -TestType 'Unit' + +# Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +# } + +# function Invoke-TestCleanup +# { +# Restore-TestEnvironment -TestEnvironment $script:testEnvironment +# } + +# Invoke-TestSetup + +# # Load the parameter List from the data file +# $moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) +# $resourceData = Import-LocalizedData ` +# -BaseDirectory (Join-Path -Path $moduleRoot -ChildPath 'source\DscResources\DSC_FirewallProfile') ` +# -FileName 'DSC_FirewallProfile.data.psd1' + +# $script:parameterList = $resourceData.ParameterList + +# # Begin Testing +# try +# { +# InModuleScope $script:dscResourceName { +# # Create the Mock Objects that will be used for running tests +# $firewallProfile = [PSObject] @{ +# Name = 'Private' +# Enabled = 'False' +# DefaultInboundAction = 'Block' +# DefaultOutboundAction = 'Block' +# AllowInboundRules = 'False' +# AllowLocalFirewallRules = 'False' +# AllowLocalIPsecRules = 'False' +# AllowUserApps = 'False' +# AllowUserPorts = 'False' +# AllowUnicastResponseToMulticast = 'False' +# NotifyOnListen = 'False' +# EnableStealthModeForIPsec = 'False' +# LogFileName = '%systemroot%\system32\LogFiles\Firewall\pfirewall.log' +# LogMaxSizeKilobytes = 32767 +# LogAllowed = 'False' +# LogBlocked = 'False' +# LogIgnored = 'False' +# DisabledInterfaceAliases = 'Ethernet' +# } + +# $firewallProfileSplat = [PSObject] @{ +# Name = $firewallProfile.Name +# Enabled = $firewallProfile.Enabled +# DefaultInboundAction = $firewallProfile.DefaultInboundAction +# DefaultOutboundAction = $firewallProfile.DefaultOutboundAction +# AllowInboundRules = $firewallProfile.AllowInboundRules +# AllowLocalFirewallRules = $firewallProfile.AllowLocalFirewallRules +# AllowLocalIPsecRules = $firewallProfile.AllowLocalIPsecRules +# AllowUserApps = $firewallProfile.AllowUserApps +# AllowUserPorts = $firewallProfile.AllowUserPorts +# AllowUnicastResponseToMulticast = $firewallProfile.AllowUnicastResponseToMulticast +# NotifyOnListen = $firewallProfile.NotifyOnListen +# EnableStealthModeForIPsec = $firewallProfile.EnableStealthModeForIPsec +# LogFileName = $firewallProfile.LogFileName +# LogMaxSizeKilobytes = $firewallProfile.LogMaxSizeKilobytes +# LogAllowed = $firewallProfile.LogAllowed +# LogBlocked = $firewallProfile.LogBlocked +# LogIgnored = $firewallProfile.LogIgnored +# DisabledInterfaceAliases = $firewallProfile.DisabledInterfaceAliases +# } + +# $gpoTypeParameters = $script:parameterList | Where-Object -FilterScript { +# $_.Name -in @( +# 'AllowInboundRules' +# 'AllowLocalFirewallRules' +# 'AllowLocalIPsecRules' +# 'AllowUnicastResponseToMulticast' +# 'AllowUserApps' +# 'AllowUserPorts' +# 'Enabled' +# 'EnableStealthModeForIPsec' +# 'LogAllowed' +# 'LogBlocked' +# 'LogIgnored' +# 'NotifyOnListen' +# ) +# } +# $actionTypeParameters = $script:parameterList | Where-Object -FilterScript { +# $_.Name -in @( +# 'DefaultInboundAction' +# 'DefaultOutboundAction' +# ) +# } + +# Describe 'DSC_FirewallProfile\Get-TargetResource' -Tag 'Get' { +# BeforeEach { +# Mock -CommandName Get-NetFirewallProfile -MockWith { $firewallProfile } +# } + +# Context 'Firewall Profile Exists' { +# It 'Should return correct Firewall Profile values' { +# $getTargetResourceParameters = Get-TargetResource -Name 'Private' +# $getTargetResourceParameters.Name | Should -Be $firewallProfile.Name +# $getTargetResourceParameters.Enabled | Should -Be $firewallProfile.Enabled +# $getTargetResourceParameters.DefaultInboundAction | Should -Be $firewallProfile.DefaultInboundAction +# $getTargetResourceParameters.DefaultOutboundAction | Should -Be $firewallProfile.DefaultOutboundAction +# $getTargetResourceParameters.AllowInboundRules | Should -Be $firewallProfile.AllowInboundRules +# $getTargetResourceParameters.AllowLocalFirewallRules | Should -Be $firewallProfile.AllowLocalFirewallRules +# $getTargetResourceParameters.AllowLocalIPsecRules | Should -Be $firewallProfile.AllowLocalIPsecRules +# $getTargetResourceParameters.AllowUserApps | Should -Be $firewallProfile.AllowUserApps +# $getTargetResourceParameters.AllowUserPorts | Should -Be $firewallProfile.AllowUserPorts +# $getTargetResourceParameters.AllowUnicastResponseToMulticast | Should -Be $firewallProfile.AllowUnicastResponseToMulticast +# $getTargetResourceParameters.NotifyOnListen | Should -Be $firewallProfile.NotifyOnListen +# $getTargetResourceParameters.EnableStealthModeForIPsec | Should -Be $firewallProfile.EnableStealthModeForIPsec +# $getTargetResourceParameters.LogFileName | Should -Be $firewallProfile.LogFileName +# $getTargetResourceParameters.LogMaxSizeKilobytes | Should -Be $firewallProfile.LogMaxSizeKilobytes +# $getTargetResourceParameters.LogAllowed | Should -Be $firewallProfile.LogAllowed +# $getTargetResourceParameters.LogBlocked | Should -Be $firewallProfile.LogBlocked +# $getTargetResourceParameters.LogIgnored | Should -Be $firewallProfile.LogIgnored +# $getTargetResourceParameters.DisabledInterfaceAliases | Should -Be $firewallProfile.DisabledInterfaceAliases +# } + +# It 'Should call the expected mocks' { +# Assert-MockCalled -CommandName Get-NetFirewallProfile -Exactly -Times 1 +# } +# } +# } + +# Describe 'DSC_FirewallProfile\Set-TargetResource' -Tag 'Set' { +# BeforeEach { +# Mock -CommandName Get-NetFirewallProfile -MockWith { $firewallProfile } +# } + +# Context 'Firewall Profile all parameters are the same' { +# Mock -CommandName Set-NetFirewallProfile + +# It 'Should not throw error' { +# { +# $setTargetResourceParameters = $firewallProfileSplat.Clone() +# Set-TargetResource @setTargetResourceParameters +# } | Should -Not -Throw +# } + +# It 'Should call expected Mocks' { +# Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 +# Assert-MockCalled -commandName Set-NetFirewallProfile -Exactly -Times 0 +# } +# } + +# foreach ($parameter in $gpoTypeParameters) +# { +# $parameterName = $parameter.Name +# Context "Firewall Profile $parameterName is different" { +# Mock -CommandName Set-NetFirewallProfile + +# It 'Should not throw error' { +# { +# $setTargetResourceParameters = $firewallProfileSplat.Clone() +# $setTargetResourceParameters.$parameterName = 'True' +# Set-TargetResource @setTargetResourceParameters +# } | Should -Not -Throw +# } + +# It 'Should call expected Mocks' { +# Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 +# Assert-MockCalled -commandName Set-NetFirewallProfile -Exactly -Times 1 +# } +# } +# } + +# foreach ($parameter in $actionTypeParameters) +# { +# $parameterName = $parameter.Name +# Context "Firewall Profile $parameterName is different" { +# Mock -CommandName Set-NetFirewallProfile + +# It 'Should not throw error' { +# { +# $setTargetResourceParameters = $firewallProfileSplat.Clone() +# $setTargetResourceParameters.$parameterName = 'Allow' +# Set-TargetResource @setTargetResourceParameters +# } | Should -Not -Throw +# } + +# It 'Should call expected Mocks' { +# Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 +# Assert-MockCalled -commandName Set-NetFirewallProfile -Exactly -Times 1 +# } +# } +# } + +# Context 'Firewall Profile LogFileName is different' { +# Mock -CommandName Set-NetFirewallProfile + +# It 'Should not throw error' { +# { +# $setTargetResourceParameters = $firewallProfileSplat.Clone() +# $setTargetResourceParameters.LogFileName = 'c:\differentfile.txt' +# Set-TargetResource @setTargetResourceParameters +# } | Should -Not -Throw +# } + +# It 'Should call expected Mocks' { +# Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 +# Assert-MockCalled -commandName Set-NetFirewallProfile -Exactly -Times 1 +# } +# } + +# Context 'Firewall Profile DisabledInterfaceAliases is different' { +# Mock -CommandName Set-NetFirewallProfile + +# It 'Should not throw error' { +# { +# $setTargetResourceParameters = $firewallProfileSplat.Clone() +# $setTargetResourceParameters.DisabledInterfaceAliases = 'DifferentInterface' +# Set-TargetResource @setTargetResourceParameters +# } | Should -Not -Throw +# } + +# It 'Should call expected Mocks' { +# Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 +# Assert-MockCalled -commandName Set-NetFirewallProfile -Exactly -Times 1 +# } +# } +# } + +# Describe 'DSC_FirewallProfile\Test-TargetResource' -Tag 'Test' { +# BeforeEach { +# Mock -CommandName Get-NetFirewallProfile -MockWith { $firewallProfile } +# } + +# Context 'Firewall Profile all parameters are the same' { +# It 'Should return true' { +# $testTargetResourceParameters = $firewallProfileSplat.Clone() +# Test-TargetResource @testTargetResourceParameters | Should -Be $true +# } + +# It 'Should call expected Mocks' { +# Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 +# } +# } + +# foreach ($parameter in $gpoTypeParameters) +# { +# $parameterName = $parameter.Name +# Context "Firewall Profile $parameterName is different" { +# It 'Should return false' { +# $testTargetResourceParameters = $firewallProfileSplat.Clone() +# $testTargetResourceParameters.$parameterName = 'True' +# Test-TargetResource @testTargetResourceParameters | Should -Be $False +# } + +# It 'Should call expected Mocks' { +# Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 +# } +# } +# } + +# foreach ($parameter in $actionTypeParameters) +# { +# $parameterName = $parameter.Name +# Context "Firewall Profile $parameterName is different" { +# It 'Should return false' { +# $testTargetResourceParameters = $firewallProfileSplat.Clone() +# $testTargetResourceParameters.$parameterName = 'Allow' +# Test-TargetResource @testTargetResourceParameters | Should -Be $False +# } + +# It 'Should call expected Mocks' { +# Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 +# } +# } +# } + +# Context 'Firewall Profile LogFileName is different' { +# It 'Should return false' { +# $testTargetResourceParameters = $firewallProfileSplat.Clone() +# $testTargetResourceParameters.LogFileName = 'c:\differentfile.txt' +# Test-TargetResource @testTargetResourceParameters | Should -Be $False +# } + +# It 'Should call expected Mocks' { +# Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 +# } +# } + +# Context 'Firewall Profile DisabledInterfaceAliases is different' { +# It 'Should return false' { +# $testTargetResourceParameters = $firewallProfileSplat.Clone() +# $testTargetResourceParameters.DisabledInterfaceAliases = 'DifferentInterface' +# Test-TargetResource @testTargetResourceParameters | Should -Be $False +# } + +# It 'Should call expected Mocks' { +# Assert-MockCalled -commandName Get-NetFirewallProfile -Exactly -Times 1 +# } +# } +# } +# } +# } +# finally +# { +# Invoke-TestCleanup +# } diff --git a/tests/Unit/DSC_HostsFile.Tests.ps1 b/tests/Unit/DSC_HostsFile.Tests.ps1 index 43d858b1..3a8ff00f 100644 --- a/tests/Unit/DSC_HostsFile.Tests.ps1 +++ b/tests/Unit/DSC_HostsFile.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_HostsFile' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_HostsFile' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,288 +35,474 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup +Describe 'DSC_HostsFile' { + BeforeAll { + Mock -CommandName Add-Content + Mock -CommandName Set-Content + } -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - Describe 'DSC_HostsFile' { - BeforeEach { - Mock -CommandName Add-Content - Mock -CommandName Set-Content + Context 'When a host entry does not exist, and should' { + BeforeAll { + Mock -CommandName Get-Content -MockWith { + return @( + '# A mocked example of a host file - this line is a comment', + '', + '127.0.0.1 localhost', + '127.0.0.1 www.anotherexample.com', + '' + ) } + } + + It 'Should return absent from the get method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'When a host entry does not exist, and should' { $testParams = @{ HostName = 'www.contoso.com' IPAddress = '192.168.0.156' - Verbose = $true } - Mock -CommandName Get-Content -MockWith { - return @( - '# A mocked example of a host file - this line is a comment', - '', - '127.0.0.1 localhost', - '127.0.0.1 www.anotherexample.com', - '' - ) - } + $result = Get-TargetResource @testParams - It 'Should return absent from the get method' { - (Get-TargetResource @testParams).Ensure | Should -Be 'Absent' - } + $result.Ensure | Should -Be 'Absent' + } + } - It 'Should return false from the test method' { - Test-TargetResource @testParams | Should -Be $false - } + It 'Should return false from the test method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should create the entry in the set method' { - Set-TargetResource @testParams - Assert-MockCalled -CommandName Add-Content + $testParams = @{ + HostName = 'www.contoso.com' + IPAddress = '192.168.0.156' } + + Test-TargetResource @testParams | Should -BeFalse } + } + + It 'Should create the entry in the set method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'When a host entry exists but has the wrong IP address' { $testParams = @{ HostName = 'www.contoso.com' IPAddress = '192.168.0.156' - Verbose = $true } - Mock -CommandName Get-Content -MockWith { - return @( - '# A mocked example of a host file - this line is a comment', - '', - '127.0.0.1 localhost', - '127.0.0.1 www.anotherexample.com', - "127.0.0.1 $($testParams.HostName)", - '' - ) - } + Set-TargetResource @testParams + } - It 'Should return present from the get method' { - (Get-TargetResource @testParams).Ensure | Should -Be 'Present' - } + Should -Invoke -CommandName Add-Content -Exactly -Times 1 -Scope It + } + } - It 'Should return false from the test method' { - Test-TargetResource @testParams | Should -Be $false - } + Context 'When a host entry exists but has the wrong IP address' { + BeforeAll { + Mock -CommandName Get-Content -MockWith { + return @( + '# A mocked example of a host file - this line is a comment', + '', + '127.0.0.1 localhost', + '127.0.0.1 www.anotherexample.com', + '127.0.0.1 www.contoso.com', + '' + ) + } + } - It 'Should update the entry in the set method' { - Set-TargetResource @testParams - Assert-MockCalled -CommandName Set-Content + It 'Should return present from the get method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + HostName = 'www.contoso.com' + IPAddress = '192.168.0.156' } + + $result = Get-TargetResource @testParams + + $result.Ensure | Should -Be 'Present' } + } + + It 'Should return false from the test method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'When a host entry exists with the correct IP address' { $testParams = @{ HostName = 'www.contoso.com' IPAddress = '192.168.0.156' - Verbose = $true } - Mock -CommandName Get-Content -MockWith { - return @( - '# A mocked example of a host file - this line is a comment', - '', - '127.0.0.1 localhost', - '127.0.0.1 www.anotherexample.com', - "$($testParams.IPAddress) $($testParams.HostName)", - '' - ) + Test-TargetResource @testParams | Should -BeFalse + } + } + + It 'Should update the entry in the set method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + HostName = 'www.contoso.com' + IPAddress = '192.168.0.156' } - It 'Should return present from the get method' { - (Get-TargetResource @testParams).Ensure | Should -Be 'Present' + Set-TargetResource @testParams + } + + Should -Invoke -CommandName Set-Content -Exactly -Times 1 -Scope It + } + } + + Context 'When a host entry exists with the correct IP address' { + BeforeAll { + Mock -CommandName Get-Content -MockWith { + return @( + '# A mocked example of a host file - this line is a comment', + '', + '127.0.0.1 localhost', + '127.0.0.1 www.anotherexample.com', + '192.168.0.156 www.contoso.com', + '' + ) + } + } + + It 'Should return present from the get method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + HostName = 'www.contoso.com' + IPAddress = '192.168.0.156' } - It 'Should return true from the test method' { - Test-TargetResource @testParams | Should -Be $true + $result = Get-TargetResource @testParams + + $result.Ensure | Should -Be 'Present' + } + } + + It 'Should return true from the test method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + HostName = 'www.contoso.com' + IPAddress = '192.168.0.156' } + + Test-TargetResource @testParams | Should -BeTrue + } + } + } + + Context 'When a host entry exists but it should not' { + BeforeAll { + Mock -CommandName Get-Content -MockWith { + return @( + '# A mocked example of a host file - this line is a comment', + '', + '127.0.0.1 localhost', + '127.0.0.1 www.anotherexample.com', + '127.0.0.1 www.contoso.com', + '' + ) } + } + + It 'Should return present from the get method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'When a host entry exists but it should not' { $testParams = @{ HostName = 'www.contoso.com' Ensure = 'Absent' - Verbose = $true } - Mock -CommandName Get-Content -MockWith { - return @( - '# A mocked example of a host file - this line is a comment', - '', - '127.0.0.1 localhost', - '127.0.0.1 www.anotherexample.com', - "127.0.0.1 $($testParams.HostName)", - '' - ) - } + $result = Get-TargetResource @testParams - It 'Should return present from the get method' { - (Get-TargetResource @testParams).Ensure | Should -Be 'Present' - } + $result.Ensure | Should -Be 'Present' + } + } - It 'Should return false from the test method' { - Test-TargetResource @testParams | Should -Be $false + It 'Should return false from the test method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + HostName = 'www.contoso.com' + Ensure = 'Absent' } - It 'Should remove the entry in the set method' { - Set-TargetResource @testParams - Assert-MockCalled -CommandName Set-Content + Test-TargetResource @testParams | Should -BeFalse + } + } + + It 'Should remove the entry in the set method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + HostName = 'www.contoso.com' + Ensure = 'Absent' } + + Set-TargetResource @testParams } - Context 'When a commented out host entry exists' { + Should -Invoke -CommandName Set-Content -Exactly -Times 1 -Scope It + } + } + + Context 'When a commented out host entry exists' { + BeforeAll { + Mock -CommandName Get-Content -MockWith { + return @( + '# A mocked example of a host file - this line is a comment', + '', + '127.0.0.1 localhost', + '127.0.0.1 www.anotherexample.com', + '# 127.0.0.1 www.contoso.com', + '' + ) + } + } + + It 'Should return present from the get method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + $testParams = @{ HostName = 'www.contoso.com' IPAddress = '127.0.0.1' - Verbose = $true } - Mock -CommandName Get-Content -MockWith { - return @( - '# A mocked example of a host file - this line is a comment', - '', - '127.0.0.1 localhost', - '127.0.0.1 www.anotherexample.com', - "# 127.0.0.1 $($testParams.HostName)", - '' - ) - } + $result = Get-TargetResource @testParams - It 'Should return present from the get method' { - (Get-TargetResource @testParams).Ensure | Should -Be 'Absent' - } + $result.Ensure | Should -Be 'Absent' + } + } + + It 'Should return false from the test method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false from the test method' { - Test-TargetResource @testParams | Should -Be $false + $testParams = @{ + HostName = 'www.contoso.com' + IPAddress = '127.0.0.1' } - It 'Should add the entry in the set method' { - Set-TargetResource @testParams - Assert-MockCalled -CommandName Add-Content + Test-TargetResource @testParams | Should -BeFalse + } + } + + It 'Should add the entry in the set method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + HostName = 'www.contoso.com' + IPAddress = '127.0.0.1' } + + Set-TargetResource @testParams } - Context 'When a host entry does not it exist and should not' { + Should -Invoke -CommandName Add-Content -Exactly -Times 1 -Scope It + } + } + + Context 'When a host entry does not it exist and should not' { + BeforeAll { + Mock -CommandName Get-Content -MockWith { + return @( + '# A mocked example of a host file - this line is a comment', + '', + '127.0.0.1 localhost', + '127.0.0.1 www.anotherexample.com', + '' + ) + } + } + + It 'Should return absent from the get method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + $testParams = @{ HostName = 'www.contoso.com' Ensure = 'Absent' - Verbose = $true } - Mock -CommandName Get-Content -MockWith { - return @( - '# A mocked example of a host file - this line is a comment', - '', - '127.0.0.1 localhost', - '127.0.0.1 www.anotherexample.com', - '' - ) - } + $result = Get-TargetResource @testParams - It 'Should return absent from the get method' { - (Get-TargetResource @testParams).Ensure | Should -Be 'Absent' - } + $result.Ensure | Should -Be 'Absent' + } + } + + It 'Should return true from the test method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true from the test method' { - Test-TargetResource @testParams | Should -Be $true + $testParams = @{ + HostName = 'www.contoso.com' + Ensure = 'Absent' } + + Test-TargetResource @testParams | Should -BeTrue + } + } + } + + Context 'When a host entry exists and is correct, but it listed with multiple entries on one line' { + BeforeAll { + Mock -CommandName Get-Content -MockWith { + return @( + '# A mocked example of a host file - this line is a comment', + '', + '127.0.0.1 localhost', + '127.0.0.1 www.anotherexample.com', + '192.168.0.156 demo.contoso.com www.contoso.com more.examples.com', + '' + ) } + } + + It 'Should return present from the get method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'When a host entry exists and is correct, but it listed with multiple entries on one line' { $testParams = @{ HostName = 'www.contoso.com' IPAddress = '192.168.0.156' - Verbose = $true } - Mock -CommandName Get-Content -MockWith { - return @( - '# A mocked example of a host file - this line is a comment', - '', - '127.0.0.1 localhost', - '127.0.0.1 www.anotherexample.com', - "$($testParams.IPAddress) demo.contoso.com $($testParams.HostName) more.examples.com", - '' - ) - } + $result = Get-TargetResource @testParams - It 'Should return present from the get method' { - (Get-TargetResource @testParams).Ensure | Should -Be 'Present' - } + $result.Ensure | Should -Be 'Present' + } + } - It 'Should return true from the test method' { - Test-TargetResource @testParams | Should -Be $true + It 'Should return true from the test method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + HostName = 'www.contoso.com' + IPAddress = '192.168.0.156' } + + Test-TargetResource @testParams | Should -BeTrue } + } + } + + Context 'When a host entry exists and is not correct, but it listed with multiple entries on one line' { + BeforeAll { + Mock -CommandName Get-Content -MockWith { + return @( + '# A mocked example of a host file - this line is a comment', + '', + '127.0.0.1 localhost', + '127.0.0.1 www.anotherexample.com', + '127.0.0.1 demo.contoso.com www.contoso.com more.examples.com', + '' + ) + } + } + + It 'Should return present from the get method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'When a host entry exists and is not correct, but it listed with multiple entries on one line' { $testParams = @{ HostName = 'www.contoso.com' IPAddress = '192.168.0.156' - Verbose = $true } - Mock -CommandName Get-Content -MockWith { - return @( - '# A mocked example of a host file - this line is a comment', - '', - '127.0.0.1 localhost', - '127.0.0.1 www.anotherexample.com', - "127.0.0.1 demo.contoso.com $($testParams.HostName) more.examples.com", - '' - ) - } + $result = Get-TargetResource @testParams - It 'Should return present from the get method' { - (Get-TargetResource @testParams).Ensure | Should -Be 'Present' - } + $result.Ensure | Should -Be 'Present' + } + } + + It 'Should return false from the test method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false from the test method' { - Test-TargetResource @testParams | Should -Be $false + $testParams = @{ + HostName = 'www.contoso.com' + IPAddress = '192.168.0.156' } - It 'Should update the entry in the set method' { - Set-TargetResource @testParams - Assert-MockCalled -CommandName Set-Content + Test-TargetResource @testParams | Should -BeFalse + } + } + + It 'Should update the entry in the set method' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + HostName = 'www.contoso.com' + IPAddress = '192.168.0.156' } + + Set-TargetResource @testParams } - Context 'When called with invalid parameters' { + Should -Invoke -CommandName Set-Content -Exactly -Times 1 -Scope It + } + } + + Context 'When called with invalid parameters' { + BeforeAll { + Mock -CommandName Get-Content -MockWith { + return @( + '# A mocked example of a host file - this line is a comment', + '', + '127.0.0.1 localhost', + '127.0.0.1 www.anotherexample.com', + '' + ) + } + } + + It 'Should throw an error when IP Address is not provide and ensure is present' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + $testParams = @{ HostName = 'www.contoso.com' - Verbose = $true } - Mock -CommandName Get-Content -MockWith { - return @( - '# A mocked example of a host file - this line is a comment', - '', - '127.0.0.1 localhost', - '127.0.0.1 www.anotherexample.com', - '' - ) - } + $errorMessage = Get-InvalidArgumentRecord -Message $script:localizedData.UnableToEnsureWithoutIP -ArgumentName 'IPAddress' - It 'Should throw an error when IP Address is not provide and ensure is present' { - { Set-TargetResource @testParams } | Should -Throw $script:localizedData.UnableToEnsureWithoutIP - } + { Set-TargetResource @testParams } | Should -Throw -ExpectedMessage $errorMessage } } - } #end InModuleScope $DSCResourceName -} -finally -{ - Invoke-TestCleanup + } } diff --git a/tests/Unit/DSC_IPAddress.Tests.ps1 b/tests/Unit/DSC_IPAddress.Tests.ps1 index 3b430665..3491c45b 100644 --- a/tests/Unit/DSC_IPAddress.Tests.ps1 +++ b/tests/Unit/DSC_IPAddress.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_IPAddress' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_IPAddress' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,1233 +35,1500 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup +Describe 'DSC_IPAddress\Get-TargetResource' -Tag 'Get' { + Context 'Invoked with a single IP address' { + BeforeAll { + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = '192.168.0.1' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 24 + AddressFamily = 'IPv4' + } + } + } + + It 'Should return existing IP details' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - Describe 'DSC_IPAddress\Get-TargetResource' -Tag 'Get' { - Context 'Invoked with a single IP address' { - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ + $getTargetResourceParameters = @{ + IPAddress = '192.168.0.1/24' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + } + + $result = Get-TargetResource @getTargetResourceParameters + $result.IPAddress | Should -Be $getTargetResourceParameters.IPAddress + } + } + } + + Context 'Invoked with multiple IP addresses' { + BeforeAll { + Mock -CommandName Get-NetIPAddress -MockWith { + @( + @{ IPAddress = '192.168.0.1' InterfaceAlias = 'Ethernet' InterfaceIndex = 1 PrefixLength = [System.Byte] 24 AddressFamily = 'IPv4' + }, + @{ + IPAddress = '192.168.0.2' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 24 + AddressFamily = 'IPv4' } + ) + } + } + + It 'Should return existing IP details' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $getTargetResourceParameters = @{ + IPAddress = @('192.168.0.1/24', '192.168.0.2/24') + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should return existing IP details' { - $getTargetResourceParameters = @{ - IPAddress = '192.168.0.1/24' + $result = Get-TargetResource @getTargetResourceParameters + $result.IPAddress | Should -Be $getTargetResourceParameters.IPAddress + } + } + } +} + +Describe 'DSC_IPAddress\Set-TargetResource' -Tag 'Set' { + Context 'A single IPv4 address is currently set on the adapter' { + BeforeAll { + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = '192.168.0.1' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 16 + AddressFamily = 'IPv4' + } + } + + Mock -CommandName New-NetIPAddress + + Mock -CommandName Get-NetRoute { + @{ + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + AddressFamily = 'IPv4' + NextHop = '192.168.0.254' + DestinationPrefix = '0.0.0.0/0' + } + } + + Mock -CommandName Remove-NetIPAddress + + Mock -CommandName Remove-NetRoute + } + + Context 'Invoked with valid IP address' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $setTargetResourceParameters = @{ + IPAddress = '10.0.0.2/24' InterfaceAlias = 'Ethernet' AddressFamily = 'IPv4' } - $result = Get-TargetResource @getTargetResourceParameters - $result.IPAddress | Should -Be $getTargetResourceParameters.IPAddress + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } } - Context 'Invoked with multiple IP addresses' { - Mock -CommandName Get-NetIPAddress -MockWith { - @('192.168.0.1', '192.168.0.2') | foreach-object { - [PSCustomObject]@{ - IPAddress = $_ - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 24 - AddressFamily = 'IPv4' - } - } - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - It 'Should return existing IP details' { - $getTargetResourceParameters = @{ - IPAddress = @('192.168.0.1/24', '192.168.0.2/24') + Context 'Invoked with multiple valid IP Address' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $setTargetResourceParameters = @{ + IPAddress = @('10.0.0.2/24', '10.0.0.3/24') InterfaceAlias = 'Ethernet' AddressFamily = 'IPv4' } - $result = Get-TargetResource @getTargetResourceParameters - $result.IPAddress | Should -Be $getTargetResourceParameters.IPAddress + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 2 -Scope Context + } } - Describe 'DSC_IPAddress\Set-TargetResource' -Tag 'Set' { - Context 'A single IPv4 address is currently set on the adapter' { - BeforeEach { - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = '192.168.0.1' - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 16 - AddressFamily = 'IPv4' - } + Context 'Invoked with multiple valid IP Addresses with one currently set' { + BeforeAll { + Mock -CommandName New-NetIPAddress -MockWith { + throw [Microsoft.Management.Infrastructure.CimException] 'InvalidOperation' + } -ParameterFilter { $IPaddress -eq '192.168.0.1' } + + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = '192.168.0.1' + InterfaceAlias = 'Ethernet' + PrefixLength = [System.Byte] 16 + AddressFamily = 'IPv4' } + } -ParameterFilter { $IPaddress -eq '192.168.0.1' } + + Mock -CommandName Write-Error + } - Mock -CommandName New-NetIPAddress + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Mock -CommandName Get-NetRoute { - [PSCustomObject] @{ - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - AddressFamily = 'IPv4' - NextHop = '192.168.0.254' - DestinationPrefix = '0.0.0.0/0' - } + $setTargetResourceParameters = @{ + IPAddress = @('192.168.0.1/16', '10.0.0.3/24') + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - Mock -CommandName Remove-NetIPAddress + $result = Set-TargetResource @setTargetResourceParameters - Mock -CommandName Remove-NetRoute + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } + } - Context 'Invoked with valid IP address' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = '10.0.0.2/24' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 2 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 2 -Scope Context + Should -Invoke -CommandName Write-Error -Exactly -Times 0 -Scope Context + } + } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 1 - } - } + Context 'Invoked with multiple valid IP Addresses with one currently set on another adapter' { + BeforeAll { + Mock -CommandName New-NetIPAddress -MockWith { + throw [Microsoft.Management.Infrastructure.CimException] 'InvalidOperation' + } -ParameterFilter { $IPaddress -eq '192.168.0.1' } - Context 'Invoked with multiple valid IP Address' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = @('10.0.0.2/24', '10.0.0.3/24') - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = '192.168.0.1' + InterfaceAlias = 'Ethernet2' + PrefixLength = [System.Byte] 16 + AddressFamily = 'IPv4' } + } -ParameterFilter { $IPaddress -eq '192.168.0.1' } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 2 + Mock -CommandName Write-Error + } + + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $setTargetResourceParameters = @{ + IPAddress = @('192.168.0.1/16', '10.0.0.3/24') + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - } - Context 'Invoked with multiple valid IP Addresses with one currently set' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = @('192.168.0.1/16', '10.0.0.3/24') - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + $result = Set-TargetResource @setTargetResourceParameters - Mock -CommandName New-NetIPAddress -MockWith { - throw [Microsoft.Management.Infrastructure.CimException] 'InvalidOperation' - } -ParameterFilter { $IPaddress -eq '192.168.0.1' } + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty + } + } - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = '192.168.0.1' - InterfaceAlias = 'Ethernet' - PrefixLength = [System.Byte] 16 - AddressFamily = 'IPv4' - } - } -ParameterFilter { $IPaddress -eq '192.168.0.1' } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 2 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 2 -Scope Context + Should -Invoke -CommandName Write-Error -Exactly -Times 1 -Scope Context + } + } - Mock -CommandName Write-Error + Context 'Invoked IPv4 Class A with no prefix' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty + $setTargetResourceParameters = @{ + IPAddress = '10.11.12.13' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 2 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 0 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 2 - Assert-MockCalled -CommandName Write-Error -Exactly -Times 0 - } + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } + } - Context 'Invoked with multiple valid IP Addresses with one currently set on another adapter' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = @('192.168.0.1/16', '10.0.0.3/24') - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 1 -Scope Context -ParameterFilter { + $PrefixLength -eq 8 + } - Mock -CommandName New-NetIPAddress -MockWith { - throw [Microsoft.Management.Infrastructure.CimException] 'InvalidOperation' - } -ParameterFilter { $IPaddress -eq '192.168.0.1' } + } + } - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = '192.168.0.1' - InterfaceAlias = 'Ethernet2' - PrefixLength = [System.Byte] 16 - AddressFamily = 'IPv4' - } - } -ParameterFilter { $IPaddress -eq '192.168.0.1' } + Context 'Invoked IPv4 Class B with no prefix' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Mock -CommandName Write-Error + $setTargetResourceParameters = @{ + IPAddress = '172.16.4.19' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty + $result = Set-TargetResource @setTargetResourceParameters - } + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty + } + } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 2 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 0 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 2 - Assert-MockCalled -CommandName Write-Error -Exactly -Times 1 - } + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 1 -Scope Context -ParameterFilter { + $PrefixLength -eq 16 } + } + } - Context 'Invoked IPv4 Class A with no prefix' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = '10.11.12.13' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'Invoked IPv4 Class C with no prefix' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty + $setTargetResourceParameters = @{ + IPAddress = '192.168.10.19' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 1 -ParameterFilter { - $PrefixLength -eq 8 - } + $result = Set-TargetResource @setTargetResourceParameters - } + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 1 -Scope Context -ParameterFilter { + $PrefixLength -eq 24 + } + } + } - Context 'Invoked IPv4 Class B with no prefix' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = '172.16.4.19' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'Invoked with parameter "KeepExistingAddress"' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty + $setTargetResourceParameters = @{ + IPAddress = '10.0.0.2/24' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + KeepExistingAddress = $true } - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 1 -ParameterFilter { - $PrefixLength -eq 16 - } - } - } + $result = Set-TargetResource @setTargetResourceParameters - Context 'Invoked IPv4 Class C with no prefix' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = '192.168.10.19' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty + } + } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 1 -Scope Context + } + } + } - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 1 -ParameterFilter { - $PrefixLength -eq 24 - } - } + Context 'A single IPv6 address is currently set on the adapter' { + BeforeAll { + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = 'fe80::15' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 64 + AddressFamily = 'IPv6' } + } - Context 'Invoked with parameter "KeepExistingAddress"' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = '10.0.0.2/24' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - KeepExistingAddress = $true - } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty - } + Mock -CommandName New-NetIPAddress - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 0 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 1 - } + Mock -CommandName Get-NetRoute { + @{ + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + AddressFamily = 'IPv6' + NextHop = 'fe80::16' + DestinationPrefix = '::/0' } } - Context 'A single IPv6 address is currently set on the adapter' { - BeforeEach { - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = 'fe80::15' - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 64 - AddressFamily = 'IPv6' - } - } + Mock -CommandName Remove-NetIPAddress + + Mock -CommandName Remove-NetRoute + } - Mock -CommandName New-NetIPAddress + Context 'Invoked with valid IPv6 Address' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Mock -CommandName Get-NetRoute { - [PSCustomObject] @{ - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - AddressFamily = 'IPv6' - NextHop = 'fe80::16' - DestinationPrefix = '::/0' - } + $setTargetResourceParameters = @{ + IPAddress = 'fe80::17/64' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } - Mock -CommandName Remove-NetIPAddress + $result = Set-TargetResource @setTargetResourceParameters - Mock -CommandName Remove-NetRoute + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } + } - Context 'Invoked with valid IPv6 Address' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = 'fe80::17/64' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty - } + Context 'Invoked with multiple valid IPv6 Addresses' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 1 + $setTargetResourceParameters = @{ + IPAddress = @('fe80::17/64', 'fe80::18/64') + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } + } - Context 'Invoked with multiple valid IPv6 Addresses' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = @('fe80::17/64', 'fe80::18/64') - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 2 -Scope Context + } + } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty - } + Context 'Invoked IPv6 with no prefix' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 2 + $setTargetResourceParameters = @{ + IPAddress = 'fe80::17' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } + } - Context 'Invoked IPv6 with no prefix' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = 'fe80::17' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty - } + Context 'Invoked with parameter "KeepExistingAddress"' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 1 + $setTargetResourceParameters = @{ + IPAddress = 'fe80::17/64' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' + KeepExistingAddress = $true } + + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } + } - Context 'Invoked with parameter "KeepExistingAddress"' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = 'fe80::17/64' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - KeepExistingAddress = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 1 -Scope Context + } + } + } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty + Context 'Multiple IPv4 addresses are currently set on the adapter' { + BeforeEach { + Mock -CommandName Get-NetIPAddress -MockWith { + @( + @{ + IPAddress = '192.168.0.1' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 24 + AddressFamily = 'IPv4' + }, + @{ + IPAddress = '172.16.4.19' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 16 + AddressFamily = 'IPv4' } + ) + } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 0 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 1 - } + Mock -CommandName New-NetIPAddress + + Mock -CommandName Get-NetRoute { + @{ + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + AddressFamily = 'IPv4' + NextHop = '192.168.0.254' + DestinationPrefix = '0.0.0.0/0' } } - Context 'Multiple IPv4 addresses are currently set on the adapter' { - BeforeEach { - Mock -CommandName Get-NetIPAddress -MockWith { - $CurrentIPs = @(([PSCustomObject] @{ - IPAddress = '192.168.0.1' - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 24 - AddressFamily = 'IPv4' - }), ([PSCustomObject] @{ - IPAddress = '172.16.4.19' - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 16 - AddressFamily = 'IPv4' - })) - Return $CurrentIPs - } + Mock -CommandName Remove-NetIPAddress + + Mock -CommandName Remove-NetRoute + } - Mock -CommandName New-NetIPAddress + Context 'Invoked with different prefixes' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Mock -CommandName Get-NetRoute { - [PSCustomObject] @{ - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - AddressFamily = 'IPv4' - NextHop = '192.168.0.254' - DestinationPrefix = '0.0.0.0/0' - } + $setTargetResourceParameters = @{ + IPAddress = '10.0.0.2/24', '172.16.4.19/16' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - Mock -CommandName Remove-NetIPAddress + $result = Set-TargetResource @setTargetResourceParameters - Mock -CommandName Remove-NetRoute + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } + } - Context 'Invoked with different prefixes' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = '10.0.0.2/24', '172.16.4.19/16' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 2 -Scope Context + } + } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty - } + Context 'Invoked with existing IP with different prefix' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 2 + $setTargetResourceParameters = @{ + IPAddress = '172.16.4.19/24' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - } - Context 'Invoked with existing IP with different prefix' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = '172.16.4.19/24' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } - - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty - } + $result = Set-TargetResource @setTargetResourceParameters - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 2 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 1 - } + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } + } - Context 'Invoked with parameter "KeepExistingAddress" and different prefixes' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = '10.0.0.2/24', '172.16.4.19/16' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - KeepExistingAddress = $true - } + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 2 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty - } + Context 'Invoked with parameter "KeepExistingAddress" and different prefixes' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 0 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 2 + $setTargetResourceParameters = @{ + IPAddress = '10.0.0.2/24', '172.16.4.19/16' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + KeepExistingAddress = $true } + + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } + } - Context 'Invoked with parameter "KeepExistingAddress" and existing IP with different prefix' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = '172.16.4.19/24' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - KeepExistingAddress = $true - } + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 2 -Scope Context + } + } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty - } + Context 'Invoked with parameter "KeepExistingAddress" and existing IP with different prefix' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetIPAddress -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetIPAddress -Exactly -Times 1 + $setTargetResourceParameters = @{ + IPAddress = '172.16.4.19/24' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + KeepExistingAddress = $true } + + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetIPAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetIPAddress -Exactly -Times 1 -Scope Context + } } + } +} - Describe 'DSC_IPAddress\Test-TargetResource' -Tag 'Test' { - Context 'A single IPv4 address is currently set on the adapter' { - BeforeEach { - Mock -CommandName Get-NetAdapter -MockWith { - [PSObject] @{ - Name = 'Ethernet' - } - } +Describe 'DSC_IPAddress\Test-TargetResource' -Tag 'Test' { + Context 'A single IPv4 address is currently set on the adapter' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + } + } - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = '192.168.0.15' - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 16 - AddressFamily = 'IPv4' - } - } + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = '192.168.0.15' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 16 + AddressFamily = 'IPv4' } + } + } - Context 'Invoked with invalid IPv4 Address' { - It 'Should throw an exception' { - $testGetResourceParameters = @{ - IPAddress = 'BadAddress' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'Invoked with invalid IPv4 Address' { + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { $result = Test-TargetResource @testGetResourceParameters } | Should -Throw + $testGetResourceParameters = @{ + IPAddress = 'BadAddress' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { $result = Test-TargetResource @testGetResourceParameters } | Should -Throw } + } + } - Context 'Invoked with different IPv4 Address' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = '192.168.0.1/16' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'Invoked with different IPv4 Address' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false + $testGetResourceParameters = @{ + IPAddress = '192.168.0.1/16' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - } + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } + } - Context 'Invoked with the same IPv4 Address' { - It 'Should return $true' { - $testGetResourceParameters = @{ - IPAddress = '192.168.0.15/16' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $true - } + Context 'Invoked with the same IPv4 Address' { + It 'Should return $true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = '192.168.0.15/16' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeTrue } + } - Context 'Invoked with the same IPv4 Address but different prefix length' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = '192.168.0.15/24' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false - } + Context 'Invoked with the same IPv4 Address but different prefix length' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = '192.168.0.15/24' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } } - Context 'Multiple IPv4 addresses are currently set on the adapter' { - BeforeEach { - Mock -CommandName Get-NetAdapter -MockWith { - [PSObject] @{ - Name = 'Ethernet' - } - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } + } - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = @('192.168.0.15', '192.168.0.16') - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 16 - AddressFamily = 'IPv4' - } - } + Context 'Multiple IPv4 addresses are currently set on the adapter' { + BeforeEach { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + } + } + + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = @('192.168.0.15', '192.168.0.16') + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 16 + AddressFamily = 'IPv4' } + } + } - Context 'Invoked with multiple different IPv4 Addresses' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = @('192.168.0.1/16', '192.168.0.2/16') - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'Invoked with multiple different IPv4 Addresses' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false + $testGetResourceParameters = @{ + IPAddress = @('192.168.0.1/16', '192.168.0.2/16') + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - } + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } + } - Context 'Invoked with a single different IPv4 Address' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = '192.168.0.1/16' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false - } + Context 'Invoked with a single different IPv4 Address' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = '192.168.0.1/16' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } + } - Context 'Invoked with the same IPv4 Addresses' { - It 'Should return $true' { - $testGetResourceParameters = @{ - IPAddress = @('192.168.0.15/16', '192.168.0.16/16') - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $true - } + Context 'Invoked with the same IPv4 Addresses' { + It 'Should return $true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = @('192.168.0.15/16', '192.168.0.16/16') + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeTrue } + } - Context 'Invoked with the combination of same and different IPv4 Addresses' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = @('192.168.0.1/16', '192.168.0.16/16') - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false - } + Context 'Invoked with the combination of same and different IPv4 Addresses' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = @('192.168.0.1/16', '192.168.0.16/16') + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } + } - Context 'Invoked with a single different Class A IPv4 Address with no prefix' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = '10.1.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false - } + Context 'Invoked with a single different Class A IPv4 Address with no prefix' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = '10.1.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } + } - Context 'Invoked with a single different Class B IPv4 Address with no prefix' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = '172.16.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false - } - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + Context 'Invoked with a single different Class B IPv4 Address with no prefix' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testGetResourceParameters = @{ + IPAddress = '172.16.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } + } - Context 'Invoked with a single different Class C IPv4 Address with no prefix' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false - } + Context 'Invoked with a single different Class C IPv4 Address with no prefix' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } } - Context 'A single IPv4 address with 8 bit prefix is currently set on the adapter' { - BeforeEach { - Mock -CommandName Get-NetAdapter -MockWith { - [PSObject] @{ - Name = 'Ethernet' - } - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } + } - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = @('10.1.0.1') - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 8 - AddressFamily = 'IPv4' - } - } + Context 'A single IPv4 address with 8 bit prefix is currently set on the adapter' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' } + } + + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = @('10.1.0.1') + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 8 + AddressFamily = 'IPv4' + } + } + } - Context 'Invoked with the same Class A IPv4 Address with no prefix' { - It 'Should return $true' { - $testGetResourceParameters = @{ - IPAddress = '10.1.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'Invoked with the same Class A IPv4 Address with no prefix' { + It 'Should return $true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $true + $testGetResourceParameters = @{ + IPAddress = '10.1.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - } + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeTrue } } - Context 'A single IPv4 address with 16 bit prefix is currently set on the adapter' { - BeforeEach { - Mock -CommandName Get-NetAdapter -MockWith { - [PSObject] @{ - Name = 'Ethernet' - } - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } + } - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = @('172.16.0.1') - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 16 - AddressFamily = 'IPv4' - } - } + Context 'A single IPv4 address with 16 bit prefix is currently set on the adapter' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' } + } - Context 'Invoked with the same Class B IPv4 Address with no prefix' { - It 'Should return $true' { - $testGetResourceParameters = @{ - IPAddress = '172.16.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = @('172.16.0.1') + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 16 + AddressFamily = 'IPv4' + } + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $true - } + Context 'Invoked with the same Class B IPv4 Address with no prefix' { + It 'Should return $true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = '172.16.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeTrue } } - Context 'A single IPv4 address with 24 bit prefix is currently set on the adapter' { - BeforeEach { - Mock -CommandName Get-NetAdapter -MockWith { - [PSObject] @{ - Name = 'Ethernet' - } - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } + } - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = @('192.168.0.1') - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 24 - AddressFamily = 'IPv4' - } - } + Context 'A single IPv4 address with 24 bit prefix is currently set on the adapter' { + BeforeEach { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' } + } - Context 'Invoked with the same Class C IPv4 Address with no prefix' { - It 'Should return $true' { - $testGetResourceParameters = @{ - IPAddress = '192.168.0.1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = @('192.168.0.1') + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 24 + AddressFamily = 'IPv4' + } + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $true - } + Context 'Invoked with the same Class C IPv4 Address with no prefix' { + It 'Should return $true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = '192.168.0.1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeTrue } } - Context 'A single IPv6 address with 64 bit prefix is currently set on the adapter' { - BeforeEach { - Mock -CommandName Get-NetAdapter -MockWith { - [PSObject] @{ - Name = 'Ethernet' - } - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } + } - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = 'fe80::15' - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 64 - AddressFamily = 'IPv6' - } - } + Context 'A single IPv6 address with 64 bit prefix is currently set on the adapter' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' } + } - Context 'Invoked with invalid IPv6 Address' { - It 'Should throw an exception' { - $testGetResourceParameters = @{ - IPAddress = 'BadAddress' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } - - { $result = Test-TargetResource @testGetResourceParameters } | Should -Throw - } + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = 'fe80::15' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 64 + AddressFamily = 'IPv6' } + } + } - Context 'Invoked with different IPv6 Address' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = 'fe80::1/64' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + Context 'Invoked with invalid IPv6 Address' { + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false + $testGetResourceParameters = @{ + IPAddress = 'BadAddress' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - } + { $result = Test-TargetResource @testGetResourceParameters } | Should -Throw } + } + } - Context 'Invoked with the same IPv6 Address' { - It 'Should return $true' { - $testGetResourceParameters = @{ - IPAddress = 'fe80::15/64' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $true - } + Context 'Invoked with different IPv6 Address' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = 'fe80::1/64' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } + } - Context 'Invoked with the same IPv6 Address with no prefix' { - It 'testGetResourceParameters return $true' { - $testGetResourceParameters = @{ - IPAddress = 'fe80::15' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $true - } + Context 'Invoked with the same IPv6 Address' { + It 'Should return $true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = 'fe80::15/64' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeTrue } } - Context 'Multiple IPv6 addresses with 64 bit prefix are currently set on the adapter' { - BeforeEach { - Mock -CommandName Get-NetAdapter -MockWith { - [PSObject] @{ - Name = 'Ethernet' - } - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject]@{ - IPAddress = @('fe80::15', 'fe80::16') - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 64 - AddressFamily = 'IPv6' - } + Context 'Invoked with the same IPv6 Address with no prefix' { + It 'testGetResourceParameters return $true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testGetResourceParameters = @{ + IPAddress = 'fe80::15' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeTrue } + } - Context 'Invoked with multiple different IPv6 Addresses' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = @('fe80::1/64', 'fe80::2/64') - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false - } + Context 'Multiple IPv6 addresses with 64 bit prefix are currently set on the adapter' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + } + } - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - } + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = @('fe80::15', 'fe80::16') + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 64 + AddressFamily = 'IPv6' } + } + } - Context 'Invoked with a single different IPv6 Address' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = 'fe80::1/64' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + Context 'Invoked with multiple different IPv6 Addresses' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false + $testGetResourceParameters = @{ + IPAddress = @('fe80::1/64', 'fe80::2/64') + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 - } + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } + } - Context 'Invoked with the same IPv6 Addresses' { - It 'Should return $true' { - $testGetResourceParameters = @{ - IPAddress = @('fe80::15/64', 'fe80::16/64') - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $true - } + Context 'Invoked with a single different IPv6 Address' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = 'fe80::1/64' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } + } - Context 'Invoked with a mix of the same and different IPv6 Addresses' { - It 'Should return $true' { - $testGetResourceParameters = @{ - IPAddress = @('fe80::1/64', 'fe80::16/64') - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false - } + Context 'Invoked with the same IPv6 Addresses' { + It 'Should return $true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = @('fe80::15/64', 'fe80::16/64') + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeTrue } + } - Context 'Invoked with a single different IPv6 Address with no prefix' { - It 'Should return $false' { - $testGetResourceParameters = @{ - IPAddress = 'fe80::1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $false - } + Context 'Invoked with a mix of the same and different IPv6 Addresses' { + It 'Should return $true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call appropriate mocks' { - Assert-MockCalled -CommandName Get-NetIPAddress -Exactly -Times 1 + $testGetResourceParameters = @{ + IPAddress = @('fe80::1/64', 'fe80::16/64') + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } } + + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } } - Describe 'DSC_IPAddress\Assert-ResourceProperty' { - BeforeEach { - Mock -CommandName Get-NetAdapter -MockWith { - [PSObject] @{ - Name = 'Ethernet' + Context 'Invoked with a single different IPv6 Address with no prefix' { + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testGetResourceParameters = @{ + IPAddress = 'fe80::1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeFalse } } - Context 'Invoked with bad interface alias' { - It 'Should throw an InterfaceNotAvailable error' { - $assertResourcePropertyParameters = @{ - IPAddress = '192.168.0.1/16' - InterfaceAlias = 'NotReal' - AddressFamily = 'IPv4' - } + It 'Should call appropriate mocks' { + Should -Invoke -CommandName Get-NetIPAddress -Exactly -Times 1 -Scope Context + } + } + } +} - $errorRecord = Get-InvalidArgumentRecord ` - -Message ($script:localizedData.InterfaceNotAvailableError -f $assertResourcePropertyParameters.InterfaceAlias) ` - -ArgumentName 'Interface' +Describe 'DSC_IPAddress\Assert-ResourceProperty' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + } + } + } - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw $errorRecord + Context 'Invoked with bad interface alias' { + It 'Should throw an InterfaceNotAvailable error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $assertResourcePropertyParameters = @{ + IPAddress = '192.168.0.1/16' + InterfaceAlias = 'NotReal' + AddressFamily = 'IPv4' } + + $errorRecord = Get-InvalidArgumentRecord ` + -Message ($script:localizedData.InterfaceNotAvailableError -f $assertResourcePropertyParameters.InterfaceAlias) ` + -ArgumentName 'InterfaceAlias' + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw $errorRecord } + } + } - Context 'Invoked with invalid IP Address' { - It 'Should throw an exception' { - $assertResourcePropertyParameters = @{ - IPAddress = 'NotReal' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'Invoked with invalid IP Address' { + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw + $assertResourcePropertyParameters = @{ + IPAddress = 'NotReal' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw } + } + } - Context 'Invoked with IPv4 Address and IPv6 family mismatch' { - It 'Should throw an exception' { - $assertResourcePropertyParameters = @{ - IPAddress = '192.168.0.1/16' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + Context 'Invoked with IPv4 Address and IPv6 family mismatch' { + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw + $assertResourcePropertyParameters = @{ + IPAddress = '192.168.0.1/16' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw } + } + } - Context 'Invoked with IPv6 Address and IPv4 family mismatch' { - It 'Should throw an exception' { - $assertResourcePropertyParameters = @{ - IPAddress = 'fe80::15' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'Invoked with IPv6 Address and IPv4 family mismatch' { + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw + $assertResourcePropertyParameters = @{ + IPAddress = 'fe80::15' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw } + } + } - Context 'Invoked with valid IPv4 Address' { - It 'Should Not Throw an error' { - $assertResourcePropertyParameters = @{ - IPAddress = '192.168.0.1/16' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'Invoked with valid IPv4 Address' { + It 'Should Not Throw an error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw + $assertResourcePropertyParameters = @{ + IPAddress = '192.168.0.1/16' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw } + } + } - Context 'Invoked with multiple valid IPv4 Addresses' { - It 'Should Not Throw an error' { - $assertResourcePropertyParameters = @{ - IPAddress = @('192.168.0.1/24', '192.168.0.2/24') - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'Invoked with multiple valid IPv4 Addresses' { + It 'Should Not Throw an error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw + $assertResourcePropertyParameters = @{ + IPAddress = @('192.168.0.1/24', '192.168.0.2/24') + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw } + } + } - Context 'Invoked with valid IPv6 Address' { - It 'Should Not Throw an error' { - $assertResourcePropertyParameters = @{ - IPAddress = 'fe80:ab04:30F5:002b::1/64' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + Context 'Invoked with valid IPv6 Address' { + It 'Should Not Throw an error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw + $assertResourcePropertyParameters = @{ + IPAddress = 'fe80:ab04:30F5:002b::1/64' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw } + } + } - Context 'Invoked with invalid IPv4 prefix length' { - It 'Should throw a PrefixLengthError when greater than 32' { - $assertResourcePropertyParameters = @{ - IPAddress = '192.168.0.1/33' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } + Context 'Invoked with invalid IPv4 prefix length' { + It 'Should throw a PrefixLengthError when greater than 32' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $prefixLength = ($assertResourcePropertyParameters.IPAddress -split '/')[-1] + $assertResourcePropertyParameters = @{ + IPAddress = '192.168.0.1/33' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + } - $errorRecord = Get-InvalidArgumentRecord ` - -Message ($script:localizedData.PrefixLengthError -f $prefixLength, $assertResourcePropertyParameters.AddressFamily) ` - -ArgumentName 'IPAddress' + $prefixLength = ($assertResourcePropertyParameters.IPAddress -split '/')[-1] - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw $errorRecord - } + $errorRecord = Get-InvalidArgumentRecord ` + -Message ($script:localizedData.PrefixLengthError -f $prefixLength, $assertResourcePropertyParameters.AddressFamily) ` + -ArgumentName 'IPAddress' - It 'Should throw an Argument error when less than 0' { - $assertResourcePropertyParameters = @{ - IPAddress = '192.168.0.1/-1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - } - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw 'Value was either too large or too small for a UInt32.' - } + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw $errorRecord } + } - Context 'Invoked with invalid IPv6 prefix length' { - It 'Should throw a PrefixLengthError error when greater than 128' { - $assertResourcePropertyParameters = @{ - IPAddress = 'fe80::1/129' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + It 'Should throw an Argument error when less than 0' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $prefixLength = ($assertResourcePropertyParameters.IPAddress -split '/')[-1] + $assertResourcePropertyParameters = @{ + IPAddress = '192.168.0.1/-1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + } - $errorRecord = Get-InvalidArgumentRecord ` - -Message ($script:localizedData.PrefixLengthError -f $prefixLength, $assertResourcePropertyParameters.AddressFamily) ` - -ArgumentName 'IPAddress' + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw ('*' + 'Value was either too large or too small for a UInt32.' + '*') + } + } + } + + Context 'Invoked with invalid IPv6 prefix length' { + It 'Should throw a PrefixLengthError error when greater than 128' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw $errorRecord + $assertResourcePropertyParameters = @{ + IPAddress = 'fe80::1/129' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } - It 'Should throw an Argument error when less than 0' { - $assertResourcePropertyParameters = @{ - IPAddress = 'fe80::1/-1' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + $prefixLength = ($assertResourcePropertyParameters.IPAddress -split '/')[-1] - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw 'Value was either too large or too small for a UInt32.' + $errorRecord = Get-InvalidArgumentRecord ` + -Message ($script:localizedData.PrefixLengthError -f $prefixLength, $assertResourcePropertyParameters.AddressFamily) ` + -ArgumentName 'IPAddress' + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw $errorRecord + } + } + + It 'Should throw an Argument error when less than 0' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $assertResourcePropertyParameters = @{ + IPAddress = 'fe80::1/-1' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + # Needs an OverflowException helper + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Throw ('*' + 'Value was either too large or too small for a UInt32.' + '*') } + } + } - Context 'Invoked with valid string IPv6 prefix length' { - It 'Should Not Throw an error' { - $assertResourcePropertyParameters = @{ - IPAddress = 'fe80::1/64' - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv6' - } + Context 'Invoked with valid string IPv6 prefix length' { + It 'Should Not Throw an error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw + $assertResourcePropertyParameters = @{ + IPAddress = 'fe80::1/64' + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv6' } + + { Assert-ResourceProperty @assertResourcePropertyParameters } | Should -Not -Throw } } - } #end InModuleScope $DSCResourceName -} -finally -{ - Invoke-TestCleanup + } } diff --git a/tests/Unit/DSC_IPAddressOption.Tests.ps1 b/tests/Unit/DSC_IPAddressOption.Tests.ps1 index 33df5a9d..531e8baa 100644 --- a/tests/Unit/DSC_IPAddressOption.Tests.ps1 +++ b/tests/Unit/DSC_IPAddressOption.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_IPAddressOption' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_IPAddressOption' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,108 +35,127 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup - -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - Describe 'DSC_IPAddressOption\Get-TargetResource' -Tag 'Get' { - Context 'Invoked with an existing IP address' { - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = '192.168.0.1' - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 24 - AddressFamily = 'IPv4' - SkipAsSource = $true - } +Describe 'DSC_IPAddressOption\Get-TargetResource' -Tag 'Get' { + Context 'Invoked with an existing IP address' { + BeforeAll { + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = '192.168.0.1' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 24 + AddressFamily = 'IPv4' + SkipAsSource = $true } + } + } - It 'Should return existing IP options' { - $getTargetResourceParameters = @{ - IPAddress = '192.168.0.1' - } - $result = Get-TargetResource @getTargetResourceParameters - $result.IPAddress | Should -Be $getTargetResourceParameters.IPAddress - $result.SkipAsSource | Should -Be $true + It 'Should return existing IP options' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $getTargetResourceParameters = @{ + IPAddress = '192.168.0.1' } + + $result = Get-TargetResource @getTargetResourceParameters + $result.IPAddress | Should -Be $getTargetResourceParameters.IPAddress + $result.SkipAsSource | Should -BeTrue } } + } +} - Describe 'DSC_IPAddressOption\Set-TargetResource' -Tag 'Set' { - Context 'Invoked with an existing IP address, SkipAsSource = $false' { - BeforeEach { - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = '192.168.0.1' - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 24 - AddressFamily = 'IPv4' - SkipAsSource = $false - } - } - - Mock -CommandName Set-NetIPAddress +Describe 'DSC_IPAddressOption\Set-TargetResource' -Tag 'Set' { + Context 'Invoked with an existing IP address, SkipAsSource = $false' { + BeforeAll { + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = '192.168.0.1' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 24 + AddressFamily = 'IPv4' + SkipAsSource = $false } + } - Context 'Invoked with valid IP address' { - It 'Should return $null' { - $setTargetResourceParameters = @{ - IPAddress = '192.168.0.1' - SkipAsSource = $true - } - { $result = Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw - $result | Should -BeNullOrEmpty - } + Mock -CommandName Set-NetIPAddress + } + + Context 'Invoked with valid IP address' { + It 'Should return $null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mock' { - Assert-MockCalled -CommandName Set-NetIPAddress -Exactly -Times 1 + $setTargetResourceParameters = @{ + IPAddress = '192.168.0.1' + SkipAsSource = $true } + + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeNullOrEmpty } } + + It 'Should call all the mock' { + Should -Invoke -CommandName Set-NetIPAddress -Exactly -Times 1 -Scope Context + } } + } +} - Describe 'DSC_IPAddressOption\Test-TargetResource' -Tag 'Test' { - Context 'Invoked with an existing IP address, SkipAsSource = $true' { - BeforeEach { - Mock -CommandName Get-NetIPAddress -MockWith { - [PSCustomObject] @{ - IPAddress = '192.168.0.1' - InterfaceAlias = 'Ethernet' - InterfaceIndex = 1 - PrefixLength = [System.Byte] 24 - AddressFamily = 'IPv4' - SkipAsSource = $true - } - } +Describe 'DSC_IPAddressOption\Test-TargetResource' -Tag 'Test' { + Context 'Invoked with an existing IP address, SkipAsSource = $true' { + BeforeAll { + Mock -CommandName Get-NetIPAddress -MockWith { + @{ + IPAddress = '192.168.0.1' + InterfaceAlias = 'Ethernet' + InterfaceIndex = 1 + PrefixLength = [System.Byte] 24 + AddressFamily = 'IPv4' + SkipAsSource = $true } + } + } - Context 'Invoked with valid IP address' { - It 'Should return $true' { - $testGetResourceParameters = @{ - IPAddress = '192.168.0.1' - SkipAsSource = $true - } + Context 'Invoked with valid IP address' { + It 'Should return $true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $result = Test-TargetResource @testGetResourceParameters - $result | Should -Be $true + $testGetResourceParameters = @{ + IPAddress = '192.168.0.1' + SkipAsSource = $true } + + $result = Test-TargetResource @testGetResourceParameters + $result | Should -BeTrue } } } - } #end InModuleScope $DSCResourceName -} -finally -{ - Invoke-TestCleanup + } } diff --git a/tests/Unit/DSC_NetAdapterAdvancedProperty.Tests.ps1 b/tests/Unit/DSC_NetAdapterAdvancedProperty.Tests.ps1 index 39d3e1f2..6237d98f 100644 --- a/tests/Unit/DSC_NetAdapterAdvancedProperty.Tests.ps1 +++ b/tests/Unit/DSC_NetAdapterAdvancedProperty.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterAdvancedProperty' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetAdapterAdvancedProperty' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,226 +35,323 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') -} -function Invoke-TestCleanup -{ - Restore-TestEnvironment -TestEnvironment $script:testEnvironment + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -Invoke-TestSetup +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - $TestJumboPacket9014 = @{ - NetworkAdapterName = 'Ethernet' - RegistryKeyword = "*JumboPacket" - RegistryValue = 9014 - } + Restore-TestEnvironment -TestEnvironment $script:testEnvironment - $TestJumboPacket1514 = @{ - NetworkAdapterName = 'Ethernet' - RegistryKeyword = '*JumboPacket' - RegistryValue = 1514 - } + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force - $TestAdapterNotFound = @{ - NetworkAdapterName = 'Ethe' - RegistryKeyword = "*JumboPacket" - RegistryValue = 1514 - } + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} - function Get-NetAdapterAdvancedProperty - { +Describe 'DSC_NetAdapterAdvancedProperty\Get-TargetResource' -Tag 'Get' { + Context 'Adapter exist and JumboPacket is enabled 9014' { + BeforeAll { + Mock Get-NetAdapterAdvancedProperty -Verbose -MockWith { + @{ + RegistryValue = 9014 + RegistryKeyword = '*JumboPacket' + } + } } - Describe 'DSC_NetAdapterAdvancedProperty\Get-TargetResource' -Tag 'Get' { + It 'Should return the JumboPacket size' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'Adapter exist and JumboPacket is enabled 9014' { - Mock Get-NetAdapterAdvancedProperty -Verbose -MockWith { - @{ - RegistryValue = $TestJumboPacket9014.RegistryValue - RegistryKeyword = $TestJumboPacket9014.RegistryKeyword - } + $testParams = @{ + NetworkAdapterName = 'Ethernet' + RegistryKeyword = '*JumboPacket' + RegistryValue = 9014 } - It 'Should return the JumboPacket size' { - $result = Get-TargetResource @TestJumboPacket9014 - $result.RegistryValue | Should -Be $TestJumboPacket9014.RegistryValue - } + $result = Get-TargetResource @testParams + $result.RegistryValue | Should -Be $testParams.RegistryValue + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 -Scope Context + } + } + + Context 'Adapter exist and JumboPacket is 1514' { + BeforeAll { + Mock Get-NetAdapterAdvancedProperty -Verbose -MockWith { + @{ + RegistryValue = 1514 + RegistryKeyword = '*JumboPacket' } } + } - Context 'Adapter exist and JumboPacket is 1514' { - Mock Get-NetAdapterAdvancedProperty -Verbose -MockWith { - @{ - RegistryValue = $TestJumboPacket1514.RegistryValue - RegistryKeyword = $TestJumboPacket1514.RegistryKeyword - } - } + It 'Should return the JumboPacket size' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return the JumboPacket size' { - $result = Get-TargetResource @TestJumboPacket1514 - $result.RegistryValue | Should -Be $TestJumboPacket1514.RegistryValue + $testParams = @{ + NetworkAdapterName = 'Ethernet' + RegistryKeyword = '*JumboPacket' + RegistryValue = 1514 } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 - } + $result = Get-TargetResource @testParams + $result.RegistryValue | Should -Be $testParams.RegistryValue } + } - Context 'Adapter does not exist' { + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 -Scope Context + } + } + + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { throw 'Network adapter not found' } + } - Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { throw 'Network adapter not found' } + + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 $errorRecord = Get-InvalidOperationRecord ` -Message ($script:localizedData.NetAdapterNotFoundMessage) - It 'Should throw an exception' { - { Get-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord + $testParams = @{ + NetworkAdapterName = 'Ethe' + RegistryKeyword = '*JumboPacket' + RegistryValue = 1514 } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 - } + { Get-TargetResource @testParams } | Should -Throw $errorRecord } + } - Describe 'DSC_NetAdapterAdvancedProperty\Set-TargetResource' -Tag 'Set' { + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 -Scope Context + } + } - Context 'Adapter exist, JumboPacket is 9014, no action required' { - Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { - @{ - RegistryValue = $TestJumboPacket9014.RegistryValue - RegistryKeyword = $TestJumboPacket9014.RegistryKeyword - } + Describe 'DSC_NetAdapterAdvancedProperty\Set-TargetResource' -Tag 'Set' { + Context 'Adapter exist, JumboPacket is 9014, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { + @{ + RegistryValue = 9014 + RegistryKeyword = '*JumboPacket' } - Mock -CommandName Set-NetAdapterAdvancedProperty + } + Mock -CommandName Set-NetAdapterAdvancedProperty + } - It 'Should not throw an exception' { - { Set-TargetResource @TestJumboPacket9014 } | Should -Not -Throw - } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterAdvancedProperty -Exactly -Time 0 + $testParams = @{ + NetworkAdapterName = 'Ethernet' + RegistryKeyword = '*JumboPacket' + RegistryValue = 9014 } + + { Set-TargetResource @testParams } | Should -Not -Throw } + } - Context 'Adapter exist, JumboPacket is 9014, should be 1514' { - Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { - @{ - RegistryValue = $TestJumboPacket9014.RegistryValue - RegistryKeyword = $TestJumboPacket9014.RegistryKeyword - } - } - Mock -CommandName Set-NetAdapterAdvancedProperty + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterAdvancedProperty -Exactly -Time 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestJumboPacket1514 } | Should -Not -Throw + Context 'Adapter exist, JumboPacket is 9014, should be 1514' { + BeforeAll { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { + @{ + RegistryValue = 9014 + RegistryKeyword = '*JumboPacket' } + } + + Mock -CommandName Set-NetAdapterAdvancedProperty + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterAdvancedProperty -Exactly -Time 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + NetworkAdapterName = 'Ethernet' + RegistryKeyword = '*JumboPacket' + RegistryValue = 1514 } + + { Set-TargetResource @testParams } | Should -Not -Throw } + } - Context 'Adapter exist, JumboPacket is 1514, should be 9014' { - Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { - @{ - RegistryValue = $TestJumboPacket1514.RegistryValue - RegistryKeyword = $TestJumboPacket1514.RegistryKeyword - } - } - Mock -CommandName Set-NetAdapterAdvancedProperty + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterAdvancedProperty -Exactly -Time 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestJumboPacket9014 } | Should -Not -Throw + Context 'Adapter exist, JumboPacket is 1514, should be 9014' { + BeforeAll { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { + @{ + RegistryValue = 1514 + RegistryKeyword = '*JumboPacket' } + } + + Mock -CommandName Set-NetAdapterAdvancedProperty + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterAdvancedProperty -Exactly -Time 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + NetworkAdapterName = 'Ethernet' + RegistryKeyword = '*JumboPacket' + RegistryValue = 9014 } + + { Set-TargetResource @testParams } | Should -Not -Throw } + } - # Adapter - Context 'Adapter does not exist' { - Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { throw 'Network adapter not found' } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterAdvancedProperty -Exactly -Time 1 -Scope Context + } + } + + # Adapter + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { throw 'Network adapter not found' } + } + + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 $errorRecord = Get-InvalidOperationRecord ` -Message ($script:localizedData.NetAdapterNotFoundMessage) - It 'Should throw an exception' { - { Set-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord + $testParams = @{ + NetworkAdapterName = 'Ethe' + RegistryKeyword = '*JumboPacket' + RegistryValue = 1514 } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 - } + { Set-TargetResource @testParams } | Should -Throw $errorRecord } } - } - Describe 'DSC_NetAdapterAdvancedProperty\Test-TargetResource' -Tag 'Test' { + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 -Scope Context + } + } + } +} - # JumboPacket - Context 'Adapter exist, JumboPacket is 9014, no action required' { - Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { - @{ - RegistryValue = $TestJumboPacket9014.RegistryValue - RegistryKeyword = $TestJumboPacket9014.RegistryKeyword - } +Describe 'DSC_NetAdapterAdvancedProperty\Test-TargetResource' -Tag 'Test' { + Context 'Adapter exist, JumboPacket is 9014, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { + @{ + RegistryValue = 9014 + RegistryKeyword = '*JumboPacket' } + } + } - It 'Should return true' { - Test-TargetResource @TestJumboPacket9014 | Should -Be $true - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly 1 + $testParams = @{ + NetworkAdapterName = 'Ethernet' + RegistryKeyword = '*JumboPacket' + RegistryValue = 9014 } + + Test-TargetResource @testParams | Should -BeTrue } + } - Context 'Adapter exist, JumboPacket is 9014 should be 1514' { - Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { - @{ - RegistryValue = $TestJumboPacket9014.RegistryValue - RegistryKeyword = $TestJumboPacket9014.RegistryKeyword - } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterAdvancedProperty -Exactly 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @TestJumboPacket1514 | Should -Be $false + Context 'Adapter exist, JumboPacket is 9014 should be 1514' { + BeforeAll { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { + @{ + RegistryValue = 9014 + RegistryKeyword = '*JumboPacket' } + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly 1 + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + NetworkAdapterName = 'Ethernet' + RegistryKeyword = '*JumboPacket' + RegistryValue = 1514 } + + Test-TargetResource @testParams | Should -BeFalse } + } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterAdvancedProperty -Exactly 1 -Scope Context + } + } - # Adapter - Context 'Adapter does not exist' { - Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { throw 'Network adapter not found' } - It 'Should throw an exception' { - { Test-TargetResource @TestAdapterNotFound } | Should -Throw - } + # Adapter + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { throw 'Network adapter not found' } + } + + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly 1 + $testParams = @{ + NetworkAdapterName = 'Ethe' + RegistryKeyword = '*JumboPacket' + RegistryValue = 1514 } + + { Test-TargetResource @testParams } | Should -Throw } } + + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterAdvancedProperty -Exactly 1 -Scope Context + } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_NetAdapterBinding.Tests.ps1 b/tests/Unit/DSC_NetAdapterBinding.Tests.ps1 index 35e462ff..2b9b794b 100644 --- a/tests/Unit/DSC_NetAdapterBinding.Tests.ps1 +++ b/tests/Unit/DSC_NetAdapterBinding.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterBinding' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetAdapterBinding' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,255 +35,438 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} -Invoke-TestSetup + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - $testBindingEnabled = @{ - InterfaceAlias = 'Ethernet' - ComponentId = 'ms_tcpip63' - State = 'Enabled' +Describe 'DSC_NetAdapterBinding\Get-TargetResource' -Tag 'Get' { + Context 'Adapter exists and binding Enabled' { + BeforeAll { + Mock -CommandName Get-Binding -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + Enabled = $true + } + } } - $testBindingDisabled = @{ - InterfaceAlias = 'Ethernet' - ComponentId = 'ms_tcpip63' - State = 'Disabled' + It 'Should return existing binding' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testBindingEnabled = @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + State = 'Enabled' + } + + $result = Get-TargetResource @testBindingEnabled + + $result.InterfaceAlias | Should -Be $testBindingEnabled.InterfaceAlias + $result.ComponentId | Should -Be $testBindingEnabled.ComponentId + $result.State | Should -Be 'Enabled' + $result.CurrentState | Should -Be 'Enabled' + } } - $testBindingMixed = @{ - InterfaceAlias = '*' - ComponentId = 'ms_tcpip63' - State = 'Enabled' + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-Binding -Exactly -Times 1 -Scope Context } + } - $mockAdapter = @{ - InterfaceAlias = 'Ethernet' + Context 'Adapter exists and binding Disabled' { + BeforeAll { + Mock -CommandName Get-Binding -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + Enabled = $False + } + } } - $mockBindingEnabled = @{ - InterfaceAlias = 'Ethernet' - ComponentId = 'ms_tcpip63' - Enabled = $true + It 'Should return existing binding' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testBindingDisabled = @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + State = 'Disabled' + } + + $result = Get-TargetResource @testBindingDisabled + + $result.InterfaceAlias | Should -Be $testBindingDisabled.InterfaceAlias + $result.ComponentId | Should -Be $testBindingDisabled.ComponentId + $result.State | Should -Be 'Disabled' + $result.CurrentState | Should -Be 'Disabled' + } } - $mockBindingDisabled = @{ - InterfaceAlias = 'Ethernet' - ComponentId = 'ms_tcpip63' - Enabled = $False + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-Binding -Exactly -Times 1 -Scope Context } + } - $mockBindingMixed = @( - @{ - InterfaceAlias = 'Ethernet' - ComponentId = 'ms_tcpip63' - Enabled = $False - }, - @{ - InterfaceAlias = 'Ethernet2' - ComponentId = 'ms_tcpip63' - Enabled = $true + Context 'More than one Adapter exists and binding is Disabled on one and Enabled on another' { + BeforeAll { + Mock -CommandName Get-Binding -MockWith { + @( + @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + Enabled = $False + }, + @{ + InterfaceAlias = 'Ethernet2' + ComponentId = 'ms_tcpip63' + Enabled = $true + } + ) } - ) - - Describe 'DSC_NetAdapterBinding\Get-TargetResource' -Tag 'Get' { - Context 'Adapter exists and binding Enabled' { - Mock -CommandName Get-Binding -MockWith { $mockBindingEnabled } - - It 'Should return existing binding' { - $result = Get-TargetResource @testBindingEnabled - $result.InterfaceAlias | Should -Be $testBindingEnabled.InterfaceAlias - $result.ComponentId | Should -Be $testBindingEnabled.ComponentId - $result.State | Should -Be 'Enabled' - $result.CurrentState | Should -Be 'Enabled' - } + } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-Binding -Exactly -Times 1 + It 'Should return existing binding' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testBindingMixed = @{ + InterfaceAlias = '*' + ComponentId = 'ms_tcpip63' + State = 'Enabled' } + + $result = Get-TargetResource @testBindingMixed + + $result.InterfaceAlias | Should -Be $testBindingMixed.InterfaceAlias + $result.ComponentId | Should -Be $testBindingMixed.ComponentId + $result.State | Should -Be 'Enabled' + $result.CurrentState | Should -Be 'Mixed' } + } - Context 'Adapter exists and binding Disabled' { - Mock -CommandName Get-Binding -MockWith { $mockBindingDisabled } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-Binding -Exactly -Times 1 -Scope Context + } + } +} - It 'Should return existing binding' { - $result = Get-TargetResource @testBindingDisabled - $result.InterfaceAlias | Should -Be $testBindingDisabled.InterfaceAlias - $result.ComponentId | Should -Be $testBindingDisabled.ComponentId - $result.State | Should -Be 'Disabled' - $result.CurrentState | Should -Be 'Disabled' +Describe 'DSC_NetAdapterBinding\Set-TargetResource' -Tag 'Set' { + Context 'Adapter exists and set binding to Enabled' { + BeforeAll { + Mock -CommandName Get-Binding -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + Enabled = $False } + } + Mock -CommandName Enable-NetAdapterBinding + Mock -CommandName Disable-NetAdapterBinding + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-Binding -Exactly -Times 1 + $testBindingEnabled = @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + State = 'Enabled' } + + { Set-TargetResource @testBindingEnabled } | Should -Not -Throw } + } - Context 'More than one Adapter exists and binding is Disabled on one and Enabled on another' { - Mock -CommandName Get-Binding -MockWith { $mockBindingMixed } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-Binding -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Enable-NetAdapterBinding -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Disable-NetAdapterBinding -Exactly -Times 0 -Scope Context + } + } - It 'Should return existing binding' { - $result = Get-TargetResource @testBindingMixed - $result.InterfaceAlias | Should -Be $testBindingMixed.InterfaceAlias - $result.ComponentId | Should -Be $testBindingMixed.ComponentId - $result.State | Should -Be 'Enabled' - $result.CurrentState | Should -Be 'Mixed' + Context 'Adapter exists and set binding to Disabled' { + BeforeAll { + Mock -CommandName Get-Binding -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + Enabled = $true } + } + Mock -CommandName Enable-NetAdapterBinding + Mock -CommandName Disable-NetAdapterBinding + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-Binding -Exactly -Times 1 + $testBindingDisabled = @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + State = 'Disabled' } - } + { Set-TargetResource @testBindingDisabled } | Should -Not -Throw + } } - Describe 'DSC_NetAdapterBinding\Set-TargetResource' -Tag 'Set' { - Context 'Adapter exists and set binding to Enabled' { - Mock -CommandName Get-Binding -MockWith { $mockBindingDisabled } - Mock -CommandName Enable-NetAdapterBinding - Mock -CommandName Disable-NetAdapterBinding + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-Binding -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Enable-NetAdapterBinding -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Disable-NetAdapterBinding -Exactly -Times 1 -Scope Context + } + } +} - It 'Should not throw an exception' { - { Set-TargetResource @testBindingEnabled } | Should -Not -Throw +Describe 'DSC_NetAdapterBinding\Test-TargetResource' -Tag 'Test' { + Context 'Adapter exists, current binding set to Enabled but want it Disabled' { + BeforeAll { + Mock -CommandName Get-Binding -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + Enabled = $true } + } + } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-Binding -Exactly -Times 1 - Assert-MockCalled -CommandName Enable-NetAdapterBinding -Exactly -Times 1 - Assert-MockCalled -CommandName Disable-NetAdapterBinding -Exactly -Times 0 + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testBindingDisabled = @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + State = 'Disabled' } + + Test-TargetResource @testBindingDisabled | Should -BeFalse } + } - Context 'Adapter exists and set binding to Disabled' { - Mock -CommandName Get-Binding -MockWith { $mockBindingEnabled } - Mock -CommandName Enable-NetAdapterBinding - Mock -CommandName Disable-NetAdapterBinding + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-Binding -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testBindingDisabled } | Should -Not -Throw + Context 'Adapter exists, current binding set to Disabled but want it Enabled' { + BeforeAll { + Mock -CommandName Get-Binding -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + Enabled = $False } + } + } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-Binding -Exactly -Times 1 - Assert-MockCalled -CommandName Enable-NetAdapterBinding -Exactly -Times 0 - Assert-MockCalled -CommandName Disable-NetAdapterBinding -Exactly -Times 1 + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testBindingEnabled = @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + State = 'Enabled' } + + Test-TargetResource @testBindingEnabled | Should -BeFalse } } - Describe 'DSC_NetAdapterBinding\Test-TargetResource' -Tag 'Test' { - Context 'Adapter exists, current binding set to Enabled but want it Disabled' { - Mock -CommandName Get-Binding -MockWith { $mockBindingEnabled } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-Binding -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @testBindingDisabled | Should -Be $False + Context 'Adapter exists, current binding set to Enabled and want it Enabled' { + BeforeAll { + Mock -CommandName Get-Binding -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + Enabled = $true } + } + } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-Binding -Exactly -Times 1 + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testBindingEnabled = @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + State = 'Enabled' } + + Test-TargetResource @testBindingEnabled | Should -BeTrue } + } - Context 'Adapter exists, current binding set to Disabled but want it Enabled' { - Mock -CommandName Get-Binding -MockWith { $mockBindingDisabled } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-Binding -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @testBindingEnabled | Should -Be $False + Context 'Adapter exists, current binding set to Disabled and want it Disabled' { + BeforeAll { + Mock -CommandName Get-Binding -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + Enabled = $False } + } + } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-Binding -Exactly -Times 1 + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testBindingDisabled = @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + State = 'Disabled' } + + Test-TargetResource @testBindingDisabled | Should -BeTrue } + } - Context 'Adapter exists, current binding set to Enabled and want it Enabled' { - Mock -CommandName Get-Binding -MockWith { $mockBindingEnabled } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-Binding -Exactly -Times 1 -Scope Context + } + } +} - It 'Should return true' { - Test-TargetResource @testBindingEnabled | Should -Be $true - } +Describe 'DSC_NetAdapterBinding\Get-Binding' { + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapter + } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-Binding -Exactly -Times 1 + It 'Should throw an InterfaceNotAvailable error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testBindingEnabled = @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + State = 'Enabled' } + + $errorRecord = Get-InvalidArgumentRecord ` + -Message ($script:localizedData.InterfaceNotAvailableError -f $testBindingEnabled.InterfaceAlias) ` + -ArgumentName 'InterfaceAlias' + + { Get-Binding @testBindingEnabled } | Should -Throw $errorRecord } + } - Context 'Adapter exists, current binding set to Disabled and want it Disabled' { - Mock -CommandName Get-Binding -MockWith { $mockBindingDisabled } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @testBindingDisabled | Should -Be $true + Context 'Adapter exists and binding enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + InterfaceAlias = 'Ethernet' } - - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-Binding -Exactly -Times 1 + } + Mock -CommandName Get-NetAdapterBinding -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + Enabled = $true } } } - Describe 'DSC_NetAdapterBinding\Get-Binding' { - Context 'Adapter does not exist' { - Mock -CommandName Get-NetAdapter + It 'Should return the adapter binding' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should throw an InterfaceNotAvailable error' { - $errorRecord = Get-InvalidArgumentRecord ` - -Message ($script:localizedData.InterfaceNotAvailableError -f $testBindingEnabled.InterfaceAlias) ` - -ArgumentName 'Interface' - - { Get-Binding @testBindingEnabled } | Should -Throw $errorRecord + $testBindingEnabled = @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + State = 'Enabled' } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } + $result = Get-Binding @testBindingEnabled + + $result.InterfaceAlias | Should -Be 'Ethernet' + $result.ComponentId | Should -Be 'ms_tcpip63' + $result.Enabled | Should -BeTrue } + } - Context 'Adapter exists and binding enabled' { - Mock -CommandName Get-NetAdapter -MockWith { $mockAdapter } - Mock -CommandName Get-NetAdapterBinding -MockWith { $mockBindingEnabled } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetAdapterBinding -Exactly -Times 1 -Scope Context + } + } - It 'Should return the adapter binding' { - $result = Get-Binding @testBindingEnabled - $result.InterfaceAlias | Should -Be $mockBindingEnabled.InterfaceAlias - $result.ComponentId | Should -Be $mockBindingEnabled.ComponentId - $result.Enabled | Should -Be $mockBindingEnabled.Enabled + Context 'Adapter exists and binding disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + InterfaceAlias = 'Ethernet' } - - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetAdapterBinding -Exactly -Times 1 + } + Mock -CommandName Get-NetAdapterBinding -MockWith { + @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + Enabled = $False } } + } - Context 'Adapter exists and binding disabled' { - Mock -CommandName Get-NetAdapter -MockWith { $mockAdapter } - Mock -CommandName Get-NetAdapterBinding -MockWith { $mockBindingDisabled } + It 'Should return the adapter binding' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return the adapter binding' { - $result = Get-Binding @testBindingDisabled - $result.InterfaceAlias | Should -Be $mockBindingDisabled.InterfaceAlias - $result.ComponentId | Should -Be $mockBindingDisabled.ComponentId - $result.Enabled | Should -Be $mockBindingDisabled.Enabled + $testBindingDisabled = @{ + InterfaceAlias = 'Ethernet' + ComponentId = 'ms_tcpip63' + State = 'Disabled' } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-NetAdapterBinding -Exactly -Times 1 - } + $result = Get-Binding @testBindingDisabled + + $result.InterfaceAlias | Should -Be 'Ethernet' + $result.ComponentId | Should -Be 'ms_tcpip63' + $result.Enabled | Should -BeFalse } } - } #end InModuleScope $DSCResourceName -} -finally -{ - Invoke-TestCleanup + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-NetAdapterBinding -Exactly -Times 1 -Scope Context + } + } } diff --git a/tests/Unit/DSC_NetAdapterLso.Tests.ps1 b/tests/Unit/DSC_NetAdapterLso.Tests.ps1 index 5c400d2d..2b5af217 100644 --- a/tests/Unit/DSC_NetAdapterLso.Tests.ps1 +++ b/tests/Unit/DSC_NetAdapterLso.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterLso' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetAdapterLso' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,574 +35,1000 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} -Invoke-TestSetup + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - $testV1IPv4LsoEnabled = @{ - Name = 'Ethernet' - Protocol = 'V1IPv4' - State = $true - } + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} - $testV1IPv4LsoDisabled = @{ - Name = 'Ethernet' - Protocol = 'V1IPv4' - State = $false +Describe 'DSC_NetAdapterLso\Get-TargetResource' -Tag 'Get' { + Context 'Adapter exist and LSO for V1IPv4 is enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + V1IPv4Enabled = $true + } + } } - $testIPv4LsoEnabled = @{ - Name = 'Ethernet' - Protocol = 'IPv4' - State = $true - } + It 'Should return the LSO state of V1IPv4' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $testIPv4LsoDisabled = @{ - Name = 'Ethernet' - Protocol = 'IPv4' - State = $false - } + $testV1IPv4LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'V1IPv4' + State = $true + } - $testIPv6LsoEnabled = @{ - Name = 'Ethernet' - Protocol = 'IPv6' - State = $true + $result = Get-TargetResource @testV1IPv4LsoEnabled + $result.State | Should -BeTrue + } } - $testIPv6LsoDisabled = @{ - Name = 'Ethernet' - Protocol = 'IPv6' - State = $false + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context } + } - $testAdapterNotFound = @{ - Name = 'Eth' - Protocol = 'IPv4' - State = $true + Context 'Adapter exist and LSO for V1IPv4 is disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + V1IPv4Enabled = $false + } + } } + It 'Should return the LSO state of V1IPv4' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Describe 'DSC_NetAdapterLso\Get-TargetResource' -Tag 'Get' { - Context 'Adapter exist and LSO for V1IPv4 is enabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $testV1IPv4LsoEnabled.State } + $testV1IPv4LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'V1IPv4' + State = $false } - It 'Should return the LSO state of V1IPv4' { - $result = Get-TargetResource @testV1IPv4LsoEnabled - $result.State | Should -Be $testV1IPv4LsoEnabled.State - } + $result = Get-TargetResource @testV1IPv4LsoDisabled + $result.State | Should -Be $testV1IPv4LsoDisabled.State + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } + + Context 'Adapter exist and LSO for IPv4 is enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv4Enabled = $true } } + } - Context 'Adapter exist and LSO for V1IPv4 is disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $testV1IPv4LsoDisabled.State } - } + It 'Should return the LSO state of IPv4' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return the LSO state of V1IPv4' { - $result = Get-TargetResource @testV1IPv4LsoDisabled - $result.State | Should -Be $testV1IPv4LsoDisabled.State + $testIPv4LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $true } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - } - } + $result = Get-TargetResource @testIPv4LsoEnabled - Context 'Adapter exist and LSO for IPv4 is enabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $testIPv4LsoEnabled.State } - } + $result.State | Should -Be $testIPv4LsoEnabled.State + } + } - It 'Should return the LSO state of IPv4' { - $result = Get-TargetResource @testIPv4LsoEnabled - $result.State | Should -Be $testIPv4LsoEnabled.State - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Context 'Adapter exist and LSO for IPv4 is disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv4Enabled = $false } } + } - Context 'Adapter exist and LSO for IPv4 is disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $testIPv4LsoDisabled.State } - } + It 'Should return the LSO state of IPv4' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return the LSO state of IPv4' { - $result = Get-TargetResource @testIPv4LsoDisabled - $result.State | Should -Be $testIPv4LsoDisabled.State + $testIPv4LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $false } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - } + $result = Get-TargetResource @testIPv4LsoDisabled + + $result.State | Should -Be $testIPv4LsoDisabled.State } + } - Context 'Adapter exist and LSO for IPv6 is enabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $testIPv6LsoEnabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return the LSO state of IPv6' { - $result = Get-TargetResource @testIPv6LsoEnabled - $result.State | Should -Be $testIPv6LsoEnabled.State + Context 'Adapter exist and LSO for IPv6 is enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv6Enabled = $true } + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + It 'Should return the LSO state of IPv6' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv6LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $true } + + $result = Get-TargetResource @testIPv6LsoEnabled + + $result.State | Should -Be $testIPv6LsoEnabled.State } + } - Context 'Adapter exist and LSO for IPv6 is disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $testIPv6LsoDisabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return the LSO state of IPv6' { - $result = Get-TargetResource @testIPv6LsoDisabled - $result.State | Should -Be $testIPv6LsoDisabled.State + Context 'Adapter exist and LSO for IPv6 is disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv6Enabled = $false } + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + It 'Should return the LSO state of IPv6' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv6LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $false } + + $result = Get-TargetResource @testIPv6LsoDisabled + + $result.State | Should -Be $testIPv6LsoDisabled.State } + } - Context 'Adapter does not exist' { - Mock -CommandName Get-NetAdapterLso -MockWith { throw 'Network adapter not found' } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } + + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { throw 'Network adapter not found' } + } - It 'Should throw the correct exception' { - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundMessage) + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Get-TargetResource @testAdapterNotFound } | Should -Throw $errorRecord + $testAdapterNotFound = @{ + Name = 'Eth' + Protocol = 'IPv4' + State = $true } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - } + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.NetAdapterNotFoundMessage) + + { Get-TargetResource @testAdapterNotFound } | Should -Throw $errorRecord } } - Describe 'DSC_NetAdapterLso\Set-TargetResource' -Tag 'Set' { - # V1IPv4 - Context 'Adapter exist, LSO is enabled for V1IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $testV1IPv4LsoEnabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } +} - It 'Should not throw an exception' { - { Set-TargetResource @testV1IPv4LsoEnabled } | Should -Not -Throw - } +Describe 'DSC_NetAdapterLso\Set-TargetResource' -Tag 'Set' { + # V1IPv4 + Context 'Adapter exist, LSO is enabled for V1IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ V1IPv4Enabled = $true } + } + Mock -CommandName Set-NetAdapterLso + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testV1IPv4LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'V1IPv4' + State = $true } + + { Set-TargetResource @testV1IPv4LsoEnabled } | Should -Not -Throw } + } - Context 'Adapter exist, LSO is enabled for V1IPv4, should be disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $testV1IPv4LsoEnabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testV1IPv4LsoDisabled } | Should -Not -Throw + Context 'Adapter exist, LSO is enabled for V1IPv4, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + V1IPv4Enabled = $true } + } + + Mock -CommandName Set-NetAdapterLso + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testV1IPv4LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'V1IPv4' + State = $false } + + { Set-TargetResource @testV1IPv4LsoDisabled } | Should -Not -Throw } + } - Context 'Adapter exist, LSO is disabled for V1IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $testV1IPv4LsoDisabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testV1IPv4LsoDisabled } | Should -Not -Throw + Context 'Adapter exist, LSO is disabled for V1IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + V1IPv4Enabled = $false } + } + + Mock -CommandName Set-NetAdapterLso + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testV1IPv4LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'V1IPv4' + State = $false } + + { Set-TargetResource @testV1IPv4LsoDisabled } | Should -Not -Throw } + } - Context 'Adapter exist, LSO is disabled for V1IPv4, should be enabled.' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $testV1IPv4LsoDisabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testV1IPv4LsoEnabled } | Should -Not -Throw + Context 'Adapter exist, LSO is disabled for V1IPv4, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + V1IPv4Enabled = $false } + } + Mock -CommandName Set-NetAdapterLso + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 + $testV1IPv4LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'V1IPv4' + State = $true } + + { Set-TargetResource @testV1IPv4LsoEnabled } | Should -Not -Throw } + } - # IPv4 - Context 'Adapter exist, LSO is enabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $testIPv4LsoEnabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testIPv4LsoEnabled } | Should -Not -Throw + # IPv4 + Context 'Adapter exist, LSO is enabled for IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv4Enabled = $true } + } + + Mock -CommandName Set-NetAdapterLso + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 + $testIPv4LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $true } + + { Set-TargetResource @testIPv4LsoEnabled } | Should -Not -Throw } + } - Context 'Adapter exist, LSO is enabled for IPv4, should be disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $testIPv4LsoEnabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testIPv4LsoDisabled } | Should -Not -Throw + Context 'Adapter exist, LSO is enabled for IPv4, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv4Enabled = $true } + } + + Mock -CommandName Set-NetAdapterLso + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 + $testIPv4LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $false } + + { Set-TargetResource @testIPv4LsoDisabled } | Should -Not -Throw } + } - Context 'Adapter exist, LSO is disabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $testIPv4LsoDisabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testIPv4LsoDisabled } | Should -Not -Throw + Context 'Adapter exist, LSO is disabled for IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv4Enabled = $false } + } + + Mock -CommandName Set-NetAdapterLso + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 + $testIPv4LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $false } + + { Set-TargetResource @testIPv4LsoDisabled } | Should -Not -Throw } + } - Context 'Adapter exist, LSO is disabled for IPv4, should be enabled.' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $testIPv4LsoDisabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testIPv4LsoEnabled } | Should -Not -Throw + Context 'Adapter exist, LSO is disabled for IPv4, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv4Enabled = $false } + } + + Mock -CommandName Set-NetAdapterLso + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 + $testIPv4LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $true } + + { Set-TargetResource @testIPv4LsoEnabled } | Should -Not -Throw } + } - # IPv6 - Context 'Adapter exist, LSO is enabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $testIPv6LsoEnabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testIPv6LsoEnabled } | Should -Not -Throw + # IPv6 + Context 'Adapter exist, LSO is enabled for IPv6, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv6Enabled = $true } + } + + Mock -CommandName Set-NetAdapterLso + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv6LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $true } + + { Set-TargetResource @testIPv6LsoEnabled } | Should -Not -Throw } + } - Context 'Adapter exist, LSO is enabled for IPv6, should be disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $testIPv6LsoEnabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testIPv6LsoDisabled } | Should -Not -Throw + Context 'Adapter exist, LSO is enabled for IPv6, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv6Enabled = $true } + } + + Mock -CommandName Set-NetAdapterLso + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv6LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $false } + + { Set-TargetResource @testIPv6LsoDisabled } | Should -Not -Throw } + } - Context 'Adapter exist, LSO is disabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $testIPv6LsoDisabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testIPv6LsoDisabled } | Should -Not -Throw + Context 'Adapter exist, LSO is disabled for IPv6, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv6Enabled = $false } + } + + Mock -CommandName Set-NetAdapterLso + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv6LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $false } + + { Set-TargetResource @testIPv6LsoDisabled } | Should -Not -Throw } + } - Context 'Adapter exist, LSO is disabled for IPv6, should be enabled.' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $testIPv6LsoDisabled.State } - } - Mock -CommandName Set-NetAdapterLso + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @testIPv6LsoEnabled } | Should -Not -Throw + Context 'Adapter exist, LSO is disabled for IPv6, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv6Enabled = $false } + } + + Mock -CommandName Set-NetAdapterLso + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv6LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $true } + + { Set-TargetResource @testIPv6LsoEnabled } | Should -Not -Throw } + } - # Adapter - Context 'Adapter does not exist' { - Mock -CommandName Get-NetAdapterLso -MockWith { throw 'Network adapter not found' } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should throw the correct exception' { - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundMessage) + # Adapter + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { throw 'Network adapter not found' } + } - { Set-TargetResource @testAdapterNotFound } | Should -Throw $errorRecord - } + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + $testAdapterNotFound = @{ + Name = 'Eth' + Protocol = 'IPv4' + State = $true } + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.NetAdapterNotFoundMessage) + + { Set-TargetResource @testAdapterNotFound } | Should -Throw $errorRecord } + } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context } + } - Describe 'DSC_NetAdapterLso\Test-TargetResource' -Tag 'Test' { - # V1IPv4 - Context 'Adapter exist, LSO is enabled for V1IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $testV1IPv4LsoEnabled.State } - } +} - It 'Should return true' { - Test-TargetResource @testV1IPv4LsoEnabled | Should -Be $true +Describe 'DSC_NetAdapterLso\Test-TargetResource' -Tag 'Test' { + # V1IPv4 + Context 'Adapter exist, LSO is enabled for V1IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + V1IPv4Enabled = $true } + } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + $testV1IPv4LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'V1IPv4' + State = $true } + + Test-TargetResource @testV1IPv4LsoEnabled | Should -BeTrue } + } - Context 'Adapter exist, LSO is enabled for V1IPv4, should be disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $testV1IPv4LsoEnabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @testV1IPv4LsoDisabled | Should -Be $false + Context 'Adapter exist, LSO is enabled for V1IPv4, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + V1IPv4Enabled = $true } + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testV1IPv4LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'V1IPv4' + State = $false } + + Test-TargetResource @testV1IPv4LsoDisabled | Should -BeFalse } + } - Context 'Adapter exist, LSO is disabled for V1IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $testV1IPv4LsoDisabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @testV1IPv4LsoDisabled | Should -Be $true + Context 'Adapter exist, LSO is disabled for V1IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + V1IPv4Enabled = $false } + } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + $testV1IPv4LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'V1IPv4' + State = $false } + + Test-TargetResource @testV1IPv4LsoDisabled | Should -BeTrue } + } - Context 'Adapter exist, LSO is disabled for V1IPv4, should be enabled.' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $testV1IPv4LsoDisabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @testV1IPv4LsoEnabled | Should -Be $false + Context 'Adapter exist, LSO is disabled for V1IPv4, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + V1IPv4Enabled = $false } + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + $testV1IPv4LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'V1IPv4' + State = $true } + + Test-TargetResource @testV1IPv4LsoEnabled | Should -BeFalse } + } - # IPv4 - Context 'Adapter exist, LSO is enabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $testIPv4LsoEnabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @testIPv4LsoEnabled | Should -Be $true + # IPv4 + Context 'Adapter exist, LSO is enabled for IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv4Enabled = $true } + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv4LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $true } + + Test-TargetResource @testIPv4LsoEnabled | Should -BeTrue } + } - Context 'Adapter exist, LSO is enabled for IPv4, should be disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $testIPv4LsoEnabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @testIPv4LsoDisabled | Should -Be $false + Context 'Adapter exist, LSO is enabled for IPv4, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv4Enabled = $true } + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + $testIPv4LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $false } + + Test-TargetResource @testIPv4LsoDisabled | Should -BeFalse } + } - Context 'Adapter exist, LSO is disabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $testIPv4LsoDisabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @testIPv4LsoDisabled | Should -Be $true + Context 'Adapter exist, LSO is disabled for IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv4Enabled = $false } + } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + $testIPv4LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $false } + + Test-TargetResource @testIPv4LsoDisabled | Should -BeTrue } + } - Context 'Adapter exist, LSO is disabled for IPv4, should be enabled.' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $testIPv4LsoDisabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @testIPv4LsoEnabled | Should -Be $false + Context 'Adapter exist, LSO is disabled for IPv4, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv4Enabled = $false } + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv4LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $true } + + Test-TargetResource @testIPv4LsoEnabled | Should -BeFalse } + } - # IPv6 - Context 'Adapter exist, LSO is enabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $testIPv6LsoEnabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @testIPv6LsoEnabled | Should -Be $true + # IPv6 + Context 'Adapter exist, LSO is enabled for IPv6, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv6Enabled = $true } + } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + $testIPv6LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $true } + + Test-TargetResource @testIPv6LsoEnabled | Should -BeTrue } + } - Context 'Adapter exist, LSO is enabled for IPv6, should be disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $testIPv6LsoEnabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @testIPv6LsoDisabled | Should -Be $false + Context 'Adapter exist, LSO is enabled for IPv6, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv6Enabled = $true } + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv6LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $false } + + Test-TargetResource @testIPv6LsoDisabled | Should -BeFalse } + } - Context 'Adapter exist, LSO is disabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $testIPv6LsoDisabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @testIPv6LsoDisabled | Should -Be $true + Context 'Adapter exist, LSO is disabled for IPv6, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv6Enabled = $false } + } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + $testIPv6LsoDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $false } + + Test-TargetResource @testIPv6LsoDisabled | Should -BeTrue } + } - Context 'Adapter exist, LSO is disabled for IPv6, should be enabled.' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $testIPv6LsoDisabled.State } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @testIPv6LsoEnabled | Should -Be $false + Context 'Adapter exist, LSO is disabled for IPv6, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ + IPv6Enabled = $false } + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv6LsoEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $true } + + Test-TargetResource @testIPv6LsoEnabled | Should -BeFalse } + } - # Adapter - Context 'Adapter does not exist' { - Mock -CommandName Get-NetAdapterLso -MockWith { throw 'Network adapter not found' } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } + } + + # Adapter + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterLso -MockWith { throw 'Network adapter not found' } + } - It 'Should throw the correct exception' { - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundMessage) + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Test-TargetResource @testAdapterNotFound } | Should -Throw $errorRecord + $testAdapterNotFound = @{ + Name = 'Eth' + Protocol = 'IPv4' + State = $true } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 - } + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.NetAdapterNotFoundMessage) + + { Test-TargetResource @testAdapterNotFound } | Should -Throw $errorRecord } } + + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterLso -Exactly -Times 1 -Scope Context + } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_NetAdapterName.Tests.ps1 b/tests/Unit/DSC_NetAdapterName.Tests.ps1 index 700262bb..b8d04414 100644 --- a/tests/Unit/DSC_NetAdapterName.Tests.ps1 +++ b/tests/Unit/DSC_NetAdapterName.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterName' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetAdapterName' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,238 +35,379 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup - -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - # Generate the adapter data to be used for Mocking - $script:adapterName = 'Adapter' - $script:newAdapterName = 'NewAdapter' - $script:adapterPhysicalMediaType = '802.3' - $script:adapterStatus = 'Up' - $script:adapterMacAddress = '11-22-33-44-55-66' - $script:adapterInterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' - $script:adapterInterfaceIndex = 2 - $script:adapterInterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' - $script:adapterDriverDescription = 'Hyper-V Virtual Ethernet Adapter' - - $script:adapterParameters = [PSObject]@{ - Name = $script:adapterName - NewName = $script:newAdapterName - PhysicalMediaType = $script:adapterPhysicalMediaType - Status = $script:adapterStatus - MacAddress = $script:adapterMacAddress - InterfaceDescription = $script:adapterInterfaceDescription - InterfaceIndex = $script:adapterInterfaceIndex - InterfaceGuid = $script:adapterInterfaceGuid - DriverDescription = $script:adapterDriverDescription +Describe 'DSC_NetAdapterName\Get-TargetResource' -Tag 'Get' { + Context 'Renamed adapter can be found' { + BeforeAll { + Mock -CommandName Find-NetworkAdapter -MockWith { + @{ + Name = 'NewAdapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' + } + } -ParameterFilter { $Name -eq 'NewAdapter' } } - $script:mockAdapter = [PSObject]@{ - Name = $script:adapterName - PhysicalMediaType = $script:adapterPhysicalMediaType - Status = $script:adapterStatus - MacAddress = $script:adapterMacAddress - InterfaceDescription = $script:adapterInterfaceDescription - InterfaceIndex = $script:adapterInterfaceIndex - InterfaceGuid = $script:adapterInterfaceGuid - DriverDescription = $script:adapterDriverDescription - } + It 'Should not throw' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $adapterParameters = @{ + Name = 'Adapter' + NewName = 'NewAdapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' + } - $script:mockRenamedAdapter = [PSObject]@{ - Name = $script:newAdapterName - PhysicalMediaType = $script:adapterPhysicalMediaType - Status = $script:adapterStatus - MacAddress = $script:adapterMacAddress - InterfaceDescription = $script:adapterInterfaceDescription - InterfaceIndex = $script:adapterInterfaceIndex - InterfaceGuid = $script:adapterInterfaceGuid - DriverDescription = $script:adapterDriverDescription + { $script:result = Get-TargetResource @adapterParameters } | Should -Not -Throw + } } - function Rename-NetAdapter - { - [CmdletBinding()] - param ( - [Parameter(ValueFromPipeline = $true)] - $InputObject, - - [Parameter()] - [System.String] - $NewName - ) + It 'Should return existing adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $mockRenamedAdapter = @{ + Name = 'NewAdapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' + } + + $script:result.Name | Should -Be $mockRenamedAdapter.Name + $script:result.PhysicalMediaType | Should -Be $mockRenamedAdapter.PhysicalMediaType + $script:result.Status | Should -Be $mockRenamedAdapter.Status + $script:result.MacAddress | Should -Be $mockRenamedAdapter.MacAddress + $script:result.InterfaceDescription | Should -Be $mockRenamedAdapter.InterfaceDescription + $script:result.InterfaceIndex | Should -Be $mockRenamedAdapter.InterfaceIndex + $script:result.InterfaceGuid | Should -Be $mockRenamedAdapter.InterfaceGuid + $script:result.DriverDescription | Should -Be $mockRenamedAdapter.DriverDescription + } } - Describe 'DSC_NetAdapterName\Get-TargetResource' -Tag 'Get' { - Context 'Renamed adapter can be found' { - Mock ` - -CommandName Find-NetworkAdapter ` - -MockWith { $script:mockRenamedAdapter } ` - -ParameterFilter { $Name -eq $script:newAdapterName } + It 'Should call all the mocks' { + Should -Invoke -CommandName Find-NetworkAdapter -ParameterFilter { $Name -eq 'NewAdapter' } -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw' { - { $script:result = Get-TargetResource @adapterParameters -Verbose } | Should -Not -Throw + Context 'Renamed adapter not found but matching adapter can be found' { + BeforeAll { + Mock -CommandName Find-NetworkAdapter -ParameterFilter { $Name -eq 'NewAdapter' } + Mock -CommandName Find-NetworkAdapter -MockWith { + @{ + Name = 'Adapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' } + } -ParameterFilter { $Name -eq 'Adapter' } + } - It 'Should return existing adapter' { - $script:result.Name | Should -Be $script:mockRenamedAdapter.Name - $script:result.PhysicalMediaType | Should -Be $script:mockRenamedAdapter.PhysicalMediaType - $script:result.Status | Should -Be $script:mockRenamedAdapter.Status - $script:result.MacAddress | Should -Be $script:mockRenamedAdapter.MacAddress - $script:result.InterfaceDescription | Should -Be $script:mockRenamedAdapter.InterfaceDescription - $script:result.InterfaceIndex | Should -Be $script:mockRenamedAdapter.InterfaceIndex - $script:result.InterfaceGuid | Should -Be $script:mockRenamedAdapter.InterfaceGuid - $script:result.DriverDescription | Should -Be $script:mockRenamedAdapter.DriverDescription - } + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled ` - -CommandName Find-NetworkAdapter -Exactly -Times 1 ` - -ParameterFilter { $Name -eq $script:newAdapterName } + { $script:result = Get-TargetResource -Name 'Adapter' -NewName 'NewAdapter' } | Should -Not -Throw } + } + + It 'Should return existing adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $mockAdapter = @{ + Name = 'Adapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' } + + $script:result.Name | Should -Be $mockAdapter.Name + $script:result.PhysicalMediaType | Should -Be $mockAdapter.PhysicalMediaType + $script:result.Status | Should -Be $mockAdapter.Status + $script:result.MacAddress | Should -Be $mockAdapter.MacAddress + $script:result.InterfaceDescription | Should -Be $mockAdapter.InterfaceDescription + $script:result.InterfaceIndex | Should -Be $mockAdapter.InterfaceIndex + $script:result.InterfaceGuid | Should -Be $mockAdapter.InterfaceGuid + $script:result.DriverDescription | Should -Be $mockAdapter.DriverDescription } + } - Context 'Renamed adapter not found but matching adapter can be found' { - Mock ` - -CommandName Find-NetworkAdapter ` - -ParameterFilter { $Name -eq $script:newAdapterName } + It 'Should call all the mocks' { + Should -Invoke -CommandName Find-NetworkAdapter -ParameterFilter { $Name -eq 'Adapter' } -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Find-NetworkAdapter -ParameterFilter { $Name -eq 'NewAdapter' } -Exactly -Times 1 -Scope Context + } + } +} - Mock ` - -CommandName Find-NetworkAdapter -MockWith { $script:mockAdapter } ` - -ParameterFilter { $Name -eq $script:adapterName } +Describe 'DSC_NetAdapterName\Set-TargetResource' -Tag 'Set' { + BeforeAll { + InModuleScope -ScriptBlock { + function script:Rename-NetAdapter + { + [CmdletBinding()] + param ( + [Parameter(ValueFromPipeline = $true)] + $InputObject, + + [Parameter()] + [System.String] + $NewName + ) + } + } + } - It 'Should not throw exception' { - { $script:result = Get-TargetResource -Name $script:adapterName -NewName $script:newAdapterName -Verbose } | Should -Not -Throw + Context 'Matching adapter can be found' { + BeforeAll { + Mock -CommandName Find-NetworkAdapter -MockWith { + @{ + Name = 'Adapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' } + } - It 'Should return existing adapter' { - $script:result.Name | Should -Be $script:mockAdapter.Name - $script:result.PhysicalMediaType | Should -Be $script:mockAdapter.PhysicalMediaType - $script:result.Status | Should -Be $script:mockAdapter.Status - $script:result.MacAddress | Should -Be $script:mockAdapter.MacAddress - $script:result.InterfaceDescription | Should -Be $script:mockAdapter.InterfaceDescription - $script:result.InterfaceIndex | Should -Be $script:mockAdapter.InterfaceIndex - $script:result.InterfaceGuid | Should -Be $script:mockAdapter.InterfaceGuid - $script:result.DriverDescription | Should -Be $script:mockAdapter.DriverDescription + Mock -CommandName Rename-NetAdapter -MockWith { + @{ + Name = 'NewAdapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' } + } -ParameterFilter { $NewName -eq 'NewAdapter' } + } - It 'Should call all the mocks' { - Assert-MockCalled ` - -CommandName Find-NetworkAdapter -Exactly -Times 1 ` - -ParameterFilter { $Name -eq $script:adapterName } - - Assert-MockCalled ` - -CommandName Find-NetworkAdapter -Exactly -Times 1 ` - -ParameterFilter { $Name -eq $script:newAdapterName } + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $adapterParameters = @{ + Name = 'Adapter' + NewName = 'NewAdapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' } + + { Set-TargetResource @adapterParameters } | Should -Not -Throw } } - Describe 'DSC_NetAdapterName\Set-TargetResource' -Tag 'Set' { - Context 'Matching adapter can be found' { - Mock ` - -CommandName Find-NetworkAdapter ` - -MockWith { $script:mockAdapter } + It 'Should call all the mocks' { + Should -Invoke -CommandName Find-NetworkAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Rename-NetAdapter -ParameterFilter { $NewName -eq 'NewAdapter' } -Exactly -Times 1 -Scope Context + } + } +} - Mock ` - -CommandName Rename-NetAdapter ` - -ParameterFilter { $NewName -eq $script:newAdapterName } ` - -MockWith { $script:mockRenamedAdapter } +Describe 'DSC_NetAdapterName\Test-TargetResource' -Tag 'Test' { + Context 'Matching adapter can be found and has correct Name' { + BeforeAll { + Mock -CommandName Find-NetworkAdapter -MockWith { + @{ + Name = 'NewAdapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' + } + } + } - It 'Should not throw exception' { - { Set-TargetResource @adapterParameters -Verbose } | Should -Not -Throw + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $adapterParameters = @{ + Name = 'Adapter' + NewName = 'NewAdapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' } - It 'Should call all the mocks' { - Assert-MockCalled ` - -CommandName Find-NetworkAdapter -Exactly -Times 1 + $script:result = Test-TargetResource @adapterParameters - Assert-MockCalled ` - -CommandName Rename-NetAdapter -Exactly -Times 1 ` - -ParameterFilter { $NewName -eq $script:newAdapterName } - } + { $script:result } | Should -Not -Throw } } - Describe 'DSC_NetAdapterName\Test-TargetResource' -Tag 'Test' { - Context 'Matching adapter can be found and has correct Name' { - Mock -CommandName Find-NetworkAdapter -MockWith { $script:mockRenamedAdapter } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw exception' { - { $script:result = Test-TargetResource @adapterParameters -Verbose } | Should -Not -Throw - } + $script:result | Should -BeTrue + } + } - It 'Should return true' { - $script:result | Should -Be $true - } + It 'Should call all the mocks' { + Should -Invoke -commandName Find-NetworkAdapter -Exactly -Times 1 -Scope Context + } + } - It 'Should call all the mocks' { - Assert-MockCalled -commandName Find-NetworkAdapter -Exactly -Times 1 + Context 'Renamed adapter does not exist, but matching adapter can be found and has wrong Name' { + BeforeAll { + Mock -CommandName Find-NetworkAdapter -MockWith { + @{ + Name = 'Adapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' } - } + } -ParameterFilter { $Name -and $Name -eq 'Adapter' } - Context 'Renamed adapter does not exist, but matching adapter can be found and has wrong Name' { - Mock ` - -CommandName Find-NetworkAdapter ` - -MockWith { $script:mockAdapter } ` - -ParameterFilter { $Name -and $Name -eq $script:AdapterName } - - Mock ` - -CommandName Find-NetworkAdapter ` - -ParameterFilter { $Name -and $Name -eq $script:newAdapterName } + Mock -CommandName Find-NetworkAdapter -ParameterFilter { $Name -and $Name -eq 'NewAdapter' } + } - It 'Should not throw exception' { - { $script:result = Test-TargetResource @adapterParameters -Verbose } | Should -Not -Throw + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $adapterParameters = @{ + Name = 'Adapter' + NewName = 'NewAdapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' } - It 'Should return false' { - $script:result | Should -Be $false - } + { $script:result = Test-TargetResource @adapterParameters } | Should -Not -Throw + } + } - It 'Should call all the mocks' { - Assert-MockCalled ` - -CommandName Find-NetworkAdapter -Exactly -Times 1 ` - -ParameterFilter { $Name -and $Name -eq $script:AdapterName } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Assert-MockCalled ` - -CommandName Find-NetworkAdapter -Exactly -Times 1 ` - -ParameterFilter { $Name -and $Name -eq $script:newAdapterName } - } + $script:result | Should -BeFalse } + } - Context 'Adapter name changed by Set-TargetResource' { - Mock ` - -CommandName Find-NetworkAdapter ` - -MockWith { $script:mockRenamedAdapter } ` - -ParameterFilter { $Name -and $Name -eq $script:newAdapterName } + It 'Should call all the mocks' { + Should -Invoke -CommandName Find-NetworkAdapter -Exactly -Times 1 -Scope Context -ParameterFilter { $Name -and $Name -eq 'Adapter' } + Should -Invoke -CommandName Find-NetworkAdapter -Exactly -Times 1 -Scope Context -ParameterFilter { $Name -and $Name -eq 'NewAdapter' } + } + } - It 'Should not throw exception' { - { $script:result = Test-TargetResource @adapterParameters -Verbose } | Should -Not -Throw + Context 'Adapter name changed by Set-TargetResource' { + BeforeAll { + Mock -CommandName Find-NetworkAdapter -MockWith { + @{ + Name = 'NewAdapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' } + } -ParameterFilter { + $Name -eq 'NewAdapter' + } + } - It 'Should return false' { - $script:result | Should -Be $true + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $adapterParameters = @{ + Name = 'Adapter' + NewName = 'NewAdapter' + PhysicalMediaType = '802.3' + Status = 'Up' + MacAddress = '11-22-33-44-55-66' + InterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + InterfaceIndex = 2 + InterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + DriverDescription = 'Hyper-V Virtual Ethernet Adapter' } - It 'Should call all the mocks' { - Assert-MockCalled ` - -CommandName Find-NetworkAdapter -Exactly -Times 1 ` - -ParameterFilter { $Name -and $Name -eq $script:newAdapterName } - } + $script:result = Test-TargetResource @adapterParameters + + { $script:result } | Should -Not -Throw } } - } #end InModuleScope $DSCResourceName -} -finally -{ - Invoke-TestCleanup + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -BeTrue + } + } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Find-NetworkAdapter -ParameterFilter { $Name -eq 'NewAdapter' } -Exactly -Times 1 -Scope Context + } + } } diff --git a/tests/Unit/DSC_NetAdapterRdma.Tests.ps1 b/tests/Unit/DSC_NetAdapterRdma.Tests.ps1 index 94560e14..a04553ec 100644 --- a/tests/Unit/DSC_NetAdapterRdma.Tests.ps1 +++ b/tests/Unit/DSC_NetAdapterRdma.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterRdma' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetAdapterRdma' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,275 +35,385 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') -} -function Invoke-TestCleanup -{ - Restore-TestEnvironment -TestEnvironment $script:testEnvironment + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -Invoke-TestSetup +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - # Create the Mock -CommandName Objects that will be used for running tests - $testAdapterName = 'SMB1_1' - $targetParameters = [PSObject] @{ - Name = $testAdapterName - } + Restore-TestEnvironment -TestEnvironment $script:testEnvironment - $mockNetAdapterRdmaEnabled = [PSCustomObject] @{ - Name = $testAdapterName - Enabled = $true - } + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force - $mockNetAdapterRdmaDisabled = [PSCustomObject] @{ - Name = $testAdapterName - Enabled = $false - } + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} - Describe 'DSC_NetAdapterRdma\Get-TargetResource' -Tag 'Get' { - function Get-NetAdapterRdma - { +Describe 'DSC_NetAdapterRdma\Get-TargetResource' -Tag 'Get' { + Context 'Network adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterRdma -MockWith { + throw 'Network adapter not found' } + } + + It 'Should throw expected exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'Network adapter does not exist' { - Mock -CommandName Get-NetAdapterRdma -MockWith { - throw 'Network adapter not found' + $targetParameters = @{ + Name = 'SMB1_1' } - It 'Should throw expected exception' { - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundError -f $testAdapterName) + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.NetAdapterNotFoundError -f $targetParameters.Name) - { - Get-TargetResource @targetParameters - } | Should -Throw $errorRecord - } + { Get-TargetResource @targetParameters } | Should -Throw $errorRecord + } + } + + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + } + } - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 + Context 'Network Team exists' { + BeforeAll { + Mock -CommandName Get-NetAdapterRdma -MockWith { + @{ + Name = 'SMB1_1' + Enabled = $true } } + } - Context 'Network Team exists' { - Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRdmaEnabled } + It 'Should return network adapter RDMA properties' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return network adapter RDMA properties' { - $Result = Get-TargetResource @targetParameters - $Result.Name | Should -Be $targetParameters.Name - $Result.Enabled | Should -Be $true + $targetParameters = @{ + Name = 'SMB1_1' } - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 - } + $Result = Get-TargetResource @targetParameters + + $Result.Name | Should -Be $targetParameters.Name + $Result.Enabled | Should -BeTrue } } - Describe 'DSC_NetAdapterRdma\Set-TargetResource' -Tag 'Set' { - function Get-NetAdapterRdma - { - } - function Set-NetAdapterRdma - { - param - ( - [Parameter(Mandatory = $true)] - [System.String] - $Name, - - [Parameter(Mandatory = $true)] - [System.Boolean] - $Enabled = $true - ) + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + } + } +} + +Describe 'DSC_NetAdapterRdma\Set-TargetResource' -Tag 'Set' { + Context 'Net Adapter does not exist' { + BeforeAll { + Mock -CommandName Set-NetAdapterRdma + Mock -CommandName Get-NetAdapterRdma -MockWith { + throw 'Network adapter not found' } + } + + It 'Should throw expected exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'Net Adapter does not exist' { - Mock -CommandName Set-NetAdapterRdma - Mock -CommandName Get-NetAdapterRdma -MockWith { - throw 'Network adapter not found' + $targetParameters = @{ + Name = 'SMB1_1' } - It 'Should throw expected exception' { - $setTargetResourceParameters = $targetParameters.Clone() - $setTargetResourceParameters['Enabled'] = $true + $targetParameters.Enabled = $true - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundError -f $testAdapterName) + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.NetAdapterNotFoundError -f $targetParameters.Name) - { - Set-TargetResource @setTargetResourceParameters - } | Should -Throw $errorRecord - } + { Set-TargetResource @targetParameters } | Should -Throw $errorRecord + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterRdma -Exactly -Times 0 + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRdma -Exactly -Times 0 -Scope Context + } + } + + Context 'Net Adapter RDMA is already enabled and no action needed' { + BeforeAll { + Mock -CommandName Set-NetAdapterRdma + Mock -CommandName Get-NetAdapterRdma -MockWith { + @{ + Name = 'SMB1_1' + Enabled = $true } } + } - Context 'Net Adapter RDMA is already enabled and no action needed' { - Mock -CommandName Set-NetAdapterRdma - Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRdmaEnabled } + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw exception' { - $setTargetResourceParameters = $targetParameters.Clone() - $setTargetResourceParameters['Enabled'] = $true - { - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw + $targetParameters = @{ + Name = 'SMB1_1' } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterRdma -Exactly -Times 0 - } + $targetParameters.Enabled = $true + + { Set-TargetResource @targetParameters } | Should -Not -Throw } + } - Context 'Net Adapter RDMA is disabled and should be enabled' { - Mock -CommandName Set-NetAdapterRdma - Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRdmaDisabled } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRdma -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw exception' { - $setTargetResourceParameters = $targetParameters.Clone() - $setTargetResourceParameters['Enabled'] = $true - { - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw + Context 'Net Adapter RDMA is disabled and should be enabled' { + BeforeAll { + Mock -CommandName Set-NetAdapterRdma + Mock -CommandName Get-NetAdapterRdma -MockWith { + @{ + Name = 'SMB1_1' + Enabled = $false } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterRdma -Exactly -Times 1 + $targetParameters = @{ + Name = 'SMB1_1' } + + $targetParameters.Enabled = $true + + { Set-TargetResource @targetParameters } | Should -Not -Throw } + } - Context 'Net Adapter RDMA is enabled and should be disabled' { - Mock -CommandName Set-NetAdapterRdma - Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRdmaEnabled } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRdma -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw exception' { - $setTargetResourceParameters = $targetParameters.Clone() - $setTargetResourceParameters['Enabled'] = $false - { - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw + Context 'Net Adapter RDMA is enabled and should be disabled' { + BeforeAll { + Mock -CommandName Set-NetAdapterRdma + Mock -CommandName Get-NetAdapterRdma -MockWith { + @{ + Name = 'SMB1_1' + Enabled = $true } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterRdma -Exactly -Times 1 + $targetParameters = @{ + Name = 'SMB1_1' } + + $targetParameters.Enabled = $false + + { Set-TargetResource @targetParameters } | Should -Not -Throw } + } - Context 'Net Adapter RDMA is already disabled and no action needed' { - Mock -CommandName Set-NetAdapterRdma - Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRdmaDisabled } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRdma -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw exception' { - $setTargetResourceParameters = $targetParameters.Clone() - $setTargetResourceParameters['Enabled'] = $false - { - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw + Context 'Net Adapter RDMA is already disabled and no action needed' { + BeforeAll { + Mock -CommandName Set-NetAdapterRdma + Mock -CommandName Get-NetAdapterRdma -MockWith { + @{ + Name = 'SMB1_1' + Enabled = $false } + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetAdapterRdma -Exactly -Times 0 + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $targetParameters = @{ + Name = 'SMB1_1' } + + $targetParameters.Enabled = $false + + { Set-TargetResource @targetParameters } | Should -Not -Throw } } - Describe 'DSC_NetAdapterRdma\Test-TargetResource' -Tag 'Test' { - function Get-NetAdapterRdma - { + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRdma -Exactly -Times 0 -Scope Context + } + } +} + +Describe 'DSC_NetAdapterRdma\Test-TargetResource' -Tag 'Test' { + Context 'Net Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterRdma -MockWith { + throw 'Network adapter not found' } + } - Context 'Net Adapter does not exist' { - Mock -CommandName Get-NetAdapterRdma -MockWith { - throw 'Network adapter not found' + It 'Should throw expected exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $targetParameters = @{ + Name = 'SMB1_1' } - It 'Should throw expected exception' { - $testTargetResourceParameters = $targetParameters.Clone() - $testTargetResourceParameters['Enabled'] = $true + $targetParameters.Enabled = $true - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundError -f $testAdapterName) + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.NetAdapterNotFoundError -f $targetParameters.Name) - { - Test-TargetResource @testTargetResourceParameters - } | Should -Throw $errorRecord - } + { Test-TargetResource @targetParameters } | Should -Throw $errorRecord + } + } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 + Context 'Net Adapter RDMA is already enabled and no action needed' { + BeforeAll { + Mock -CommandName Get-NetAdapterRdma -MockWith { + @{ + Name = 'SMB1_1' + Enabled = $true } } + } - Context 'Net Adapter RDMA is already enabled and no action needed' { - Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRdmaEnabled } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true' { - $testTargetResourceParameters = $targetParameters.Clone() - $testTargetResourceParameters['Enabled'] = $true - Test-TargetResource @testTargetResourceParameters | Should -Be $true + $targetParameters = @{ + Name = 'SMB1_1' } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 - } + $targetParameters.Enabled = $true + + Test-TargetResource @targetParameters | Should -BeTrue } + } - Context 'Net Adapter RDMA is disabled and should be enabled' { - Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRdmaDisabled } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - $testTargetResourceParameters = $targetParameters.Clone() - $testTargetResourceParameters['Enabled'] = $true - Test-TargetResource @testTargetResourceParameters | Should -Be $false + Context 'Net Adapter RDMA is disabled and should be enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRdma -MockWith { + @{ + Name = 'SMB1_1' + Enabled = $false } + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 + $targetParameters = @{ + Name = 'SMB1_1' } + + $targetParameters.Enabled = $true + + Test-TargetResource @targetParameters | Should -BeFalse } + } - Context 'Net Adapter RDMA is enabled and should be disabled' { - Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRdmaEnabled } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - $testTargetResourceParameters = $targetParameters.Clone() - $testTargetResourceParameters['Enabled'] = $false - Test-TargetResource @testTargetResourceParameters | Should -Be $false + Context 'Net Adapter RDMA is enabled and should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRdma -MockWith { + @{ + Name = 'SMB1_1' + Enabled = $true } + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 + $targetParameters = @{ + Name = 'SMB1_1' } + + $targetParameters.Enabled = $false + + Test-TargetResource @targetParameters | Should -BeFalse } + } - Context 'Net Adapter RDMA is already disabled and no action needed' { - Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRdmaDisabled } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + } + } - It 'Should return true' { - $testTargetResourceParameters = $targetParameters.Clone() - $testTargetResourceParameters['Enabled'] = $false - Test-TargetResource @testTargetResourceParameters | Should -Be $true + Context 'Net Adapter RDMA is already disabled and no action needed' { + BeforeAll { + Mock -CommandName Get-NetAdapterRdma -MockWith { + @{ + Name = 'SMB1_1' + Enabled = $false } + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $targetParameters = @{ + Name = 'SMB1_1' } + + $targetParameters.Enabled = $false + + Test-TargetResource @targetParameters | Should -BeTrue } } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetAdapterRdma -Exactly -Times 1 -Scope Context + } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_NetAdapterRsc.Tests.ps1 b/tests/Unit/DSC_NetAdapterRsc.Tests.ps1 index 430b4a4e..e2fb3644 100644 --- a/tests/Unit/DSC_NetAdapterRsc.Tests.ps1 +++ b/tests/Unit/DSC_NetAdapterRsc.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterRsc' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetAdapterRsc' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,651 +35,1050 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} -Invoke-TestSetup + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - $TestAllRscEnabled = @{ - Name = 'Ethernet' - Protocol = 'All' - State = $true - } + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} - $TestAllRscDisabled = @{ - Name = 'Ethernet' - Protocol = 'All' - State = $false +Describe 'DSC_NetAdapterRsc\Get-TargetResource' -Tag 'Get' { + Context 'Adapter exists and Rsc is enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $true + IPv6Enabled = $true + } + } } - $TestIPv4RscEnabled = @{ - Name = 'Ethernet' - Protocol = 'IPv4' - State = $true - } + It 'Should return the Rsc state' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $TestIPv4RscDisabled = @{ - Name = 'Ethernet' - Protocol = 'IPv4' - State = $false - } + $TestAllRscEnabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $true + } - $TestIPv6RscEnabled = @{ - Name = 'Ethernet' - Protocol = 'IPv6' - State = $true - } + $result = Get-TargetResource @TestAllRscEnabled - $TestIPv6RscDisabled = @{ - Name = 'Ethernet' - Protocol = 'IPv6' - State = $false + $result.StateIPv4 | Should -Be $TestAllRscEnabled.State + $result.StateIPv6 | Should -Be $TestAllRscEnabled.State + } } - $TestAdapterNotFound = @{ - Name = 'Eth' - Protocol = 'IPv4' - State = $true + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context } + } - Describe 'DSC_NetAdapterRsc\Get-TargetResource' -Tag 'Get' { - Context 'Adapter exists and Rsc is enabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestAllRscEnabled.State - IPv6Enabled = $TestAllRscEnabled.State - } + Context 'Adapter exists and Rsc is disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $false + IPv6Enabled = $false } + } + } - It 'Should return the Rsc state' { - $result = Get-TargetResource @TestAllRscEnabled - $result.StateIPv4 | Should -Be $TestAllRscEnabled.State - $result.StateIPv6 | Should -Be $TestAllRscEnabled.State - } + It 'Should return the Rsc state' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestAllRscDisabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $false } + + $result = Get-TargetResource @TestAllRscDisabled + + $result.StateIPv4 | Should -Be $TestAllRscDisabled.State + $result.StateIPv6 | Should -Be $TestAllRscDisabled.State } - Context 'Adapter exists and Rsc is disabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestAllRscDisabled.State - IPv6Enabled = $TestAllRscDisabled.State - } - } + } - It 'Should return the Rsc state' { - $result = Get-TargetResource @TestAllRscDisabled - $result.StateIPv4 | Should -Be $TestAllRscDisabled.State - $result.StateIPv6 | Should -Be $TestAllRscDisabled.State + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + Context 'Adapter exists and Rsc for IPv4 is enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $true } } + } + It 'Should return the Rsc state of IPv4' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'Adapter exists and Rsc for IPv4 is enabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestIPv4RscEnabled.State - } + $TestIPv4RscEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $true } - It 'Should return the Rsc state of IPv4' { - $result = Get-TargetResource @TestIPv4RscEnabled - $result.State | Should -Be $TestIPv4RscEnabled.State - } + $result = Get-TargetResource @TestIPv4RscEnabled - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - } + $result.State | Should -Be $TestIPv4RscEnabled.State } + } - Context 'Adapter exists and Rsc for IPv4 is disabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestIPv4RscDisabled.State - } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return the Rsc state of IPv4' { - $result = Get-TargetResource @TestIPv4RscDisabled - $result.State | Should -Be $TestIPv4RscDisabled.State + Context 'Adapter exists and Rsc for IPv4 is disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $false } + } + } + + It 'Should return the Rsc state of IPv4' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestIPv4RscDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $false } + + $result = Get-TargetResource @TestIPv4RscDisabled + $result.State | Should -Be $TestIPv4RscDisabled.State } + } - Context 'Adapter exists and Rsc for IPv6 is enabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv6Enabled = $TestIPv6RscEnabled.State - } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return the Rsc state of IPv6' { - $result = Get-TargetResource @TestIPv6RscEnabled - $result.State | Should -Be $TestIPv6RscEnabled.State + Context 'Adapter exists and Rsc for IPv6 is enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv6Enabled = $true } + } + } + + It 'Should return the Rsc state of IPv6' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestIPv6RscEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $true } + + $result = Get-TargetResource @TestIPv6RscEnabled + + $result.State | Should -Be $TestIPv6RscEnabled.State } + } - Context 'Adapter exists and Rsc for IPv6 is disabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv6Enabled = $TestIPv6RscDisabled.State - } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return the Rsc state of IPv6' { - $result = Get-TargetResource @TestIPv6RscDisabled - $result.State | Should -Be $TestIPv6RscDisabled.State + Context 'Adapter exists and Rsc for IPv6 is disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv6Enabled = $false } + } + } + + It 'Should return the Rsc state of IPv6' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestIPv6RscDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $false } + + $result = Get-TargetResource @TestIPv6RscDisabled + + $result.State | Should -Be $TestIPv6RscDisabled.State } + } - Context 'Adapter does not exist' { - Mock -CommandName Get-NetAdapterRsc -MockWith { throw 'Network adapter not found' } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } + + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { throw 'Network adapter not found' } + } + + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestAdapterNotFound = @{ + Name = 'Eth' + Protocol = 'IPv4' + State = $true + } $errorRecord = Get-InvalidOperationRecord ` -Message ($script:localizedData.NetAdapterNotFoundMessage) - It 'Should throw an exception' { - { Get-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord - } + { Get-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord + } + } + + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } +} - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 +Describe 'DSC_NetAdapterRsc\Set-TargetResource' -Tag 'Set' { + # All + Context 'Adapter exists, Rsc is enabled, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $true + IPv6Enabled = $true } } + + Mock -CommandName Set-NetAdapterRsc } - Describe 'DSC_NetAdapterRsc\Set-TargetResource' -Tag 'Set' { - # All - Context 'Adapter exists, Rsc is enabled, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestAllRscEnabled.State - IPv6Enabled = $TestAllRscEnabled.State - } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { Set-TargetResource @TestAllRscEnabled } | Should -Not -Throw + $TestAllRscEnabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $true } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 0 - } + { Set-TargetResource @TestAllRscEnabled } | Should -Not -Throw } + } - Context 'Adapter exists, Rsc is enabled, should be disabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestAllRscEnabled.State - IPv6Enabled = $TestAllRscEnabled.State - } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestAllRscDisabled } | Should -Not -Throw + Context 'Adapter exists, Rsc is enabled, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $true + IPv6Enabled = $true } + } + + Mock -CommandName Set-NetAdapterRsc + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 2 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestAllRscDisabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $false } + + { Set-TargetResource @TestAllRscDisabled } | Should -Not -Throw } + } - Context 'Adapter exists, Rsc is disabled, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestAllRscDisabled.State - IPv6Enabled = $TestAllRscDisabled.State - } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 2 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestAllRscDisabled } | Should -Not -Throw + Context 'Adapter exists, Rsc is disabled, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $false + IPv6Enabled = $false } + } + + Mock -CommandName Set-NetAdapterRsc + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 0 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestAllRscDisabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $false } + + { Set-TargetResource @TestAllRscDisabled } | Should -Not -Throw } + } - Context 'Adapter exists, Rsc is disabled, should be enabled.' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestAllRscDisabled.State - IPv6Enabled = $TestAllRscDisabled.State - } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestAllRscEnabled } | Should -Not -Throw + Context 'Adapter exists, Rsc is disabled, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $false + IPv6Enabled = $false } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 2 + Mock -CommandName Set-NetAdapterRsc + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestAllRscEnabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $true } + + { Set-TargetResource @TestAllRscEnabled } | Should -Not -Throw } + } - Context 'Adapter exists, Rsc is disabled for IPv4, should be enabled.' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestAllRscDisabled.State - IPv6Enabled = $TestAllRscEnabled.State - } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 2 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestAllRscEnabled } | Should -Not -Throw + Context 'Adapter exists, Rsc is disabled for IPv4, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $false + IPv6Enabled = $true } + } + + Mock -CommandName Set-NetAdapterRsc + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 1 + $TestAllRscEnabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $true } + + { Set-TargetResource @TestAllRscEnabled } | Should -Not -Throw } + } - Context 'Adapter exists, Rsc is Enabled for IPv6, should be disabled.' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestAllRscDisabled.State - IPv6Enabled = $TestAllRscEnabled.State - } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestAllRscDisabled } | Should -Not -Throw + Context 'Adapter exists, Rsc is Enabled for IPv6, should be disabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $false + IPv6Enabled = $true } + } + + Mock -CommandName Set-NetAdapterRsc + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestAllRscDisabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $false } + + { Set-TargetResource @TestAllRscDisabled } | Should -Not -Throw } + } - # IPv4 - Context 'Adapter exists, Rsc is enabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv4Enabled = $TestIPv4RscEnabled.State } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestIPv4RscEnabled } | Should -Not -Throw - } + # IPv4 + Context 'Adapter exists, Rsc is enabled for IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv4Enabled = $true } + } + + Mock -CommandName Set-NetAdapterRsc + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 0 + $TestIPv4RscEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $true } + + { Set-TargetResource @TestIPv4RscEnabled } | Should -Not -Throw } + } - Context 'Adapter exists, Rsc is enabled for IPv4, should be disabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv4Enabled = $TestIPv4RscEnabled.State } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestIPv4RscDisabled } | Should -Not -Throw - } + Context 'Adapter exists, Rsc is enabled for IPv4, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv4Enabled = $true } + } + + Mock -CommandName Set-NetAdapterRsc + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 1 + $TestIPv4RscDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $false } + + { Set-TargetResource @TestIPv4RscDisabled } | Should -Not -Throw } + } - Context 'Adapter exists, Rsc is disabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv4Enabled = $TestIPv4RscDisabled.State } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestIPv4RscDisabled } | Should -Not -Throw - } + Context 'Adapter exists, Rsc is disabled for IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv4Enabled = $false } + } + + Mock -CommandName Set-NetAdapterRsc + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 0 + $TestIPv4RscDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $false } + + { Set-TargetResource @TestIPv4RscDisabled } | Should -Not -Throw } + } - Context 'Adapter exists, Rsc is disabled for IPv4, should be enabled.' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv4Enabled = $TestIPv4RscDisabled.State } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestIPv4RscEnabled } | Should -Not -Throw - } + Context 'Adapter exists, Rsc is disabled for IPv4, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv4Enabled = $false } + } + + Mock -CommandName Set-NetAdapterRsc + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 1 + $TestIPv4RscEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $true } + + { Set-TargetResource @TestIPv4RscEnabled } | Should -Not -Throw } + } - # IPv6 - Context 'Adapter exists, Rsc is enabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv6Enabled = $TestIPv6RscEnabled.State } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestIPv6RscEnabled } | Should -Not -Throw - } + # IPv6 + Context 'Adapter exists, Rsc is enabled for IPv6, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv6Enabled = $true } + } + + Mock -CommandName Set-NetAdapterRsc + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 0 + $TestIPv6RscEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $true } + + { Set-TargetResource @TestIPv6RscEnabled } | Should -Not -Throw } + } - Context 'Adapter exists, Rsc is enabled for IPv6, should be disabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv6Enabled = $TestIPv6RscEnabled.State } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestIPv6RscDisabled } | Should -Not -Throw - } + Context 'Adapter exists, Rsc is enabled for IPv6, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv6Enabled = $true } + } + + Mock -CommandName Set-NetAdapterRsc + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestIPv6RscDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $false } + + { Set-TargetResource @TestIPv6RscDisabled } | Should -Not -Throw } + } - Context 'Adapter exists, Rsc is disabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv6Enabled = $TestIPv6RscDisabled.State } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestIPv6RscDisabled } | Should -Not -Throw - } + Context 'Adapter exists, Rsc is disabled for IPv6, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv6Enabled = $false } + } + + Mock -CommandName Set-NetAdapterRsc + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 0 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestIPv6RscDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $false } + + { Set-TargetResource @TestIPv6RscDisabled } | Should -Not -Throw } + } - Context 'Adapter exists, Rsc is disabled for IPv6, should be enabled.' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv6Enabled = $TestIPv6RscDisabled.State } - } - Mock -CommandName Set-NetAdapterRsc + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestIPv6RscEnabled } | Should -Not -Throw - } + Context 'Adapter exists, Rsc is disabled for IPv6, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv6Enabled = $false } + } + + Mock -CommandName Set-NetAdapterRsc + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRsc -Exactly -Time 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestIPv6RscEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $true } + + { Set-TargetResource @TestIPv6RscEnabled } | Should -Not -Throw } + } - # Adapter - Context 'Adapter does not exist' { - Mock -CommandName Get-NetAdapterRsc -MockWith { throw 'Network adapter not found' } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundMessage) + # Adapter + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { throw 'Network adapter not found' } + } - It 'Should throw an exception' { - { Set-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord - } + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestAdapterNotFound = @{ + Name = 'Eth' + Protocol = 'IPv4' + State = $true } + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.NetAdapterNotFoundMessage) + + { Set-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord } + } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context } + } +} - Describe 'DSC_NetAdapterRsc\Test-TargetResource' -Tag 'Test' { - # All - Context 'Adapter exists, Rsc is enabled, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestAllRscEnabled.State - IPv6Enabled = $TestAllRscEnabled.State - } +Describe 'DSC_NetAdapterRsc\Test-TargetResource' -Tag 'Test' { + # All + Context 'Adapter exists, Rsc is enabled, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $true + IPv6Enabled = $true } + } + } - It 'Should return true' { - Test-TargetResource @TestAllRscEnabled | Should -Be $true - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestAllRscEnabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $true } + + Test-TargetResource @TestAllRscEnabled | Should -BeTrue } + } - Context 'Adapter exists, Rsc is enabled, should be disabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ - IPv4Enabled = $TestAllRscEnabled.State - IPv6Enabled = $TestAllRscEnabled.State - } - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @TestAllRscDisabled | Should -Be $false + Context 'Adapter exists, Rsc is enabled, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $true + IPv6Enabled = $true } + } + } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestAllRscDisabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $false } + + Test-TargetResource @TestAllRscDisabled | Should -BeFalse } + } - Context 'Adapter exists, Rsc is disabled, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{IPv4Enabled = $TestAllRscDisabled.State - IPv6Enabled = $TestAllRscDisabled.State - } - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @TestAllRscDisabled | Should -Be $true + Context 'Adapter exists, Rsc is disabled, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $false + IPv6Enabled = $false } + } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestAllRscDisabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $false } + + Test-TargetResource @TestAllRscDisabled | Should -BeTrue } + } - Context 'Adapter exists, Rsc is disabled, should be enabled.' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv4Enabled = $TestAllRscDisabled.State - IPv6Enabled = $TestAllRscDisabled.State - } - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @TestAllRscEnabled | Should -Be $false + Context 'Adapter exists, Rsc is disabled, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ + IPv4Enabled = $false + IPv6Enabled = $false } + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestAllRscEnabled = @{ + Name = 'Ethernet' + Protocol = 'All' + State = $true } + + Test-TargetResource @TestAllRscEnabled | Should -BeFalse } + } - # IPv4 - Context 'Adapter exists, Rsc is enabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv4Enabled = $TestIPv4RscEnabled.State } - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @TestIPv4RscEnabled | Should -Be $true - } + # IPv4 + Context 'Adapter exists, Rsc is enabled for IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv4Enabled = $true } + } + } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestIPv4RscEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $true } + + Test-TargetResource @TestIPv4RscEnabled | Should -BeTrue } + } - Context 'Adapter exists, Rsc is enabled for IPv4, should be disabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv4Enabled = $TestIPv4RscEnabled.State } - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @TestIPv4RscDisabled | Should -Be $false - } + Context 'Adapter exists, Rsc is enabled for IPv4, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv4Enabled = $true } + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestIPv4RscDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $false } + + Test-TargetResource @TestIPv4RscDisabled | Should -BeFalse } + } - Context 'Adapter exists, Rsc is disabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv4Enabled = $TestIPv4RscDisabled.State } - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @TestIPv4RscDisabled | Should -Be $true - } + Context 'Adapter exists, Rsc is disabled for IPv4, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv4Enabled = $false } + } + } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestIPv4RscDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $false } + + Test-TargetResource @TestIPv4RscDisabled | Should -BeTrue } + } - Context 'Adapter exists, Rsc is disabled for IPv4, should be enabled.' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv4Enabled = $TestIPv4RscDisabled.State } - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @TestIPv4RscEnabled | Should -Be $false - } + Context 'Adapter exists, Rsc is disabled for IPv4, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv4Enabled = $false } + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestIPv4RscEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv4' + State = $true } + + Test-TargetResource @TestIPv4RscEnabled | Should -BeFalse } + } - # IPv6 - Context 'Adapter exists, Rsc is enabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv6Enabled = $TestIPv6RscEnabled.State } - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @TestIPv6RscEnabled | Should -Be $true - } + # IPv6 + Context 'Adapter exists, Rsc is enabled for IPv6, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv6Enabled = $true } + } + } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestIPv6RscEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $true } + + Test-TargetResource @TestIPv6RscEnabled | Should -BeTrue } + } - Context 'Adapter exists, Rsc is enabled for IPv6, should be disabled' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv6Enabled = $TestIPv6RscEnabled.State } - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @TestIPv6RscDisabled | Should -Be $false - } + Context 'Adapter exists, Rsc is enabled for IPv6, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv6Enabled = $true } + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestIPv6RscDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $false } + + Test-TargetResource @TestIPv6RscDisabled | Should -BeFalse } + } - Context 'Adapter exists, Rsc is disabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv6Enabled = $TestIPv6RscDisabled.State } - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @TestIPv6RscDisabled | Should -Be $true - } + Context 'Adapter exists, Rsc is disabled for IPv6, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv6Enabled = $false } + } + } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestIPv6RscDisabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $false } + + Test-TargetResource @TestIPv6RscDisabled | Should -BeTrue } + } - Context 'Adapter exists, Rsc is disabled for IPv6, should be enabled.' { - Mock -CommandName Get-NetAdapterRsc -MockWith { - @{ IPv6Enabled = $TestIPv6RscDisabled.State } - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - It 'Should return false' { - Test-TargetResource @TestIPv6RscEnabled | Should -Be $false - } + Context 'Adapter exists, Rsc is disabled for IPv6, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { + @{ IPv6Enabled = $false } + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestIPv6RscEnabled = @{ + Name = 'Ethernet' + Protocol = 'IPv6' + State = $true } + + Test-TargetResource @TestIPv6RscEnabled | Should -BeFalse } + } - # Adapter - Context 'Adapter does not exist' { - Mock -CommandName Get-NetAdapterRsc -MockWith { throw 'Network adapter not found' } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } + } - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundMessage) + # Adapter + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterRsc -MockWith { throw 'Network adapter not found' } + } - It 'Should throw an exception' { - { Test-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord - } + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRsc -Exactly -Time 1 + $TestAdapterNotFound = @{ + Name = 'Eth' + Protocol = 'IPv4' + State = $true } + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.NetAdapterNotFoundMessage) + + { Test-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord } } + + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRsc -Exactly -Time 1 -Scope Context + } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_NetAdapterRss.Tests.ps1 b/tests/Unit/DSC_NetAdapterRss.Tests.ps1 index 96f3d3ef..742dbe62 100644 --- a/tests/Unit/DSC_NetAdapterRss.Tests.ps1 +++ b/tests/Unit/DSC_NetAdapterRss.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterRss' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetAdapterRss' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,240 +35,375 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup +Describe 'DSC_NetAdapterRss\Get-TargetResource' -Tag 'Get' { + Context 'Adapter exist and RSS is enabled' { + BeforeAll { + Mock Get-NetAdapterRss -Verbose -MockWith { + @{ Enabled = $true } + } + } + + It 'Should return the RSS Enabled' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestRssEnabled = @{ + Name = 'Ethernet' + Enabled = $true + } + + $result = Get-TargetResource @TestRssEnabled -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - $TestRssEnabled = @{ - Name = 'Ethernet' - Enabled = $true + $result.Enabled | Should -Be $TestRSSEnabled.Enabled + } } - $TestRssDisabled = @{ - Name = 'Ethernet' - Enabled = $false + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context } + } - $TestAdapterNotFound = @{ - Name = 'Ethe' - Enabled = $true + Context 'Adapter exist and RSS is disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRSS -MockWith { + @{ Enabled = $false } + } } - Describe 'DSC_NetAdapterRss\Get-TargetResource' -Tag 'Get' { - Context 'Adapter exist and RSS is enabled' { - Mock Get-NetAdapterRss -Verbose -MockWith { @{ Enabled = $true } } + It 'Should return the RSS Enabled' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return the RSS Enabled' { - $result = Get-TargetResource @TestRssEnabled - $result.Enabled | Should -Be $TestRSSEnabled.Enabled + $TestRssDisabled = @{ + Name = 'Ethernet' + Enabled = $false } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 - } + $result = Get-TargetResource @TestRSSDisabled + + $result.Enabled | Should -Be $TestRSSDisabled.Enabled } + } - Context 'Adapter exist and RSS is disabled' { - Mock -CommandName Get-NetAdapterRSS -MockWith { - @{ Enabled = $TestRSSDisabled.Enabled } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context + } + } + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterRss -MockWith { throw 'Network adapter not found' } + } - It 'Should return the RSS Enabled' { - $result = Get-TargetResource @TestRSSDisabled - $result.Enabled | Should -Be $TestRSSDisabled.Enabled - } + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 + $TestAdapterNotFound = @{ + Name = 'Ethe' + Enabled = $true } - } - Context 'Adapter does not exist' { - - Mock -CommandName Get-NetAdapterRss -MockWith { throw 'Network adapter not found' } $errorRecord = Get-InvalidOperationRecord ` -Message ($script:localizedData.NetAdapterNotFoundMessage) - It 'Should throw an exception' { - { Get-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord - } + { Get-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord + } + } + + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRss -Exactly -Time 1 -Scope Context + } + } +} + +Describe 'DSC_NetAdapterRss\Set-TargetResource' -Tag 'Set' { + Context 'Adapter exist, RSS is enabled, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRSS -MockWith { + @{ Enabled = $true } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRss -Exactly -Time 1 + Mock -CommandName Set-NetAdapterRSS + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestRssEnabled = @{ + Name = 'Ethernet' + Enabled = $true } + + { Set-TargetResource @TestRSSEnabled } | Should -Not -Throw } + } - Describe 'DSC_NetAdapterRss\Set-TargetResource' -Tag 'Set' { + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRSS -Exactly -Time 0 -Scope Context + } + } - Context 'Adapter exist, RSS is enabled, no action required' { - Mock -CommandName Get-NetAdapterRSS -MockWith { - @{ Enabled = $TestRSSEnabled.Enabled } - } - Mock -CommandName Set-NetAdapterRSS + Context 'Adapter exist, RSS is enabled, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRSS -MockWith { + @{ Enabled = $true } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestRSSEnabled } | Should -Not -Throw - } + Mock -CommandName Set-NetAdapterRSS + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRSS -Exactly -Time 0 - } + $TestRssDisabled = @{ + Name = 'Ethernet' + Enabled = $false } - Context 'Adapter exist, RSS is enabled, should be disabled' { - Mock -CommandName Get-NetAdapterRSS -MockWith { - @{ Enabled = $TestRSSEnabled.Enabled } - } - Mock -CommandName Set-NetAdapterRSS + { Set-TargetResource @TestRSSDisabled } | Should -Not -Throw + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestRSSDisabled } | Should -Not -Throw - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRSS -Exactly -Time 1 -Scope Context + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRSS -Exactly -Time 1 - } - } + Context 'Adapter exist, RSS is disabled, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRSS -MockWith { + @{ Enabled = $false } + } - Context 'Adapter exist, RSS is disabled, no action required' { - Mock -CommandName Get-NetAdapterRSS -MockWith { - @{ Enabled = $TestRSSDisabled.Enabled } - } - Mock -CommandName Set-NetAdapterRSS + Mock -CommandName Set-NetAdapterRSS + } - It 'Should not throw an exception' { - { Set-TargetResource @TestRSSDisabled } | Should -Not -Throw - } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRSS -Exactly -Time 0 - } + $TestRssDisabled = @{ + Name = 'Ethernet' + Enabled = $false } - Context 'Adapter exist, RSS is disabled, should be enabled.' { - Mock -CommandName Get-NetAdapterRSS -MockWith { - @{ Enabled = $TestRSSDisabled.Enabled } - } - Mock -CommandName Set-NetAdapterRSS + { Set-TargetResource @TestRSSDisabled } | Should -Not -Throw + } + } - It 'Should not throw an exception' { - { Set-TargetResource @TestRSSEnabled } | Should -Not -Throw - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRSS -Exactly -Time 0 -Scope Context + } + } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 - Assert-MockCalled -CommandName Set-NetAdapterRSS -Exactly -Time 1 - } + Context 'Adapter exist, RSS is disabled, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterRSS -MockWith { + @{ Enabled = $false } + } + + Mock -CommandName Set-NetAdapterRSS + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestRssEnabled = @{ + Name = 'Ethernet' + Enabled = $true } - # Adapter - Context 'Adapter does not exist' { - Mock -CommandName Get-NetAdapterRSS -MockWith { throw 'Network adapter not found' } + { Set-TargetResource @TestRSSEnabled } | Should -Not -Throw + } + } - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundMessage) + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context + Should -Invoke -CommandName Set-NetAdapterRSS -Exactly -Time 1 -Scope Context + } + } - It 'Should throw an exception' { - { Set-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord - } + # Adapter + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterRSS -MockWith { throw 'Network adapter not found' } + } + + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 - } + $TestAdapterNotFound = @{ + Name = 'Ethe' + Enabled = $true } + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.NetAdapterNotFoundMessage) + + { Set-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord } + } - Describe 'DSC_NetAdapterRss\Test-TargetResource' -Tag 'Test' { - # All - Context 'Adapter exist, RSS is enabled, no action required' { - Mock -CommandName Get-NetAdapterRSS -MockWith { - @{ Enabled = $TestRSSEnabled.Enabled } - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context + } + } - It 'Should return true' { - Test-TargetResource @TestRSSEnabled | Should -Be $true - } +} - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 - } +Describe 'DSC_NetAdapterRss\Test-TargetResource' -Tag 'Test' { + # All + Context 'Adapter exist, RSS is enabled, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRSS -MockWith { + @{ Enabled = $true } + } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestRssEnabled = @{ + Name = 'Ethernet' + Enabled = $true } - Context 'Adapter exist, RSS is enabled, should be disabled' { - Mock -CommandName Get-NetAdapterRSS -MockWith { - @{ Enabled = $TestRSSEnabled.Enabled } - } + Test-TargetResource @TestRSSEnabled | Should -BeTrue + } + } + + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context + } + } + + Context 'Adapter exist, RSS is enabled, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapterRSS -MockWith { + @{ Enabled = $true } + } + } - It 'Should return false' { - Test-TargetResource @TestRSSDisabled | Should -Be $false - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 - } + $TestRssDisabled = @{ + Name = 'Ethernet' + Enabled = $false } - Context 'Adapter exist, RSS is disabled, no action required' { - Mock -CommandName Get-NetAdapterRSS -MockWith { - @{ Enabled = $TestRSSDisabled.Enabled } - } + Test-TargetResource @TestRSSDisabled | Should -BeFalse + } + } + + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context + } + } + + Context 'Adapter exist, RSS is disabled, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapterRSS -MockWith { + @{ Enabled = $false } + } + } - It 'Should return true' { - Test-TargetResource @TestRSSDisabled | Should -Be $true - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 - } + $TestRssDisabled = @{ + Name = 'Ethernet' + Enabled = $false } - Context 'Adapter exist, RSS is disabled, should be enabled.' { - Mock -CommandName Get-NetAdapterRSS -MockWith { - @{ Enabled = $TestRSSDisabled.Enabled } - } + Test-TargetResource @TestRSSDisabled | Should -BeTrue + } + } - It 'Should return false' { - Test-TargetResource @TestRSSEnabled | Should -Be $false - } + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context + } + } + + Context 'Adapter exist, RSS is disabled, should be enabled.' { + BeforeAll { + Mock -CommandName Get-NetAdapterRSS -MockWith { + @{ Enabled = $false } + } + } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $TestRssEnabled = @{ + Name = 'Ethernet' + Enabled = $true } - # Adapter - Context 'Adapter does not exist' { - Mock -CommandName Get-NetAdapterRSS -MockWith { throw 'Network adapter not found' } + Test-TargetResource @TestRSSEnabled | Should -BeFalse + } + } - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundMessage) + it 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context + } + } + + # Adapter + Context 'Adapter does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapterRSS -MockWith { throw 'Network adapter not found' } + } - It 'Should throw an exception' { - { Test-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord - } + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterRSS -Exactly -Time 1 - } + $TestAdapterNotFound = @{ + Name = 'Ethe' + Enabled = $true } + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.NetAdapterNotFoundMessage) + + { Test-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord } } + + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapterRSS -Exactly -Time 1 -Scope Context + } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_NetAdapterState.Tests.ps1 b/tests/Unit/DSC_NetAdapterState.Tests.ps1 index 669d83ca..81fe83f0 100644 --- a/tests/Unit/DSC_NetAdapterState.Tests.ps1 +++ b/tests/Unit/DSC_NetAdapterState.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetAdapterState' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetAdapterState' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,297 +35,486 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + # Import the NetAdapter module to load the required NET_IF_ADMIN_STATUS enums + Import-Module -Name NetAdapter + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Remove module NetAdapter. + Get-Module -Name 'NetAdapter' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup +Describe 'DSC_NetAdapterState\Get-TargetResource' -Tag 'Get' { + Context 'When adapter exists and is enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Up + State = 'Enabled' + } + } + } -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - # Import the NetAdapter module to load the required NET_IF_ADMIN_STATUS enums - Import-Module -Name NetAdapter + It 'Should return the state of the network adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $netAdapterEnabled = [PSCustomObject]@{ - Name = 'Ethernet' - AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Up - State = 'Enabled' + $getTargetResource = @{ + Name = 'Ethernet' + State = 'Enabled' + } + + $result = Get-TargetResource @getTargetResource + + $result.State | Should -Be 'Enabled' + } } - $netAdapterDisabled = [PSCustomObject]@{ - Name = 'Ethernet' - AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Down - State = 'Disabled' + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context } + } - $netAdapterUnsupported = [PSCustomObject]@{ - Name = 'Ethernet' - AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Testing + Context 'When adapter exists and is in unsupported state' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Testing + } + } } - Describe 'DSC_NetAdapterState\Get-TargetResource' -Tag 'Get' { - BeforeEach { + It 'Should return the state of the network adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + $getTargetResource = @{ - Name = 'Ethernet' - State = 'Enabled' - Verbose = $true + Name = 'Ethernet' + State = 'Enabled' } + + $result = Get-TargetResource @getTargetResource + + $result.State | Should -Be 'Unsupported' } + } + } - Context 'When adapter exists and is enabled' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterEnabled + Context 'When adapter exists and is disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Down + State = 'Disabled' } + } + } - It 'Should return the state of the network adapter' { - $result = Get-TargetResource @getTargetResource - $result.State | Should -Be 'Enabled' - } + It 'Should return the state of the network adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 + $getTargetResource = @{ + Name = 'Ethernet' + State = 'Enabled' } + + $result = Get-TargetResource @getTargetResource + + $result.State | Should -Be 'Disabled' } + } - Context 'When adapter exists and is in unsupported state' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterUnsupported - } + It 'Should call all mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } - It 'Should return the state of the network adapter' { - $result = Get-TargetResource @getTargetResource - $result.State | Should -Be 'Unsupported' - } + Context 'When Get-NetAdapter returns error' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + throw 'Throwing from Get-NetAdapter' } + } - Context 'When adapter exists and is disabled' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterDisabled - } + It 'Should display warning when network adapter cannot be found' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return the state of the network adapter' { - $result = Get-TargetResource @getTargetResource - $result.State | Should -Be 'Disabled' + $getTargetResource = @{ + Name = 'Ethernet' + State = 'Enabled' } - It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } + $warning = Get-TargetResource @getTargetResource 3>&1 - Context 'When Get-NetAdapter returns error' { - Mock -CommandName Get-NetAdapter -MockWith { - Throw 'Throwing from Get-NetAdapter' - } + $warning.Message | Should -Be "Get-TargetResource: Network adapter 'Ethernet' not found." + } + } + } +} - It 'Should display warning when network adapter cannot be found' { - $warning = Get-TargetResource @getTargetResource 3>&1 - $warning.Message | Should -Be "Get-TargetResource: Network adapter 'Ethernet' not found." +Describe 'DSC_NetAdapterState\Set-TargetResource' -Tag 'Set' { + Context 'When adapter exists and is enabled, desired state is enabled, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Up + State = 'Enabled' } } + + Mock -CommandName Disable-NetAdapter + Mock -CommandName Enable-NetAdapter } - Describe 'DSC_NetAdapterState\Set-TargetResource' -Tag 'Set' { - BeforeEach { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + $setTargetResourceEnabled = @{ - Name = 'Ethernet' - State = 'Enabled' - Verbose = $true + Name = 'Ethernet' + State = 'Enabled' } - $setTargetResourceDisabled = @{ - Name = 'Ethernet' - State = 'Disabled' - Verbose = $true - } + { Set-TargetResource @setTargetResourceEnabled } | Should -Not -Throw } + } - Context 'When adapter exists and is enabled, desired state is enabled, no action required' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterEnabled - } - Mock -CommandName Disable-NetAdapter - Mock -CommandName Enable-NetAdapter + It 'Should not call Disable-NetAdapter' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Disable-NetAdapter -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Enable-NetAdapter -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @setTargetResourceEnabled } | Should -Not -Throw + Context 'When adapter exists and is enabled, desired state is disabled, should be disabled' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Up + State = 'Enabled' } + } - It 'Should not call Disable-NetAdapter' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Disable-NetAdapter -Exactly -Times 0 - Assert-MockCalled -CommandName Enable-NetAdapter -Exactly -Times 0 + Mock -CommandName Disable-NetAdapter + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $setTargetResourceDisabled = @{ + Name = 'Ethernet' + State = 'Disabled' } + + { Set-TargetResource @setTargetResourceDisabled } | Should -Not -Throw } + } - Context 'When adapter exists and is enabled, desired state is disabled, should be disabled' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterEnabled - } - Mock -CommandName Disable-NetAdapter + It 'Should call Disable-NetAdapter' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Disable-NetAdapter -Exactly -Times 1 -Scope Context -ParameterFilter { + $Name -eq 'Ethernet' + } + } + } - It 'Should not throw an exception' { - { Set-TargetResource @setTargetResourceDisabled } | Should -Not -Throw + Context 'When adapter exists and is disabled, desired state is disabled, no action required' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Down + State = 'Disabled' } + } + + Mock -CommandName Disable-NetAdapter + Mock -CommandName Enable-NetAdapter + } - It 'Should call Disable-NetAdapter' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Disable-NetAdapter -Exactly -Times 1 -ParameterFilter { - $Name -eq $setTargetResourceEnabled.Name - } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $setTargetResourceDisabled = @{ + Name = 'Ethernet' + State = 'Disabled' } + + { Set-TargetResource @setTargetResourceDisabled } | Should -Not -Throw } + } - Context 'When adapter exists and is disabled, desired state is disabled, no action required' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterDisabled - } - Mock -CommandName Disable-NetAdapter - Mock -CommandName Enable-NetAdapter + It 'Should not call Enable-NetAdapter' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Disable-NetAdapter -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Enable-NetAdapter -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw an exception' { - { Set-TargetResource @setTargetResourceDisabled } | Should -Not -Throw + Context 'When adapter exists and is disabled, desired state is enabled, should be enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Down + State = 'Disabled' } + } + + Mock -CommandName Enable-NetAdapter + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not call Enable-NetAdapter' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Disable-NetAdapter -Exactly -Times 0 - Assert-MockCalled -CommandName Enable-NetAdapter -Exactly -Times 0 + $setTargetResourceEnabled = @{ + Name = 'Ethernet' + State = 'Enabled' } + + { Set-TargetResource @setTargetResourceEnabled } | Should -Not -Throw } + } - Context 'When adapter exists and is disabled, desired state is enabled, should be enabled' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterDisabled - } - Mock -CommandName Enable-NetAdapter + It 'Should call Enable-NetAdapter' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Enable-NetAdapter -Exactly -Times 1 -Scope Context -ParameterFilter { + $Name -eq 'Ethernet' + } + } + } - It 'Should not throw an exception' { - { Set-TargetResource @setTargetResourceEnabled } | Should -Not -Throw + Context 'When adapter exists and is disabled, desired state is enabled, set failed' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Down + State = 'Disabled' } + } - It 'Should call Enable-NetAdapter' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Enable-NetAdapter -Exactly -Times 1 -ParameterFilter { - $Name -eq $setTargetResourceEnabled.Name - } - } + Mock -CommandName Enable-NetAdapter -MockWith { + throw 'Throwing from Enable-NetAdapter' } + } - Context 'When adapter exists and is disabled, desired state is enabled, set failed' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterDisabled - } - Mock -CommandName Enable-NetAdapter -MockWith { - Throw 'Throwing from Enable-NetAdapter' + It 'Should raise a non terminating error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $setTargetResourceEnabled = @{ + Name = 'Ethernet' + State = 'Enabled' } $errorText = "Set-TargetResource: Failed to set network adapter 'Ethernet' to state 'Enabled'. Error: 'Throwing from Enable-NetAdapter'." - It 'Should raise a non terminating error' { - $netAdapterError = Set-TargetResource @setTargetResourceEnabled -ErrorAction Continue 2>&1 - $netAdapterError.Exception.Message | Should -Be $errorText - } + $netAdapterError = Set-TargetResource @setTargetResourceEnabled -ErrorAction Continue 2>&1 + + $netAdapterError.Exception.Message | Should -Be $errorText + } + } + } + + Context 'When adapter does not exist and desired state is enabled' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + throw 'Throwing from Get-NetAdapter' } + } + + + It 'Should raise a non terminating error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'When adapter does not exist and desired state is enabled' { - Mock -CommandName Get-NetAdapter -MockWith { - throw 'Throwing from Get-NetAdapter' + $setTargetResourceEnabled = @{ + Name = 'Ethernet' + State = 'Enabled' } $errorText = "Set-TargetResource: Network adapter 'Ethernet' not found." - It 'Should raise a non terminating error' { - $netAdapterError = Set-TargetResource @setTargetResourceEnabled -ErrorAction Continue 2>&1 - $netAdapterError.Exception.Message | Should -Be $errorText + $netAdapterError = Set-TargetResource @setTargetResourceEnabled -ErrorAction Continue 2>&1 + + $netAdapterError.Exception.Message | Should -Be $errorText + } + } + } +} + +Describe 'DSC_NetAdapterState\Test-TargetResource' -Tag 'Test' { + Context 'When adapter exists and is enabled, desired state is enabled, test true' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Up + State = 'Enabled' } } } - Describe 'DSC_NetAdapterState\Test-TargetResource' -Tag 'Test' { - BeforeEach { + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + $testTargetResourceEnabled = @{ - Name = 'Ethernet' - State = 'Enabled' - Verbose = $true + Name = 'Ethernet' + State = 'Enabled' } - $testTargetResourceDisabled = @{ - Name = 'Ethernet' - State = 'Disabled' - Verbose = $true - } + Test-TargetResource @testTargetResourceEnabled | Should -BeTrue } + } + } - Context 'When adapter exists and is enabled, desired state is enabled, test true' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterEnabled - } - - It 'Should return true' { - Test-TargetResource @testTargetResourceEnabled | Should -Be $true + Context 'When adapter exists and is enabled, desired state is disabled, test false' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Up + State = 'Enabled' } } + } - Context 'When adapter exists and is enabled, desired state is disabled, test false' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterEnabled - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - Test-TargetResource @testTargetResourceDisabled | Should -Be $false + $testTargetResourceDisabled = @{ + Name = 'Ethernet' + State = 'Disabled' } + + Test-TargetResource @testTargetResourceDisabled | Should -BeFalse } + } + } - Context 'When adapter exists and is disabled, desired state is disabled, test true' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterDisabled + Context 'When adapter exists and is disabled, desired state is disabled, test true' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Down + State = 'Disabled' } + } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true' { - Test-TargetResource @testTargetResourceDisabled | Should -Be $true + $testTargetResourceDisabled = @{ + Name = 'Ethernet' + State = 'Disabled' } + + Test-TargetResource @testTargetResourceDisabled | Should -BeTrue } + } + } - Context 'When adapter exists and is disabled, desired state is enabled, test false' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterDisabled + Context 'When adapter exists and is disabled, desired state is enabled, test false' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Down + State = 'Disabled' } + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - Test-TargetResource @testTargetResourceEnabled | Should -Be $false + $testTargetResourceEnabled = @{ + Name = 'Ethernet' + State = 'Enabled' } + + Test-TargetResource @testTargetResourceEnabled | Should -BeFalse } + } + } - Context 'When adapter exists and is in Unsupported state, desired state is enabled, test false' { - Mock -CommandName Get-NetAdapter -MockWith { - $netAdapterUnsupported + Context 'When adapter exists and is in Unsupported state, desired state is enabled, test false' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'Ethernet' + AdminStatus = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetAdapter.NET_IF_ADMIN_STATUS]::Testing } + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - Test-TargetResource @testTargetResourceEnabled | Should -Be $false + $testTargetResourceEnabled = @{ + Name = 'Ethernet' + State = 'Enabled' } + + Test-TargetResource @testTargetResourceEnabled | Should -BeFalse } + } + } - Context 'When adapter does not exist, desired state is enabled, test false' { - Mock -CommandName Get-NetAdapter -MockWith { - $null - } + Context 'When adapter does not exist, desired state is enabled, test false' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + $null + } + } - It 'Should return false' { - Test-TargetResource @testTargetResourceEnabled | Should -Be $false + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testTargetResourceEnabled = @{ + Name = 'Ethernet' + State = 'Enabled' } + + Test-TargetResource @testTargetResourceEnabled | Should -BeFalse } } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_NetBios.Tests.ps1 b/tests/Unit/DSC_NetBios.Tests.ps1 index 0b120dca..986c9efb 100644 --- a/tests/Unit/DSC_NetBios.Tests.ps1 +++ b/tests/Unit/DSC_NetBios.Tests.ps1 @@ -1,1023 +1,1023 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetBios' - -function Invoke-TestSetup -{ - try - { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' - } - catch [System.IO.FileNotFoundException] - { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' - } - - $script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Unit' - - Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') -} - -function Invoke-TestCleanup -{ - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} - -Invoke-TestSetup - -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - $script:interfaceAliasA = 'Test Adapter A' - $script:interfaceAliasB = 'Test Adapter B' - - $script:networkAdapterACimInstance = New-Object ` - -TypeName CimInstance ` - -ArgumentList 'Win32_NetworkAdapter' | - Add-Member ` - -MemberType NoteProperty ` - -Name Name ` - -Value $script:interfaceAliasA ` - -PassThru | - Add-Member ` - -MemberType NoteProperty ` - -Name NetConnectionID ` - -Value $script:interfaceAliasA ` - -PassThru | - Add-Member ` - -MemberType NoteProperty ` - -Name 'GUID' ` - -Value '{00000000-0000-0000-0000-000000000001}' ` - -PassThru | - Add-Member ` - -MemberType NoteProperty ` - -Name InterfaceIndex ` - -Value 1 ` - -PassThru - - $script:networkAdapterBCimInstance = New-Object ` - -TypeName CimInstance ` - -ArgumentList 'Win32_NetworkAdapter' | - Add-Member ` - -MemberType NoteProperty ` - -Name Name ` - -Value $script:interfaceAliasB ` - -PassThru | - Add-Member ` - -MemberType NoteProperty ` - -Name NetConnectionID ` - -Value $script:interfaceAliasB ` - -PassThru | - Add-Member ` - -MemberType NoteProperty ` - -Name 'GUID' ` - -Value '{00000000-0000-0000-0000-000000000002}' ` - -PassThru | - Add-Member ` - -MemberType NoteProperty ` - -Name InterfaceIndex ` - -Value 2 ` - -PassThru - - $script:mockNetadapterA = { - $script:networkAdapterACimInstance - } - - $script:mockNetadapterB = { - $script:networkAdapterBCimInstance - } - - $script:mockNetadapterMulti = { - @( - $script:networkAdapterACimInstance, - $script:networkAdapterBCimInstance - ) - } - - $script:mockWin32NetworkAdapterConfiguration = { - New-Object ` - -TypeName CimInstance ` - -ArgumentList 'Win32_NetworkAdapterConfiguration' | - Add-Member ` - -MemberType NoteProperty ` - -Name IPEnabled ` - -Value $false ` - -PassThru | - Add-Member ` - -MemberType NoteProperty ` - -Name SettingID ` - -Value '{00000000-0000-0000-0000-000000000001}' ` - -PassThru - } - - $script:mockWin32NetworkAdapterConfigurationIpEnabled = { - New-Object ` - -TypeName CimInstance ` - -ArgumentList 'Win32_NetworkAdapterConfiguration' | - Add-Member ` - -MemberType NoteProperty ` - -Name IPEnabled ` - -Value $true ` - -PassThru - } - - $script:mockInvokeCimMethodError0 = { - @{ - ReturnValue = 0 - } - } - - $script:mockInvokeCimMethodError74 = { - @{ - ReturnValue = 74 - } - } - - $script:getCimInstanceParameterFilter = { - $ClassName -eq 'Win32_NetworkAdapter' -and ` - $Filter -eq 'NetConnectionID="Test Adapter A"' - } - - $script:getCimInstanceMultiParameterFilter = { - $ClassName -eq 'Win32_NetworkAdapter' -and ` - $Filter -eq 'NetConnectionID LIKE "%"' - } - - $script:getCimAssociatedInstanceAParameterFilter = { - $ResultClassName -eq 'Win32_NetworkAdapterConfiguration' -and ` - $InputObject.Name -eq $script:interfaceAliasA - } - - $script:getCimAssociatedInstanceBParameterFilter = { - $ResultClassName -eq 'Win32_NetworkAdapterConfiguration' -and ` - $InputObject.Name -eq $script:interfaceAliasB - } - - # Base registry key path for NetBios settings - $script:hklmInterfacesPath = 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters\Interfaces' - - $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter = { - $Path -eq "$($script:hklmInterfacesPath)\Tcpip_{00000000-0000-0000-0000-000000000001}" -and ` - $Name -eq 'NetbiosOptions' - } - - $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter = { - $Path -eq "$($script:hklmInterfacesPath)\Tcpip_{00000000-0000-0000-0000-000000000002}" -and ` - $Name -eq 'NetbiosOptions' - } - - $script:setItemPropertyValue_NetbiosOptions_Default_ParameterFilter = { - $Path -eq "$($script:hklmInterfacesPath)\Tcpip_{00000000-0000-0000-0000-000000000001}" -and ` - $Name -eq 'NetbiosOptions' -and ` - $Value -eq 0 - } - - $script:setItemPropertyValue_NetbiosOptions_Enable_ParameterFilter = { - $Path -eq "$($script:hklmInterfacesPath)\Tcpip_{00000000-0000-0000-0000-000000000001}" -and ` - $Name -eq 'NetbiosOptions' -and ` - $Value -eq 1 - } - - $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter = { - $Path -eq "$($script:hklmInterfacesPath)\Tcpip_{00000000-0000-0000-0000-000000000001}" -and ` - $Name -eq 'NetbiosOptions' -and ` - $Value -eq 2 - } - - $script:testCases = @( - @{ - Setting = 'Default' - SettingInt = 0 - NotSetting = 'Enable' - }, - @{ - Setting = 'Enable' - SettingInt = 1 - NotSetting = 'Disable' - }, - @{ - Setting = 'Disable' - SettingInt = 2 - NotSetting = 'Default' - } - ) - - Describe 'DSC_NetBios\Get-TargetResource' -Tag 'Get' { - - Context 'When specifying a single network adapter' { - - foreach ($testCase in $script:testCases) - { - Context "When NetBios over TCP/IP is set to '$($testCase.Setting)'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA - Mock -CommandName Get-ItemPropertyValue -MockWith { return $testCase.SettingInt } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - - It 'Should not throw exception' { - { - $script:result = Get-TargetResource -InterfaceAlias $script:interfaceAliasA ` - -Setting $testCase.Setting -Verbose - } | Should -Not -Throw - } - - It 'Returns a hashtable' { - $script:result -is [System.Collections.Hashtable] | Should -BeTrue - } - - It "Setting should return '$($testCase.Setting)'" { - $script:result.Setting | Should -Be $testCase.Setting - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - } - } - } - - Context 'When specifying a wildcard network adapter' { - - Context "When both NetBios over TCP/IP is set to 'Default' on both and Setting is 'Default'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - - It 'Should not throw exception' { - { - $script:result = Get-TargetResource -InterfaceAlias '*' ` - -Setting 'Default' -Verbose - } | Should -Not -Throw - } - - It 'Returns a hashtable' { - $script:result -is [System.Collections.Hashtable] | Should -BeTrue - } - - It "Setting should return 'Default'" { - $script:result.Setting | Should -Be 'Default' - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - } - } - - Context "When both NetBios over TCP/IP is set to 'Enable' on both and Setting is 'Default'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - - It 'Should not throw exception' { - { - $script:result = Get-TargetResource -InterfaceAlias '*' ` - -Setting 'Default' -Verbose - } | Should -Not -Throw - } - - It 'Returns a hashtable' { - $script:result -is [System.Collections.Hashtable] | Should -BeTrue - } - - It "Setting should return 'Enable'" { - $script:result.Setting | Should -Be 'Enable' - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - } - } - - Context "When NetBios over TCP/IP is set to 'Enable' on the first, 'Disable' on the second and Setting is 'Default'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 2 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - - It 'Should not throw exception' { - { - $script:result = Get-TargetResource -InterfaceAlias '*' ` - -Setting 'Default' -Verbose - } | Should -Not -Throw - } - - It 'Returns a hashtable' { - $script:result -is [System.Collections.Hashtable] | Should -BeTrue - } - - It "Setting should return 'Enable'" { - $script:result.Setting | Should -Be 'Enable' - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - } - } - - Context "When NetBios over TCP/IP is set to 'Default' on the first, 'Disable' on the second and Setting is 'Default'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 2 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - - It 'Should not throw exception' { - { - $script:result = Get-TargetResource -InterfaceAlias '*' ` - -Setting 'Default' -Verbose - } | Should -Not -Throw - } - - It 'Returns a hashtable' { - $script:result -is [System.Collections.Hashtable] | Should -BeTrue - } - - It "Setting should return 'Enable'" { - $script:result.Setting | Should -Be 'Disable' - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - } - } - } - - Context 'When interface does not exist' { - Mock -CommandName Get-CimInstance - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.InterfaceNotFoundError -f $script:interfaceAliasA) - - It 'Should throw expected exception' { - { - $script:result = Get-TargetResource -InterfaceAlias $script:interfaceAliasA ` - -Setting 'Default' -Verbose - } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceParameterFilter ` - -Exactly -Times 1 - } - } - } - } - - Describe 'DSC_NetBios\Test-TargetResource' -Tag 'Test' { - - Context 'When specifying a single network adapter' { - - foreach ($testCase in $script:testCases) - { - Context "When NetBios over TCP/IP is set to '$($testCase.Setting)'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA - Mock -CommandName Get-ItemPropertyValue -MockWith { return $testCase.SettingInt } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - - It "Should return true when value '$($testCase.Setting)' is set" { - Test-TargetResource -InterfaceAlias $script:interfaceAliasA ` - -Setting $testCase.Setting -Verbose | Should -BeTrue - } - - It "Should return false when value '$($testCase.NotSetting)' is set" { - Test-TargetResource -InterfaceAlias $script:interfaceAliasA ` - -Setting $testCase.NotSetting -Verbose | Should -BeFalse - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceParameterFilter ` - -Exactly -Times 2 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 2 - } - } - } - - Context 'When specifying a wildcard network adapter' { - - Context "When NetBios set to 'Default' on both and Setting is 'Default'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - - It 'Should return true' { - Test-TargetResource -InterfaceAlias '*' -Setting 'Default' -Verbose | Should -BeTrue - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - } - } - - Context "When NetBios set to 'Default' on both and Setting is 'Enable'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - - It 'Should return false' { - Test-TargetResource -InterfaceAlias '*' -Setting 'Default' -Verbose | Should -BeFalse - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - } - } - - Context "When NetBios set to 'Default' on first and 'Enable' on second and Setting is 'Enable'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - - It 'Should return false' { - Test-TargetResource -InterfaceAlias '*' ` - -Setting 'Default' -Verbose | Should -BeFalse - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - } - } - } - - Context 'When interface does not exist' { - Mock -CommandName Get-CimInstance - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.InterfaceNotFoundError -f $script:interfaceAliasA) - - It 'Should throw expected exception' { - { - Test-TargetResource -InterfaceAlias $script:interfaceAliasA ` - -Setting 'Enable' -Verbose - } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 1 - } - } - } - } - - Describe 'DSC_NetBios\Set-TargetResource' -Tag 'Set' { - - Context 'When specifying a single network adapter' { - - foreach ($testCase in $script:testCases) - { - Context "When NetBios over TCP/IP should be set to '$($testCase.Setting)' and IPEnabled=True" { - $setItemPropertyParameterFilter = (Get-Variable ` - -Name "setItemPropertyValue_NetbiosOptions_$($testCase.Setting)_ParameterFilter" ` - -Scope Script).Value - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled - Mock -CommandName Set-ItemProperty ` - -ParameterFilter $setItemPropertyParameterFilter - Mock -CommandName Invoke-CimMethod ` - -MockWith $script:mockInvokeCimMethodError0 - - It 'Should not throw exception' { - { - Set-TargetResource -InterfaceAlias $script:interfaceAliasA ` - -Setting $testCase.Setting -Verbose - } | Should -Not -Throw - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-CimAssociatedInstance ` - -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Set-ItemProperty ` - -ParameterFilter $setItemPropertyParameterFilter ` - -Exactly -Times 0 - Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 - } - } - } - - foreach ($testCase in $script:testCases) - { - Context "When NetBios over TCP/IP should be set to '$($testCase.Setting)' and IPEnabled=False" { - $setItemPropertyParameterFilter = (Get-Variable ` - -Name "setItemPropertyValue_NetbiosOptions_$($testCase.Setting)_ParameterFilter" ` - -Scope Script).Value - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfiguration - Mock -CommandName Set-ItemProperty ` - -ParameterFilter $setItemPropertyParameterFilter - Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 - - It 'Should not throw exception' { - { - Set-TargetResource -InterfaceAlias $script:interfaceAliasA ` - -Setting $testCase.Setting -Verbose - } | Should -Not -Throw - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-CimAssociatedInstance ` - -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Set-ItemProperty ` - -ParameterFilter $setItemPropertyParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 0 - } - } - } - - Context 'When specifying a wildcard network adapter' { - - Context "When all Interfaces are IPEnabled and NetBios set to 'Default' on both and Setting is 'Disable'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 - Mock -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter - - It 'Should not throw exception' { - { - Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose - } | Should -Not -Throw - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 2 - Assert-MockCalled -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` - -Exactly -Times 0 - } - } - - Context "When all Interfaces are NOT IPEnabled and NetBios set to 'Default' on both and Setting is 'Disable'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfiguration - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 - Mock -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter - - It 'Should not throw exception' { - { - Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose - } | Should -Not -Throw - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 0 - Assert-MockCalled -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` - -Exactly -Times 2 - } - } - - Context "When first Interface is IPEnabled and NetBios set to 'Default' on both and Setting is 'Disable'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled ` - -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfiguration ` - -ParameterFilter $script:getCimAssociatedInstanceBParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - Mock -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter - Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 - - It 'Should not throw exception' { - { - Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose - } | Should -Not -Throw - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 - Assert-MockCalled -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` - -Exactly -Times 1 - } - } - - Context "When second Interface is IPEnabled and NetBios set to 'Default' on both and Setting is 'Disable'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfiguration ` - -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled ` - -ParameterFilter $script:getCimAssociatedInstanceBParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 - Mock -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter - - It 'Should not throw exception' { - { - Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose - } | Should -Not -Throw - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 - Assert-MockCalled -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` - -Exactly -Times 1 - } - } - - Context "When first Interface is IPEnabled and NetBios set to 'Default' second Interface Netbios set to 'Disable' and Setting is 'Disable'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled ` - -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfiguration ` - -ParameterFilter $script:getCimAssociatedInstanceBParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 2 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 - Mock -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter - - It 'Should not throw exception' { - { - Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose - } | Should -Not -Throw - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 - Assert-MockCalled -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` - -Exactly -Times 0 - } - } - - Context "When first Interface is IPEnabled and NetBios set to 'Disable' second Interface Netbios set to 'Default' and Setting is 'Disable'" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled ` - -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfiguration ` - -ParameterFilter $script:getCimAssociatedInstanceBParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 2 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter - Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 - Mock -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter - - It 'Should not throw exception' { - { - Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose - } | Should -Not -Throw - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance ` - -ParameterFilter $script:getCimInstanceMultiParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 0 - Assert-MockCalled -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` - -Exactly -Times 1 - } - } - } - - Context 'When interface does not exist' { - Mock -CommandName Get-CimInstance - Mock -CommandName Get-CimAssociatedInstance - Mock -CommandName Invoke-CimMethod - Mock -CommandName Set-ItemProperty - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.InterfaceNotFoundError -f $script:interfaceAliasA) - - It 'Should throw expected exception' { - { - Set-TargetResource -InterfaceAlias $script:interfaceAliasA -Setting 'Enable' -Verbose - } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 1 - Assert-MockCalled -CommandName Get-CimAssociatedInstance -Exactly -Times 0 - Assert-MockCalled -CommandName Set-ItemProperty -Exactly -Times 0 - Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 0 - } - } - } - } - - Describe 'DSC_NetBios\Get-NetAdapterNetbiosOptionsFromRegistry' { - - foreach ($testCase in $script:testCases) - { - Context "When interface NetBios is '$($testCase.Setting)'" { - Mock -CommandName Get-ItemPropertyValue -MockWith { return $testCase.SettingInt } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - - It "Should return true when value '$($testCase.Setting)' is set" { - $Result = Get-NetAdapterNetbiosOptionsFromRegistry ` - -NetworkAdapterGUID $script:networkAdapterACimInstance.GUID ` - -Setting $testCase.Setting - $Result -eq $testCase.Setting | Should -BeTrue - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - } - } - } - - Context 'When interface Netbios setting missing from registry' { - Mock -CommandName Get-ItemPropertyValue -MockWith { return $null } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - - It 'Should return true' { - $Result = Get-NetAdapterNetbiosOptionsFromRegistry ` - -NetworkAdapterGUID $script:networkAdapterACimInstance.GUID ` - -Setting 'Enable' - $Result -eq 'Default' | Should -BeTrue - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - } - } - - Context 'When Netbios registry setting invalid number' { - Mock -CommandName Get-ItemPropertyValue -MockWith { return 5 } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - - It 'Should evaluate true' { - $Result = Get-NetAdapterNetbiosOptionsFromRegistry ` - -NetworkAdapterGUID $script:networkAdapterACimInstance.GUID ` - -Setting 'Enable' - $Result -eq 'Default' | Should -BeTrue - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - } - } - - Context 'When Netbios registry setting invalid letters' { - Mock -CommandName Get-ItemPropertyValue -MockWith { return 'invalid' } ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter - - It 'Should evaluate true' { - $Result = Get-NetAdapterNetbiosOptionsFromRegistry ` - -NetworkAdapterGUID $script:networkAdapterACimInstance.GUID ` - -Setting 'Enable' - $Result -eq 'Default' | Should -BeTrue - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-ItemPropertyValue ` - -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` - -Exactly -Times 1 - } - } - } - - Describe 'DSC_NetBios\Set-NetAdapterNetbiosOptions' { - - Context "When NetBios over TCP/IP should be set to 'Default' and IPEnabled=True" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled - Mock -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Default_ParameterFilter - Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 - - It 'Should not throw exception' { - { - $netAdapter = Get-CimInstance ` - -ClassName Win32_NetworkAdapter ` - -Filter 'NetConnectionID="$($script:interfaceAliasA)"' - - $netAdapterConfig = $netAdapter | Get-CimAssociatedInstance ` - -ResultClassName Win32_NetworkAdapterConfiguration ` - -ErrorAction Stop - - Set-NetAdapterNetbiosOptions ` - -NetworkAdapterObject $netAdapterConfig ` - -InterfaceAlias $script:interfaceAliasA ` - -Setting 'Default' -Verbose - } | Should -Not -Throw - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Default_ParameterFilter ` - -Exactly -Times 0 - Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 - Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 1 - Assert-MockCalled -CommandName Get-CimAssociatedInstance -Exactly -Times 1 - } - } - - Context "When NetBios over TCP/IP should be set to 'Default' and IPEnabled=False" { - Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA - Mock -CommandName Get-CimAssociatedInstance ` - -MockWith $script:mockWin32NetworkAdapterConfiguration - Mock -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Default_ParameterFilter - Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 - - It 'Should not throw exception' { - { - $netAdapter = Get-CimInstance ` - -ClassName Win32_NetworkAdapter ` - -Filter 'NetConnectionID="$($script:interfaceAliasA)"' - - $netAdapterConfig = $netAdapter | Get-CimAssociatedInstance ` - -ResultClassName Win32_NetworkAdapterConfiguration ` - -ErrorAction Stop - - Set-NetAdapterNetbiosOptions ` - -NetworkAdapterObject $netAdapterConfig ` - -InterfaceAlias $script:interfaceAliasA ` - -Setting 'Default' -Verbose - } | Should -Not -Throw - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Set-ItemProperty ` - -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Default_ParameterFilter ` - -Exactly -Times 1 - Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 0 - Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 1 - Assert-MockCalled -CommandName Get-CimAssociatedInstance -Exactly -Times 1 - } - } - } - } -} -finally -{ - Invoke-TestCleanup -} +# $script:dscModuleName = 'NetworkingDsc' +# $script:dscResourceName = 'DSC_NetBios' + +# function Invoke-TestSetup +# { +# try +# { +# Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' +# } +# catch [System.IO.FileNotFoundException] +# { +# throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' +# } + +# $script:testEnvironment = Initialize-TestEnvironment ` +# -DSCModuleName $script:dscModuleName ` +# -DSCResourceName $script:dscResourceName ` +# -ResourceType 'Mof' ` +# -TestType 'Unit' + +# Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') +# } + +# function Invoke-TestCleanup +# { +# Restore-TestEnvironment -TestEnvironment $script:testEnvironment +# } + +# Invoke-TestSetup + +# # Begin Testing +# try +# { +# InModuleScope $script:dscResourceName { +# $script:interfaceAliasA = 'Test Adapter A' +# $script:interfaceAliasB = 'Test Adapter B' + +# $script:networkAdapterACimInstance = New-Object ` +# -TypeName CimInstance ` +# -ArgumentList 'Win32_NetworkAdapter' | +# Add-Member ` +# -MemberType NoteProperty ` +# -Name Name ` +# -Value $script:interfaceAliasA ` +# -PassThru | +# Add-Member ` +# -MemberType NoteProperty ` +# -Name NetConnectionID ` +# -Value $script:interfaceAliasA ` +# -PassThru | +# Add-Member ` +# -MemberType NoteProperty ` +# -Name 'GUID' ` +# -Value '{00000000-0000-0000-0000-000000000001}' ` +# -PassThru | +# Add-Member ` +# -MemberType NoteProperty ` +# -Name InterfaceIndex ` +# -Value 1 ` +# -PassThru + +# $script:networkAdapterBCimInstance = New-Object ` +# -TypeName CimInstance ` +# -ArgumentList 'Win32_NetworkAdapter' | +# Add-Member ` +# -MemberType NoteProperty ` +# -Name Name ` +# -Value $script:interfaceAliasB ` +# -PassThru | +# Add-Member ` +# -MemberType NoteProperty ` +# -Name NetConnectionID ` +# -Value $script:interfaceAliasB ` +# -PassThru | +# Add-Member ` +# -MemberType NoteProperty ` +# -Name 'GUID' ` +# -Value '{00000000-0000-0000-0000-000000000002}' ` +# -PassThru | +# Add-Member ` +# -MemberType NoteProperty ` +# -Name InterfaceIndex ` +# -Value 2 ` +# -PassThru + +# $script:mockNetadapterA = { +# $script:networkAdapterACimInstance +# } + +# $script:mockNetadapterB = { +# $script:networkAdapterBCimInstance +# } + +# $script:mockNetadapterMulti = { +# @( +# $script:networkAdapterACimInstance, +# $script:networkAdapterBCimInstance +# ) +# } + +# $script:mockWin32NetworkAdapterConfiguration = { +# New-Object ` +# -TypeName CimInstance ` +# -ArgumentList 'Win32_NetworkAdapterConfiguration' | +# Add-Member ` +# -MemberType NoteProperty ` +# -Name IPEnabled ` +# -Value $false ` +# -PassThru | +# Add-Member ` +# -MemberType NoteProperty ` +# -Name SettingID ` +# -Value '{00000000-0000-0000-0000-000000000001}' ` +# -PassThru +# } + +# $script:mockWin32NetworkAdapterConfigurationIpEnabled = { +# New-Object ` +# -TypeName CimInstance ` +# -ArgumentList 'Win32_NetworkAdapterConfiguration' | +# Add-Member ` +# -MemberType NoteProperty ` +# -Name IPEnabled ` +# -Value $true ` +# -PassThru +# } + +# $script:mockInvokeCimMethodError0 = { +# @{ +# ReturnValue = 0 +# } +# } + +# $script:mockInvokeCimMethodError74 = { +# @{ +# ReturnValue = 74 +# } +# } + +# $script:getCimInstanceParameterFilter = { +# $ClassName -eq 'Win32_NetworkAdapter' -and ` +# $Filter -eq 'NetConnectionID="Test Adapter A"' +# } + +# $script:getCimInstanceMultiParameterFilter = { +# $ClassName -eq 'Win32_NetworkAdapter' -and ` +# $Filter -eq 'NetConnectionID LIKE "%"' +# } + +# $script:getCimAssociatedInstanceAParameterFilter = { +# $ResultClassName -eq 'Win32_NetworkAdapterConfiguration' -and ` +# $InputObject.Name -eq $script:interfaceAliasA +# } + +# $script:getCimAssociatedInstanceBParameterFilter = { +# $ResultClassName -eq 'Win32_NetworkAdapterConfiguration' -and ` +# $InputObject.Name -eq $script:interfaceAliasB +# } + +# # Base registry key path for NetBios settings +# $script:hklmInterfacesPath = 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters\Interfaces' + +# $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter = { +# $Path -eq "$($script:hklmInterfacesPath)\Tcpip_{00000000-0000-0000-0000-000000000001}" -and ` +# $Name -eq 'NetbiosOptions' +# } + +# $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter = { +# $Path -eq "$($script:hklmInterfacesPath)\Tcpip_{00000000-0000-0000-0000-000000000002}" -and ` +# $Name -eq 'NetbiosOptions' +# } + +# $script:setItemPropertyValue_NetbiosOptions_Default_ParameterFilter = { +# $Path -eq "$($script:hklmInterfacesPath)\Tcpip_{00000000-0000-0000-0000-000000000001}" -and ` +# $Name -eq 'NetbiosOptions' -and ` +# $Value -eq 0 +# } + +# $script:setItemPropertyValue_NetbiosOptions_Enable_ParameterFilter = { +# $Path -eq "$($script:hklmInterfacesPath)\Tcpip_{00000000-0000-0000-0000-000000000001}" -and ` +# $Name -eq 'NetbiosOptions' -and ` +# $Value -eq 1 +# } + +# $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter = { +# $Path -eq "$($script:hklmInterfacesPath)\Tcpip_{00000000-0000-0000-0000-000000000001}" -and ` +# $Name -eq 'NetbiosOptions' -and ` +# $Value -eq 2 +# } + +# $script:testCases = @( +# @{ +# Setting = 'Default' +# SettingInt = 0 +# NotSetting = 'Enable' +# }, +# @{ +# Setting = 'Enable' +# SettingInt = 1 +# NotSetting = 'Disable' +# }, +# @{ +# Setting = 'Disable' +# SettingInt = 2 +# NotSetting = 'Default' +# } +# ) + +# Describe 'DSC_NetBios\Get-TargetResource' -Tag 'Get' { + +# Context 'When specifying a single network adapter' { + +# foreach ($testCase in $script:testCases) +# { +# Context "When NetBios over TCP/IP is set to '$($testCase.Setting)'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA +# Mock -CommandName Get-ItemPropertyValue -MockWith { return $testCase.SettingInt } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter + +# It 'Should not throw exception' { +# { +# $script:result = Get-TargetResource -InterfaceAlias $script:interfaceAliasA ` +# -Setting $testCase.Setting -Verbose +# } | Should -Not -Throw +# } + +# It 'Returns a hashtable' { +# $script:result -is [System.Collections.Hashtable] | Should -BeTrue +# } + +# It "Setting should return '$($testCase.Setting)'" { +# $script:result.Setting | Should -Be $testCase.Setting +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# } +# } +# } + +# Context 'When specifying a wildcard network adapter' { + +# Context "When both NetBios over TCP/IP is set to 'Default' on both and Setting is 'Default'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter + +# It 'Should not throw exception' { +# { +# $script:result = Get-TargetResource -InterfaceAlias '*' ` +# -Setting 'Default' -Verbose +# } | Should -Not -Throw +# } + +# It 'Returns a hashtable' { +# $script:result -is [System.Collections.Hashtable] | Should -BeTrue +# } + +# It "Setting should return 'Default'" { +# $script:result.Setting | Should -Be 'Default' +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# } +# } + +# Context "When both NetBios over TCP/IP is set to 'Enable' on both and Setting is 'Default'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter + +# It 'Should not throw exception' { +# { +# $script:result = Get-TargetResource -InterfaceAlias '*' ` +# -Setting 'Default' -Verbose +# } | Should -Not -Throw +# } + +# It 'Returns a hashtable' { +# $script:result -is [System.Collections.Hashtable] | Should -BeTrue +# } + +# It "Setting should return 'Enable'" { +# $script:result.Setting | Should -Be 'Enable' +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# } +# } + +# Context "When NetBios over TCP/IP is set to 'Enable' on the first, 'Disable' on the second and Setting is 'Default'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 2 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter + +# It 'Should not throw exception' { +# { +# $script:result = Get-TargetResource -InterfaceAlias '*' ` +# -Setting 'Default' -Verbose +# } | Should -Not -Throw +# } + +# It 'Returns a hashtable' { +# $script:result -is [System.Collections.Hashtable] | Should -BeTrue +# } + +# It "Setting should return 'Enable'" { +# $script:result.Setting | Should -Be 'Enable' +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# } +# } + +# Context "When NetBios over TCP/IP is set to 'Default' on the first, 'Disable' on the second and Setting is 'Default'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 2 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter + +# It 'Should not throw exception' { +# { +# $script:result = Get-TargetResource -InterfaceAlias '*' ` +# -Setting 'Default' -Verbose +# } | Should -Not -Throw +# } + +# It 'Returns a hashtable' { +# $script:result -is [System.Collections.Hashtable] | Should -BeTrue +# } + +# It "Setting should return 'Enable'" { +# $script:result.Setting | Should -Be 'Disable' +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# } +# } +# } + +# Context 'When interface does not exist' { +# Mock -CommandName Get-CimInstance + +# $errorRecord = Get-InvalidOperationRecord ` +# -Message ($script:localizedData.InterfaceNotFoundError -f $script:interfaceAliasA) + +# It 'Should throw expected exception' { +# { +# $script:result = Get-TargetResource -InterfaceAlias $script:interfaceAliasA ` +# -Setting 'Default' -Verbose +# } | Should -Throw $errorRecord +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceParameterFilter ` +# -Exactly -Times 1 +# } +# } +# } +# } + +# Describe 'DSC_NetBios\Test-TargetResource' -Tag 'Test' { + +# Context 'When specifying a single network adapter' { + +# foreach ($testCase in $script:testCases) +# { +# Context "When NetBios over TCP/IP is set to '$($testCase.Setting)'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA +# Mock -CommandName Get-ItemPropertyValue -MockWith { return $testCase.SettingInt } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter + +# It "Should return true when value '$($testCase.Setting)' is set" { +# Test-TargetResource -InterfaceAlias $script:interfaceAliasA ` +# -Setting $testCase.Setting -Verbose | Should -BeTrue +# } + +# It "Should return false when value '$($testCase.NotSetting)' is set" { +# Test-TargetResource -InterfaceAlias $script:interfaceAliasA ` +# -Setting $testCase.NotSetting -Verbose | Should -BeFalse +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceParameterFilter ` +# -Exactly -Times 2 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 2 +# } +# } +# } + +# Context 'When specifying a wildcard network adapter' { + +# Context "When NetBios set to 'Default' on both and Setting is 'Default'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter + +# It 'Should return true' { +# Test-TargetResource -InterfaceAlias '*' -Setting 'Default' -Verbose | Should -BeTrue +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# } +# } + +# Context "When NetBios set to 'Default' on both and Setting is 'Enable'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter + +# It 'Should return false' { +# Test-TargetResource -InterfaceAlias '*' -Setting 'Default' -Verbose | Should -BeFalse +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# } +# } + +# Context "When NetBios set to 'Default' on first and 'Enable' on second and Setting is 'Enable'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 1 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter + +# It 'Should return false' { +# Test-TargetResource -InterfaceAlias '*' ` +# -Setting 'Default' -Verbose | Should -BeFalse +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# } +# } +# } + +# Context 'When interface does not exist' { +# Mock -CommandName Get-CimInstance + +# $errorRecord = Get-InvalidOperationRecord ` +# -Message ($script:localizedData.InterfaceNotFoundError -f $script:interfaceAliasA) + +# It 'Should throw expected exception' { +# { +# Test-TargetResource -InterfaceAlias $script:interfaceAliasA ` +# -Setting 'Enable' -Verbose +# } | Should -Throw $errorRecord +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 1 +# } +# } +# } +# } + +# Describe 'DSC_NetBios\Set-TargetResource' -Tag 'Set' { + +# Context 'When specifying a single network adapter' { + +# foreach ($testCase in $script:testCases) +# { +# Context "When NetBios over TCP/IP should be set to '$($testCase.Setting)' and IPEnabled=True" { +# $setItemPropertyParameterFilter = (Get-Variable ` +# -Name "setItemPropertyValue_NetbiosOptions_$($testCase.Setting)_ParameterFilter" ` +# -Scope Script).Value +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled +# Mock -CommandName Set-ItemProperty ` +# -ParameterFilter $setItemPropertyParameterFilter +# Mock -CommandName Invoke-CimMethod ` +# -MockWith $script:mockInvokeCimMethodError0 + +# It 'Should not throw exception' { +# { +# Set-TargetResource -InterfaceAlias $script:interfaceAliasA ` +# -Setting $testCase.Setting -Verbose +# } | Should -Not -Throw +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-CimAssociatedInstance ` +# -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Set-ItemProperty ` +# -ParameterFilter $setItemPropertyParameterFilter ` +# -Exactly -Times 0 +# Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 +# } +# } +# } + +# foreach ($testCase in $script:testCases) +# { +# Context "When NetBios over TCP/IP should be set to '$($testCase.Setting)' and IPEnabled=False" { +# $setItemPropertyParameterFilter = (Get-Variable ` +# -Name "setItemPropertyValue_NetbiosOptions_$($testCase.Setting)_ParameterFilter" ` +# -Scope Script).Value +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfiguration +# Mock -CommandName Set-ItemProperty ` +# -ParameterFilter $setItemPropertyParameterFilter +# Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 + +# It 'Should not throw exception' { +# { +# Set-TargetResource -InterfaceAlias $script:interfaceAliasA ` +# -Setting $testCase.Setting -Verbose +# } | Should -Not -Throw +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-CimAssociatedInstance ` +# -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Set-ItemProperty ` +# -ParameterFilter $setItemPropertyParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 0 +# } +# } +# } + +# Context 'When specifying a wildcard network adapter' { + +# Context "When all Interfaces are IPEnabled and NetBios set to 'Default' on both and Setting is 'Disable'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter +# Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 +# Mock -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter + +# It 'Should not throw exception' { +# { +# Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose +# } | Should -Not -Throw +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 2 +# Assert-MockCalled -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` +# -Exactly -Times 0 +# } +# } + +# Context "When all Interfaces are NOT IPEnabled and NetBios set to 'Default' on both and Setting is 'Disable'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfiguration +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter +# Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 +# Mock -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter + +# It 'Should not throw exception' { +# { +# Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose +# } | Should -Not -Throw +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 0 +# Assert-MockCalled -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` +# -Exactly -Times 2 +# } +# } + +# Context "When first Interface is IPEnabled and NetBios set to 'Default' on both and Setting is 'Disable'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled ` +# -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfiguration ` +# -ParameterFilter $script:getCimAssociatedInstanceBParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter +# Mock -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter +# Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 + +# It 'Should not throw exception' { +# { +# Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose +# } | Should -Not -Throw +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 +# Assert-MockCalled -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` +# -Exactly -Times 1 +# } +# } + +# Context "When second Interface is IPEnabled and NetBios set to 'Default' on both and Setting is 'Disable'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfiguration ` +# -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled ` +# -ParameterFilter $script:getCimAssociatedInstanceBParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter +# Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 +# Mock -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter + +# It 'Should not throw exception' { +# { +# Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose +# } | Should -Not -Throw +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 +# Assert-MockCalled -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` +# -Exactly -Times 1 +# } +# } + +# Context "When first Interface is IPEnabled and NetBios set to 'Default' second Interface Netbios set to 'Disable' and Setting is 'Disable'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled ` +# -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfiguration ` +# -ParameterFilter $script:getCimAssociatedInstanceBParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 2 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter +# Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 +# Mock -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter + +# It 'Should not throw exception' { +# { +# Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose +# } | Should -Not -Throw +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 +# Assert-MockCalled -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` +# -Exactly -Times 0 +# } +# } + +# Context "When first Interface is IPEnabled and NetBios set to 'Disable' second Interface Netbios set to 'Default' and Setting is 'Disable'" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterMulti +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled ` +# -ParameterFilter $script:getCimAssociatedInstanceAParameterFilter +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfiguration ` +# -ParameterFilter $script:getCimAssociatedInstanceBParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 2 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 0 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter +# Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 +# Mock -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter + +# It 'Should not throw exception' { +# { +# Set-TargetResource -InterfaceAlias '*' -Setting 'Disable' -Verbose +# } | Should -Not -Throw +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance ` +# -ParameterFilter $script:getCimInstanceMultiParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_Two_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 0 +# Assert-MockCalled -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Disable_ParameterFilter ` +# -Exactly -Times 1 +# } +# } +# } + +# Context 'When interface does not exist' { +# Mock -CommandName Get-CimInstance +# Mock -CommandName Get-CimAssociatedInstance +# Mock -CommandName Invoke-CimMethod +# Mock -CommandName Set-ItemProperty + +# $errorRecord = Get-InvalidOperationRecord ` +# -Message ($script:localizedData.InterfaceNotFoundError -f $script:interfaceAliasA) + +# It 'Should throw expected exception' { +# { +# Set-TargetResource -InterfaceAlias $script:interfaceAliasA -Setting 'Enable' -Verbose +# } | Should -Throw $errorRecord +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-CimAssociatedInstance -Exactly -Times 0 +# Assert-MockCalled -CommandName Set-ItemProperty -Exactly -Times 0 +# Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 0 +# } +# } +# } +# } + +# Describe 'DSC_NetBios\Get-NetAdapterNetbiosOptionsFromRegistry' { + +# foreach ($testCase in $script:testCases) +# { +# Context "When interface NetBios is '$($testCase.Setting)'" { +# Mock -CommandName Get-ItemPropertyValue -MockWith { return $testCase.SettingInt } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter + +# It "Should return true when value '$($testCase.Setting)' is set" { +# $Result = Get-NetAdapterNetbiosOptionsFromRegistry ` +# -NetworkAdapterGUID $script:networkAdapterACimInstance.GUID ` +# -Setting $testCase.Setting +# $Result -eq $testCase.Setting | Should -BeTrue +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# } +# } +# } + +# Context 'When interface Netbios setting missing from registry' { +# Mock -CommandName Get-ItemPropertyValue -MockWith { return $null } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter + +# It 'Should return true' { +# $Result = Get-NetAdapterNetbiosOptionsFromRegistry ` +# -NetworkAdapterGUID $script:networkAdapterACimInstance.GUID ` +# -Setting 'Enable' +# $Result -eq 'Default' | Should -BeTrue +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# } +# } + +# Context 'When Netbios registry setting invalid number' { +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 5 } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter + +# It 'Should evaluate true' { +# $Result = Get-NetAdapterNetbiosOptionsFromRegistry ` +# -NetworkAdapterGUID $script:networkAdapterACimInstance.GUID ` +# -Setting 'Enable' +# $Result -eq 'Default' | Should -BeTrue +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# } +# } + +# Context 'When Netbios registry setting invalid letters' { +# Mock -CommandName Get-ItemPropertyValue -MockWith { return 'invalid' } ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter + +# It 'Should evaluate true' { +# $Result = Get-NetAdapterNetbiosOptionsFromRegistry ` +# -NetworkAdapterGUID $script:networkAdapterACimInstance.GUID ` +# -Setting 'Enable' +# $Result -eq 'Default' | Should -BeTrue +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Get-ItemPropertyValue ` +# -ParameterFilter $script:getItemPropertyValue_NetbiosOptions_One_ParameterFilter ` +# -Exactly -Times 1 +# } +# } +# } + +# Describe 'DSC_NetBios\Set-NetAdapterNetbiosOptions' { + +# Context "When NetBios over TCP/IP should be set to 'Default' and IPEnabled=True" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfigurationIpEnabled +# Mock -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Default_ParameterFilter +# Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 + +# It 'Should not throw exception' { +# { +# $netAdapter = Get-CimInstance ` +# -ClassName Win32_NetworkAdapter ` +# -Filter 'NetConnectionID="$($script:interfaceAliasA)"' + +# $netAdapterConfig = $netAdapter | Get-CimAssociatedInstance ` +# -ResultClassName Win32_NetworkAdapterConfiguration ` +# -ErrorAction Stop + +# Set-NetAdapterNetbiosOptions ` +# -NetworkAdapterObject $netAdapterConfig ` +# -InterfaceAlias $script:interfaceAliasA ` +# -Setting 'Default' -Verbose +# } | Should -Not -Throw +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Default_ParameterFilter ` +# -Exactly -Times 0 +# Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-CimAssociatedInstance -Exactly -Times 1 +# } +# } + +# Context "When NetBios over TCP/IP should be set to 'Default' and IPEnabled=False" { +# Mock -CommandName Get-CimInstance -MockWith $script:mockNetadapterA +# Mock -CommandName Get-CimAssociatedInstance ` +# -MockWith $script:mockWin32NetworkAdapterConfiguration +# Mock -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Default_ParameterFilter +# Mock -CommandName Invoke-CimMethod -MockWith $script:mockInvokeCimMethodError0 + +# It 'Should not throw exception' { +# { +# $netAdapter = Get-CimInstance ` +# -ClassName Win32_NetworkAdapter ` +# -Filter 'NetConnectionID="$($script:interfaceAliasA)"' + +# $netAdapterConfig = $netAdapter | Get-CimAssociatedInstance ` +# -ResultClassName Win32_NetworkAdapterConfiguration ` +# -ErrorAction Stop + +# Set-NetAdapterNetbiosOptions ` +# -NetworkAdapterObject $netAdapterConfig ` +# -InterfaceAlias $script:interfaceAliasA ` +# -Setting 'Default' -Verbose +# } | Should -Not -Throw +# } + +# It 'Should call expected mocks' { +# Assert-MockCalled -CommandName Set-ItemProperty ` +# -ParameterFilter $script:setItemPropertyValue_NetbiosOptions_Default_ParameterFilter ` +# -Exactly -Times 1 +# Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 0 +# Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 1 +# Assert-MockCalled -CommandName Get-CimAssociatedInstance -Exactly -Times 1 +# } +# } +# } +# } +# } +# finally +# { +# Invoke-TestCleanup +# } diff --git a/tests/Unit/DSC_NetConnectionProfile.Tests.ps1 b/tests/Unit/DSC_NetConnectionProfile.Tests.ps1 new file mode 100644 index 00000000..91d1c64a --- /dev/null +++ b/tests/Unit/DSC_NetConnectionProfile.Tests.ps1 @@ -0,0 +1,333 @@ +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetConnectionProfile' + + $script:testEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:dscModuleName ` + -DSCResourceName $script:dscResourceName ` + -ResourceType 'Mof' ` + -TestType 'Unit' + + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName +} + +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} + +Describe 'DSC_NetConnectionProfile\Get-TargetResource' -Tag 'Get' { + BeforeAll { + Mock -CommandName Get-NetConnectionProfile { + @{ + InterfaceAlias = 'TestAdapter' + NetworkCategory = 'Public' + IPv4Connectivity = 'Internet' + IPv6Connectivity = 'Internet' + } + } + } + + It 'Should return the correct values' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $mockNetConnectionProfileAll = @{ + InterfaceAlias = 'TestAdapter' + NetworkCategory = 'Public' + IPv4Connectivity = 'Internet' + IPv6Connectivity = 'Internet' + } + + $result = Get-TargetResource -InterfaceAlias 'TestAdapter' + $result.InterfaceAlias | Should -Be $mockNetConnectionProfileAll.InterfaceAlias + $result.NetworkCategory | Should -Be $mockNetConnectionProfileAll.NetworkCategory + $result.IPv4Connectivity | Should -Be $mockNetConnectionProfileAll.IPv4Connectivity + $result.IPv6Connectivity | Should -Be $mockNetConnectionProfileAll.IPv6Connectivity + } + } +} + +Describe 'DSC_NetConnectionProfile\Test-TargetResource' -Tag 'Test' { + BeforeAll { + Mock -CommandName Get-TargetResource -MockWith { + @{ + InterfaceAlias = 'TestAdapter' + NetworkCategory = 'Public' + IPv4Connectivity = 'Internet' + IPv6Connectivity = 'Internet' + } + } + + Mock -CommandName Assert-ResourceProperty + } + + Context 'NetworkCategory matches' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testNetworkCategoryMatches = @{ + InterfaceAlias = 'TestAdapter' + NetworkCategory = 'Public' + } + + Test-TargetResource @testNetworkCategoryMatches | Should -BeTrue + } + } + } + + Context 'NetworkCategory does not match' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testNetworkCategoryNoMatches = @{ + InterfaceAlias = 'TestAdapter' + NetworkCategory = 'Private' + } + + Test-TargetResource @testNetworkCategoryNoMatches | Should -BeFalse + } + } + } + + Context 'IPv4Connectivity matches' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv4ConnectivityMatches = @{ + InterfaceAlias = 'TestAdapter' + IPv4Connectivity = 'Internet' + } + + Test-TargetResource @testIPv4ConnectivityMatches | Should -BeTrue + } + } + } + + Context 'IPv4Connectivity does not match' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv4ConnectivityNoMatches = @{ + InterfaceAlias = 'TestAdapter' + IPv4Connectivity = 'Disconnected' + } + + Test-TargetResource @testIPv4ConnectivityNoMatches | Should -BeFalse + } + } + } + + Context 'IPv6Connectivity matches' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv6ConnectivityMatches = @{ + InterfaceAlias = 'TestAdapter' + IPv6Connectivity = 'Internet' + } + + Test-TargetResource @testIPv6ConnectivityMatches | Should -BeTrue + } + } + } + + Context 'IPv6Connectivity does not match' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv6ConnectivityNoMatches = @{ + InterfaceAlias = 'TestAdapter' + IPv6Connectivity = 'Disconnected' + } + + Test-TargetResource @testIPv6ConnectivityNoMatches | Should -BeFalse + } + } + } +} + +Describe 'DSC_NetConnectionProfile\Set-TargetResource' -Tag 'Set' { + BeforeAll { + Mock -CommandName Set-NetConnectionProfile + Mock -CommandName Assert-ResourceProperty + } + + It 'Should call all the mocks' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testNetworkCategoryMatches = @{ + InterfaceAlias = 'TestAdapter' + NetworkCategory = 'Public' + } + + Set-TargetResource @testNetworkCategoryMatches + } + + Should -Invoke -CommandName Set-NetConnectionProfile + } +} + +Describe 'DSC_NetConnectionProfile\Assert-ResourceProperty' { + Context 'Invoking with bad interface alias' { + BeforeAll { + Mock -CommandName Get-NetAdapter + } + + It 'Should throw testValidInterfaceAliasOnlyPassed exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testValidInterfaceAliasOnlyPassed = @{ + InterfaceAlias = 'TestAdapter' + } + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.InterfaceNotAvailableError -f $testValidInterfaceAliasOnlyPassed.InterfaceAlias) + + + { Assert-ResourceProperty @testValidInterfaceAliasOnlyPassed } | Should -Throw $errorRecord + } + } + } + + Context 'Invoking with valid interface alias but all empty parameters' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'TestAdapter' + } + } + } + + It 'Should not ParameterCombinationError exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.ParameterCombinationError) + + $testValidInterfaceAliasOnlyPassed = @{ + InterfaceAlias = 'TestAdapter' + } + + { Assert-ResourceProperty @testValidInterfaceAliasOnlyPassed } | Should -Throw $errorRecord + } + } + } + + Context 'Invoking with valid interface alias and one NetworkCategory' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'TestAdapter' + } + } + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testNetworkCategoryMatches = @{ + InterfaceAlias = 'TestAdapter' + NetworkCategory = 'Public' + } + + { Assert-ResourceProperty @testNetworkCategoryMatches } | Should -Not -Throw + } + } + } + + Context 'Invoking with valid interface alias and one IPv4Connectivity' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'TestAdapter' + } + } + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv4ConnectivityMatches = @{ + InterfaceAlias = 'TestAdapter' + IPv4Connectivity = 'Internet' + } + + { Assert-ResourceProperty @testIPv4ConnectivityMatches } | Should -Not -Throw + } + } + } + + Context 'Invoking with valid interface alias and one IPv6Connectivity' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { + @{ + Name = 'TestAdapter' + } + } + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testIPv6ConnectivityMatches = @{ + InterfaceAlias = 'TestAdapter' + IPv6Connectivity = 'Internet' + } + + { Assert-ResourceProperty @testIPv6ConnectivityMatches } | Should -Not -Throw + } + } + } +} diff --git a/tests/Unit/DSC_NetIPInterface.Tests.ps1 b/tests/Unit/DSC_NetIPInterface.Tests.ps1 index c5081d4f..ca8abd56 100644 --- a/tests/Unit/DSC_NetIPInterface.Tests.ps1 +++ b/tests/Unit/DSC_NetIPInterface.Tests.ps1 @@ -1,17 +1,36 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetIPInterface' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } + # Import the NetTCPIP module + Import-Module -Name NetTCPIP +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetIPInterface' + $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` -DSCResourceName $script:dscResourceName ` @@ -19,29 +38,44 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + # Import the NetTCPIP module + Import-Module -Name NetTCPIP + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} -Invoke-TestSetup + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Remove module NetTCPIP. + Get-Module -Name 'NetTCPIP' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { +Describe 'DSC_NetIPInterface\Get-TargetResource' -Tag 'Get' { + BeforeDiscovery { <# - This is an array of parameters that will be used with pester test cases - to test each individual parameter. The array contains a hash table - representing each paramter to test. The properties of the hash table are - - Name: the name of the parameter. - - MockedValue: The value that the mock for Get-NetIPInterface will return for - the parameter - - TestValue: The value that will be used to change the setting to. - - ParameterFilter: The parameter filter condition used to determine if the - value has been successfully set in Set-TargetResource. + This is an array of parameters that will be used with pester test cases + to test each individual parameter. The array contains a hash table + representing each parameter to test. The properties of the hash table are + - Name: the name of the parameter. + - MockedValue: The value that the mock for Get-NetIPInterface will return for + the parameter + - TestValue: The value that will be used to change the setting to. + - ParameterFilter: The parameter filter condition used to determine if the + value has been successfully set in Set-TargetResource. #> $testParameterList = @( @{ @@ -181,206 +215,648 @@ try } } ) + } - $script:netIPInterfaceExists = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' - Verbose = $true + Context 'When called with alias and address family of an existing interface' { + BeforeAll { + Mock -CommandName Get-NetworkIPInterface -ParameterFilter { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' + } -MockWith { + @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + AdvertiseDefaultRoute = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AdvertiseDefaultRoute]::Enabled + Advertising = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Advertising]::Enabled + AutomaticMetric = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AutomaticMetric]::Enabled + Dhcp = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Dhcp]::Enabled + DirectedMacWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.DirectedMacWolPattern]::Enabled + EcnMarking = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.EcnMarking]::AppDecide + ForceArpNdWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ForceArpNdWolPattern]::Enabled + Forwarding = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Forwarding]::Enabled + IgnoreDefaultRoutes = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.IgnoreDefaultRoutes]::Enabled + ManagedAddressConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ManagedAddressConfiguration]::Enabled + NeighborUnreachabilityDetection = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.NeighborUnreachabilityDetection]::Enabled + OtherStatefulConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.OtherStatefulConfiguration]::Enabled + RouterDiscovery = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.RouterDiscovery]::Enabled + WeakHostReceive = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostReceive]::Enabled + WeakHostSend = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostSend]::Enabled + NlMtu = [System.Uint32] 1600 + InterfaceMetric = [System.Uint32] 20 + } + } } - $script:netIPInterfaceExists_ParameterFilter = { - $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' - } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $netIPInterfaceExists = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + } - $script:netIPInterfaceExists_Settings = @{ - InterfaceAlias = 'Ethernet' - AddressFamily = 'IPv4' + { $script:result = Get-TargetResource @netIPInterfaceExists } | Should -Not -Throw + } } - foreach ($parameter in $testParameterList) - { - $null = $script:netIPInterfaceExists_Settings.Add($parameter.Name, $parameter.MockedValue) + It 'Should return for parameter ' -ForEach $testParameterList { + InModuleScope -Parameters $_ -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result[$Name] | Should -Be $MockedValue + } } + } +} - $script:netIPInterfaceMissing = @{ - InterfaceAlias = 'EthernetDoesNotExist' - AddressFamily = 'IPv4' - Verbose = $true +Describe 'DSC_NetIPInterface\Test-TargetResource' -Tag 'Test' { + BeforeDiscovery { + BeforeDiscovery { + <# + This is an array of parameters that will be used with pester test cases + to test each individual parameter. The array contains a hash table + representing each parameter to test. The properties of the hash table are + - Name: the name of the parameter. + - MockedValue: The value that the mock for Get-NetIPInterface will return for + the parameter + - TestValue: The value that will be used to change the setting to. + - ParameterFilter: The parameter filter condition used to determine if the + value has been successfully set in Set-TargetResource. + #> + $testParameterList = @( + @{ + Name = 'AdvertiseDefaultRoute' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AdvertiseDefaultRoute]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $AdvertiseDefaultRoute -eq 'Disabled' + } + }, + @{ + Name = 'Advertising' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Advertising]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $Advertising -eq 'Disabled' + } + }, + @{ + Name = 'AutomaticMetric' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AutomaticMetric]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $AutomaticMetric -eq 'Disabled' + } + }, + @{ + Name = 'Dhcp' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Dhcp]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $Dhcp -eq 'Disabled' + } + }, + @{ + Name = 'DirectedMacWolPattern' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.DirectedMacWolPattern]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $DirectedMacWolPattern -eq 'Disabled' + } + }, + @{ + Name = 'EcnMarking' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.EcnMarking]::AppDecide + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $EcnMarking -eq 'Disabled' + } + }, + @{ + Name = 'ForceArpNdWolPattern' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ForceArpNdWolPattern]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $ForceArpNdWolPattern -eq 'Disabled' + } + }, + @{ + Name = 'Forwarding' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Forwarding]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $Forwarding -eq 'Disabled' + } + }, + @{ + Name = 'IgnoreDefaultRoutes' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.IgnoreDefaultRoutes]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $IgnoreDefaultRoutes -eq 'Disabled' + } + }, + @{ + Name = 'ManagedAddressConfiguration' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ManagedAddressConfiguration]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $ManagedAddressConfiguration -eq 'Disabled' + } + }, + @{ + Name = 'NeighborUnreachabilityDetection' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.NeighborUnreachabilityDetection]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $NeighborUnreachabilityDetection -eq 'Disabled' + } + }, + @{ + Name = 'OtherStatefulConfiguration' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.OtherStatefulConfiguration]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $OtherStatefulConfiguration -eq 'Disabled' + } + }, + @{ + Name = 'RouterDiscovery' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.RouterDiscovery]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $RouterDiscovery -eq 'Disabled' + } + }, + @{ + Name = 'WeakHostReceive' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostReceive]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $WeakHostReceive -eq 'Disabled' + } + }, + @{ + Name = 'WeakHostSend' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostSend]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $WeakHostSend -eq 'Disabled' + } + }, + @{ + Name = 'NlMtu' + MockedValue = [System.Uint32] 1600 + TestValue = [System.Uint32] 1500 + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $NlMtuBytes -eq 1500 + } + }, + @{ + Name = 'InterfaceMetric' + MockedValue = [System.Uint32] 20 + TestValue = [System.Uint32] 15 + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $InterfaceMetric -eq 15 + } + } + ) } + } - $script:netIPInterfaceMissing_ParameterFilter = { - $InterfaceAlias -eq 'EthernetDoesNotExist' -and $AddressFamily -eq 'IPv4' + Context 'When called with alias and address family of an existing interface and a mismatching value' { + BeforeAll { + Mock -CommandName Get-NetworkIPInterface ` + -ParameterFilter { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' + } -MockWith { + @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + AdvertiseDefaultRoute = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AdvertiseDefaultRoute]::Enabled + Advertising = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Advertising]::Enabled + AutomaticMetric = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AutomaticMetric]::Enabled + Dhcp = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Dhcp]::Enabled + DirectedMacWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.DirectedMacWolPattern]::Enabled + EcnMarking = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.EcnMarking]::AppDecide + ForceArpNdWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ForceArpNdWolPattern]::Enabled + Forwarding = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Forwarding]::Enabled + IgnoreDefaultRoutes = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.IgnoreDefaultRoutes]::Enabled + ManagedAddressConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ManagedAddressConfiguration]::Enabled + NeighborUnreachabilityDetection = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.NeighborUnreachabilityDetection]::Enabled + OtherStatefulConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.OtherStatefulConfiguration]::Enabled + RouterDiscovery = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.RouterDiscovery]::Enabled + WeakHostReceive = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostReceive]::Enabled + WeakHostSend = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostSend]::Enabled + NlMtu = [System.Uint32] 1600 + InterfaceMetric = [System.Uint32] 20 + } + } } - Describe 'DSC_NetIPInterface\Get-TargetResource' -Tag 'Get' { - Context 'When called with alias and address family of an existing interface' { - Mock ` - -CommandName Get-NetworkIPInterface ` - -ParameterFilter $script:netIPInterfaceExists_ParameterFilter ` - -MockWith { $script:netIPInterfaceExists_Settings } + It 'Should return $false when existing value for parameter is set to but should be ' -ForEach $testParameterList { + InModuleScope -Parameters $_ -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { - $script:result = Get-TargetResource @script:netIPInterfaceExists - } | Should -Not -Throw + $netIPInterfaceExists = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - It 'Should return for parameter ' -TestCases $testParameterList { - param - ( - $Name, $MockedValue, $TestValue, $ParameterFilter - ) - - $script:result[$Name] | Should -Be $MockedValue + $comparisonParameter = @{ + $Name = $TestValue } + + $result = Test-TargetResource @netIPInterfaceExists @comparisonParameter + + $result | Should -BeFalse } } + } - Describe 'DSC_NetIPInterface\Test-TargetResource' -Tag 'Test' { - Context 'When called with alias and address family of an existing interface and a mismatching value' { - Mock ` - -CommandName Get-NetworkIPInterface ` - -ParameterFilter $script:netIPInterfaceExists_ParameterFilter ` - -MockWith { $script:netIPInterfaceExists_Settings } - - It 'Should return $false when existing value for parameter is set to but should be ' -TestCases $testParameterList { - param - ( - $Name, $MockedValue, $TestValue, $ParameterFilter - ) - - $comparisonParameter = @{ - $Name = $TestValue - } + Context 'When called with alias and address family of an existing interface and no mismatching values' { + BeforeAll { + Mock -CommandName Get-NetworkIPInterface -ParameterFilter { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' + } -MockWith { + @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + AdvertiseDefaultRoute = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AdvertiseDefaultRoute]::Enabled + Advertising = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Advertising]::Enabled + AutomaticMetric = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AutomaticMetric]::Enabled + Dhcp = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Dhcp]::Enabled + DirectedMacWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.DirectedMacWolPattern]::Enabled + EcnMarking = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.EcnMarking]::AppDecide + ForceArpNdWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ForceArpNdWolPattern]::Enabled + Forwarding = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Forwarding]::Enabled + IgnoreDefaultRoutes = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.IgnoreDefaultRoutes]::Enabled + ManagedAddressConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ManagedAddressConfiguration]::Enabled + NeighborUnreachabilityDetection = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.NeighborUnreachabilityDetection]::Enabled + OtherStatefulConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.OtherStatefulConfiguration]::Enabled + RouterDiscovery = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.RouterDiscovery]::Enabled + WeakHostReceive = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostReceive]::Enabled + WeakHostSend = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostSend]::Enabled + NlMtu = [System.Uint32] 1600 + InterfaceMetric = [System.Uint32] 20 + } + } + } - $script:result = Test-TargetResource @script:netIPInterfaceExists @comparisonParameter + It 'Should return $true when existing value for parameter is set to and should be ' -ForEach $testParameterList { + InModuleScope -Parameters $_ -ScriptBlock { + Set-StrictMode -Version 1.0 - $script:result | Should -BeFalse + $netIPInterfaceExists = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } - } - Context 'When called with alias and address family of an existing interface and no mismatching values' { - Mock ` - -CommandName Get-NetworkIPInterface ` - -ParameterFilter $script:netIPInterfaceExists_ParameterFilter ` - -MockWith { $script:netIPInterfaceExists_Settings } + $comparisonParameter = @{ + $Name = $MockedValue + } - It 'Should return $true when existing value for parameter is set to and should be ' -TestCases $testParameterList { - param - ( - $Name, $MockedValue, $TestValue, $ParameterFilter - ) + $result = Test-TargetResource @netIPInterfaceExists @comparisonParameter - $comparisonParameter = @{ - $Name = $MockedValue - } + $result | Should -BeTrue + } + } + } +} - $script:result = Test-TargetResource @script:netIPInterfaceExists @comparisonParameter +Describe 'DSC_NetIPInterface\Set-TargetResource' -Tag 'Set' { + BeforeDiscovery { + <# + This is an array of parameters that will be used with pester test cases + to test each individual parameter. The array contains a hash table + representing each parameter to test. The properties of the hash table are + - Name: the name of the parameter. + - MockedValue: The value that the mock for Get-NetIPInterface will return for + the parameter + - TestValue: The value that will be used to change the setting to. + - ParameterFilter: The parameter filter condition used to determine if the + value has been successfully set in Set-TargetResource. + #> + $testParameterList = @( + @{ + Name = 'AdvertiseDefaultRoute' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AdvertiseDefaultRoute]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $AdvertiseDefaultRoute -eq 'Disabled' + } + }, + @{ + Name = 'Advertising' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Advertising]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $Advertising -eq 'Disabled' + } + }, + @{ + Name = 'AutomaticMetric' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AutomaticMetric]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $AutomaticMetric -eq 'Disabled' + } + }, + @{ + Name = 'Dhcp' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Dhcp]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $Dhcp -eq 'Disabled' + } + }, + @{ + Name = 'DirectedMacWolPattern' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.DirectedMacWolPattern]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $DirectedMacWolPattern -eq 'Disabled' + } + }, + @{ + Name = 'EcnMarking' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.EcnMarking]::AppDecide + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $EcnMarking -eq 'Disabled' + } + }, + @{ + Name = 'ForceArpNdWolPattern' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ForceArpNdWolPattern]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $ForceArpNdWolPattern -eq 'Disabled' + } + }, + @{ + Name = 'Forwarding' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Forwarding]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $Forwarding -eq 'Disabled' + } + }, + @{ + Name = 'IgnoreDefaultRoutes' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.IgnoreDefaultRoutes]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $IgnoreDefaultRoutes -eq 'Disabled' + } + }, + @{ + Name = 'ManagedAddressConfiguration' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ManagedAddressConfiguration]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $ManagedAddressConfiguration -eq 'Disabled' + } + }, + @{ + Name = 'NeighborUnreachabilityDetection' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.NeighborUnreachabilityDetection]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $NeighborUnreachabilityDetection -eq 'Disabled' + } + }, + @{ + Name = 'OtherStatefulConfiguration' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.OtherStatefulConfiguration]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $OtherStatefulConfiguration -eq 'Disabled' + } + }, + @{ + Name = 'RouterDiscovery' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.RouterDiscovery]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $RouterDiscovery -eq 'Disabled' + } + }, + @{ + Name = 'WeakHostReceive' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostReceive]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $WeakHostReceive -eq 'Disabled' + } + }, + @{ + Name = 'WeakHostSend' + MockedValue = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostSend]::Enabled + TestValue = 'Disabled' + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $WeakHostSend -eq 'Disabled' + } + }, + @{ + Name = 'NlMtu' + MockedValue = [System.Uint32] 1600 + TestValue = [System.Uint32] 1500 + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $NlMtuBytes -eq 1500 + } + }, + @{ + Name = 'InterfaceMetric' + MockedValue = [System.Uint32] 20 + TestValue = [System.Uint32] 15 + ParameterFilter = { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' -and $InterfaceMetric -eq 15 + } + } + ) + } - $script:result | Should -BeTrue + Context 'When called with alias and address family of an existing interface and a mismatching value' { + BeforeAll { + Mock -CommandName Get-NetworkIPInterface -ParameterFilter { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' + } -MockWith { + @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + AdvertiseDefaultRoute = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AdvertiseDefaultRoute]::Enabled + Advertising = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Advertising]::Enabled + AutomaticMetric = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AutomaticMetric]::Enabled + Dhcp = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Dhcp]::Enabled + DirectedMacWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.DirectedMacWolPattern]::Enabled + EcnMarking = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.EcnMarking]::AppDecide + ForceArpNdWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ForceArpNdWolPattern]::Enabled + Forwarding = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Forwarding]::Enabled + IgnoreDefaultRoutes = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.IgnoreDefaultRoutes]::Enabled + ManagedAddressConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ManagedAddressConfiguration]::Enabled + NeighborUnreachabilityDetection = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.NeighborUnreachabilityDetection]::Enabled + OtherStatefulConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.OtherStatefulConfiguration]::Enabled + RouterDiscovery = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.RouterDiscovery]::Enabled + WeakHostReceive = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostReceive]::Enabled + WeakHostSend = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostSend]::Enabled + NlMtu = [System.Uint32] 1600 + InterfaceMetric = [System.Uint32] 20 } } - } - Describe 'DSC_NetIPInterface\Set-TargetResource' -Tag 'Set' { - Context 'When called with alias and address family of an existing interface and a mismatching value' { - Mock ` - -CommandName Get-NetworkIPInterface ` - -ParameterFilter $script:netIPInterfaceExists_ParameterFilter ` - -MockWith { $script:netIPInterfaceExists_Settings } - - It 'Should set parameter to ' -TestCases $testParameterList { - param - ( - $Name, $MockedValue, $TestValue, $ParameterFilter - ) - - $comparisonParameter = @{ - $Name = $TestValue - } + Mock -CommandName Set-NetIPInterface + } - Mock ` - -CommandName Set-NetIPInterface + It 'Should set parameter to ' -ForEach $testParameterList { + InModuleScope -Parameters $_ -ScriptBlock { + Set-StrictMode -Version 1.0 - Set-TargetResource @script:netIPInterfaceExists @comparisonParameter + $netIPInterfaceExists = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + } - Assert-MockCalled ` - -CommandName Set-NetIPInterface ` - -ParameterFilter $ParameterFilter ` - -Exactly -Times 1 + $comparisonParameter = @{ + $Name = $TestValue } + + Set-TargetResource @netIPInterfaceExists @comparisonParameter } - Context 'When called with alias and address family of an existing interface and no mismatching values' { - Mock ` - -CommandName Get-NetworkIPInterface ` - -ParameterFilter $script:netIPInterfaceExists_ParameterFilter ` - -MockWith { $script:netIPInterfaceExists_Settings } + Should -Invoke -CommandName Set-NetIPInterface -ParameterFilter $ParameterFilter -Exactly -Times 1 -Scope It + } + } + + Context 'When called with alias and address family of an existing interface and no mismatching values' { + BeforeAll { + Mock -CommandName Get-NetworkIPInterface -ParameterFilter { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' + } -MockWith { + @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + AdvertiseDefaultRoute = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AdvertiseDefaultRoute]::Enabled + Advertising = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Advertising]::Enabled + AutomaticMetric = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AutomaticMetric]::Enabled + Dhcp = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Dhcp]::Enabled + DirectedMacWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.DirectedMacWolPattern]::Enabled + EcnMarking = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.EcnMarking]::AppDecide + ForceArpNdWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ForceArpNdWolPattern]::Enabled + Forwarding = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Forwarding]::Enabled + IgnoreDefaultRoutes = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.IgnoreDefaultRoutes]::Enabled + ManagedAddressConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ManagedAddressConfiguration]::Enabled + NeighborUnreachabilityDetection = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.NeighborUnreachabilityDetection]::Enabled + OtherStatefulConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.OtherStatefulConfiguration]::Enabled + RouterDiscovery = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.RouterDiscovery]::Enabled + WeakHostReceive = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostReceive]::Enabled + WeakHostSend = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostSend]::Enabled + NlMtu = [System.Uint32] 1600 + InterfaceMetric = [System.Uint32] 20 + } + } - It 'Should not call Set-NetIPInterface' { - $comparisonParameter = @{ - $testParameterList[0].Name = $testParameterList[0].MockedValue - } + Mock -CommandName Set-NetIPInterface + } - Mock ` - -CommandName Set-NetIPInterface + It 'Should not call Set-NetIPInterface' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Set-TargetResource @script:netIPInterfaceExists @comparisonParameter + $comparisonParameter = @{ + AdvertiseDefaultRoute = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AdvertiseDefaultRoute]::Enabled + } - Assert-MockCalled ` - -CommandName Set-NetIPInterface ` - -ParameterFilter $ParameterFilter ` - -Exactly -Times 0 + $netIPInterfaceExists = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + Set-TargetResource @netIPInterfaceExists @comparisonParameter } + + Should -Invoke -CommandName Set-NetIPInterface -ParameterFilter $ParameterFilter -Exactly -Times 0 -Scope It } + } +} - Describe 'DSC_NetIPInterface\Get-NetworkIPInterface' { - Context 'When called with alias and address family of an interface that does not exist' { - Mock ` - -CommandName Get-NetIPInterface ` - -ParameterFilter $script:netIPInterfaceMissing_ParameterFilter +Describe 'DSC_NetIPInterface\Get-NetworkIPInterface' { + Context 'When called with alias and address family of an interface that does not exist' { + BeforeAll { + Mock -CommandName Get-NetIPInterface -ParameterFilter { + $InterfaceAlias -eq 'EthernetDoesNotExist' -and $AddressFamily -eq 'IPv4' + } + } - It 'Should throw expected exception' { - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetworkIPInterfaceDoesNotExistMessage -f $script:netIPInterfaceMissing.InterfaceAlias, $script:netIPInterfaceMissing.AddressFamily) + It 'Should throw expected exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { - $script:result = Get-NetworkIPInterface @script:netIPInterfaceMissing - } | Should -Throw $errorRecord + $netIPInterfaceMissing = @{ + InterfaceAlias = 'EthernetDoesNotExist' + AddressFamily = 'IPv4' } - It 'Should call the expected mocks' { - Assert-MockCalled ` - -CommandName Get-NetIPInterface ` - -ParameterFilter $script:netIPInterfaceMissing_ParameterFilter ` - -Exactly -Times 1 - } + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.NetworkIPInterfaceDoesNotExistMessage -f $netIPInterfaceMissing.InterfaceAlias, $netIPInterfaceMissing.AddressFamily) + + { Get-NetworkIPInterface @netIPInterfaceMissing } | Should -Throw $errorRecord } + } - Context 'When called with alias and address family of an existing interface' { - Mock ` - -CommandName Get-NetIPInterface ` - -ParameterFilter $script:netIPInterfaceExists_ParameterFilter ` - -MockWith { $script:netIPInterfaceExists_Settings } + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetIPInterface -ParameterFilter { + $InterfaceAlias -eq 'EthernetDoesNotExist' -and $AddressFamily -eq 'IPv4' + } -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw exception' { - { - $script:result = Get-NetworkIPInterface @script:netIPInterfaceExists - } | Should -Not -Throw + Context 'When called with alias and address family of an existing interface' { + BeforeAll { + Mock -CommandName Get-NetIPInterface -ParameterFilter { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' + } -MockWith { + @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + AdvertiseDefaultRoute = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AdvertiseDefaultRoute]::Enabled + Advertising = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Advertising]::Enabled + AutomaticMetric = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.AutomaticMetric]::Enabled + Dhcp = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Dhcp]::Enabled + DirectedMacWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.DirectedMacWolPattern]::Enabled + EcnMarking = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.EcnMarking]::AppDecide + ForceArpNdWolPattern = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ForceArpNdWolPattern]::Enabled + Forwarding = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.Forwarding]::Enabled + IgnoreDefaultRoutes = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.IgnoreDefaultRoutes]::Enabled + ManagedAddressConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.ManagedAddressConfiguration]::Enabled + NeighborUnreachabilityDetection = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.NeighborUnreachabilityDetection]::Enabled + OtherStatefulConfiguration = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.OtherStatefulConfiguration]::Enabled + RouterDiscovery = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.RouterDiscovery]::Enabled + WeakHostReceive = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostReceive]::Enabled + WeakHostSend = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetIPInterface.WeakHostSend]::Enabled + NlMtu = [System.Uint32] 1600 + InterfaceMetric = [System.Uint32] 20 } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call the expected mocks' { - Assert-MockCalled ` - -CommandName Get-NetIPInterface ` - -ParameterFilter $script:netIPInterfaceExists_ParameterFilter ` - -Exactly -Times 1 + $netIPInterfaceExists = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' } + + { Get-NetworkIPInterface @netIPInterfaceExists } | Should -Not -Throw } } + + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetIPInterface -ParameterFilter { + $InterfaceAlias -eq 'Ethernet' -and $AddressFamily -eq 'IPv4' + } -Exactly -Times 1 -Scope Context + } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_NetconnectionProfile.tests.ps1 b/tests/Unit/DSC_NetconnectionProfile.tests.ps1 deleted file mode 100644 index 99c25ab1..00000000 --- a/tests/Unit/DSC_NetconnectionProfile.tests.ps1 +++ /dev/null @@ -1,206 +0,0 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetConnectionProfile' - -function Invoke-TestSetup -{ - try - { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' - } - catch [System.IO.FileNotFoundException] - { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' - } - - $script:testEnvironment = Initialize-TestEnvironment ` - -DSCModuleName $script:dscModuleName ` - -DSCResourceName $script:dscResourceName ` - -ResourceType 'Mof' ` - -TestType 'Unit' - - Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') -} - -function Invoke-TestCleanup -{ - Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} - -Invoke-TestSetup - -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - - # Create the Mock Objects that will be used for running tests - $mockNetAdapter = [PSCustomObject] @{ - Name = 'TestAdapter' - } - - $mockNetConnnectionProfileAll = [PSObject] @{ - InterfaceAlias = $mockNetAdapter.Name - NetworkCategory = 'Public' - IPv4Connectivity = 'Internet' - IPv6Connectivity = 'Internet' - } - - $testValidInterfaceAliasOnlyPassed = [PSObject] @{ - InterfaceAlias = $mockNetAdapter.Name - } - - $testNetworkCategoryMatches = [PSObject] @{ - InterfaceAlias = $mockNetAdapter.Name - NetworkCategory = 'Public' - } - - $testNetworkCategoryNoMatches = [PSObject] @{ - InterfaceAlias = $mockNetAdapter.Name - NetworkCategory = 'Private' - } - - $testIPv4ConnectivityMatches = [PSObject] @{ - InterfaceAlias = $mockNetAdapter.Name - IPv4Connectivity = 'Internet' - } - - $testIPv4ConnectivityNoMatches = [PSObject] @{ - InterfaceAlias = $mockNetAdapter.Name - IPv4Connectivity = 'Disconnected' - } - - $testIPv6ConnectivityMatches = [PSObject] @{ - InterfaceAlias = $mockNetAdapter.Name - IPv6Connectivity = 'Internet' - } - - $testIPv6ConnectivityNoMatches = [PSObject] @{ - InterfaceAlias = $mockNetAdapter.Name - IPv6Connectivity = 'Disconnected' - } - - Describe 'DSC_NetConnectionProfile\Get-TargetResource' -Tag 'Get' { - Mock -CommandName Get-NetConnectionProfile { - return $mockNetConnnectionProfileAll - } - - $result = Get-TargetResource -InterfaceAlias $mockNetAdapter.Name - - It 'Should return the correct values' { - $result.InterfaceAlias | Should -Be $mockNetConnnectionProfileAll.InterfaceAlias - $result.NetworkCategory | Should -Be $mockNetConnnectionProfileAll.NetworkCategory - $result.IPv4Connectivity | Should -Be $mockNetConnnectionProfileAll.IPv4Connectivity - $result.IPv6Connectivity | Should -Be $mockNetConnnectionProfileAll.IPv6Connectivity - } - } - - Describe 'DSC_NetConnectionProfile\Test-TargetResource' -Tag 'Test' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { - return $mockNetConnnectionProfileAll - } - - Mock -CommandName Assert-ResourceProperty - } - - Context 'NetworkCategory matches' { - It 'Should return false' { - Test-TargetResource @testNetworkCategoryMatches | should -be $true - } - } - - Context 'NetworkCategory does not match' { - It 'Should return false' { - Test-TargetResource @testNetworkCategoryNoMatches | should -be $false - } - } - - Context 'IPv4Connectivity matches' { - It 'Should return false' { - Test-TargetResource @testIPv4ConnectivityMatches | should -be $true - } - } - - Context 'IPv4Connectivity does not match' { - It 'Should return false' { - Test-TargetResource @testIPv4ConnectivityNoMatches | should -be $false - } - } - - Context 'IPv6Connectivity matches' { - It 'Should return false' { - Test-TargetResource @testIPv6ConnectivityMatches | should -be $true - } - } - - Context 'IPv6Connectivity does not match' { - It 'Should return false' { - Test-TargetResource @testIPv6ConnectivityNoMatches | should -be $false - } - } - } - - Describe 'DSC_NetConnectionProfile\Set-TargetResource' -Tag 'Set' { - It 'Should call all the mocks' { - Mock -CommandName Set-NetConnectionProfile - Mock -CommandName Assert-ResourceProperty - - Set-TargetResource @testNetworkCategoryMatches - - Assert-MockCalled -CommandName Set-NetConnectionProfile - } - } - - Describe 'DSC_NetConnectionProfile\Assert-ResourceProperty' { - Context 'Invoking with bad interface alias' { - Mock -CommandName Get-NetAdapter - - It 'Should throw testValidInterfaceAliasOnlyPassed exception' { - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.InterfaceNotAvailableError -f $testValidInterfaceAliasOnlyPassed.InterfaceAlias) - - { Assert-ResourceProperty @testValidInterfaceAliasOnlyPassed } | Should -Throw $errorRecord - } - } - - Context 'Invoking with valid interface alias but all empty parameters' { - Mock -CommandName Get-NetAdapter -MockWith { return $mockNetAdapter } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.ParameterCombinationError) - - It 'Should not ParameterCombinationError exception' { - { Assert-ResourceProperty @testValidInterfaceAliasOnlyPassed } | Should -Throw $errorRecord - } - } - - Context 'Invoking with valid interface alias and one NetworkCategory' { - Mock -CommandName Get-NetAdapter -MockWith { return $mockNetAdapter } - - It 'Should not throw an exception' { - { Assert-ResourceProperty @testNetworkCategoryMatches } | Should -Not -Throw - } - } - - Context 'Invoking with valid interface alias and one IPv4Connectivity' { - Mock -CommandName Get-NetAdapter -MockWith { return $mockNetAdapter } - - It 'Should not throw an exception' { - { Assert-ResourceProperty @testIPv4ConnectivityMatches } | Should -Not -Throw - } - } - - Context 'Invoking with valid interface alias and one IPv6Connectivity' { - Mock -CommandName Get-NetAdapter -MockWith { return $mockNetAdapter } - - It 'Should not throw an exception' { - { Assert-ResourceProperty @testIPv6ConnectivityMatches } | Should -Not -Throw - } - } - } - } #end InModuleScope $DSCResourceName -} -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_NetworkTeam.Tests.ps1 b/tests/Unit/DSC_NetworkTeam.Tests.ps1 index 4e9d016a..52225f55 100644 --- a/tests/Unit/DSC_NetworkTeam.Tests.ps1 +++ b/tests/Unit/DSC_NetworkTeam.Tests.ps1 @@ -1,17 +1,32 @@ +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetworkTeam' - -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetworkTeam' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -20,416 +35,738 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup +Describe 'DSC_NetworkTeam\Get-TargetResource' -Tag 'Get' { + Context 'When network team does not exist' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - # Create the Mock -CommandName Objects that will be used for running tests - $mockNetTeam = [PSCustomObject] @{ - Name = 'HostTeam' - Members = @('NIC1', 'NIC2') + $testTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + } + + $script:result = Get-TargetResource @testTeam + } } - $testTeam = [PSObject] @{ - Name = $mockNetTeam.Name - TeamMembers = $mockNetTeam.Members - Verbose = $true + It 'Should return ensure as absent' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Ensure | Should -Be 'Absent' + } } - $newTeam = [PSObject] @{ - Name = $testTeam.Name - TeamMembers = $testTeam.TeamMembers - LoadBalancingAlgorithm = 'Dynamic' - TeamingMode = 'SwitchIndependent' - Ensure = 'Present' - Verbose = $true + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context } + } - $mockTeam = { - [PSObject] @{ - Name = $testTeam.Name - Members = $testTeam.TeamMembers - LoadBalancingAlgorithm = 'Dynamic' - TeamingMode = 'SwitchIndependent' - Ensure = 'Present' + Context 'When network team exists with matching members' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' + } } } - Describe 'DSC_NetworkTeam\Get-TargetResource' -Tag 'Get' { - Context 'When network team does not exist' { - Mock -CommandName Get-NetLbfoTeam + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw exception' { - $script:result = Get-TargetResource @testTeam + $script:testTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') } - It 'Should return ensure as absent' { - $script:result.Ensure | Should -Be 'Absent' - } + $script:result = Get-TargetResource @testTeam + } + } - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 - } + It 'Should return team properties' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Ensure | Should -Be 'Present' + $script:result.Name | Should -Be $script:testTeam.Name + $script:result.TeamMembers | Should -Be $script:testTeam.TeamMembers + $script:result.LoadBalancingAlgorithm | Should -Be 'Dynamic' + $script:result.TeamingMode | Should -Be 'SwitchIndependent' } + } - Context 'When network team exists with matching members' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw exception' { - $script:result = Get-TargetResource @testTeam + Context 'When network team exists and different members' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + } + } - It 'Should return team properties' { - $script:result.Ensure | Should -Be 'Present' - $script:result.Name | Should -Be $testTeam.Name - $script:result.TeamMembers | Should -Be $testTeam.TeamMembers - $script:result.LoadBalancingAlgorithm | Should -Be 'Dynamic' - $script:result.TeamingMode | Should -Be 'SwitchIndependent' - } + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 + $script:testTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') } + + $script:testTeam.TeamMembers = @('NIC1', 'NIC3') + + $script:result = Get-TargetResource @script:testTeam } + } - Context 'When network team exists and different members' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam + It 'Should return team properties' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw exception' { - $getTestTeam = $testTeam.Clone() - $getTestTeam.TeamMembers = @('NIC1', 'NIC3') - $script:result = Get-TargetResource @getTestTeam - } + $script:result.Ensure | Should -Be 'Present' + $script:result.Name | Should -Be $script:testTeam.Name + $script:result.TeamMembers | Should -Be @('NIC1', 'NIC2') + $script:result.LoadBalancingAlgorithm | Should -Be 'Dynamic' + $script:result.TeamingMode | Should -Be 'SwitchIndependent' + } + } - It 'Should return team properties' { - $result.Ensure | Should -Be 'Present' - $result.Name | Should -Be $testTeam.Name - $result.TeamMembers | Should -Be @('NIC1', 'NIC2') - $result.LoadBalancingAlgorithm | Should -Be 'Dynamic' - $result.TeamingMode | Should -Be 'SwitchIndependent' - } + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } + } +} - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 +Describe 'DSC_NetworkTeam\Set-TargetResource' -Tag 'Set' { + Context 'When team does not exist but should' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam + Mock -CommandName New-NetLbfoTeam + Mock -CommandName Set-NetLbfoTeam + Mock -CommandName Remove-NetLbfoTeamMember + Mock -CommandName Add-NetLbfoTeamMember + } + + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + + { Set-TargetResource @newTeam } | Should -Not -Throw } } - Describe 'DSC_NetworkTeam\Set-TargetResource' -Tag 'Set' { - Context 'When team does not exist but should' { - Mock -CommandName Get-NetLbfoTeam - Mock -CommandName New-NetLbfoTeam - Mock -CommandName Set-NetLbfoTeam - Mock -CommandName Remove-NetLbfoTeamMember - Mock -CommandName Add-NetLbfoTeamMember + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetLbfoTeam -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetLbfoTeam -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Remove-NetLbfoTeamMember -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Add-NetLbfoTeamMember -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw error' { - { - Set-TargetResource @newTeam - } | Should -Not -Throw + Context 'When team exists but needs a different teaming mode' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + } + + Mock -CommandName New-NetLbfoTeam + Mock -CommandName Set-NetLbfoTeam + Mock -CommandName Remove-NetLbfoTeam + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetLbfoTeam -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetLbfoTeam -Exactly -Times 0 - Assert-MockCalled -CommandName Remove-NetLbfoTeamMember -Exactly -Times 0 - Assert-MockCalled -CommandName Add-NetLbfoTeamMember -Exactly -Times 0 + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + + $newTeam.TeamingMode = 'LACP' + + { Set-TargetResource @newTeam } | Should -Not -Throw } + } - Context 'When team exists but needs a different teaming mode' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam - Mock -CommandName New-NetLbfoTeam - Mock -CommandName Set-NetLbfoTeam - Mock -CommandName Remove-NetLbfoTeam + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetLbfoTeam -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetLbfoTeam -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetLbfoTeam -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $updateTeam.TeamingMode = 'LACP' - Set-TargetResource @updateTeam - } | Should -Not -Throw + Context 'When team exists but needs a different load balacing algorithm' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + } + + Mock -CommandName New-NetLbfoTeam + Mock -CommandName Set-NetLbfoTeam + Mock -CommandName Remove-NetLbfoTeam + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetLbfoTeam -Exactly -Times 0 - Assert-MockCalled -CommandName Set-NetLbfoTeam -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetLbfoTeam -Exactly -Times 0 + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + + $newTeam.LoadBalancingAlgorithm = 'HyperVPort' + + { Set-TargetResource @newTeam } | Should -Not -Throw } + } - Context 'When team exists but needs a different load balacing algorithm' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam - Mock -CommandName New-NetLbfoTeam - Mock -CommandName Set-NetLbfoTeam - Mock -CommandName Remove-NetLbfoTeam + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetLbfoTeam -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetLbfoTeam -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetLbfoTeam -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $updateTeam.LoadBalancingAlgorithm = 'HyperVPort' - Set-TargetResource @updateTeam - } | Should -Not -Throw + Context 'When team exists but has to remove a member adapter' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + } + + Mock -CommandName New-NetLbfoTeam + Mock -CommandName Set-NetLbfoTeam + Mock -CommandName Remove-NetLbfoTeam + Mock -CommandName Remove-NetLbfoTeamMember + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetLbfoTeam -Exactly -Times 0 - Assert-MockCalled -CommandName Set-NetLbfoTeam -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetLbfoTeam -Exactly -Times 0 + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + + $newTeam.TeamMembers = $newTeam.TeamMembers[0] + + { Set-TargetResource @newTeam } | Should -Not -Throw } + } - Context 'When team exists but has to remove a member adapter' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam - Mock -CommandName New-NetLbfoTeam - Mock -CommandName Set-NetLbfoTeam - Mock -CommandName Remove-NetLbfoTeam - Mock -CommandName Remove-NetLbfoTeamMember + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetLbfoTeam -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetLbfoTeam -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Remove-NetLbfoTeam -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Remove-NetLbfoTeamMember -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $updateTeam.TeamMembers = $newTeam.TeamMembers[0] - Set-TargetResource @updateTeam - } | Should -Not -Throw + Context 'When team exists but has to add a member adapter' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + } + + Mock -CommandName New-NetLbfoTeam + Mock -CommandName Set-NetLbfoTeam + Mock -CommandName Remove-NetLbfoTeam + Mock -CommandName Remove-NetLbfoTeamMember + Mock -CommandName Add-NetLbfoTeamMember + } + + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetLbfoTeam -Exactly -Times 0 - Assert-MockCalled -CommandName Set-NetLbfoTeam -Exactly -Times 0 - Assert-MockCalled -CommandName Remove-NetLbfoTeam -Exactly -Times 0 - Assert-MockCalled -CommandName Remove-NetLbfoTeamMember -Exactly -Times 1 + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + + $newTeam.TeamMembers += 'NIC3' + + { Set-TargetResource @newTeam } | Should -Not -Throw } + } - Context 'When team exists but has to add a member adapter' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam - Mock -CommandName New-NetLbfoTeam - Mock -CommandName Set-NetLbfoTeam - Mock -CommandName Remove-NetLbfoTeam - Mock -CommandName Remove-NetLbfoTeamMember - Mock -CommandName Add-NetLbfoTeamMember - - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $updateTeam.TeamMembers += 'NIC3' - Set-TargetResource @updateTeam - } | Should -Not -Throw - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetLbfoTeam -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetLbfoTeam -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Remove-NetLbfoTeam -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Remove-NetLbfoTeamMember -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Add-NetLbfoTeamMember -Exactly -Times 1 -Scope Context + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetLbfoTeam -Exactly -Times 0 - Assert-MockCalled -CommandName Set-NetLbfoTeam -Exactly -Times 0 - Assert-MockCalled -CommandName Remove-NetLbfoTeam -Exactly -Times 0 - Assert-MockCalled -CommandName Remove-NetLbfoTeamMember -Exactly -Times 0 - Assert-MockCalled -CommandName Add-NetLbfoTeamMember -Exactly -Times 1 + Context 'When team exists but should not exist' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } } - Context 'When team exists but should not exist' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam - Mock -CommandName New-NetLbfoTeam - Mock -CommandName Set-NetLbfoTeam - Mock -CommandName Remove-NetLbfoTeam - Mock -CommandName Remove-NetLbfoTeamMember - Mock -CommandName Add-NetLbfoTeamMember - - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $updateTeam.Ensure = 'Absent' - Set-TargetResource @updateTeam - } | Should -Not -Throw - } + Mock -CommandName New-NetLbfoTeam + Mock -CommandName Set-NetLbfoTeam + Mock -CommandName Remove-NetLbfoTeam + Mock -CommandName Remove-NetLbfoTeamMember + Mock -CommandName Add-NetLbfoTeamMember + } + + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetLbfoTeam -Exactly -Times 0 - Assert-MockCalled -CommandName Set-NetLbfoTeam -Exactly -Times 0 - Assert-MockCalled -CommandName Remove-NetLbfoTeam -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetLbfoTeamMember -Exactly -Times 0 - Assert-MockCalled -CommandName Add-NetLbfoTeamMember -Exactly -Times 0 + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + + $newTeam.Ensure = 'Absent' + + { Set-TargetResource @newTeam } | Should -Not -Throw } } - Describe 'DSC_NetworkTeam\Test-TargetResource' -Tag 'Test' { - Context 'When team does not exist but should' { - Mock -CommandName Get-NetLbfoTeam + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetLbfoTeam -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetLbfoTeam -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Remove-NetLbfoTeam -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetLbfoTeamMember -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Add-NetLbfoTeamMember -Exactly -Times 0 -Scope Context + } + } +} - It 'Should not throw error' { - { - $script:Result = Test-TargetResource @newTeam - } | Should -Not -Throw - } +Describe 'DSC_NetworkTeam\Test-TargetResource' -Tag 'Test' { + Context 'When team does not exist but should' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam + } - It 'Should return false' { - $script:Result | Should -Be $false - } + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + + { $script:Result = Test-TargetResource @newTeam } | Should -Not -Throw } + } - Context 'When team exists but needs a different teaming mode' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $updateTeam.TeamingMode = 'LACP' - $script:Result = Test-TargetResource @updateTeam - } | Should -Not -Throw - } + $script:Result | Should -BeFalse + } + } - It 'Should return false' { - $script:Result | Should -Be $false - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 + Context 'When team exists but needs a different teaming mode' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } } + } - Context 'When team exists but needs a different load balacing algorithm' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $updateTeam.LoadBalancingAlgorithm = 'HyperVPort' - $script:Result = Test-TargetResource @updateTeam - } | Should -Not -Throw + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } - It 'Should return false' { - $script:Result | Should -Be $false - } + $newTeam.TeamingMode = 'LACP' - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 - } + { $script:Result = Test-TargetResource @newTeam } | Should -Not -Throw } + } - Context 'When team exists but has to remove a member adapter' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $updateTeam.TeamMembers = $newTeam.TeamMembers[0] - $script:Result = Test-TargetResource @updateTeam - } | Should -Not -Throw - } + $script:Result | Should -BeFalse + } + } - It 'Should return false' { - $script:Result | Should -Be $false - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 + Context 'When team exists but needs a different load balacing algorithm' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } } + } - Context 'When team exists but has to add a member adapter' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $updateTeam.TeamMembers += 'NIC3' - $script:Result = Test-TargetResource @updateTeam - } | Should -Not -Throw + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } - It 'Should return false' { - $script:Result | Should -Be $false - } + $newTeam.LoadBalancingAlgorithm = 'HyperVPort' - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 - } + { $script:Result = Test-TargetResource @newTeam } | Should -Not -Throw } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:Result | Should -BeFalse + } + } - Context 'When team exists but should not exist' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $updateTeam.Ensure = 'Absent' - $script:Result = Test-TargetResource @updateTeam - } | Should -Not -Throw + Context 'When team exists but has to remove a member adapter' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + } + } - It 'Should return $false' { - $script:Result | Should -Be $false + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 + $newTeam.TeamMembers = $newTeam.TeamMembers[0] + + { $script:Result = Test-TargetResource @newTeam } | Should -Not -Throw + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:Result | Should -BeFalse + } + } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } + } + + Context 'When team exists but has to add a member adapter' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } } + } - Context 'When team exists and no action needed' { - Mock -CommandName Get-NetLbfoTeam -MockWith $mockTeam + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $script:Result = Test-TargetResource @updateTeam - } | Should -Not -Throw + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } - It 'Should return true' { - $script:Result | Should -Be $true + $newTeam.TeamMembers += 'NIC3' + + { $script:Result = Test-TargetResource @newTeam } | Should -Not -Throw + } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:Result | Should -BeFalse + } + } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } + } + + Context 'When team exists but should not exist' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + + $newTeam.Ensure = 'Absent' + + { $script:Result = Test-TargetResource @newTeam } | Should -Not -Throw } + } - Context 'When team does not and no action needed' { - Mock -CommandName Get-NetLbfoTeam + It 'Should return $false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw error' { - { - $updateTeam = $newTeam.Clone() - $updateTeam.Ensure = 'Absent' - $script:Result = Test-TargetResource @updateTeam - } | Should -Not -Throw + $script:Result | Should -BeFalse + } + } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } + } + + Context 'When team exists and no action needed' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + } + } + + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true' { - $script:Result | Should -Be $true + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 + { $script:Result = Test-TargetResource @newTeam } | Should -Not -Throw + } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:Result | Should -BeTrue + } + } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } + } + + Context 'When team does not and no action needed' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam + } + + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $newTeam = @{ + Name = 'HostTeam' + TeamMembers = @('NIC1', 'NIC2') + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } + + $newTeam.Ensure = 'Absent' + + { $script:Result = Test-TargetResource @newTeam } | Should -Not -Throw } } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:Result | Should -BeTrue + } + } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_NetworkTeamInterface.Tests.ps1 b/tests/Unit/DSC_NetworkTeamInterface.Tests.ps1 index b3e6cc25..139dcb4e 100644 --- a/tests/Unit/DSC_NetworkTeamInterface.Tests.ps1 +++ b/tests/Unit/DSC_NetworkTeamInterface.Tests.ps1 @@ -1,17 +1,32 @@ +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_NetworkTeamInterface' - -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_NetworkTeamInterface' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -20,422 +35,556 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup +# # Create the Mock -CommandName Objects that will be used for running tests +# $script:testNicName = 'HostTeamNic' +# $script:testTeamName = 'HostTeam' + +# $mockNetTeamNic = @{ +# Name = 'HostTeamNic' +# Team = 'HostTeam' +# } + +# $testTeamNic = @{ +# Name = 'HostTeamNic' +# TeamName = 'HostTeam' +# Verbose = $true +# } + +# $newTeamNic = @{ +# Name = 'HostTeamNic' +# TeamName = 'HostTeam' +# VlanId = 100 +# Verbose = $true +# } + +# $mockTeamNic = { +# @{ +# Name = 'HostTeamNic' +# Team = 'HostTeam' +# VlanId = 100 +# } +# } + +# $mockTeamNicDefaultVLAN = { +# @{ +# Name = 'HostTeamNic' +# Team = 'HostTeam' +# VlanId = $null +# } +# } + +# $getNetLbfoTeamNic_ParameterFilter = { +# $Name -eq 'HostTeamNic' ` +# -and $Team -eq 'HostTeam' +# } + +# $addNetLbfoTeamNic_ParameterFilter = { +# $Name -eq 'HostTeamNic' ` +# -and $Team -eq 'HostTeam' ` +# -and $VlanId -eq 100 +# } + +# $setNetLbfoTeamNic_ParameterFilter = { +# $Name -eq 'HostTeamNic' ` +# -and $Team -eq 'HostTeam' ` +# -and $VlanId -eq 105 +# } + +# $removeNetLbfoTeamNic_ParameterFilter = { +# $Team -eq 'HostTeam' ` +# -and $VlanId -eq 100 +# } + +Describe 'DSC_NetworkTeamInterface\Get-TargetResource' -Tag 'Get' { + BeforeAll { + $mockTeamNic = { + @{ + Name = 'HostTeamNic' + Team = 'HostTeam' + VlanId = 100 + } + } -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - # Create the Mock -CommandName Objects that will be used for running tests - $script:testNicName = 'HostTeamNic' - $script:testTeamName = 'HostTeam' + $getNetLbfoTeamNic_ParameterFilter = { + $Name -eq 'HostTeamNic' ` + -and $Team -eq 'HostTeam' + } + } - $mockNetTeamNic = [PSCustomObject] @{ - Name = $script:testNicName - Team = $script:testTeamName + Context 'When team Interface does not exist' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter } - $testTeamNic = [PSObject] @{ - Name = $script:testNicName - TeamName = $script:testTeamName - Verbose = $true + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + } + + $script:result = Get-TargetResource @testTeamNic + } } - $newTeamNic = [PSObject] @{ - Name = $script:testNicName - TeamName = $script:testTeamName - VlanId = 100 - Verbose = $true + It 'Should return ensure as absent' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Ensure | Should -Be 'Absent' + } } - $mockTeamNic = { - [PSObject] @{ - Name = $script:testNicName - Team = $script:testTeamName - VlanId = 100 + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + } + } + + Context 'Network Team Interface exists' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -MockWith $mockTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:testTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + } + + $script:result = Get-TargetResource @testTeamNic } } - $mockTeamNicDefaultVLAN = { - [PSObject] @{ - Name = $script:testNicName - Team = $script:testTeamName - VlanId = $null + It 'Should return team properties' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Ensure | Should -Be 'Present' + $script:result.Name | Should -Be $testTeamNic.Name + $script:result.TeamName | Should -Be $testTeamNic.TeamName + $script:result.VlanId | Should -Be 100 + } + } + + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + } + } +} + +Describe 'DSC_NetworkTeamInterface\Set-TargetResource' -Tag 'Set' { + BeforeAll { + $mockTeamNic = { + @{ + Name = 'HostTeamNic' + Team = 'HostTeam' + VlanId = 100 } } $getNetLbfoTeamNic_ParameterFilter = { - $Name -eq $script:testNicName ` - -and $Team -eq $script:testTeamName + $Name -eq 'HostTeamNic' ` + -and $Team -eq 'HostTeam' } $addNetLbfoTeamNic_ParameterFilter = { - $Name -eq $script:testNicName ` - -and $Team -eq $script:testTeamName ` + $Name -eq 'HostTeamNic' ` + -and $Team -eq 'HostTeam' ` -and $VlanId -eq 100 } $setNetLbfoTeamNic_ParameterFilter = { - $Name -eq $script:testNicName ` - -and $Team -eq $script:testTeamName ` + $Name -eq 'HostTeamNic' ` + -and $Team -eq 'HostTeam' ` -and $VlanId -eq 105 } $removeNetLbfoTeamNic_ParameterFilter = { - $Team -eq $script:testTeamName ` + $Team -eq 'HostTeam' ` -and $VlanId -eq 100 } + } - Describe 'DSC_NetworkTeamInterface\Get-TargetResource' -Tag 'Get' { - Context 'When team Interface does not exist' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter + Context 'When team Interface does not exist but invalid VlanId (0) is passed' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter + Mock -CommandName Add-NetLbfoTeamNic + Mock -CommandName Set-NetLbfoTeamNic + } - It 'Should not throw exception' { - $script:result = Get-TargetResource @testTeamNic - } - It 'Should return ensure as absent' { - $script:result.Ensure | Should -Be 'Absent' - } + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call the expected mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.FailedToCreateTeamNic) + + $newTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + VlanId = 100 } + + $errorTeamNic = $newTeamNic.Clone() + $errorTeamNic.VlanId = 0 + + { Set-TargetResource @errorTeamNic } | Should -Throw $errorRecord } + } - Context 'Network Team Interface exists' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -MockWith $mockTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Add-NetLbfoTeamNic -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetLbfoTeamNic -Exactly -Times 0 -Scope Context + } + } - It 'Should not throw exception' { - $script:result = Get-TargetResource @testTeamNic - } + Context 'When team Interface does not exist but should' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter + Mock -CommandName Add-NetLbfoTeamNic -ParameterFilter $addNetLbfoTeamNic_ParameterFilter + Mock -CommandName Set-NetLbfoTeamNic + } - It 'Should return team properties' { - $script:result.Ensure | Should -Be 'Present' - $script:result.Name | Should -Be $testTeamNic.Name - $script:result.TeamName | Should -Be $testTeamNic.TeamName - $script:result.VlanId | Should -Be 100 - } + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call the expected mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 + $newTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + VlanId = 100 } + + { Set-TargetResource @newTeamNic } | Should -Not -Throw } } - Describe 'DSC_NetworkTeamInterface\Set-TargetResource' -Tag 'Set' { - Context 'When team Interface does not exist but invalid VlanId (0) is passed' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Add-NetLbfoTeamNic -ParameterFilter $addNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetLbfoTeamNic -Exactly -Times 0 -Scope Context + } + } - Mock -CommandName Add-NetLbfoTeamNic - Mock -CommandName Set-NetLbfoTeamNic + Context 'When team Interface exists but needs a different VlanId' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -MockWith $mockTeamNic + Mock -CommandName Add-NetLbfoTeamNic + Mock -CommandName Set-NetLbfoTeamNic -ParameterFilter $setNetLbfoTeamNic_ParameterFilter + } - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.FailedToCreateTeamNic) + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw exception' { - { - $errorTeamNic = $newTeamNic.Clone() - $errorTeamNic.VlanId = 0 - Set-TargetResource @errorTeamNic - } | Should -Throw $errorRecord + $newTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + VlanId = 100 } - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 + $updateTeamNic = $newTeamNic.Clone() + $updateTeamNic.VlanId = 105 - Assert-MockCalled ` - -CommandName Add-NetLbfoTeamNic ` - -Exactly -Times 0 - - Assert-MockCalled ` - -CommandName Set-NetLbfoTeamNic ` - -Exactly -Times 0 - } + { Set-TargetResource @updateTeamNic } | Should -Not -Throw } + } - Context 'When team Interface does not exist but should' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Add-NetLbfoTeamNic -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetLbfoTeamNic -ParameterFilter $setNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + } + } - Mock ` - -CommandName Add-NetLbfoTeamNic ` - -ParameterFilter $addNetLbfoTeamNic_ParameterFilter + Context 'When team Interface exists but should not exist' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -MockWith $mockTeamNic + Mock -CommandName Add-NetLbfoTeamNic + Mock -CommandName Set-NetLbfoTeamNic + Mock -CommandName Remove-NetLbfoTeamNic -ParameterFilter $removeNetLbfoTeamNic_ParameterFilter + } - Mock -CommandName Set-NetLbfoTeamNic + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw exception' { - { - Set-TargetResource @newTeamNic - } | Should -Not -Throw + $newTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + VlanId = 100 } - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 + $updateTeamNic = $newTeamNic.Clone() + $updateTeamNic.Ensure = 'Absent' - Assert-MockCalled ` - -CommandName Add-NetLbfoTeamNic ` - -ParameterFilter $addNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 + { Set-TargetResource @updateTeamNic } | Should -Not -Throw + } + } - Assert-MockCalled ` - -CommandName Set-NetLbfoTeamNic ` - -Exactly -Times 0 - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Add-NetLbfoTeamNic -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetLbfoTeamNic -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Remove-NetLbfoTeamNic -ParameterFilter $removeNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + } + } +} + +Describe 'DSC_NetworkTeamInterface\Test-TargetResource' -Tag 'Test' { + BeforeAll { + $mockTeamNic = { + @{ + Name = 'HostTeamNic' + Team = 'HostTeam' + VlanId = 100 + } + } + + $mockTeamNicDefaultVLAN = { + @{ + Name = 'HostTeamNic' + Team = 'HostTeam' + VlanId = $null } + } - Context 'When team Interface exists but needs a different VlanId' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -MockWith $mockTeamNic + $getNetLbfoTeamNic_ParameterFilter = { + $Name -eq 'HostTeamNic' ` + -and $Team -eq 'HostTeam' + } + } - Mock -CommandName Add-NetLbfoTeamNic + Context 'When team Interface does not exist but should' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter + } - Mock ` - -CommandName Set-NetLbfoTeamNic ` - -ParameterFilter $setNetLbfoTeamNic_ParameterFilter + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw exception' { - { - $updateTeamNic = $newTeamNic.Clone() - $updateTeamNic.VlanId = 105 - Set-TargetResource @updateTeamNic - } | Should -Not -Throw + $newTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + VlanId = 100 } - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 + { $script:result = Test-TargetResource @newTeamNic } | Should -Not -Throw + } + } - Assert-MockCalled ` - -CommandName Add-NetLbfoTeamNic ` - -Exactly -Times 0 + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Assert-MockCalled ` - -CommandName Set-NetLbfoTeamNic ` - -ParameterFilter $setNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 - } + $script:result | Should -BeFalse } + } - Context 'When team Interface exists but should not exist' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -MockWith $mockTeamNic - - Mock -CommandName Add-NetLbfoTeamNic - Mock -CommandName Set-NetLbfoTeamNic - - Mock ` - -CommandName Remove-NetLbfoTeamNic ` - -ParameterFilter $removeNetLbfoTeamNic_ParameterFilter - - It 'Should not throw exception' { - { - $updateTeamNic = $newTeamNic.Clone() - $updateTeamNic.Ensure = 'Absent' - Set-TargetResource @updateTeamNic - } | Should -Not -Throw + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + } + } + + Context 'When team Interface exists but needs a different VlanId' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -MockWith $mockTeamNic + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $newTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + VlanId = 100 } - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 + $updateTeamNic = $newTeamNic.Clone() + $updateTeamNic.VlanId = 105 - Assert-MockCalled ` - -CommandName Add-NetLbfoTeamNic ` - -Exactly -Times 0 + $script:result = Test-TargetResource @updateTeamNic + } + } - Assert-MockCalled ` - -CommandName Set-NetLbfoTeamNic ` - -Exactly -Times 0 + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Assert-MockCalled ` - -CommandName Remove-NetLbfoTeamNic ` - -ParameterFilter $removeNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 - } + $script:result | Should -BeFalse } } - Describe 'DSC_NetworkTeamInterface\Test-TargetResource' -Tag 'Test' { - Context 'When team Interface does not exist but should' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw exception' { - { - $script:result = Test-TargetResource @newTeamNic - } | Should -Not -Throw - } + Context 'When team Interface exists but should not exist' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -MockWith $mockTeamNic + } - It 'Should return false' { - $script:result | Should -Be $false - } + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 + $newTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + VlanId = 100 } - } - Context 'When team Interface exists but needs a different VlanId' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -MockWith $mockTeamNic + $updateTeamNic = $newTeamNic.Clone() + $updateTeamNic.Ensure = 'Absent' - It 'Should not throw exception' { - $updateTeamNic = $newTeamNic.Clone() - $updateTeamNic.VlanId = 105 - $script:result = Test-TargetResource @updateTeamNic - } + $script:result = Test-TargetResource @updateTeamNic + } + } - It 'Should return false' { - $script:result | Should -Be $false - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 - } + $script:result | Should -BeFalse } + } - Context 'When team Interface exists but should not exist' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -MockWith $mockTeamNic + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw exception' { - $updateTeamNic = $newTeamNic.Clone() - $updateTeamNic.Ensure = 'Absent' - $script:result = Test-TargetResource @updateTeamNic - } + Context 'When team Interface exists and no action needed' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -MockWith $mockTeamNic + } - It 'Should return false' { - $script:result | Should -Be $false - } + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 + $newTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + VlanId = 100 } - } - Context 'When team Interface exists and no action needed' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -MockWith $mockTeamNic + $updateTeamNic = $newTeamNic.Clone() - It 'Should not throw exception' { - $updateTeamNic = $newTeamNic.Clone() - $script:result = Test-TargetResource @updateTeamNic - } + $script:result = Test-TargetResource @updateTeamNic + } + } - It 'Should return true' { - $script:result | Should -Be $true - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 - } + $script:result | Should -BeTrue } + } - Context 'When team Interface does not exist and no action needed' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw exception' { - $updateTeamNic = $newTeamNic.Clone() - $updateTeamNic.Ensure = 'Absent' - $script:result = Test-TargetResource @updateTeamNic - } + Context 'When team Interface does not exist and no action needed' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter + } - It 'Should return true' { - $script:result | Should -Be $true - } + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 + $newTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + VlanId = 100 } + + $updateTeamNic = $newTeamNic.Clone() + $updateTeamNic.Ensure = 'Absent' + + $script:result = Test-TargetResource @updateTeamNic } + } - Context 'When team Interface exists on the default 0 VLAN' { - Mock ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -MockWith $mockTeamNicDefaultVLAN + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw exception' { - $TeamNicOnDefaultVLAN = $newTeamNic.Clone() - $TeamNicOnDefaultVLAN.VlanId = 0 - $script:result = Test-TargetResource @TeamNicOnDefaultVLAN - } + $script:result | Should -BeTrue + } + } - It 'Should return true' { - $script:result | Should -Be $true - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + } + } + + Context 'When team Interface exists on the default 0 VLAN' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -MockWith $mockTeamNicDefaultVLAN + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamNic ` - -ParameterFilter $getNetLbfoTeamNic_ParameterFilter ` - -Exactly -Times 1 + $newTeamNic = @{ + Name = 'HostTeamNic' + TeamName = 'HostTeam' + VlanId = 100 } + + $TeamNicOnDefaultVLAN = $newTeamNic.Clone() + $TeamNicOnDefaultVLAN.VlanId = 0 + + $script:result = Test-TargetResource @TeamNicOnDefaultVLAN } } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -BeTrue + } + } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamNic -ParameterFilter $getNetLbfoTeamNic_ParameterFilter -Exactly -Times 1 -Scope Context + } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_ProxySettings.Tests.ps1 b/tests/Unit/DSC_ProxySettings.Tests.ps1 index b4e58c70..ed4252f5 100644 --- a/tests/Unit/DSC_ProxySettings.Tests.ps1 +++ b/tests/Unit/DSC_ProxySettings.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_ProxySettings' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_ProxySettings' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,1021 +35,1352 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} -Invoke-TestSetup + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - $script:dscResourceName = 'DSC_ProxySettings' + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} - # Create the Mock Objects that will be used for running tests +Describe 'DSC_ProxySettings\Get-TargetResource' -Tag 'Get' { + BeforeAll { $testProxyServer = 'testproxy:8888' $testProxyExceptions = 1..20 | Foreach-Object -Process { "exception$_.contoso.com" } - $testProxyAlternateExceptions = @('exception1.contoso.com') $testAutoConfigURL = 'http://wpad.contoso.com/test.wpad' - $testProxyAllDisabledSettings = [PSObject] @{ - EnableAutoDetection = $False - EnableManualProxy = $False - EnableAutoConfiguration = $False - } - - $testProxyManualProxySettings = [PSObject] @{ - EnableAutoDetection = $False - EnableManualProxy = $True - ProxyServer = $testProxyServer - EnableAutoConfiguration = $False - } - - $testProxyManualProxyWithExceptionsSettings = [PSObject] @{ - EnableAutoDetection = $False + $testProxyAllEnabledWithBypassLocalSettings = @{ + EnableAutoDetection = $True EnableManualProxy = $True ProxyServer = $testProxyServer + ProxyServerBypassLocal = $True ProxyServerExceptions = $testProxyExceptions - EnableAutoConfiguration = $False + EnableAutoConfiguration = $True + AutoConfigURL = $testAutoConfigURL } - $testProxyManualProxyWithAlternateExceptionsSettings = [PSObject] @{ - EnableAutoDetection = $False - EnableManualProxy = $True - ProxyServer = $testProxyServer - ProxyServerExceptions = $testProxyAlternateExceptions - EnableAutoConfiguration = $False + [System.Byte[]] $testBinary = @(0x46, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0) + + InModuleScope -ScriptBlock { + $testProxyServer = 'testproxy:8888' + $testProxyExceptions = 1..20 | Foreach-Object -Process { + "exception$_.contoso.com" + } + $testAutoConfigURL = 'http://wpad.contoso.com/test.wpad' + + $script:testProxyAllEnabledWithBypassLocalSettings = @{ + EnableAutoDetection = $True + EnableManualProxy = $True + ProxyServer = $testProxyServer + ProxyServerBypassLocal = $True + ProxyServerExceptions = $testProxyExceptions + EnableAutoConfiguration = $True + AutoConfigURL = $testAutoConfigURL + } } + } - $testProxyManualProxyWithBypassLocalOnlySettings = [PSObject] @{ - EnableAutoDetection = $False - EnableManualProxy = $True - ProxyServer = $testProxyServer - ProxyServerBypassLocal = $True - EnableAutoConfiguration = $False + Context 'When no proxy settings are defined in the registry' { + BeforeAll { + Mock -CommandName Get-ItemProperty -Verifiable } - $testProxyAutoConfigOnlySettings = [PSObject] @{ - EnableAutoDetection = $False - EnableManualProxy = $False - EnableAutoConfiguration = $True - AutoConfigURL = $testAutoConfigURL + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $localMachineParameters = @{ + Target = 'LocalMachine' + } + + { $script:getTargetResourceResult = Get-TargetResource @localMachineParameters } | Should -Not -Throw + } } - $testProxyAllEnabledWithoutBypassLocalSettings = [PSObject] @{ - EnableAutoDetection = $True - EnableManualProxy = $True - ProxyServer = $testProxyServer - ProxyServerBypassLocal = $False - ProxyServerExceptions = $testProxyExceptions - EnableAutoConfiguration = $True - AutoConfigURL = $testAutoConfigURL + It 'Should return the expected values' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:getTargetResourceResult.Ensure | Should -Be 'Absent' + } } - $testProxyAllEnabledWithBypassLocalSettings = [PSObject] @{ - EnableAutoDetection = $True - EnableManualProxy = $True - ProxyServer = $testProxyServer - ProxyServerBypassLocal = $True - ProxyServerExceptions = $testProxyExceptions - EnableAutoConfiguration = $True - AutoConfigURL = $testAutoConfigURL + It 'Should call expected mocks' { + Should -InvokeVerifiable } + } - $localMachineParameters = @{ - Target = 'LocalMachine' - Verbose = $true + Context 'When the DefaultConnectionSettings proxy settings are defined in the registry' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + DefaultConnectionSettings = $testBinary + } + } -Verifiable + + Mock -CommandName ConvertFrom-ProxySettingsBinary -MockWith { + return $testProxyAllEnabledWithBypassLocalSettings + } -Verifiable } - $currentUserParameters = @{ - Target = 'CurrentUser' - Verbose = $true + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $localMachineParameters = @{ + Target = 'LocalMachine' + } + + { $script:getTargetResourceResult = Get-TargetResource @localMachineParameters } | Should -Not -Throw + } } - [System.Byte[]] $testBinary = @(0x46, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0) + It 'Should return the expected values' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:getTargetResourceResult.Ensure | Should -Be 'Present' + $script:getTargetResourceResult.EnableAutoDetection | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoDetection + $script:getTargetResourceResult.EnableManualProxy | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableManualProxy + $script:getTargetResourceResult.ProxyServer | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServer + $script:getTargetResourceResult.ProxyServerBypassLocal | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerBypassLocal + $script:getTargetResourceResult.ProxyServerExceptions | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerExceptions + $script:getTargetResourceResult.EnableAutoConfiguration | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoConfiguration + $script:getTargetResourceResult.AutoConfigURL | Should -Be $testProxyAllEnabledWithBypassLocalSettings.AutoConfigURL + } + } - Describe 'DSC_ProxySettings\Get-TargetResource' -Tag 'Get' { - Context 'When no proxy settings are defined in the registry' { - Mock ` - -CommandName Get-ItemProperty ` - -Verifiable + It 'Should call expected mocks' { + Should -InvokeVerifiable + } + } - It 'Should not throw an exception' { - { - $script:getTargetResourceResult = Get-TargetResource @localMachineParameters - } | Should -Not -Throw + Context 'When the SavedLegacySettings proxy settings are defined in the registry' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + SavedLegacySettings = $testBinary } + } -Verifiable - It 'Should return the expected values' { - $script:getTargetResourceResult.Ensure | Should -Be 'Absent' - } + Mock -CommandName ConvertFrom-ProxySettingsBinary -MockWith { + return $testProxyAllEnabledWithBypassLocalSettings + } -Verifiable + } - It 'Should call expected mocks' { - Assert-VerifiableMock + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $localMachineParameters = @{ + Target = 'LocalMachine' } + + { $script:getTargetResourceResult = Get-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When the DefaultConnectionSettings proxy settings are defined in the registry' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - DefaultConnectionSettings = $testBinary - } - } ` - -Verifiable - - Mock ` - -CommandName ConvertFrom-ProxySettingsBinary ` - -MockWith { - return $testProxyAllEnabledWithBypassLocalSettings - } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:getTargetResourceResult = Get-TargetResource @localMachineParameters - } | Should -Not -Throw - } + It 'Should return the expected values' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:getTargetResourceResult.Ensure | Should -Be 'Present' + $script:getTargetResourceResult.EnableAutoDetection | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoDetection + $script:getTargetResourceResult.EnableManualProxy | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableManualProxy + $script:getTargetResourceResult.ProxyServer | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServer + $script:getTargetResourceResult.ProxyServerBypassLocal | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerBypassLocal + $script:getTargetResourceResult.ProxyServerExceptions | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerExceptions + $script:getTargetResourceResult.EnableAutoConfiguration | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoConfiguration + $script:getTargetResourceResult.AutoConfigURL | Should -Be $testProxyAllEnabledWithBypassLocalSettings.AutoConfigURL + } + } - It 'Should return the expected values' { - $script:getTargetResourceResult.Ensure | Should -Be 'Present' - $script:getTargetResourceResult.EnableAutoDetection | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoDetection - $script:getTargetResourceResult.EnableManualProxy | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableManualProxy - $script:getTargetResourceResult.ProxyServer | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServer - $script:getTargetResourceResult.ProxyServerBypassLocal | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerBypassLocal - $script:getTargetResourceResult.ProxyServerExceptions | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerExceptions - $script:getTargetResourceResult.EnableAutoConfiguration | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoConfiguration - $script:getTargetResourceResult.AutoConfigURL | Should -Be $testProxyAllEnabledWithBypassLocalSettings.AutoConfigURL - } + It 'Should call expected mocks' { + Should -InvokeVerifiable + } + } +} + +Describe 'DSC_ProxySettings\Set-TargetResource' -Tag 'Set' { + Context 'When ensuring proxy settings not defined for All Connection types' { + BeforeAll { + Mock -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + Mock -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'SavedLegacySettings' } + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected mocks' { - Assert-VerifiableMock + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Absent' + ConnectionType = 'All' } + + { Set-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When the SavedLegacySettings proxy settings are defined in the registry' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - SavedLegacySettings = $testBinary - } - } ` - -Verifiable - - Mock ` - -CommandName ConvertFrom-ProxySettingsBinary ` - -MockWith { - return $testProxyAllEnabledWithBypassLocalSettings - } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:getTargetResourceResult = Get-TargetResource @localMachineParameters - } | Should -Not -Throw - } + It 'Should call expected mocks' { + Should -Invoke -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'SavedLegacySettings' } -Exactly -Times 1 -Scope Context + } + } - It 'Should return the expected values' { - $script:getTargetResourceResult.Ensure | Should -Be 'Present' - $script:getTargetResourceResult.EnableAutoDetection | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoDetection - $script:getTargetResourceResult.EnableManualProxy | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableManualProxy - $script:getTargetResourceResult.ProxyServer | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServer - $script:getTargetResourceResult.ProxyServerBypassLocal | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerBypassLocal - $script:getTargetResourceResult.ProxyServerExceptions | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerExceptions - $script:getTargetResourceResult.EnableAutoConfiguration | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoConfiguration - $script:getTargetResourceResult.AutoConfigURL | Should -Be $testProxyAllEnabledWithBypassLocalSettings.AutoConfigURL - } + Context 'When ensuring proxy settings not defined for Default Connection type' { + BeforeAll { + Mock -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + Mock -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'SavedLegacySettings' } + } - It 'Should call expected mocks' { - Assert-VerifiableMock + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Absent' + ConnectionType = 'Default' } + + { Set-TargetResource @localMachineParameters } | Should -Not -Throw } } - Describe 'DSC_ProxySettings\Set-TargetResource' -Tag 'Set' { - Context 'When ensuring proxy settings not defined for All Connection types' { - Mock ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + It 'Should call expected mocks' { + Should -Invoke -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'SavedLegacySettings' } -Exactly -Times 0 -Scope Context + } + } + + Context 'When ensuring proxy settings not defined for Legacy Connection type' { + BeforeAll { + Mock -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + Mock -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'SavedLegacySettings' } + } - Mock ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { - Set-TargetResource @localMachineParameters -Ensure 'Absent' -ConnectionType 'All' - } | Should -Not -Throw + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Absent' + ConnectionType = 'Legacy' } - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } ` - -Exactly -Times 1 + { Set-TargetResource @localMachineParameters } | Should -Not -Throw + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Remove-ItemProperty -ParameterFilter { $Name -eq 'SavedLegacySettings' } -Exactly -Times 1 -Scope Context + } + } + + Context 'When ensuring proxy settings are defined for All Connection types' { + BeforeAll { + Mock -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + Mock -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'SavedLegacySettings' } + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Assert-MockCalled ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } ` - -Exactly -Times 1 + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Present' + ConnectionType = 'All' } + + { Set-TargetResource @localMachineParameters } | Should -Not -Throw } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'SavedLegacySettings' } -Exactly -Times 1 -Scope Context + } + } - Context 'When ensuring proxy settings not defined for Default Connection type' { - Mock ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + Context 'When ensuring proxy settings are defined for Default Connection type' { + BeforeAll { + Mock -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + Mock -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'SavedLegacySettings' } + } - Mock ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { - Set-TargetResource @localMachineParameters -Ensure 'Absent' -ConnectionType 'Default' - } | Should -Not -Throw + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Present' + ConnectionType = 'Default' } - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } ` - -Exactly -Times 1 + { Set-TargetResource @localMachineParameters } | Should -Not -Throw + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'SavedLegacySettings' } -Exactly -Times 0 -Scope Context + } + } - Assert-MockCalled ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } ` - -Exactly -Times 0 + Context 'When ensuring proxy settings are defined for Legacy Connection type' { + BeforeAll { + Mock -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + Mock -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'SavedLegacySettings' } + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Present' + ConnectionType = 'Legacy' } + + { Set-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When ensuring proxy settings not defined for Legacy Connection type' { - Mock ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + It 'Should call expected mocks' { + Should -Invoke -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-BinaryRegistryValue -ParameterFilter { $Name -eq 'SavedLegacySettings' } -Exactly -Times 1 -Scope Context + } + } +} - Mock ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } +Describe 'DSC_ProxySettings\Test-TargetResource' -Tag 'Test' { + BeforeAll { + [System.Byte[]] $testBinary = @(0x46, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0) + } - It 'Should not throw an exception' { - { - Set-TargetResource @localMachineParameters -Ensure 'Absent' -ConnectionType 'Legacy' - } | Should -Not -Throw - } + Context 'When no proxy settings are defined in the registry and None Required for All Connection types' { + BeforeAll { + Mock -CommandName Get-ItemProperty -Verifiable + } - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } ` - -Exactly -Times 0 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Assert-MockCalled ` - -CommandName Remove-ItemProperty ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } ` - -Exactly -Times 1 + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Absent' + ConnectionType = 'All' } + + { $script:testTargetResourceResult = Test-TargetResource @localMachineParameters } | Should -Not -Throw } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'When ensuring proxy settings are defined for All Connection types' { - Mock ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + $script:testTargetResourceResult | Should -BeTrue + } + } - Mock ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw an exception' { - { - Set-TargetResource @localMachineParameters -Ensure 'Present' -ConnectionType 'All' - } | Should -Not -Throw + Context 'When DefaultConnectionSettings are defined in the registry and None Required for All Connection types' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + DefaultConnectionSettings = $testBinary } + } -Verifiable + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } ` - -Exactly -Times 1 - Assert-MockCalled ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } ` - -Exactly -Times 1 + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Absent' + ConnectionType = 'All' } + + { $script:testTargetResourceResult = Test-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When ensuring proxy settings are defined for Default Connection type' { - Mock ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Mock ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } + $script:testTargetResourceResult | Should -BeFalse + } + } - It 'Should not throw an exception' { - { - Set-TargetResource @localMachineParameters -Ensure 'Present' -ConnectionType 'Default' - } | Should -Not -Throw + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'When DefaultConnectionSettings are defined in the registry and None Required for Legacy Connection types' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + DefaultConnectionSettings = $testBinary } + } -Verifiable + } - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } ` - -Exactly -Times 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Assert-MockCalled ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } ` - -Exactly -Times 0 + + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Absent' + ConnectionType = 'Legacy' } + + { $script:testTargetResourceResult = Test-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When ensuring proxy settings are defined for Legacy Connection type' { - Mock ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Mock ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } + $script:testTargetResourceResult | Should -BeTrue + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } - It 'Should not throw an exception' { - { - Set-TargetResource @localMachineParameters -Ensure 'Present' -ConnectionType 'Legacy' - } | Should -Not -Throw + Context 'When SavedLegacySettings are defined in the registry and None Required for All Connection types' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + SavedLegacySettings = $testBinary } + } -Verifiable + } - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'DefaultConnectionSettings' } ` - -Exactly -Times 0 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Assert-MockCalled ` - -CommandName Set-BinaryRegistryValue ` - -ParameterFilter { $Name -eq 'SavedLegacySettings' } ` - -Exactly -Times 1 + + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Absent' + ConnectionType = 'All' } + + { $script:testTargetResourceResult = Test-TargetResource @localMachineParameters } | Should -Not -Throw } } - Describe 'DSC_ProxySettings\Test-TargetResource' -Tag 'Test' { - Context 'When no proxy settings are defined in the registry and None Required for All Connection types' { - Mock ` - -CommandName Get-ItemProperty ` - -Verifiable + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { - $script:testTargetResourceResult = Test-TargetResource @localMachineParameters -Ensure 'Absent' -ConnectionType 'All' - } | Should -Not -Throw - } + $script:testTargetResourceResult | Should -BeFalse + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } - It 'Should return true' { - $script:testTargetResourceResult | Should -Be $True + Context 'When SavedLegacySettings are defined in the registry and None Required for Default Connection types' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + SavedLegacySettings = $testBinary } + } -Verifiable + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -Exactly -Times 1 + + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Absent' + ConnectionType = 'Default' } + + { $script:testTargetResourceResult = Test-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When DefaultConnectionSettings are defined in the registry and None Required for All Connection types' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - DefaultConnectionSettings = $testBinary - } - } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:testTargetResourceResult = Test-TargetResource @localMachineParameters -Ensure 'Absent' -ConnectionType 'All' - } | Should -Not -Throw - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:testTargetResourceResult | Should -BeTrue + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - $script:testTargetResourceResult | Should -Be $False + Context 'When DefaultConnectionSettings are defined in the registry but are Different for Default Connection type' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + DefaultConnectionSettings = $testBinary } + } -Verifiable + + Mock -CommandName Test-ProxySettings -MockWith { $false } -Verifiable + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -Exactly -Times 1 + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Present' + ConnectionType = 'Default' } + + { $script:testTargetResourceResult = Test-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When DefaultConnectionSettings are defined in the registry and None Required for Legacy Connection types' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - DefaultConnectionSettings = $testBinary - } - } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:testTargetResourceResult = Test-TargetResource @localMachineParameters -Ensure 'Absent' -ConnectionType 'Legacy' - } | Should -Not -Throw - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:testTargetResourceResult | Should -BeFalse + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Test-ProxySettings -Exactly -Times 1 -Scope Context + } + } - It 'Should return true' { - $script:testTargetResourceResult | Should -Be $True + Context 'When SavedLegacySettings are defined in the registry but are Different for Legacy Connection type' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + SavedLegacySettings = $testBinary } + } -Verifiable - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -Exactly -Times 1 + Mock -CommandName Test-ProxySettings -MockWith { $false } -Verifiable + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Present' + ConnectionType = 'Legacy' } + + { $script:testTargetResourceResult = Test-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When SavedLegacySettings are defined in the registry and None Required for All Connection types' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - SavedLegacySettings = $testBinary - } - } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:testTargetResourceResult = Test-TargetResource @localMachineParameters -Ensure 'Absent' -ConnectionType 'All' - } | Should -Not -Throw - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - $script:testTargetResourceResult | Should -Be $False + $script:testTargetResourceResult | Should -BeFalse + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Test-ProxySettings -Exactly -Times 1 -Scope Context + } + } + + Context 'When DefaultConnectionSettings are defined in the registry and matches for Default Connection type' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + DefaultConnectionSettings = $testBinary } + } -Verifiable - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -Exactly -Times 1 + Mock -CommandName Test-ProxySettings -MockWith { $true } -Verifiable + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Present' + ConnectionType = 'Default' } + + { $script:testTargetResourceResult = Test-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When SavedLegacySettings are defined in the registry and None Required for Default Connection types' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - SavedLegacySettings = $testBinary - } - } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:testTargetResourceResult = Test-TargetResource @localMachineParameters -Ensure 'Absent' -ConnectionType 'Default' - } | Should -Not -Throw - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:testTargetResourceResult | Should -BeTrue + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Test-ProxySettings -Exactly -Times 1 -Scope Context + } + } - It 'Should return true' { - $script:testTargetResourceResult | Should -Be $True + Context 'When SavedLegacySettings are defined in the registry and matches for Legacy Connection type' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + SavedLegacySettings = $testBinary } + } -Verifiable + + Mock -CommandName Test-ProxySettings -MockWith { $true } -Verifiable + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -Exactly -Times 1 + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Present' + ConnectionType = 'Legacy' } + + { $script:testTargetResourceResult = Test-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When DefaultConnectionSettings are defined in the registry but are Different for Default Connection type' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - DefaultConnectionSettings = $testBinary - } - } ` - -Verifiable - - Mock ` - -CommandName Test-ProxySettings ` - -MockWith { $false } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:testTargetResourceResult = Test-TargetResource @localMachineParameters -Ensure 'Present' -ConnectionType 'Default' - } | Should -Not -Throw - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - $script:testTargetResourceResult | Should -Be $False + $script:testTargetResourceResult | Should -BeTrue + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Test-ProxySettings -Exactly -Times 1 -Scope Context + } + } + + Context 'When DefaultConnectionSettings are defined in the registry but Legacy Connection Type settings required' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + DefaultConnectionSettings = $testBinary } + } -Verifiable + + Mock -CommandName Test-ProxySettings -MockWith { $false } -Verifiable + } - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -Exactly -Times 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Assert-MockCalled ` - -CommandName Test-ProxySettings ` - -Exactly -Times 1 + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Present' + ConnectionType = 'Legacy' } + + { $script:testTargetResourceResult = Test-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When SavedLegacySettings are defined in the registry but are Different for Legacy Connection type' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - SavedLegacySettings = $testBinary - } - } ` - -Verifiable - - Mock ` - -CommandName Test-ProxySettings ` - -MockWith { $false } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:testTargetResourceResult = Test-TargetResource @localMachineParameters -Ensure 'Present' -ConnectionType 'Legacy' - } | Should -Not -Throw - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - $script:testTargetResourceResult | Should -Be $False + $script:testTargetResourceResult | Should -BeFalse + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Test-ProxySettings -Exactly -Times 1 -Scope Context + } + } + + Context 'When DefaultConnectionSettings are defined in the registry but Default Connection Type settings required' { + BeforeAll { + Mock -CommandName Get-ItemProperty -MockWith { + @{ + SavedLegacySettings = $testBinary } + } -Verifiable + + Mock -CommandName Test-ProxySettings -MockWith { $false } -Verifiable + } - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -Exactly -Times 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Assert-MockCalled ` - -CommandName Test-ProxySettings ` - -Exactly -Times 1 + $localMachineParameters = @{ + Target = 'LocalMachine' + Ensure = 'Present' + ConnectionType = 'Default' } + + { $script:testTargetResourceResult = Test-TargetResource @localMachineParameters } | Should -Not -Throw } + } - Context 'When DefaultConnectionSettings are defined in the registry and matches for Default Connection type' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - DefaultConnectionSettings = $testBinary - } - } ` - -Verifiable - - Mock ` - -CommandName Test-ProxySettings ` - -MockWith { $true } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:testTargetResourceResult = Test-TargetResource @localMachineParameters -Ensure 'Present' -ConnectionType 'Default' - } | Should -Not -Throw - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true' { - $script:testTargetResourceResult | Should -Be $True - } + $script:testTargetResourceResult | Should -BeFalse + } + } - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -Exactly -Times 1 + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Test-ProxySettings -Exactly -Times 1 -Scope Context + } + } +} - Assert-MockCalled ` - -CommandName Test-ProxySettings ` - -Exactly -Times 1 - } +Describe 'DSC_ProxySettings\Test-ProxySettings' { + BeforeAll { + InModuleScope -ScriptBlock { + $testProxyServer = 'testproxy:8888' + $testProxyExceptions = 1..20 | Foreach-Object -Process { + "exception$_.contoso.com" } + $testProxyAlternateExceptions = @('exception1.contoso.com') + $testAutoConfigURL = 'http://wpad.contoso.com/test.wpad' - Context 'When SavedLegacySettings are defined in the registry and matches for Legacy Connection type' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - SavedLegacySettings = $testBinary - } - } ` - -Verifiable - - Mock ` - -CommandName Test-ProxySettings ` - -MockWith { $true } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:testTargetResourceResult = Test-TargetResource @localMachineParameters -Ensure 'Present' -ConnectionType 'Legacy' - } | Should -Not -Throw - } + $script:testProxyAllDisabledSettings = [PSObject] @{ + EnableAutoDetection = $False + EnableManualProxy = $False + EnableAutoConfiguration = $False + } - It 'Should return true' { - $script:testTargetResourceResult | Should -Be $True - } + $script:testProxyManualProxyWithExceptionsSettings = [PSObject] @{ + EnableAutoDetection = $False + EnableManualProxy = $True + ProxyServer = $testProxyServer + ProxyServerExceptions = $testProxyExceptions + EnableAutoConfiguration = $False + } - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -Exactly -Times 1 + $script:testProxyManualProxyWithAlternateExceptionsSettings = [PSObject] @{ + EnableAutoDetection = $False + EnableManualProxy = $True + ProxyServer = $testProxyServer + ProxyServerExceptions = $testProxyAlternateExceptions + EnableAutoConfiguration = $False + } - Assert-MockCalled ` - -CommandName Test-ProxySettings ` - -Exactly -Times 1 - } + $script:testProxyAllEnabledWithoutBypassLocalSettings = [PSObject] @{ + EnableAutoDetection = $True + EnableManualProxy = $True + ProxyServer = $testProxyServer + ProxyServerBypassLocal = $False + ProxyServerExceptions = $testProxyExceptions + EnableAutoConfiguration = $True + AutoConfigURL = $testAutoConfigURL } - Context 'When DefaultConnectionSettings are defined in the registry but Legacy Connection Type settings required' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - DefaultConnectionSettings = $testBinary - } - } ` - -Verifiable - - Mock ` - -CommandName Test-ProxySettings ` - -MockWith { $false } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:testTargetResourceResult = Test-TargetResource @localMachineParameters -Ensure 'Present' -ConnectionType 'Legacy' - } | Should -Not -Throw - } + $script:testProxyAllEnabledWithBypassLocalSettings = [PSObject] @{ + EnableAutoDetection = $True + EnableManualProxy = $True + ProxyServer = $testProxyServer + ProxyServerBypassLocal = $True + ProxyServerExceptions = $testProxyExceptions + EnableAutoConfiguration = $True + AutoConfigURL = $testAutoConfigURL + } + } + } + Context 'When all proxy types are Disabled' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - $script:testTargetResourceResult | Should -Be $False + $testParams = @{ + CurrentValues = $testProxyAllDisabledSettings + DesiredValues = $testProxyAllDisabledSettings } - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -Exactly -Times 1 + { $script:testProxySettingsResult = Test-ProxySettings @testParams } | Should -Not -Throw + } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Assert-MockCalled ` - -CommandName Test-ProxySettings ` - -Exactly -Times 1 - } + $script:testProxySettingsResult | Should -BeTrue } + } + } - Context 'When DefaultConnectionSettings are defined in the registry but Default Connection Type settings required' { - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - @{ - SavedLegacySettings = $testBinary - } - } ` - -Verifiable - - Mock ` - -CommandName Test-ProxySettings ` - -MockWith { $false } ` - -Verifiable - - It 'Should not throw an exception' { - { - $script:testTargetResourceResult = Test-TargetResource @localMachineParameters -Ensure 'Present' -ConnectionType 'Default' - } | Should -Not -Throw - } + Context 'When all proxy types are Enabled and Proxy Bypass Local is Disabled with all Values matching' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - $script:testTargetResourceResult | Should -Be $False + $testParams = @{ + CurrentValues = $testProxyAllEnabledWithoutBypassLocalSettings + DesiredValues = $testProxyAllEnabledWithoutBypassLocalSettings } - It 'Should call expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -Exactly -Times 1 + { $script:testProxySettingsResult = Test-ProxySettings @testParams } | Should -Not -Throw + } + } - Assert-MockCalled ` - -CommandName Test-ProxySettings ` - -Exactly -Times 1 - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:testProxySettingsResult | Should -BeTrue } } + } - Describe 'DSC_ProxySettings\Test-ProxySettings' { - Context 'When all proxy types are Disabled' { - It 'Should not throw an exception' { - { $script:testProxySettingsResult = Test-ProxySettings ` - -CurrentValues $testProxyAllDisabledSettings ` - -DesiredValues $testProxyAllDisabledSettings ` - -Verbose } | Should -Not -Throw - } + Context 'When all proxy types Enabled and Proxy Bypass Local Enabled with all Values matching' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true' { - $script:testProxySettingsResult | Should -Be $true + $testParams = @{ + CurrentValues = $testProxyAllEnabledWithBypassLocalSettings + DesiredValues = $testProxyAllEnabledWithBypassLocalSettings } + + { $script:testProxySettingsResult = Test-ProxySettings @testParams } | Should -Not -Throw } + } - Context 'When all proxy types are Enabled and Proxy Bypass Local is Disabled with all Values matching' { - It 'Should not throw an exception' { - { $script:testProxySettingsResult = Test-ProxySettings ` - -CurrentValues $testProxyAllEnabledWithoutBypassLocalSettings ` - -DesiredValues $testProxyAllEnabledWithoutBypassLocalSettings ` - -Verbose } | Should -Not -Throw - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true' { - $script:testProxySettingsResult | Should -Be $true - } + $script:testProxySettingsResult | Should -BeTrue } + } + } - Context 'When all proxy types Enabled and Proxy Bypass Local Enabled with all Values matching' { - It 'Should not throw an exception' { - { $script:testProxySettingsResult = Test-ProxySettings ` - -CurrentValues $testProxyAllEnabledWithBypassLocalSettings ` - -DesiredValues $testProxyAllEnabledWithBypassLocalSettings ` - -Verbose } | Should -Not -Throw - } + Context 'When all proxy types Enabled and Proxy Bypass Local Enabled with Bypass Local not matching' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true' { - $script:testProxySettingsResult | Should -Be $true + $testParams = @{ + CurrentValues = $testProxyAllEnabledWithBypassLocalSettings + DesiredValues = $testProxyAllEnabledWithoutBypassLocalSettings } + + { $script:testProxySettingsResult = Test-ProxySettings @testParams } | Should -Not -Throw } + } - Context 'When all proxy types Enabled and Proxy Bypass Local Enabled with Bypass Local not matching' { - It 'Should not throw an exception' { - { $script:testProxySettingsResult = Test-ProxySettings ` - -CurrentValues $testProxyAllEnabledWithBypassLocalSettings ` - -DesiredValues $testProxyAllEnabledWithoutBypassLocalSettings ` - -Verbose } | Should -Not -Throw - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - $script:testProxySettingsResult | Should -Be $false - } + $script:testProxySettingsResult | Should -BeFalse } + } + } - Context 'When only Manual Proxy Server type Enabled with Exceptions Only that match' { - It 'Should not throw an exception' { - { $script:testProxySettingsResult = Test-ProxySettings ` - -CurrentValues $testProxyManualProxyWithExceptionsSettings ` - -DesiredValues $testProxyManualProxyWithExceptionsSettings ` - -Verbose } | Should -Not -Throw - } + Context 'When only Manual Proxy Server type Enabled with Exceptions Only that match' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true' { - $script:testProxySettingsResult | Should -Be $true + $testParams = @{ + CurrentValues = $testProxyManualProxyWithExceptionsSettings + DesiredValues = $testProxyManualProxyWithExceptionsSettings } + + { $script:testProxySettingsResult = Test-ProxySettings @testParams } | Should -Not -Throw } + } - Context 'When only Manual Proxy Server type Enabled with Exceptions Only that do not match' { - It 'Should not throw an exception' { - { $script:testProxySettingsResult = Test-ProxySettings ` - -CurrentValues $testProxyManualProxyWithExceptionsSettings ` - -DesiredValues $testProxyManualProxyWithAlternateExceptionsSettings ` - -Verbose } | Should -Not -Throw - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - $script:testProxySettingsResult | Should -Be $false - } + $script:testProxySettingsResult | Should -BeTrue } } + } + + Context 'When only Manual Proxy Server type Enabled with Exceptions Only that do not match' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Describe 'DSC_ProxySettings\Get-StringLengthInHexBytes' { - Context 'When an empty value string is passed' { - It 'Should return @(0x00,0x00,0x00,0x00)' { - Get-StringLengthInHexBytes -Value '' | Should -Be @( '0x00', '0x00', '0x00', '0x00' ) + $testParams = @{ + CurrentValues = $testProxyManualProxyWithExceptionsSettings + DesiredValues = $testProxyManualProxyWithAlternateExceptionsSettings } + + { $script:testProxySettingsResult = Test-ProxySettings @testParams } | Should -Not -Throw } + } - Context 'When a value string less than 256 characters is passed' { - It 'Should return @(0xFF,0x00,0x00,0x00)' { - Get-StringLengthInHexBytes -Value ([System.String]::new('a', 255)) | Should -Be @( '0xFF', '0x00', '0x00', '0x00' ) - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:testProxySettingsResult | Should -BeFalse } + } + } +} - Context 'When a value string more than 256 characters is passed' { - It 'Should return @(0x01,0x01,0x00,0x00)' { - Get-StringLengthInHexBytes -Value ([System.String]::new('a', 257)) | Should -Be @( '0x01', '0x01', '0x00', '0x00' ) - } +Describe 'DSC_ProxySettings\Get-StringLengthInHexBytes' { + Context 'When an empty value string is passed' { + It 'Should return @(0x00,0x00,0x00,0x00)' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Get-StringLengthInHexBytes -Value '' | Should -Be @( '0x00', '0x00', '0x00', '0x00' ) } } + } - Describe 'DSC_ProxySettings\Get-Int32FromByteArray' { - Context 'When a byte array with a little endian integer less than 256 starting at byte 0' { - It 'Should return 255' { - Get-Int32FromByteArray -Byte ([System.Byte[]] @(255, 0, 0, 0, 99)) -StartByte 0 | Should -Be 255 - } + Context 'When a value string less than 256 characters is passed' { + It 'Should return @(0xFF,0x00,0x00,0x00)' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Get-StringLengthInHexBytes -Value ([System.String]::new('a', 255)) | Should -Be @( '0xFF', '0x00', '0x00', '0x00' ) } + } + } - Context 'When a byte array with a little endian integer less than 256 starting at byte 1' { - It 'Should return 255' { - Get-Int32FromByteArray -Byte ([System.Byte[]] @(99, 255, 0, 0, 0, 99)) -StartByte 1 | Should -Be 255 - } + Context 'When a value string more than 256 characters is passed' { + It 'Should return @(0x01,0x01,0x00,0x00)' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Get-StringLengthInHexBytes -Value ([System.String]::new('a', 257)) | Should -Be @( '0x01', '0x01', '0x00', '0x00' ) } + } + } +} - Context 'When a byte array with a little endian integer more than 256 starting at byte 0' { - It 'Should return 256' { - Get-Int32FromByteArray -Byte ([System.Byte[]] @(1, 1, 0, 0, 99)) -StartByte 0 | Should -Be 257 - } +Describe 'DSC_ProxySettings\Get-Int32FromByteArray' { + Context 'When a byte array with a little endian integer less than 256 starting at byte 0' { + It 'Should return 255' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Get-Int32FromByteArray -Byte ([System.Byte[]] @(255, 0, 0, 0, 99)) -StartByte 0 | Should -Be 255 } + } + } - Context 'When a byte array with a little endian integer more than 256 starting at byte 1' { - It 'Should return 256' { - Get-Int32FromByteArray -Byte ([System.Byte[]] @(99, 1, 1, 0, 0, 99)) -StartByte 1 | Should -Be 257 - } + Context 'When a byte array with a little endian integer less than 256 starting at byte 1' { + It 'Should return 255' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Get-Int32FromByteArray -Byte ([System.Byte[]] @(99, 255, 0, 0, 0, 99)) -StartByte 1 | Should -Be 255 } } + } - Describe 'DSC_ProxySettings\Convert*-ProxySettingsBinary' { - Context 'When all proxy types are Disabled' { - It 'Should not throw an exception when converting to proxy settings Binary' { - { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyAllDisabledSettings -Verbose } | Should -Not -Throw - } + Context 'When a byte array with a little endian integer more than 256 starting at byte 0' { + It 'Should return 256' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception when converting from proxy settings Binary' { - { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw - } + Get-Int32FromByteArray -Byte ([System.Byte[]] @(1, 1, 0, 0, 99)) -StartByte 0 | Should -Be 257 + } + } + } - It 'Should convert the values to binary and back to source values correctly' { - $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyAllDisabledSettings.EnableAutoDetection - $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyAllDisabledSettings.EnableManualProxy - $script:proxySettingsResult.ProxyServer | Should -BeNullOrEmpty - $script:proxySettingsResult.ProxyServerBypassLocal | Should -Be $False - $script:proxySettingsResult.ProxyServerExceptions | Should -BeNullOrEmpty - $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyAllDisabledSettings.EnableAutoConfiguration - $script:proxySettingsResult.AutoConfigURL | Should -BeNullOrEmpty - } + Context 'When a byte array with a little endian integer more than 256 starting at byte 1' { + It 'Should return 256' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Get-Int32FromByteArray -Byte ([System.Byte[]] @(99, 1, 1, 0, 0, 99)) -StartByte 1 | Should -Be 257 } + } + } +} - Context 'When only Manual Proxy Server type Enabled' { - It 'Should not throw an exception when converting to proxy settings Binary' { - { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyManualProxySettings -Verbose } | Should -Not -Throw - } +Describe 'DSC_ProxySettings\Convert*-ProxySettingsBinary' { + Context 'When all proxy types are Disabled' { + It 'Should not throw an exception when converting to proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception when converting from proxy settings Binary' { - { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw + $script:testProxyAllDisabledSettings = @{ + EnableAutoDetection = $False + EnableManualProxy = $False + EnableAutoConfiguration = $False } - It 'Should convert the values to binary and back to source values correctly' { - $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyManualProxySettings.EnableAutoDetection - $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyManualProxySettings.EnableManualProxy - $script:proxySettingsResult.ProxyServer | Should -Be $testProxyManualProxySettings.ProxyServer - $script:proxySettingsResult.ProxyServerBypassLocal | Should -Be $False - $script:proxySettingsResult.ProxyServerExceptions | Should -BeNullOrEmpty - $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyManualProxySettings.EnableAutoConfiguration - $script:proxySettingsResult.AutoConfigURL | Should -BeNullOrEmpty - } + { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyAllDisabledSettings } | Should -Not -Throw } + } - Context 'When only Manual Proxy Server type Enabled with Exceptions Only' { - It 'Should not throw an exception when converting to proxy settings Binary' { - { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyManualProxyWithExceptionsSettings -Verbose } | Should -Not -Throw - } + It 'Should not throw an exception when converting from proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception when converting from proxy settings Binary' { - { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw - } + { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw + } + } - It 'Should convert the values to binary and back to source values correctly' { - $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyManualProxyWithExceptionsSettings.EnableAutoDetection - $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyManualProxyWithExceptionsSettings.EnableManualProxy - $script:proxySettingsResult.ProxyServer | Should -Be $testProxyManualProxyWithExceptionsSettings.ProxyServer - $script:proxySettingsResult.ProxyServerBypassLocal | Should -Be $False - $script:proxySettingsResult.ProxyServerExceptions | Should -Be $testProxyManualProxyWithExceptionsSettings.ProxyServerExceptions - $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyManualProxyWithExceptionsSettings.EnableAutoConfiguration - $script:proxySettingsResult.AutoConfigURL | Should -BeNullOrEmpty - } + It 'Should convert the values to binary and back to source values correctly' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyAllDisabledSettings.EnableAutoDetection + $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyAllDisabledSettings.EnableManualProxy + $script:proxySettingsResult.ProxyServer | Should -BeNullOrEmpty + $script:proxySettingsResult.ProxyServerBypassLocal | Should -BeFalse + $script:proxySettingsResult.ProxyServerExceptions | Should -BeNullOrEmpty + $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyAllDisabledSettings.EnableAutoConfiguration + $script:proxySettingsResult.AutoConfigURL | Should -BeNullOrEmpty } + } + } - Context 'When only Manual Proxy Server type Enabled with Bypass Local Only' { - It 'Should not throw an exception when converting to proxy settings Binary' { - { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyManualProxyWithBypassLocalOnlySettings -Verbose } | Should -Not -Throw - } + Context 'When only Manual Proxy Server type Enabled' { + It 'Should not throw an exception when converting to proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception when converting from proxy settings Binary' { - { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw + $script:testProxyManualProxySettings = @{ + EnableAutoDetection = $False + EnableManualProxy = $True + ProxyServer = 'testproxy:8888' + EnableAutoConfiguration = $False } - It 'Should convert the values to binary and back to source values correctly' { - $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyManualProxyWithBypassLocalOnlySettings.EnableAutoDetection - $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyManualProxyWithBypassLocalOnlySettings.EnableManualProxy - $script:proxySettingsResult.ProxyServer | Should -Be $testProxyManualProxyWithBypassLocalOnlySettings.ProxyServer - $script:proxySettingsResult.ProxyServerBypassLocal | Should -Be $True - $script:proxySettingsResult.ProxyServerExceptions | Should -BeNullOrEmpty - $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyManualProxyWithBypassLocalOnlySettings.EnableAutoConfiguration - $script:proxySettingsResult.AutoConfigURL | Should -BeNullOrEmpty - } + { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyManualProxySettings } | Should -Not -Throw } + } - Context 'When only Auto Config Proxy type Enabled' { - It 'Should not throw an exception when converting to proxy settings Binary' { - { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyAutoConfigOnlySettings -Verbose } | Should -Not -Throw - } + It 'Should not throw an exception when converting from proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception when converting from proxy settings Binary' { - { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw - } + { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw + } + } - It 'Should convert the values to binary and back to source values correctly' { - $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyAutoConfigOnlySettings.EnableAutoDetection - $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyAutoConfigOnlySettings.EnableManualProxy - $script:proxySettingsResult.ProxyServer | Should -BeNullOrEmpty - $script:proxySettingsResult.ProxyServerBypassLocal | Should -Be $False - $script:proxySettingsResult.ProxyServerExceptions | Should -BeNullOrEmpty - $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyAutoConfigOnlySettings.EnableAutoConfiguration - $script:proxySettingsResult.AutoConfigURL | Should -Be $testProxyAutoConfigOnlySettings.AutoConfigURL - } + It 'Should convert the values to binary and back to source values correctly' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyManualProxySettings.EnableAutoDetection + $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyManualProxySettings.EnableManualProxy + $script:proxySettingsResult.ProxyServer | Should -Be $testProxyManualProxySettings.ProxyServer + $script:proxySettingsResult.ProxyServerBypassLocal | Should -BeFalse + $script:proxySettingsResult.ProxyServerExceptions | Should -BeNullOrEmpty + $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyManualProxySettings.EnableAutoConfiguration + $script:proxySettingsResult.AutoConfigURL | Should -BeNullOrEmpty } + } + } - Context 'When all Proxy Types Enabled and Proxy Bypass Local Disabled' { - It 'Should not throw an exception when converting to proxy settings Binary' { - { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyAllEnabledWithoutBypassLocalSettings -Verbose } | Should -Not -Throw - } + Context 'When only Manual Proxy Server type Enabled with Exceptions Only' { + It 'Should not throw an exception when converting to proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception when converting from proxy settings Binary' { - { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw + $script:testProxyManualProxyWithExceptionsSettings = @{ + EnableAutoDetection = $False + EnableManualProxy = $True + ProxyServer = 'testproxy:8888' + ProxyServerExceptions = 1..20 | Foreach-Object -Process { "exception$_.contoso.com" } + EnableAutoConfiguration = $False } - It 'Should convert the values to binary and back to source values correctly' { - $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.EnableAutoDetection - $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.EnableManualProxy - $script:proxySettingsResult.ProxyServer | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.ProxyServer - $script:proxySettingsResult.ProxyServerBypassLocal | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.ProxyServerBypassLocal - $script:proxySettingsResult.ProxyServerExceptions | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.ProxyServerExceptions - $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.EnableAutoConfiguration - $script:proxySettingsResult.AutoConfigURL | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.AutoConfigURL - } + { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyManualProxyWithExceptionsSettings -Verbose } | Should -Not -Throw } + } - Context 'When all Proxy Types Enabled and Proxy Bypass Local Enabled' { - It 'Should not throw an exception when converting to proxy settings Binary' { - { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyAllEnabledWithBypassLocalSettings -Verbose } | Should -Not -Throw - } + It 'Should not throw an exception when converting from proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception when converting from proxy settings Binary' { - { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw - } + { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw + } + } - It 'Should convert the values to binary and back to source values correctly' { - $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoDetection - $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableManualProxy - $script:proxySettingsResult.ProxyServer | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServer - $script:proxySettingsResult.ProxyServerBypassLocal | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerBypassLocal - $script:proxySettingsResult.ProxyServerExceptions | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerExceptions - $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoConfiguration - $script:proxySettingsResult.AutoConfigURL | Should -Be $testProxyAllEnabledWithBypassLocalSettings.AutoConfigURL - } + It 'Should convert the values to binary and back to source values correctly' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyManualProxyWithExceptionsSettings.EnableAutoDetection + $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyManualProxyWithExceptionsSettings.EnableManualProxy + $script:proxySettingsResult.ProxyServer | Should -Be $testProxyManualProxyWithExceptionsSettings.ProxyServer + $script:proxySettingsResult.ProxyServerBypassLocal | Should -BeFalse + $script:proxySettingsResult.ProxyServerExceptions | Should -Be $testProxyManualProxyWithExceptionsSettings.ProxyServerExceptions + $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyManualProxyWithExceptionsSettings.EnableAutoConfiguration + $script:proxySettingsResult.AutoConfigURL | Should -BeNullOrEmpty } } + } + + Context 'When only Manual Proxy Server type Enabled with Bypass Local Only' { + It 'Should not throw an exception when converting to proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Describe 'DSC_ProxySettings\Get-ProxySettingsRegistryKeyPath' { - Context 'When target is default (LocalMachine)' { - It 'Should return "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"' { - Get-ProxySettingsRegistryKeyPath | Should -BeExactly 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections' + $script:testProxyManualProxyWithBypassLocalOnlySettings = @{ + EnableAutoDetection = $False + EnableManualProxy = $True + ProxyServer = 'testproxy:8888' + ProxyServerBypassLocal = $True + EnableAutoConfiguration = $False } + + { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyManualProxyWithBypassLocalOnlySettings -Verbose } | Should -Not -Throw + } + } + + It 'Should not throw an exception when converting from proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw + } + } + + It 'Should convert the values to binary and back to source values correctly' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyManualProxyWithBypassLocalOnlySettings.EnableAutoDetection + $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyManualProxyWithBypassLocalOnlySettings.EnableManualProxy + $script:proxySettingsResult.ProxyServer | Should -Be $testProxyManualProxyWithBypassLocalOnlySettings.ProxyServer + $script:proxySettingsResult.ProxyServerBypassLocal | Should -BeTrue + $script:proxySettingsResult.ProxyServerExceptions | Should -BeNullOrEmpty + $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyManualProxyWithBypassLocalOnlySettings.EnableAutoConfiguration + $script:proxySettingsResult.AutoConfigURL | Should -BeNullOrEmpty } + } + } - Context 'When target is CurrentUser' { - It 'Should return "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"' { - Get-ProxySettingsRegistryKeyPath -Target 'CurrentUser' | Should -BeExactly 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections' + Context 'When only Auto Config Proxy type Enabled' { + It 'Should not throw an exception when converting to proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:testProxyAutoConfigOnlySettings = @{ + EnableAutoDetection = $False + EnableManualProxy = $False + EnableAutoConfiguration = $True + AutoConfigURL = 'http://wpad.contoso.com/test.wpad' } + + { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyAutoConfigOnlySettings -Verbose } | Should -Not -Throw } } - Describe 'DSC_ProxySettings\ConvertTo-Win32RegistryPath' { - Context 'When path contains "HKLM:\SOFTWARE"' { - It 'Should return "HKEY_LOCAL_MACHINE\SOFTWARE"' { - ConvertTo-Win32RegistryPath -Path 'HKLM:\SOFTWARE' | Should -Be 'HKEY_LOCAL_MACHINE\SOFTWARE' + It 'Should not throw an exception when converting from proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw + } + } + + It 'Should convert the values to binary and back to source values correctly' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyAutoConfigOnlySettings.EnableAutoDetection + $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyAutoConfigOnlySettings.EnableManualProxy + $script:proxySettingsResult.ProxyServer | Should -BeNullOrEmpty + $script:proxySettingsResult.ProxyServerBypassLocal | Should -BeFalse + $script:proxySettingsResult.ProxyServerExceptions | Should -BeNullOrEmpty + $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyAutoConfigOnlySettings.EnableAutoConfiguration + $script:proxySettingsResult.AutoConfigURL | Should -Be $testProxyAutoConfigOnlySettings.AutoConfigURL + } + } + } + + Context 'When all Proxy Types Enabled and Proxy Bypass Local Disabled' { + It 'Should not throw an exception when converting to proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:testProxyAllEnabledWithoutBypassLocalSettings = @{ + EnableAutoDetection = $True + EnableManualProxy = $True + ProxyServer = 'testproxy:8888' + ProxyServerBypassLocal = $False + ProxyServerExceptions = 1..20 | Foreach-Object -Process { "exception$_.contoso.com" } + EnableAutoConfiguration = $True + AutoConfigURL = 'http://wpad.contoso.com/test.wpad' } + + { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyAllEnabledWithoutBypassLocalSettings -Verbose } | Should -Not -Throw + } + } + + It 'Should not throw an exception when converting from proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw } + } - Context 'When path contains "HKCU:\SOFTWARE"' { - It 'Should return "HKEY_CURRENT_USER\SOFTWARE"' { - ConvertTo-Win32RegistryPath -Path 'HKCU:\Software' | Should -Be 'HKEY_CURRENT_USER\Software' + It 'Should convert the values to binary and back to source values correctly' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.EnableAutoDetection + $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.EnableManualProxy + $script:proxySettingsResult.ProxyServer | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.ProxyServer + $script:proxySettingsResult.ProxyServerBypassLocal | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.ProxyServerBypassLocal + $script:proxySettingsResult.ProxyServerExceptions | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.ProxyServerExceptions + $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.EnableAutoConfiguration + $script:proxySettingsResult.AutoConfigURL | Should -Be $testProxyAllEnabledWithoutBypassLocalSettings.AutoConfigURL + } + } + } + + Context 'When all Proxy Types Enabled and Proxy Bypass Local Enabled' { + It 'Should not throw an exception when converting to proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:testProxyAllEnabledWithBypassLocalSettings = @{ + EnableAutoDetection = $True + EnableManualProxy = $True + ProxyServer = 'testproxy:8888' + ProxyServerBypassLocal = $True + ProxyServerExceptions = 1..20 | Foreach-Object -Process { "exception$_.contoso.com" } + EnableAutoConfiguration = $True + AutoConfigURL = 'http://wpad.contoso.com/test.wpad' } + + { $script:proxyBinary = ConvertTo-ProxySettingsBinary @testProxyAllEnabledWithBypassLocalSettings -Verbose } | Should -Not -Throw + } + } + + It 'Should not throw an exception when converting from proxy settings Binary' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:proxySettingsResult = ConvertFrom-ProxySettingsBinary -ProxySettings $script:proxyBinary -Verbose } | Should -Not -Throw + } + } + + It 'Should convert the values to binary and back to source values correctly' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:proxySettingsResult.EnableAutoDetection | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoDetection + $script:proxySettingsResult.EnableManualProxy | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableManualProxy + $script:proxySettingsResult.ProxyServer | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServer + $script:proxySettingsResult.ProxyServerBypassLocal | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerBypassLocal + $script:proxySettingsResult.ProxyServerExceptions | Should -Be $testProxyAllEnabledWithBypassLocalSettings.ProxyServerExceptions + $script:proxySettingsResult.EnableAutoConfiguration | Should -Be $testProxyAllEnabledWithBypassLocalSettings.EnableAutoConfiguration + $script:proxySettingsResult.AutoConfigURL | Should -Be $testProxyAllEnabledWithBypassLocalSettings.AutoConfigURL } } } } -finally -{ - Invoke-TestCleanup + +Describe 'DSC_ProxySettings\Get-ProxySettingsRegistryKeyPath' { + Context 'When target is default (LocalMachine)' { + It 'Should return "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Get-ProxySettingsRegistryKeyPath | Should -BeExactly 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections' + } + } + } + + Context 'When target is CurrentUser' { + It 'Should return "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Get-ProxySettingsRegistryKeyPath -Target 'CurrentUser' | Should -BeExactly 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections' + } + } + } +} + +Describe 'DSC_ProxySettings\ConvertTo-Win32RegistryPath' { + Context 'When path contains "HKLM:\SOFTWARE"' { + It 'Should return "HKEY_LOCAL_MACHINE\SOFTWARE"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + ConvertTo-Win32RegistryPath -Path 'HKLM:\SOFTWARE' | Should -Be 'HKEY_LOCAL_MACHINE\SOFTWARE' + } + } + } + + Context 'When path contains "HKCU:\SOFTWARE"' { + It 'Should return "HKEY_CURRENT_USER\SOFTWARE"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + ConvertTo-Win32RegistryPath -Path 'HKCU:\Software' | Should -Be 'HKEY_CURRENT_USER\Software' + } + } + } } diff --git a/tests/Unit/DSC_Route.Tests.ps1 b/tests/Unit/DSC_Route.Tests.ps1 index 1c8e5cc3..17612513 100644 --- a/tests/Unit/DSC_Route.Tests.ps1 +++ b/tests/Unit/DSC_Route.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_Route' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_Route' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,474 +35,744 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} -Invoke-TestSetup + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - # Create the Mock Objects that will be used for running tests - $mockNetAdapter = [PSCustomObject] @{ + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} + +Describe 'DSC_Route\Get-TargetResource' -Tag 'Get' { + BeforeAll { + $mockNetAdapter = @{ Name = 'Ethernet' } - $testRoute = [PSObject]@{ - InterfaceAlias = $mockNetAdapter.Name + $mockRoute = @{ + InterfaceAlias = 'Ethernet' AddressFamily = 'IPv4' DestinationPrefix = '10.0.0.1/8' NextHop = '10.0.0.2' Ensure = 'Present' RouteMetric = 200 Publish = 'Age' - PreferredLifetime = 50000 + PreferredLifetime = ([Timespan]::FromSeconds(50000)) } - $testRouteKeys = [PSObject]@{ - InterfaceAlias = $mockNetAdapter.Name - AddressFamily = $testRoute.AddressFamily - DestinationPrefix = $testRoute.DestinationPrefix - NextHop = $testRoute.NextHop + $testRoute = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + DestinationPrefix = '10.0.0.1/8' + NextHop = '10.0.0.2' + Ensure = 'Present' + RouteMetric = 200 + Publish = 'Age' + PreferredLifetime = 50000 } - $mockRoute = [PSObject]@{ - InterfaceAlias = $mockNetAdapter.Name - AddressFamily = $testRoute.AddressFamily - DestinationPrefix = $testRoute.DestinationPrefix - NextHop = $testRoute.NextHop - Ensure = $testRoute.Ensure - RouteMetric = $testRoute.RouteMetric - Publish = $testRoute.Publish - PreferredLifetime = ([Timespan]::FromSeconds($testRoute.PreferredLifetime)) + InModuleScope -ScriptBlock { + $script:testRoute = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + DestinationPrefix = '10.0.0.1/8' + NextHop = '10.0.0.2' + Ensure = 'Present' + RouteMetric = 200 + Publish = 'Age' + PreferredLifetime = 50000 + } + } + } + Context 'Route does not exist' { + BeforeAll { + Mock -CommandName Get-NetRoute } - Describe 'DSC_Route\Get-TargetResource' -Tag 'Get' { - Context 'Route does not exist' { - Mock -CommandName Get-NetRoute + It 'Should return absent Route' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return absent Route' { - $result = Get-TargetResource @testRouteKeys - $result.Ensure | Should -Be 'Absent' + $testRouteKeys = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + DestinationPrefix = '10.0.0.1/8' + NextHop = '10.0.0.2' } - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - } + $result = Get-TargetResource @testRouteKeys + $result.Ensure | Should -Be 'Absent' } + } - Context 'Route does exist' { - Mock -CommandName Get-NetRoute -MockWith { $mockRoute } - - It 'Should return correct Route' { - $result = Get-TargetResource @testRouteKeys - $result.Ensure | Should -Be 'Present' - $result.InterfaceAlias | Should -Be $testRoute.InterfaceAlias - $result.AddressFamily | Should -Be $testRoute.AddressFamily - $result.DestinationPrefix | Should -Be $testRoute.DestinationPrefix - $result.NextHop | Should -Be $testRoute.NextHop - $result.RouteMetric | Should -Be $testRoute.RouteMetric - $result.Publish | Should -Be $testRoute.Publish - $result.PreferredLifetime | Should -Be $testRoute.PreferredLifetime - } + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + } + } - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - } + Context 'Route does exist' { + BeforeAll { + Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + } + + It 'Should return correct Route' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testRouteKeys = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + DestinationPrefix = '10.0.0.1/8' + NextHop = '10.0.0.2' + } + + $result = Get-TargetResource @testRouteKeys + $result.Ensure | Should -Be 'Present' + $result.InterfaceAlias | Should -Be $testRoute.InterfaceAlias + $result.AddressFamily | Should -Be $testRoute.AddressFamily + $result.DestinationPrefix | Should -Be $testRoute.DestinationPrefix + $result.NextHop | Should -Be $testRoute.NextHop + $result.RouteMetric | Should -Be $testRoute.RouteMetric + $result.Publish | Should -Be $testRoute.Publish + $result.PreferredLifetime | Should -Be $testRoute.PreferredLifetime } } - Describe 'DSC_Route\Set-TargetResource' -Tag 'Set' { - Context 'Route does not exist but should' { - Mock -CommandName Get-NetRoute - Mock -CommandName New-NetRoute - Mock -CommandName Set-NetRoute - Mock -CommandName Remove-NetRoute + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + } + } +} + +Describe 'DSC_Route\Set-TargetResource' -Tag 'Set' { + BeforeAll { + $mockNetAdapter = @{ + Name = 'Ethernet' + } - It 'Should not throw error' { - { - $setTargetResourceParameters = $testRoute.Clone() - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } + $mockRoute = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + DestinationPrefix = '10.0.0.1/8' + NextHop = '10.0.0.2' + Ensure = 'Present' + RouteMetric = 200 + Publish = 'Age' + PreferredLifetime = ([Timespan]::FromSeconds(50000)) + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Set-NetRoute -Exactly -Times 0 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 0 - } + $testRoute = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + DestinationPrefix = '10.0.0.1/8' + NextHop = '10.0.0.2' + Ensure = 'Present' + RouteMetric = 200 + Publish = 'Age' + PreferredLifetime = 50000 + } + + InModuleScope -ScriptBlock { + $script:testRoute = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + DestinationPrefix = '10.0.0.1/8' + NextHop = '10.0.0.2' + Ensure = 'Present' + RouteMetric = 200 + Publish = 'Age' + PreferredLifetime = 50000 } + } + } + Context 'Route does not exist but should' { + BeforeAll { + Mock -CommandName Get-NetRoute + Mock -CommandName New-NetRoute + Mock -CommandName Set-NetRoute + Mock -CommandName Remove-NetRoute + } - Context 'Route exists and should but has a different RouteMetric' { - Mock -CommandName Get-NetRoute -MockWith { $mockRoute } - Mock -CommandName New-NetRoute - Mock -CommandName Set-NetRoute - Mock -CommandName Remove-NetRoute - - It 'Should not throw error' { - { - $setTargetResourceParameters = $testRoute.Clone() - $setTargetResourceParameters.RouteMetric = $setTargetResourceParameters.RouteMetric + 10 - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetRoute -Exactly -Times 0 - Assert-MockCalled -CommandName Set-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 0 - } + $setTargetResourceParameters = $testRoute.Clone() + + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } + } - Context 'Route exists and should but has a different Publish' { - Mock -CommandName Get-NetRoute -MockWith { $mockRoute } - Mock -CommandName New-NetRoute - Mock -CommandName Set-NetRoute - Mock -CommandName Remove-NetRoute - - It 'Should not throw error' { - { - $setTargetResourceParameters = $testRoute.Clone() - $setTargetResourceParameters.Publish = 'No' - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-NetRoute -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 0 -Scope Context + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetRoute -Exactly -Times 0 - Assert-MockCalled -CommandName Set-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 0 - } + Context 'Route exists and should but has a different RouteMetric' { + BeforeAll { + Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + Mock -CommandName New-NetRoute + Mock -CommandName Set-NetRoute + Mock -CommandName Remove-NetRoute + } + + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $setTargetResourceParameters = $script:testRoute.Clone() + $setTargetResourceParameters.RouteMetric = $setTargetResourceParameters.RouteMetric + 10 + + $result = Set-TargetResource @setTargetResourceParameters + + { $result } | Should -Not -Throw } + } - Context 'Route exists and should but has a different PreferredLifetime' { - Mock -CommandName Get-NetRoute -MockWith { $mockRoute } - Mock -CommandName New-NetRoute - Mock -CommandName Set-NetRoute - Mock -CommandName Remove-NetRoute - - It 'Should not throw error' { - { - $setTargetResourceParameters = $testRoute.Clone() - $setTargetResourceParameters.PreferredLifetime = $testRoute.PreferredLifetime + 1000 - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetRoute -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 0 -Scope Context + } + } - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetRoute -Exactly -Times 0 - Assert-MockCalled -CommandName Set-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 0 - } + Context 'Route exists and should but has a different Publish' { + BeforeAll { + Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + Mock -CommandName New-NetRoute + Mock -CommandName Set-NetRoute + Mock -CommandName Remove-NetRoute + } + + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $setTargetResourceParameters = $testRoute.Clone() + $setTargetResourceParameters.Publish = 'No' + + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } + } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetRoute -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 0 -Scope Context + } + } + + Context 'Route exists and should but has a different PreferredLifetime' { + BeforeAll { + Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + Mock -CommandName New-NetRoute + Mock -CommandName Set-NetRoute + Mock -CommandName Remove-NetRoute + } + + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $setTargetResourceParameters = $testRoute.Clone() + $setTargetResourceParameters.PreferredLifetime = $testRoute.PreferredLifetime + 1000 - Context 'Route exists and but should not' { - Mock -CommandName Get-NetRoute -MockWith { $mockRoute } - Mock -CommandName New-NetRoute - Mock -CommandName Set-NetRoute - Mock -CommandName Remove-NetRoute ` - -ParameterFilter { + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetRoute -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 0 -Scope Context + } + } + + Context 'Route exists and but should not' { + BeforeAll { + Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + Mock -CommandName New-NetRoute + Mock -CommandName Set-NetRoute + Mock -CommandName Remove-NetRoute ` + -ParameterFilter { ($InterfaceAlias -eq $testRoute.InterfaceAlias) -and ` - ($AddressFamily -eq $testRoute.AddressFamily) -and ` - ($DestinationPrefix -eq $testRoute.DestinationPrefix) -and ` - ($NextHop -eq $testRoute.NextHop) -and ` - ($RouteMetric -eq $testRoute.RouteMetric) - } + ($AddressFamily -eq $testRoute.AddressFamily) -and ` + ($DestinationPrefix -eq $testRoute.DestinationPrefix) -and ` + ($NextHop -eq $testRoute.NextHop) -and ` + ($RouteMetric -eq $testRoute.RouteMetric) + } + } - It 'Should not throw error' { - { - $setTargetResourceParameters = $testRoute.Clone() - $setTargetResourceParameters.Ensure = 'Absent' - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected mocks and parameters' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetRoute -Exactly -Times 0 - Assert-MockCalled -CommandName Set-NetRoute -Exactly -Times 0 - Assert-MockCalled -CommandName Remove-NetRoute ` - -ParameterFilter { - ($InterfaceAlias -eq $testRoute.InterfaceAlias) -and ` - ($AddressFamily -eq $testRoute.AddressFamily) -and ` - ($DestinationPrefix -eq $testRoute.DestinationPrefix) -and ` - ($NextHop -eq $testRoute.NextHop) -and ` - ($RouteMetric -eq $testRoute.RouteMetric) - } ` - -Exactly -Times 1 - } + $setTargetResourceParameters = $testRoute.Clone() + $setTargetResourceParameters.Ensure = 'Absent' + + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } + } - Context 'Route does not exist and should not' { - Mock -CommandName Get-NetRoute - Mock -CommandName New-NetRoute - Mock -CommandName Set-NetRoute - Mock -CommandName Remove-NetRoute - - It 'Should not throw error' { - { - $setTargetResourceParameters = $testRoute.Clone() - $setTargetResourceParameters.Ensure = 'Absent' - Set-TargetResource @setTargetResourceParameters - } | Should -Not -Throw - } + It 'Should call expected mocks and parameters' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetRoute -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetRoute -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Remove-NetRoute ` + -ParameterFilter { + $InterfaceAlias -eq $testRoute.InterfaceAlias -and ` + $AddressFamily -eq $testRoute.AddressFamily -and ` + $DestinationPrefix -eq $testRoute.DestinationPrefix -and ` + $NextHop -eq $testRoute.NextHop -and ` + $RouteMetric -eq $testRoute.RouteMetric + } -Exactly -Times 1 -Scope Context + } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - Assert-MockCalled -CommandName New-NetRoute -Exactly -Times 0 - Assert-MockCalled -CommandName Set-NetRoute -Exactly -Times 0 - Assert-MockCalled -CommandName Remove-NetRoute -Exactly -Times 0 - } + Context 'Route does not exist and should not' { + BeforeAll { + Mock -CommandName Get-NetRoute + Mock -CommandName New-NetRoute + Mock -CommandName Set-NetRoute + Mock -CommandName Remove-NetRoute + } + + It 'Should not throw error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $setTargetResourceParameters = $testRoute.Clone() + $setTargetResourceParameters.Ensure = 'Absent' + + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } } - Describe 'DSC_Route\Test-TargetResource' -Tag 'Test' { - Context 'Route does not exist but should' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } - Mock -CommandName Get-NetRoute + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName New-NetRoute -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Set-NetRoute -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Remove-NetRoute -Exactly -Times 0 -Scope Context + } + } +} - It 'Should return false' { - $testTargetResourceParameters = $testRoute.Clone() - Test-TargetResource @testTargetResourceParameters | Should -Be $False +Describe 'DSC_Route\Test-TargetResource' -Tag 'Test' { + BeforeAll { + $mockNetAdapter = @{ + Name = 'Ethernet' + } - } + $mockRoute = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + DestinationPrefix = '10.0.0.1/8' + NextHop = '10.0.0.2' + Ensure = 'Present' + RouteMetric = 200 + Publish = 'Age' + PreferredLifetime = ([Timespan]::FromSeconds(50000)) + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - } + $testRoute = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + DestinationPrefix = '10.0.0.1/8' + NextHop = '10.0.0.2' + Ensure = 'Present' + RouteMetric = 200 + Publish = 'Age' + PreferredLifetime = 50000 + } + + InModuleScope -ScriptBlock { + $script:testRoute = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + DestinationPrefix = '10.0.0.1/8' + NextHop = '10.0.0.2' + Ensure = 'Present' + RouteMetric = 200 + Publish = 'Age' + PreferredLifetime = 50000 } + } + } + Context 'Route does not exist but should' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Mock -CommandName Get-NetRoute + } - Context 'Route exists and should but has a different RouteMetric' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } - Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - { - $testTargetResourceParameters = $testRoute.Clone() - $testTargetResourceParameters.RouteMetric = $testTargetResourceParameters.RouteMetric + 5 - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } | Should -Not -Throw - } + $testTargetResourceParameters = $testRoute.Clone() + Test-TargetResource @testTargetResourceParameters | Should -BeFalse + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - } + } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + } + } + + Context 'Route exists and should but has a different RouteMetric' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testTargetResourceParameters = $testRoute.Clone() + $testTargetResourceParameters.RouteMetric = $testTargetResourceParameters.RouteMetric + 5 + + $result = Test-TargetResource @testTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeFalse } + } - Context 'Route exists and should but has a different Publish' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } - Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - { - $testTargetResourceParameters = $testRoute.Clone() - $testTargetResourceParameters.Publish = 'Yes' - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } | Should -Not -Throw - } + Context 'Route exists and should but has a different Publish' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testTargetResourceParameters = $testRoute.Clone() + $testTargetResourceParameters.Publish = 'Yes' + + $result = Test-TargetResource @testTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeFalse } + } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + } + } - Context 'Route exists and should but has a different PreferredLifetime' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } - Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + Context 'Route exists and should but has a different PreferredLifetime' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + } - It 'Should return false' { - { - $testTargetResourceParameters = $testRoute.Clone() - $testTargetResourceParameters.PreferredLifetime = $Splat.PreferredLifetime + 5000 - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } | Should -Not -Throw - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - } + $testTargetResourceParameters = $testRoute.Clone() + $testTargetResourceParameters.PreferredLifetime = $testTargetResourceParameters.PreferredLifetime + 5000 + + $result = Test-TargetResource @testTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeFalse } + } - Context 'Route exists and should and all parameters match' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } - Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + } + } - It 'Should return true' { - { - $testTargetResourceParameters = $testRoute.Clone() - Test-TargetResource @testTargetResourceParameters | Should -Be $True - } | Should -Not -Throw - } + Context 'Route exists and should and all parameters match' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testTargetResourceParameters = $testRoute.Clone() + + $result = Test-TargetResource @testTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeTrue } + } - Context 'Route exists but should not' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } - Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + } + } - It 'Should return false' { - { - $testTargetResourceParameters = $testRoute.Clone() - $testTargetResourceParameters.Ensure = 'Absent' - Test-TargetResource @testTargetResourceParameters | Should -Be $False - } | Should -Not -Throw - } + Context 'Route exists but should not' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Mock -CommandName Get-NetRoute -MockWith { $mockRoute } + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testTargetResourceParameters = $testRoute.Clone() + $testTargetResourceParameters.Ensure = 'Absent' + + $result = Test-TargetResource @testTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeFalse + } + } + + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + } + } + + Context 'Route does not exist and should not' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Mock -CommandName Get-NetRoute + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testTargetResourceParameters = $testRoute.Clone() + $testTargetResourceParameters.Ensure = 'Absent' + + $result = Test-TargetResource @testTargetResourceParameters + + { $result } | Should -Not -Throw + $result | Should -BeTrue } + } - Context 'Route does not exist and should not' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } - Mock -CommandName Get-NetRoute + It 'Should call expected Mocks' { + Should -Invoke -CommandName Get-NetRoute -Exactly -Times 1 -Scope Context + } + } +} - It 'Should return true' { - { - $testTargetResourceParameters = $testRoute.Clone() - $testTargetResourceParameters.Ensure = 'Absent' - Test-TargetResource @testTargetResourceParameters | Should -Be $True - } | Should -Not -Throw - } +Describe 'DSC_Route\Assert-ResourceProperty' { + BeforeAll { + $mockNetAdapter = @{ + Name = 'Ethernet' + } - It 'Should call expected Mocks' { - Assert-MockCalled -CommandName Get-NetRoute -Exactly -Times 1 - } + InModuleScope -ScriptBlock { + $script:testRoute = @{ + InterfaceAlias = 'Ethernet' + AddressFamily = 'IPv4' + DestinationPrefix = '10.0.0.1/8' + NextHop = '10.0.0.2' + Ensure = 'Present' + RouteMetric = 200 + Publish = 'Age' + PreferredLifetime = 50000 } } + } + Context 'Invoking with bad interface alias' { + BeforeAll { + Mock -CommandName Get-NetAdapter + } - Describe 'DSC_Route\Assert-ResourceProperty' { - Context 'Invoking with bad interface alias' { - Mock -CommandName Get-NetAdapter + It 'Should throw an InterfaceNotAvailable error' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should throw an InterfaceNotAvailable error' { - $errorRecord = Get-InvalidArgumentRecord ` - -Message ($script:localizedData.InterfaceNotAvailableError -f $testRoute.InterfaceAlias) ` - -ArgumentName 'Interface' + $errorRecord = Get-InvalidArgumentRecord ` + -Message ($script:localizedData.InterfaceNotAvailableError -f $testRoute.InterfaceAlias) ` + -ArgumentName 'InterfaceAlias' - { Assert-ResourceProperty @testRoute } | Should -Throw $errorRecord - } + { Assert-ResourceProperty @testRoute } | Should -Throw $errorRecord } + } + } - Context 'Invoking with bad IPv4 DestinationPrefix address' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Context 'Invoking with bad IPv4 DestinationPrefix address' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + } - It 'Should throw an exception' { - $Splat = $testRoute.Clone() - $Splat.DestinationPrefix = '10.0.300.0/24' - $Splat.NextHop = '10.0.1.0' - $Splat.AddressFamily = 'IPv4' + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @Splat } | Should -Throw - } + $Splat = $testRoute.Clone() + $Splat.DestinationPrefix = '10.0.300.0/24' + $Splat.NextHop = '10.0.1.0' + $Splat.AddressFamily = 'IPv4' + + { Assert-ResourceProperty @Splat } | Should -Throw } + } + } - Context 'Invoking with bad IPv6 DestinationPrefix address' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Context 'Invoking with bad IPv6 DestinationPrefix address' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + } - It 'Should throw an exception' { - $Splat = $testRoute.Clone() - $Splat.DestinationPrefix = 'fe8x::/64' - $Splat.NextHop = 'fe90::' - $Splat.AddressFamily = 'IPv6' + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @Splat } | Should -Throw - } + $Splat = $testRoute.Clone() + $Splat.DestinationPrefix = 'fe8x::/64' + $Splat.NextHop = 'fe90::' + $Splat.AddressFamily = 'IPv6' + + { Assert-ResourceProperty @Splat } | Should -Throw } + } + } + + Context 'Invoking with IPv4 DestinationPrefix mismatch' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + } - Context 'Invoking with IPv4 DestinationPrefix mismatch' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should throw an exception' { - $Splat = $testRoute.Clone() - $Splat.DestinationPrefix = 'fe80::/64' - $Splat.NextHop = '10.0.1.0' - $Splat.AddressFamily = 'IPv4' + $Splat = $testRoute.Clone() + $Splat.DestinationPrefix = 'fe80::/64' + $Splat.NextHop = '10.0.1.0' + $Splat.AddressFamily = 'IPv4' - { Assert-ResourceProperty @Splat } | Should -Throw - } + { Assert-ResourceProperty @Splat } | Should -Throw } + } + } - Context 'Invoking with IPv6 DestinationPrefix mismatch' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Context 'Invoking with IPv6 DestinationPrefix mismatch' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + } - It 'Should throw an exception' { - $Splat = $testRoute.Clone() - $Splat.DestinationPrefix = '10.0.0.0/24' - $Splat.NextHop = 'fe81::' - $Splat.AddressFamily = 'IPv6' + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @Splat } | Should -Throw - } + $Splat = $testRoute.Clone() + $Splat.DestinationPrefix = '10.0.0.0/24' + $Splat.NextHop = 'fe81::' + $Splat.AddressFamily = 'IPv6' + + { Assert-ResourceProperty @Splat } | Should -Throw } + } + } - Context 'Invoking with bad IPv4 NextHop address' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Context 'Invoking with bad IPv4 NextHop address' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + } - It 'Should throw an exception' { - $Splat = $testRoute.Clone() - $Splat.DestinationPrefix = '10.0.0.0/24' - $Splat.NextHop = '10.0.300.0' - $Splat.AddressFamily = 'IPv4' + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @Splat } | Should -Throw - } + $Splat = $testRoute.Clone() + $Splat.DestinationPrefix = '10.0.0.0/24' + $Splat.NextHop = '10.0.300.0' + $Splat.AddressFamily = 'IPv4' + + { Assert-ResourceProperty @Splat } | Should -Throw } + } + } + + Context 'Invoking with bad IPv6 NextHop address' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + } - Context 'Invoking with bad IPv6 NextHop address' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should throw an exception' { - $Splat = $testRoute.Clone() - $Splat.DestinationPrefix = 'fe80::/64' - $Splat.NextHop = 'fe9x::' - $Splat.AddressFamily = 'IPv6' + $Splat = $testRoute.Clone() + $Splat.DestinationPrefix = 'fe80::/64' + $Splat.NextHop = 'fe9x::' + $Splat.AddressFamily = 'IPv6' - { Assert-ResourceProperty @Splat } | Should -Throw - } + { Assert-ResourceProperty @Splat } | Should -Throw } + } + } - Context 'Invoking with IPv4 NextHop mismatch' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Context 'Invoking with IPv4 NextHop mismatch' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + } - It 'Should throw an exception' { - $Splat = $testRoute.Clone() - $Splat.DestinationPrefix = '10.0.0.0/24' - $Splat.NextHop = 'fe90::' - $Splat.AddressFamily = 'IPv4' + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @Splat } | Should -Throw - } + $Splat = $testRoute.Clone() + $Splat.DestinationPrefix = '10.0.0.0/24' + $Splat.NextHop = 'fe90::' + $Splat.AddressFamily = 'IPv4' + + { Assert-ResourceProperty @Splat } | Should -Throw } + } + } - Context 'Invoking with IPv6 NextHop mismatch' { - Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + Context 'Invoking with IPv6 NextHop mismatch' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $mockNetAdapter } + } - It 'Should throw an exception' { - $Splat = $testRoute.Clone() - $Splat.DestinationPrefix = 'fe80::/64' - $Splat.NextHop = '10.0.1.0' - $Splat.AddressFamily = 'IPv6' + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - { Assert-ResourceProperty @Splat } | Should -Throw - } + $Splat = $testRoute.Clone() + $Splat.DestinationPrefix = 'fe80::/64' + $Splat.NextHop = '10.0.1.0' + $Splat.AddressFamily = 'IPv6' + + { Assert-ResourceProperty @Splat } | Should -Throw } } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_WaitForNetworkTeam.Tests.ps1 b/tests/Unit/DSC_WaitForNetworkTeam.Tests.ps1 index cd3048d8..c579cfe9 100644 --- a/tests/Unit/DSC_WaitForNetworkTeam.Tests.ps1 +++ b/tests/Unit/DSC_WaitForNetworkTeam.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_WaitForNetworkTeam' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_WaitForNetworkTeam' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,226 +35,304 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup - -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - $testTeamName = 'TestTeam' - $mockedGetNetLbfoTeamUp = [pscustomobject] @{ - Name = $testTeamName - Status = 'Up' - } - $mockedGetNetLbfoTeamDegraded = [pscustomobject] @{ - Name = $testTeamName - Status = 'Degraded' - } - $testTeamParametersGet = @{ - Name = $testTeamName - Verbose = $true - } - $testTeamParameters = @{ - Name = $testTeamName - RetryIntervalSec = 5 - RetryCount = 20 - Verbose = $true - } - $getNetLbfoTeamStatusParameters = @{ - Name = $testTeamName - Verbose = $true - } - - Describe 'DSC_WaitForVolume\Get-TargetResource' -Tag 'Get' { - Context 'When the network team exists' { - Mock ` - -CommandName Get-NetLbfoTeamStatus ` - -MockWith { 'Up' } - - It 'Should not throw exception' { - { - $script:result = Get-TargetResource @testTeamParametersGet - } | Should -Not -Throw - } +Describe 'DSC_WaitForNetworkTeam\Get-TargetResource' -Tag 'Get' { + Context 'When the network team exists' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamStatus -MockWith { 'Up' } + } - It "Should return Name $testTeamName" { - $script:result.Name | Should -Be $testTeamName - } + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call the expected mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamStatus ` - -Exactly ` - -Times 1 + $testParams = @{ + Name = 'TestTeam' } + + { $script:result = Get-TargetResource @testParams } | Should -Not -Throw } + } - Context 'When the network team does not exist' { - Mock ` - -CommandName Get-NetLbfoTeamStatus ` - -MockWith { - New-InvalidOperationException -Message $($script:localizedData.NetworkTeamNotFoundMessage -f $testTeamName) - } + It "Should return Name 'TestTeam'" { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetworkTeamNotFoundMessage -f $testTeamName) + $script:result.Name | Should -Be 'TestTeam' + } + } - It 'Should throw exception' { - { - $script:result = Get-TargetResource @testTeamParametersGet - } | Should -Throw $errorRecord - } + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamStatus -Exactly -Times 1 -Scope Context + } + } - It 'Should call the expected mocks' { - Assert-MockCalled ` - -CommandName Get-NetLbfoTeamStatus ` - -Exactly ` - -Times 1 - } + Context 'When the network team does not exist' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamStatus -MockWith { + New-InvalidOperationException -Message ('Network Team {0} not found' -f 'TestTeam') -PassThru } } - Describe 'DSC_WaitForVolume\Set-TargetResource' -Tag 'Set' { - Context 'When network team is Up' { - Mock Start-Sleep - Mock -CommandName Get-NetLbfoTeamStatus -MockWith { 'Up' } + # TODO: Not working + It 'Should throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { - Set-TargetResource @testTeamParameters - } | Should -Not -Throw + $testParams = @{ + Name = 'TestTeam' } - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Start-Sleep -Exactly -Times 0 - Assert-MockCalled -CommandName Get-NetLbfoTeamStatus -Exactly -Times 1 + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.NetworkTeamNotFoundMessage -f $testParams.Name) + + $result = Get-TargetResource @testParams + { $result } | Should -Throw -Not + } + } + + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamStatus -Exactly -Times 1 -Scope Context + } + } +} + +Describe 'DSC_WaitForNetworkTeam\Set-TargetResource' -Tag 'Set' { + Context 'When network team is Up' { + BeforeAll { + Mock -CommandName Start-Sleep + Mock -CommandName Get-NetLbfoTeamStatus -MockWith { 'Up' } + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + Name = 'TestTeam' + RetryIntervalSec = 5 + RetryCount = 20 } + + { Set-TargetResource @testParams } | Should -Not -Throw } + } + + It 'Should call the expected mocks' { + Should -Invoke -CommandName Start-Sleep -Exactly -Times 0 -Scope Context + Should -Invoke -CommandName Get-NetLbfoTeamStatus -Exactly -Times 1 -Scope Context + } + } + + Context 'When network team is not Up' { + BeforeAll { + Mock -CommandName Start-Sleep + Mock -CommandName Get-NetLbfoTeamStatus -MockWith { 'Degraded' } + } - Context 'When network team is not Up' { - Mock Start-Sleep - Mock -CommandName Get-NetLbfoTeamStatus -MockWith { 'Degraded' } + It 'Should throw VolumeNotFoundAfterError' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 $errorRecord = Get-InvalidOperationRecord ` - -Message $($script:localizedData.NetworkTeamNotUpAfterError -f $testTeamName, $testTeamParameters.RetryCount) + -Message $($script:localizedData.NetworkTeamNotUpAfterError -f 'TestTeam', 20) - It 'Should throw VolumeNotFoundAfterError' { - { - Set-TargetResource @testTeamParameters - } | Should -Throw $errorRecord + $testParams = @{ + Name = 'TestTeam' + RetryIntervalSec = 5 + RetryCount = 20 } - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Start-Sleep -Exactly -Times $testTeamParameters.RetryCount - Assert-MockCalled -CommandName Get-NetLbfoTeamStatus -Exactly -Times $testTeamParameters.RetryCount - } + { Set-TargetResource @testParams } | Should -Throw $errorRecord } } - Describe 'DSC_WaitForVolume\Test-TargetResource' -Tag 'Test' { - Context 'When network team is Up' { - Mock -CommandName Get-NetLbfoTeamStatus -MockWith { 'Up' } + It 'Should call the expected mocks' { + Should -Invoke -CommandName Start-Sleep -Exactly -Times 20 -Scope Context + Should -Invoke -CommandName Get-NetLbfoTeamStatus -Exactly -Times 20 -Scope Context + } + } +} + +Describe 'DSC_WaitForNetworkTeam\Test-TargetResource' -Tag 'Test' { + Context 'When network team is Up' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamStatus -MockWith { 'Up' } + } - It 'Should not throw an exception' { - { - $script:result = Test-TargetResource @testTeamParameters - } | Should -Not -Throw - } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true' { - $script:result | Should -Be $true + $testParams = @{ + Name = 'TestTeam' + RetryIntervalSec = 5 + RetryCount = 20 } - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeamStatus -Exactly -Times 1 - } + { $script:result = Test-TargetResource @testParams } | Should -Not -Throw } + } - Context 'When network team is not Up' { - Mock -CommandName Get-NetLbfoTeamStatus -MockWith { 'Degraded' } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { - $script:result = Test-TargetResource @testTeamParameters - } | Should -Not -Throw - } + $script:result | Should -BeTrue + } + } - It 'Should return false' { - $script:result | Should -Be $false - } + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamStatus -Exactly -Times 1 -Scope Context + } + } + + Context 'When network team is not Up' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeamStatus -MockWith { 'Degraded' } + } - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeamStatus -Exactly -Times 1 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + Name = 'TestTeam' + RetryIntervalSec = 5 + RetryCount = 20 } + + { $script:result = Test-TargetResource @testParams } | Should -Not -Throw } } - Describe 'DSC_WaitForVolume\Get-NetLbfoTeamStatus' { - Context 'When network team exists and is Up' { - Mock -CommandName Get-NetLbfoTeam -MockWith { $mockedGetNetLbfoTeamUp } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { - $script:result = Get-NetLbfoTeamStatus @getNetLbfoTeamStatusParameters - } | Should -Not -Throw - } + $script:result | Should -BeFalse + } + } - It 'Should return "Up"' { - $script:result | Should -Be 'Up' - } + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeamStatus -Exactly -Times 1 -Scope Context + } + } +} - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 +Describe 'DSC_WaitForNetworkTeam\Get-NetLbfoTeamStatus' { + Context 'When network team exists and is Up' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'TestTeam' + Status = 'Up' } } + } - Context 'When network team exists and is Degraded' { - Mock -CommandName Get-NetLbfoTeam -MockWith { $mockedGetNetLbfoTeamDegraded } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { - $script:result = Get-NetLbfoTeamStatus @getNetLbfoTeamStatusParameters - } | Should -Not -Throw + $testParams = @{ + Name = 'TestTeam' } - It 'Should return "Degraded"' { - $script:result | Should -Be 'Degraded' + { $script:result = Get-NetLbfoTeamStatus @testParams } | Should -Not -Throw + } + } + + It 'Should return "Up"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -Be 'Up' + } + } + + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } + } + + Context 'When network team exists and is Degraded' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + @{ + Name = 'TestTeam' + Status = 'Degraded' } + } + } + + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 + $testParams = @{ + Name = 'TestTeam' } + + { $script:result = Get-NetLbfoTeamStatus @testParams } | Should -Not -Throw + } + } + + It 'Should return "Degraded"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -Be 'Degraded' + } + } + + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } + } + + Context 'When network team does not exist' { + BeforeAll { + Mock -CommandName Get-NetLbfoTeam -MockWith { + Throw New-Object -TypeName 'Microsoft.PowerShell.Cmdletization.Cim.CimJobException' } + } - Context 'When network team does not exist' { - Mock ` - -CommandName Get-NetLbfoTeam ` - -MockWith { Throw (New-Object -TypeName 'Microsoft.PowerShell.Cmdletization.Cim.CimJobException') } + It 'Should throw expected exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetworkTeamNotFoundMessage -f $testTeamName) + -Message ($script:localizedData.NetworkTeamNotFoundMessage -f 'TestTeam') - It 'Should throw expected exception' { - { - $script:result = Get-NetLbfoTeamStatus @getNetLbfoTeamStatusParameters - } | Should -Throw $errorRecord + $testParams = @{ + Name = 'TestTeam' } - It 'Should call the expected mocks' { - Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 - } + { $script:result = Get-NetLbfoTeamStatus @testParams } | Should -Throw $errorRecord } } + + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-NetLbfoTeam -Exactly -Times 1 -Scope Context + } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/DSC_WinsServerAddress.Tests.ps1 b/tests/Unit/DSC_WinsServerAddress.Tests.ps1 index 5242da46..8f542fbf 100644 --- a/tests/Unit/DSC_WinsServerAddress.Tests.ps1 +++ b/tests/Unit/DSC_WinsServerAddress.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_WinsServerAddress' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_WinsServerAddress' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,220 +35,253 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment -} -Invoke-TestSetup + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - Describe 'DSC_WinsServerAddress\Get-TargetResource' { - Context 'When invoking with an address and one address is currently set' { - Mock Get-WinsClientServerStaticAddress -MockWith { '192.168.0.1' } - Mock Assert-ResourceProperty -MockWith { } + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force +} - It 'Should return current WINS address' { - $getTargetResourceSplat = @{ - InterfaceAlias = 'Ethernet' - Verbose = $true - } +Describe 'DSC_WinsServerAddress\Get-TargetResource' { + Context 'When invoking with an address and one address is currently set' { + BeforeAll { + Mock -CommandName Get-WinsClientServerStaticAddress -MockWith { '192.168.0.1' } + Mock -CommandName Assert-ResourceProperty + } - $result = Get-TargetResource @getTargetResourceSplat - $result.Address | Should -Be '192.168.0.1' - } + It 'Should return current WINS address' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-WinsClientServerStaticAddress -Exactly 1 #-ParameterFilter { Write-Host "--$($InterfaceName)--"; $InterfaceName -eq 'Ethernet' } - Assert-MockCalled -CommandName Assert-ResourceProperty -Exactly 1 #-ParameterFilter { $InterfaceName -eq 'Ethernet' } + $getTargetResourceSplat = @{ + InterfaceAlias = 'Ethernet' } + + $result = Get-TargetResource @getTargetResourceSplat + $result.Address | Should -Be '192.168.0.1' } } - Describe 'DSC_WinsServerAddress\Set-TargetResource' { - BeforeEach { - Mock Get-WinsClientServerStaticAddress -MockWith { '192.168.0.1' } - Mock Set-WinsClientServerStaticAddress -MockWith { } - Mock Assert-ResourceProperty -MockWith { } - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-WinsClientServerStaticAddress -Exactly -Times 1 -Scope Context #-ParameterFilter { Write-Host "--$($InterfaceName)--"; $InterfaceName -eq 'Ethernet' } + Should -Invoke -CommandName Assert-ResourceProperty -Exactly -Times 1 -Scope Context #-ParameterFilter { $InterfaceName -eq 'Ethernet' } + } + } +} - Context 'When invoking with single server address' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - Verbose = $true - } +Describe 'DSC_WinsServerAddress\Set-TargetResource' { + BeforeAll { + Mock -CommandName Get-WinsClientServerStaticAddress -MockWith { '192.168.0.1' } + Mock -CommandName Set-WinsClientServerStaticAddress + Mock -CommandName Assert-ResourceProperty + } - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw - } + Context 'When invoking with single server address' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Set-WinsClientServerStaticAddress -Exactly 1 - Assert-MockCalled -CommandName Assert-ResourceProperty -Exactly 1 + $setTargetResourceSplat = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' } + + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } + } - Context 'When invoking with multiple server addresses' { - It 'Should not throw an exception' { - $setTargetResourceSplat = @{ - Address = @( '192.168.0.99', '192.168.0.100' ) - InterfaceAlias = 'Ethernet' - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Set-WinsClientServerStaticAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Assert-ResourceProperty -Exactly -Times 1 -Scope Context + } + } - { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw - } + Context 'When invoking with multiple server addresses' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -commandName Set-WinsClientServerStaticAddress -Exactly 1 - Assert-MockCalled -CommandName Assert-ResourceProperty -Exactly 1 + $setTargetResourceSplat = @{ + Address = @( '192.168.0.99', '192.168.0.100' ) + InterfaceAlias = 'Ethernet' } + + { Set-TargetResource @setTargetResourceSplat } | Should -Not -Throw } } - Describe 'DSC_WinsServerAddress\Test-TargetResource' { - Context 'When a single WINS server is currently configured' { - BeforeEach { - Mock Get-WinsClientServerStaticAddress -MockWith { '192.168.0.1' } - Mock Assert-ResourceProperty -MockWith { } - } + It 'Should call all the mocks' { + Should -Invoke -commandName Set-WinsClientServerStaticAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Assert-ResourceProperty -Exactly -Times 1 -Scope Context + } + } +} + +Describe 'DSC_WinsServerAddress\Test-TargetResource' { + Context 'When a single WINS server is currently configured' { + BeforeAll { + Mock -CommandName Get-WinsClientServerStaticAddress -MockWith { '192.168.0.1' } + Mock -CommandName Assert-ResourceProperty + } - Context 'When invoking with single server address that is the same as current' { - It 'Should return true' { - $testTargetResourceSplat = @{ - Address = '192.168.0.1' - InterfaceAlias = 'Ethernet' - Verbose = $true - } + Context 'When invoking with single server address that is the same as current' { + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Test-TargetResource @testTargetResourceSplat | Should -Be $true + $testTargetResourceSplat = @{ + Address = '192.168.0.1' + InterfaceAlias = 'Ethernet' } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-WinsClientServerStaticAddress -Exactly 1 - Assert-MockCalled -CommandName Assert-ResourceProperty -Exactly 2 - } + Test-TargetResource @testTargetResourceSplat | Should -BeTrue } + } - Context 'When invoking with single server address that is different to current' { - It 'Should return false' { - $testTargetResourceSplat = @{ - Address = '192.168.0.2' - InterfaceAlias = 'Ethernet' - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-WinsClientServerStaticAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Assert-ResourceProperty -Exactly -Times 2 -Scope Context + } + } - Test-TargetResource @testTargetResourceSplat | Should -Be $False - } + Context 'When invoking with single server address that is different to current' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-WinsClientServerStaticAddress -Exactly 1 - Assert-MockCalled -CommandName Assert-ResourceProperty -Exactly 2 + $testTargetResourceSplat = @{ + Address = '192.168.0.2' + InterfaceAlias = 'Ethernet' } + + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } + } - Context 'Invoking with multiple server addresses that are different to current' { - It 'Should return false' { - $testTargetResourceSplat = @{ - Address = '192.168.0.2', '192.168.0.3' - InterfaceAlias = 'Ethernet' - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-WinsClientServerStaticAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Assert-ResourceProperty -Exactly -Times 2 -Scope Context + } + } - Test-TargetResource @testTargetResourceSplat | Should -Be $False - } + Context 'Invoking with multiple server addresses that are different to current' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-WinsClientServerStaticAddress -Exactly 1 - Assert-MockCalled -CommandName Assert-ResourceProperty -Exactly 2 + $testTargetResourceSplat = @{ + Address = '192.168.0.2', '192.168.0.3' + InterfaceAlias = 'Ethernet' } + + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } } - Context 'When two WINS servers are currently configured' { - BeforeEach { - Mock Get-WinsClientServerStaticAddress -MockWith { '192.168.0.1', '192.168.0.2' } - Mock Assert-ResourceProperty -MockWith { } - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-WinsClientServerStaticAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Assert-ResourceProperty -Exactly -Times 2 -Scope Context + } + } + } + + Context 'When two WINS servers are currently configured' { + BeforeAll { + Mock -CommandName Get-WinsClientServerStaticAddress -MockWith { '192.168.0.1', '192.168.0.2' } + Mock -CommandName Assert-ResourceProperty + } - Context 'When invoking with multiple server addresses that are the same as current' { - It 'Should return true' { - $testTargetResourceSplat = @{ - Address = '192.168.0.1', '192.168.0.2' - InterfaceAlias = 'Ethernet' - Verbose = $true - } + Context 'When invoking with multiple server addresses that are the same as current' { + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Test-TargetResource @testTargetResourceSplat | Should -Be $true + $testTargetResourceSplat = @{ + Address = '192.168.0.1', '192.168.0.2' + InterfaceAlias = 'Ethernet' } - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-WinsClientServerStaticAddress -Exactly 1 - Assert-MockCalled -CommandName Assert-ResourceProperty -Exactly 2 - } + Test-TargetResource @testTargetResourceSplat | Should -BeTrue } + } - Context 'When invoking with multiple server addresses that are different to current 1' { - It 'Should return false' { - $testTargetResourceSplat = @{ - Address = '192.168.0.2', '192.168.0.99' - InterfaceAlias = 'Ethernet' - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-WinsClientServerStaticAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Assert-ResourceProperty -Exactly -Times 2 -Scope Context + } + } - Test-TargetResource @testTargetResourceSplat | Should -Be $false - } + Context 'When invoking with multiple server addresses that are different to current 1' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-WinsClientServerStaticAddress -Exactly 1 - Assert-MockCalled -CommandName Assert-ResourceProperty -Exactly 2 + $testTargetResourceSplat = @{ + Address = '192.168.0.2', '192.168.0.99' + InterfaceAlias = 'Ethernet' } + + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } + } - Context 'When invoking with multiple server addresses that are different to current 2' { - It 'Should return false' { - $testTargetResourceSplat = @{ - Address = '192.168.0.1', '192.168.0.2', '192.168.0.3' - InterfaceAlias = 'Ethernet' - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-WinsClientServerStaticAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Assert-ResourceProperty -Exactly -Times 2 -Scope Context + } + } - Test-TargetResource @testTargetResourceSplat | Should -Be $false - } + Context 'When invoking with multiple server addresses that are different to current 2' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-WinsClientServerStaticAddress -Exactly 1 - Assert-MockCalled -CommandName Assert-ResourceProperty -Exactly 2 + $testTargetResourceSplat = @{ + Address = '192.168.0.1', '192.168.0.2', '192.168.0.3' + InterfaceAlias = 'Ethernet' } + + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } + } - Context 'When invoking with multiple server addresses that are in a different order to current' { - It 'Should return false' { - $testTargetResourceSplat = @{ - Address = '192.168.0.2', '192.168.0.1' - InterfaceAlias = 'Ethernet' - Verbose = $true - } + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-WinsClientServerStaticAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Assert-ResourceProperty -Exactly -Times 2 -Scope Context + } + } - Test-TargetResource @testTargetResourceSplat | Should -Be $false - } + Context 'When invoking with multiple server addresses that are in a different order to current' { + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call all the mocks' { - Assert-MockCalled -CommandName Get-WinsClientServerStaticAddress -Exactly 1 - Assert-MockCalled -CommandName Assert-ResourceProperty -Exactly 2 + $testTargetResourceSplat = @{ + Address = '192.168.0.2', '192.168.0.1' + InterfaceAlias = 'Ethernet' } + + Test-TargetResource @testTargetResourceSplat | Should -BeFalse } } + + It 'Should call all the mocks' { + Should -Invoke -CommandName Get-WinsClientServerStaticAddress -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Assert-ResourceProperty -Exactly -Times 2 -Scope Context + } } - } #end InModuleScope $DSCResourceName -} -finally -{ - Invoke-TestCleanup + } } diff --git a/tests/Unit/DSC_WinsSetting.Tests.ps1 b/tests/Unit/DSC_WinsSetting.Tests.ps1 index 1ba62d23..2e13b9fc 100644 --- a/tests/Unit/DSC_WinsSetting.Tests.ps1 +++ b/tests/Unit/DSC_WinsSetting.Tests.ps1 @@ -1,16 +1,32 @@ -$script:dscModuleName = 'NetworkingDsc' -$script:dscResourceName = 'DSC_WinsSetting' +# Suppressing this rule because Script Analyzer does not understand Pester's syntax. +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () -function Invoke-TestSetup -{ +BeforeDiscovery { try { - Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop' + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } } catch [System.IO.FileNotFoundException] { - throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.' + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + $script:dscResourceName = 'DSC_WinsSetting' $script:testEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:dscModuleName ` @@ -19,323 +35,391 @@ function Invoke-TestSetup -TestType 'Unit' Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1') + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscResourceName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscResourceName } -function Invoke-TestCleanup -{ +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + Restore-TestEnvironment -TestEnvironment $script:testEnvironment + + # Remove module common test helper. + Get-Module -Name 'CommonTestHelper' -All | Remove-Module -Force + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscResourceName -All | Remove-Module -Force } -Invoke-TestSetup +Describe 'DSC_WinsSetting\Get-TargetResource' -Tag 'Get' { + Context 'EnableLmHosts is enabled and EnableDns is enabled' { + BeforeAll { + Mock -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableLMHOSTS' + } -MockWith { + @{ + EnableLMHOSTS = 1 + } + } -# Begin Testing -try -{ - InModuleScope $script:dscResourceName { - # Create the Mock Objects that will be used for running tests - $mockEnabledLmHostsRegistryKey = { - [PSObject] @{ - EnableLMHOSTS = 1 + Mock -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableDNS' + } -MockWith { + @{ + EnableDNS = 1 + } } } - $mockDisabledLmHostsRegistryKey = { - [PSObject] @{ - EnableLMHOSTS = 0 + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + IsSingleInstance = 'Yes' + } + + { $script:result = Get-TargetResource @testParams } | Should -Not -Throw } } - $mockEnabledDNSRegistryKey = { - [PSObject] @{ - EnableDNS = 1 + It 'Should return expected results' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.EnableLmHosts | Should -BeTrue + $script:result.EnableDns | Should -BeTrue } } - $mockDisabledDNSRegistryKey = { - [PSObject] @{ - EnableDNS = 0 - } + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableLMHOSTS' + } -Exactly -Times 1 -Scope Context + + Should -Invoke -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableDNS' + } -Exactly -Times 1 -Scope Context } + } - $mockGetTargetResourceAllEnabled = { - [PSObject] @{ - IsSingleInstance = 'Yes' - EnableLmHosts = $true - EnableDns = $true + Context 'EnableLmHosts is disabled and EnableDns is disabled' { + BeforeAll { + Mock -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableLMHOSTS' + } -MockWith { + @{ + EnableLMHOSTS = 0 + } + } + + Mock -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableDNS' + } -MockWith { + @{ + EnableDNS = 0 + } } } - $mockGetTargetResourceAllDisabled = { - [PSObject] @{ - IsSingleInstance = 'Yes' - EnableLmHosts = $false - EnableDns = $false + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + IsSingleInstance = 'Yes' + } + + { $script:result = Get-TargetResource @testParams } | Should -Not -Throw } } - $mockInvokeCimMethodReturnValueOK = { - @{ - ReturnValue = 0 + It 'Should return expected results' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.EnableLmHosts | Should -BeFalse + $script:result.EnableDns | Should -BeFalse } } - $mockInvokeCimMethodReturnValueError = { + It 'Should call the expected mocks' { + Should -Invoke -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableLMHOSTS' + } -Exactly -Times 1 -Scope Context + + Should -Invoke -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableDNS' + } -Exactly -Times 1 -Scope Context + } + } +} + +Describe 'DSC_DnsClientGlobalSetting\Set-TargetResource' -Tag 'Set' { + BeforeAll { + Mock -CommandName Get-TargetResource -MockWith { @{ - ReturnValue = 74 + IsSingleInstance = 'Yes' + EnableLmHosts = $true + EnableDns = $true } } + } - $getItemProperty_EnableLmHosts_ParameterFilter = { - $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableLMHOSTS' + Context 'Set EnableLmHosts to enabled and EnableDns to enabled' { + BeforeAll { + Mock -CommandName Invoke-CimMethod -MockWith { + @{ + ReturnValue = 0 + } + } } - $getItemProperty_EnableDns_ParameterFilter = { - $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableDNS' - } + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $testParams = @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $true + EnableDns = $true + } - $invokeCimMethod_EnableAll_ParameterFilter = { - $ClassName -eq 'Win32_NetworkAdapterConfiguration' ` - -and $MethodName -eq 'EnableWins' ` - -and $Arguments.DNSEnabledForWINSResolution -eq $true ` - -and $Arguments.WINSEnableLMHostsLookup -eq $true + { Set-TargetResource @testParams } | Should -Not -Throw + } } - $invokeCimMethod_DisableAll_ParameterFilter = { - $ClassName -eq 'Win32_NetworkAdapterConfiguration' ` - -and $MethodName -eq 'EnableWins' ` - -and $Arguments.DNSEnabledForWINSResolution -eq $false ` - -and $Arguments.WINSEnableLMHostsLookup -eq $false + It 'Should call expected Mocks' { + Should -Invoke -CommandName Invoke-CimMethod -Exactly -Times 1 -Scope Context } + } - Describe 'DSC_WinsSetting\Get-TargetResource' -Tag 'Get' { - Context 'EnableLmHosts is enabled and EnableDns is enabled' { - Mock ` - -CommandName Get-ItemProperty ` - -ParameterFilter $getItemProperty_EnableLmHosts_ParameterFilter ` - -MockWith $mockEnabledLmHostsRegistryKey + Context 'Set EnableLmHosts to disabled and EnableDns to disabled' { + BeforeAll { + Mock -CommandName Invoke-CimMethod -MockWith { + @{ + ReturnValue = 0 + } + } + } - Mock ` - -CommandName Get-ItemProperty ` - -ParameterFilter $getItemProperty_EnableDns_ParameterFilter ` - -MockWith $mockEnabledDNSRegistryKey + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { $script:result = Get-TargetResource -IsSingleInstance 'Yes' -Verbose } | Should -Not -Throw + $testParams = @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $false + EnableDns = $false } - It 'Should return expected results' { - $script:result.EnableLmHosts | Should -Be $true - $script:result.EnableDns | Should -Be $true - } + { Set-TargetResource @testParams } | Should -Not -Throw + } + } - It 'Should call the expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -ParameterFilter $getItemProperty_EnableLmHosts_ParameterFilter ` - -Exactly -Times 1 + It 'Should call expected Mocks' { + Should -Invoke -CommandName Invoke-CimMethod -Exactly -Times 1 -Scope Context + } + } - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -ParameterFilter $getItemProperty_EnableDns_ParameterFilter ` - -Exactly -Times 1 + Context 'Set EnableLmHosts and EnableDNS but Invoke-CimMethod returns error' { + BeforeAll { + Mock -CommandName Invoke-CimMethod -MockWith { + @{ + ReturnValue = 74 } } + } - Context 'EnableLmHosts is disabled and EnableDns is disabled' { - Mock ` - -CommandName Get-ItemProperty ` - -ParameterFilter $getItemProperty_EnableLmHosts_ParameterFilter ` - -MockWith $mockDisabledLmHostsRegistryKey + It 'Should throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Mock ` - -CommandName Get-ItemProperty ` - -ParameterFilter $getItemProperty_EnableDns_ParameterFilter ` - -MockWith $mockDisabledDNSRegistryKey + $errorRecord = Get-InvalidOperationRecord ` + -Message ($script:localizedData.FailedUpdatingWinsSettingError -f 74, 'Enable') - It 'Should not throw an exception' { - { $script:result = Get-TargetResource -IsSingleInstance 'Yes' -Verbose } | Should -Not -Throw + $testParams = @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $true + EnableDns = $true } - It 'Should return expected results' { - $script:result.EnableLmHosts | Should -Be $false - $script:result.EnableDns | Should -Be $false - } + { Set-TargetResource @testParams } | Should -Throw $errorRecord + } + } - It 'Should call the expected mocks' { - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -ParameterFilter $getItemProperty_EnableLmHosts_ParameterFilter ` - -Exactly -Times 1 + It 'Should call expected Mocks' { + Should -Invoke -CommandName Invoke-CimMethod -Exactly -Times 1 -Scope Context + } + } +} - Assert-MockCalled ` - -CommandName Get-ItemProperty ` - -ParameterFilter $getItemProperty_EnableDns_ParameterFilter ` - -Exactly -Times 1 +Describe 'DSC_DnsClientGlobalSetting\Test-TargetResource' -Tag 'Test' { + Context 'EnableLmHosts is enabled and EnableDns is enabled' { + BeforeAll { + Mock -CommandName Get-TargetResource -MockWith { + @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $true + EnableDns = $true } } } - Describe 'DSC_DnsClientGlobalSetting\Set-TargetResource' -Tag 'Set' { - BeforeEach { - Mock -CommandName Get-TargetResource -MockWith { $mockGetTargetResourceAllEnabled } - } + Context 'Set EnableLmHosts to true and EnableDns to true' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'Set EnableLmHosts to enabled and EnableDns to enabled' { - Mock ` - -CommandName Invoke-CimMethod ` - -ParameterFilter $invokeCimMethod_EnableAll_ParameterFilter ` - -MockWith $mockInvokeCimMethodReturnValueOK + $testParams = @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $true + EnableDns = $true + } - It 'Should not throw an exception' { - { - Set-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $true -EnableDns $true -Verbose - } | Should -Not -Throw + { $script:result = Test-TargetResource @testParams } | Should -Not -Throw } + } + + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Invoke-CimMethod ` - -ParameterFilter $invokeCimMethod_EnableAll_ParameterFilter ` - -Exactly -Times 1 + $script:result | Should -BeTrue } } + } + + Context 'Set EnableLmHosts to false' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - Context 'Set EnableLmHosts to disabled and EnableDns to disabled' { - Mock ` - -CommandName Invoke-CimMethod ` - -ParameterFilter $invokeCimMethod_DisableAll_ParameterFilter ` - -MockWith $mockInvokeCimMethodReturnValueOK + $testParams = @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $false + } - It 'Should not throw an exception' { - { - Set-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $false -EnableDns $false -Verbose - } | Should -Not -Throw + { $script:result = Test-TargetResource @testParams } | Should -Not -Throw } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Invoke-CimMethod ` - -ParameterFilter $invokeCimMethod_DisableAll_ParameterFilter ` ` - -Exactly -Times 1 + $script:result | Should -BeFalse } } + } - Context 'Set EnableLmHosts and EnableDNS but Invoke-CimMethod returns error' { - Mock ` - -CommandName Invoke-CimMethod ` - -ParameterFilter $invokeCimMethod_EnableAll_ParameterFilter ` ` - -MockWith $mockInvokeCimMethodReturnValueError + Context 'Set EnableDns to false' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.FailedUpdatingWinsSettingError -f 74, 'Enable') + $testParams = @{ + IsSingleInstance = 'Yes' + EnableDns = $false + } - It 'Should throw an exception' { - { - Set-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $true -EnableDns $true -Verbose - } | Should -Throw $errorRecord + { $script:result = Test-TargetResource @testParams } | Should -Not -Throw } + } + + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should call expected Mocks' { - Assert-MockCalled ` - -CommandName Invoke-CimMethod ` - -ParameterFilter $invokeCimMethod_EnableAll_ParameterFilter ` ` - -Exactly -Times 1 + $script:result | Should -BeFalse } } } + } - Describe 'DSC_DnsClientGlobalSetting\Test-TargetResource' -Tag 'Test' { - Context 'EnableLmHosts is enabled and EnableDns is enabled' { - Context 'Set EnableLmHosts to true and EnableDns to true' { - Mock -CommandName Get-TargetResource -MockWith $mockGetTargetResourceAllEnabled + Context 'EnableLmHosts is disabled and EnableDNS is disabled' { + BeforeAll { + Mock -CommandName Get-TargetResource -MockWith { + @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $false + EnableDns = $false + } + } + } - It 'Should not throw an exception' { - { - $script:result = Test-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $true -EnableDns $true -Verbose - } | Should -Not -Throw - } + Context 'Set EnableLmHosts to false and EnableDNS to false' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true' { - $script:result | Should -Be $true + $testParams = @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $false + EnableDns = $false } - } - Context 'Set EnableLmHosts to false' { - Mock -CommandName Get-TargetResource -MockWith $mockGetTargetResourceAllEnabled + { $script:result = Test-TargetResource @testParams } | Should -Not -Throw + } + } - It 'Should not throw an exception' { - { - $script:result = Test-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $false -Verbose - } | Should -Not -Throw - } + It 'Should return true' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - $script:result | Should -Be $false - } + $script:result | Should -BeTrue } + } + } - Context 'Set EnableDns to false' { - Mock -CommandName Get-TargetResource -MockWith $mockGetTargetResourceAllEnabled + Context 'Set EnableLmHosts to true' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { - $script:result = Test-TargetResource -IsSingleInstance 'Yes' -EnableDns $false -Verbose - } | Should -Not -Throw + $testParams = @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $true } - It 'Should return false' { - $script:result | Should -Be $false - } + { $script:result = Test-TargetResource @testParams } | Should -Not -Throw } } - Context 'EnableLmHosts is disabled and EnableDNS is disabled' { - Context 'Set EnableLmHosts to false and EnableDNS to false' { - Mock -CommandName Get-TargetResource -MockWith $mockGetTargetResourceAllDisabled - - It 'Should not throw an exception' { - { - $script:result = Test-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $false -EnableDns $false -Verbose - } | Should -Not -Throw - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return true' { - $script:result | Should -Be $true - } + $script:result | Should -BeFalse } + } + } - Context 'Set EnableLmHosts to true' { - Mock -CommandName Get-TargetResource -MockWith $mockGetTargetResourceAllDisabled + Context 'Set EnableDns to true' { + It 'Should not throw an exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should not throw an exception' { - { - $script:result = Test-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $true -Verbose - } | Should -Not -Throw + $testParams = @{ + IsSingleInstance = 'Yes' + EnableDns = $true } - It 'Should return false' { - $script:result | Should -Be $false - } + { $script:result = Test-TargetResource @testParams } | Should -Not -Throw } + } - Context 'Set EnableDns to true' { - Mock -CommandName Get-TargetResource -MockWith $mockGetTargetResourceAllDisabled - - It 'Should not throw an exception' { - { - $script:result = Test-TargetResource -IsSingleInstance 'Yes' -EnableDns $true -Verbose - } | Should -Not -Throw - } + It 'Should return false' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 - It 'Should return false' { - $script:result | Should -Be $false - } + $script:result | Should -BeFalse } } } } } -finally -{ - Invoke-TestCleanup -} diff --git a/tests/Unit/NetworkingDsc.Common.tests.ps1 b/tests/Unit/NetworkingDsc.Common.tests.ps1 deleted file mode 100644 index 4298a76c..00000000 --- a/tests/Unit/NetworkingDsc.Common.tests.ps1 +++ /dev/null @@ -1,1025 +0,0 @@ -#region HEADER -$script:projectPath = "$PSScriptRoot\..\.." | Convert-Path -$script:projectName = (Get-ChildItem -Path "$script:projectPath\*\*.psd1" | Where-Object -FilterScript { - ($_.Directory.Name -match 'source|src' -or $_.Directory.Name -eq $_.BaseName) -and - $(try - { Test-ModuleManifest -Path $_.FullName -ErrorAction Stop - } - catch - { $false - }) - }).BaseName - -$script:parentModule = Get-Module -Name $script:projectName -ListAvailable | Select-Object -First 1 -$script:subModulesFolder = Join-Path -Path $script:parentModule.ModuleBase -ChildPath 'Modules' -Remove-Module -Name $script:parentModule -Force -ErrorAction 'SilentlyContinue' - -$script:subModuleName = (Split-Path -Path $PSCommandPath -Leaf) -replace '\.Tests.ps1' -$script:subModuleFile = Join-Path -Path $script:subModulesFolder -ChildPath "$($script:subModuleName)/$($script:subModuleName).psm1" - -Import-Module $script:subModuleFile -Force -ErrorAction Stop -#endregion HEADER - -InModuleScope $script:subModuleName { - Describe 'NetworkingDsc.Common\Convert-CIDRToSubhetMask' { - Context 'Subnet Mask Notation Used "192.168.0.0/255.255.0.0"' { - It 'Should Return "192.168.0.0/255.255.0.0"' { - Convert-CIDRToSubhetMask -Address @('192.168.0.0/255.255.0.0') | Should -Be '192.168.0.0/255.255.0.0' - } - } - Context 'Subnet Mask Notation Used "192.168.0.10/255.255.0.0" resulting in source bits masked' { - It 'Should Return "192.168.0.0/255.255.0.0" with source bits masked' { - Convert-CIDRToSubhetMask -Address @('192.168.0.10/255.255.0.0') | Should -Be '192.168.0.0/255.255.0.0' - } - } - Context 'CIDR Notation Used "192.168.0.0/16"' { - It 'Should Return "192.168.0.0/255.255.0.0"' { - Convert-CIDRToSubhetMask -Address @('192.168.0.0/16') | Should -Be '192.168.0.0/255.255.0.0' - } - } - Context 'CIDR Notation Used "192.168.0.10/16" resulting in source bits masked' { - It 'Should Return "192.168.0.0/255.255.0.0" with source bits masked' { - Convert-CIDRToSubhetMask -Address @('192.168.0.10/16') | Should -Be '192.168.0.0/255.255.0.0' - } - } - Context 'Multiple Notations Used "192.168.0.0/16,10.0.0.24/255.255.255.0"' { - $Result = Convert-CIDRToSubhetMask -Address @('192.168.0.0/16', '10.0.0.24/255.255.255.0') - It 'Should Return "192.168.0.0/255.255.0.0,10.0.0.0/255.255.255.0"' { - $Result[0] | Should -Be '192.168.0.0/255.255.0.0' - $Result[1] | Should -Be '10.0.0.0/255.255.255.0' - } - } - Context 'Range Used "192.168.1.0-192.168.1.128"' { - It 'Should Return "192.168.1.0-192.168.1.128"' { - Convert-CIDRToSubhetMask -Address @('192.168.1.0-192.168.1.128') | Should -Be '192.168.1.0-192.168.1.128' - } - } - Context 'IPv6 Used "fe80::/112"' { - It 'Should Return "fe80::/112"' { - Convert-CIDRToSubhetMask -Address @('fe80::/112') | Should -Be 'fe80::/112' - } - } - } - - <# - InModuleScope has to be used to enable the Get-NetAdapter Mock - This is because forcing the ModuleName in the Mock command throws - an exception because the GetAdapter module has no manifest - #> - Describe 'NetworkingDsc.Common\Find-NetworkAdapter' { - - # Generate the adapter data to be used for Mocking - $adapterName = 'Adapter' - $adapterPhysicalMediaType = '802.3' - $adapterStatus = 'Up' - $adapterMacAddress = '11-22-33-44-55-66' - $adapterInterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' - $adapterInterfaceIndex = 2 - $adapterInterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' - $adapterDriverDescription = 'Hyper-V Virtual Ethernet Adapter' - $nomatchAdapter = [PSObject]@{ - Name = 'No Match Adapter' - PhysicalMediaType = '802.11' - Status = 'Disconnected' - MacAddress = '66-55-44-33-22-11' - InterfaceDescription = 'Some Other Interface #2' - InterfaceIndex = 3 - InterfaceGuid = 'FFFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF' - DriverDescription = 'Some Other Interface' - } - $matchAdapter = [PSObject]@{ - Name = $adapterName - PhysicalMediaType = $adapterPhysicalMediaType - Status = $adapterStatus - MacAddress = $adapterMacAddress - InterfaceDescription = $adapterInterfaceDescription - InterfaceIndex = $adapterInterfaceIndex - InterfaceGuid = $adapterInterfaceGuid - DriverDescription = $adapterDriverDescription - } - $adapterArray = @( $nomatchAdapter, $matchAdapter ) - $multipleMatchingAdapterArray = @( $matchAdapter, $matchAdapter ) - - Context 'Name is passed and one adapter matches' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - It 'Should not throw exception' { - { $script:result = Find-NetworkAdapter -Name $adapterName -Verbose } | Should -Not -Throw - } - - It 'Should return expected adapter' { - $script:result.Name | Should -Be $adapterName - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'Name is passed and no adapters match' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundError) - - It 'Should throw the correct exception' { - { $script:result = Find-NetworkAdapter -Name 'NOMATCH' -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'PhysicalMediaType is passed and one adapter matches' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - It 'Should not throw exception' { - { $script:result = Find-NetworkAdapter -PhysicalMediaType $adapterPhysicalMediaType -Verbose } | Should -Not -Throw - } - - It 'Should return expected adapter' { - $script:result.Name | Should -Be $adapterName - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'PhysicalMediaType is passed and no adapters match' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundError) - - It 'Should throw the correct exception' { - { $script:result = Find-NetworkAdapter -PhysicalMediaType 'NOMATCH' -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'Status is passed and one adapter matches' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - It 'Should not throw exception' { - { $script:result = Find-NetworkAdapter -Status $adapterStatus -Verbose } | Should -Not -Throw - } - - It 'Should return expected adapter' { - $script:result.Name | Should -Be $adapterName - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'Status is passed and no adapters match' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundError) - - It 'Should throw the correct exception' { - { $script:result = Find-NetworkAdapter -Status 'Disabled' -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'MacAddress is passed and one adapter matches' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - It 'Should not throw exception' { - { $script:result = Find-NetworkAdapter -MacAddress $adapterMacAddress -Verbose } | Should -Not -Throw - } - - It 'Should return expected adapter' { - $script:result.Name | Should -Be $adapterName - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'MacAddress is passed and no adapters match' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundError) - - It 'Should throw the correct exception' { - { $script:result = Find-NetworkAdapter -MacAddress '00-00-00-00-00-00' -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'InterfaceDescription is passed and one adapter matches' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - It 'Should not throw exception' { - { $script:result = Find-NetworkAdapter -InterfaceDescription $adapterInterfaceDescription -Verbose } | Should -Not -Throw - } - - It 'Should return expected adapter' { - $script:result.Name | Should -Be $adapterName - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'InterfaceDescription is passed and no adapters match' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundError) - - It 'Should throw the correct exception' { - { $script:result = Find-NetworkAdapter -InterfaceDescription 'NOMATCH' -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'InterfaceIndex is passed and one adapter matches' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - It 'Should not throw exception' { - { $script:result = Find-NetworkAdapter -InterfaceIndex $adapterInterfaceIndex -Verbose } | Should -Not -Throw - } - - It 'Should return expected adapter' { - $script:result.Name | Should -Be $adapterName - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'InterfaceIndex is passed and no adapters match' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundError) - - It 'Should throw the correct exception' { - { $script:result = Find-NetworkAdapter -InterfaceIndex 99 -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'InterfaceGuid is passed and one adapter matches' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - It 'Should not throw exception' { - { $script:result = Find-NetworkAdapter -InterfaceGuid $adapterInterfaceGuid -Verbose } | Should -Not -Throw - } - - It 'Should return expected adapter' { - $script:result.Name | Should -Be $adapterName - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'InterfaceGuid is passed and no adapters match' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundError) - - It 'Should throw the correct exception' { - { $script:result = Find-NetworkAdapter -InterfaceGuid 'NOMATCH' -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'DriverDescription is passed and one adapter matches' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - It 'Should not throw exception' { - { $script:result = Find-NetworkAdapter -DriverDescription $adapterDriverDescription -Verbose } | Should -Not -Throw - } - - It 'Should return expected adapter' { - $script:result.Name | Should -Be $adapterName - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'DriverDescription is passed and no adapters match' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.NetAdapterNotFoundError) - - It 'Should throw the correct exception' { - { $script:result = Find-NetworkAdapter -DriverDescription 'NOMATCH' -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'No parameters are passed and multiple Adapters adapters match but IgnoreMultipleMatchingAdapters is not set' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.MultipleMatchingNetAdapterFound -f 2) - - It 'Should throw the correct exception' { - { $script:result = Find-NetworkAdapter -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'No parameters are passed and multiple Adapters adapters match and IgnoreMultipleMatchingAdapters is set and interface number is 2' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $adapterArray } - - It 'Should not throw exception' { - { $script:result = Find-NetworkAdapter -IgnoreMultipleMatchingAdapters:$true -InterfaceNumber 2 -Verbose } | Should -Not -Throw - } - - It 'Should return expected adapter' { - $script:result.Name | Should -Be $adapterName - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'Multiple Adapters adapters match but IgnoreMultipleMatchingAdapters is not set' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $multipleMatchingAdapterArray } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.MultipleMatchingNetAdapterFound -f 2) - - It 'Should throw the correct exception' { - { $script:result = Find-NetworkAdapter -PhysicalMediaType $adapterPhysicalMediaType -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'Multiple Adapters adapters match and IgnoreMultipleMatchingAdapters is set' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $multipleMatchingAdapterArray } - - It 'Should not throw exception' { - { $script:result = Find-NetworkAdapter -PhysicalMediaType $adapterPhysicalMediaType -IgnoreMultipleMatchingAdapters:$true -Verbose } | Should -Not -Throw - } - - It 'Should return expected adapter' { - $script:result.Name | Should -Be $adapterName - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'Multiple Adapters adapters match and IgnoreMultipleMatchingAdapters is set and InterfaceNumber is greater than matching adapters' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $multipleMatchingAdapterArray } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.InvalidNetAdapterNumberError -f 2, 3) - - It 'Should throw the correct exception' { - { $script:result = Find-NetworkAdapter -PhysicalMediaType $adapterPhysicalMediaType -IgnoreMultipleMatchingAdapters:$true -InterfaceNumber 3 -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - } - - <# - InModuleScope has to be used to enable the Get-NetAdapter Mock - This is because forcing the ModuleName in the Mock command throws - an exception because the GetAdapter module has no manifest - #> - Describe 'NetworkingDsc.Common\Get-DnsClientServerStaticAddress' { - - # Generate the adapter data to be used for Mocking - $interfaceAlias = 'Adapter' - $interfaceGuid = [Guid]::NewGuid().ToString() - $nomatchAdapter = $null - $matchAdapter = [PSObject]@{ - InterfaceGuid = $interfaceGuid - } - $ipv4Parameters = @{ - InterfaceAlias = $interfaceAlias - AddressFamily = 'IPv4' - } - $ipv6Parameters = @{ - InterfaceAlias = $interfaceAlias - AddressFamily = 'IPv6' - } - $noIpv4StaticAddressString = '' - $oneIpv4StaticAddressString = '8.8.8.8' - $secondIpv4StaticAddressString = '4.4.4.4' - $twoIpv4StaticAddressString = "$oneIpv4StaticAddressString,$secondIpv4StaticAddressString" - $noIpv6StaticAddressString = '' - $oneIpv6StaticAddressString = '::1' - $secondIpv6StaticAddressString = '::2' - $twoIpv6StaticAddressString = "$oneIpv6StaticAddressString,$secondIpv6StaticAddressString" - - Context 'Interface Alias does not match adapter in system' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $nomatchAdapter } - - $errorRecord = Get-InvalidOperationRecord ` - -Message ($script:localizedData.InterfaceAliasNotFoundError -f $interfaceAlias) - - It 'Should throw exception' { - { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'Interface Alias was found in system but IPv4 NameServer is empty' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $matchAdapter } - - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - [psobject] @{ - NameServer = $noIpv4StaticAddressString - } - } - - It 'Should not throw exception' { - { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters -Verbose } | Should -Not -Throw - } - - It 'Should return null' { - $script:result | Should -BeNullOrEmpty - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 - } - } - - Context 'Interface Alias was found in system but IPv4 NameServer property does not exist' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $matchAdapter } - - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - [psobject] @{ - Dummy = '' - } - } - - It 'Should not throw exception' { - { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters -Verbose } | Should -Not -Throw - } - - It 'Should return null' { - $script:result | Should -BeNullOrEmpty - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 - } - } - - Context 'Interface Alias was found in system but IPv4 NameServer contains one DNS entry' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $matchAdapter } - - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - [psobject] @{ - NameServer = $oneIpv4StaticAddressString - } - } - - It 'Should not throw exception' { - { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters -Verbose } | Should -Not -Throw - } - - It 'Should return expected address' { - $script:result | Should -Be $oneIpv4StaticAddressString - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 - } - } - - Context 'Interface Alias was found in system but IPv4 NameServer contains two DNS entries' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $matchAdapter } - - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - [psobject] @{ - NameServer = $twoIpv4StaticAddressString - } - } - - It 'Should not throw exception' { - { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters -Verbose } | Should -Not -Throw - } - - It 'Should return two expected addresses' { - $script:result[0] | Should -Be $oneIpv4StaticAddressString - $script:result[1] | Should -Be $secondIpv4StaticAddressString - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 - } - } - - Context 'Interface Alias was found in system but IPv6 NameServer is empty' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $matchAdapter } - - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - [psobject] @{ - NameServer = $noIpv6StaticAddressString - } - } - - It 'Should not throw exception' { - { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters -Verbose } | Should -Not -Throw - } - - It 'Should return null' { - $script:result | Should -BeNullOrEmpty - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 - } - } - - Context 'Interface Alias was found in system but IPv6 NameServer property does not exist' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $matchAdapter } - - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - [psobject] @{ - Dummy = '' - } - } - - It 'Should not throw exception' { - { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters -Verbose } | Should -Not -Throw - } - - It 'Should return null' { - $script:result | Should -BeNullOrEmpty - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 - } - } - - Context 'Interface Alias was found in system but IPv6 NameServer contains one DNS entry' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $matchAdapter } - - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - [psobject] @{ - NameServer = $oneIpv6StaticAddressString - } - } - - It 'Should not throw exception' { - { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters -Verbose } | Should -Not -Throw - } - - It 'Should return expected address' { - $script:result | Should -Be $oneIpv6StaticAddressString - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 - } - } - - Context 'Interface Alias was found in system but IPv6 NameServer contains two DNS entries' { - Mock ` - -CommandName Get-NetAdapter ` - -MockWith { $matchAdapter } - - Mock ` - -CommandName Get-ItemProperty ` - -MockWith { - [psobject] @{ - NameServer = $twoIpv6StaticAddressString - } - } - - It 'Should not throw exception' { - { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters -Verbose } | Should -Not -Throw - } - - It 'Should return two expected addresses' { - $script:result[0] | Should -Be $oneIpv6StaticAddressString - $script:result[1] | Should -Be $secondIpv6StaticAddressString - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 - } - } - } - - Describe 'NetworkingDsc.Common\Get-IPAddressPrefix' { - Context 'IPv4 CIDR notation provided' { - it 'Should return the provided IP and prefix as separate properties' { - $IPaddress = Get-IPAddressPrefix -IPAddress '192.168.10.0/24' - - $IPaddress.IPaddress | Should -Be '192.168.10.0' - $IPaddress.PrefixLength | Should -Be 24 - } - } - - Context 'IPv4 Class A address with no CIDR notation' { - it 'Should return correct prefix when Class A address provided' { - $IPaddress = Get-IPAddressPrefix -IPAddress '10.1.2.3' - - $IPaddress.IPaddress | Should -Be '10.1.2.3' - $IPaddress.PrefixLength | Should -Be 8 - } - } - - Context 'IPv4 Class B address with no CIDR notation' { - it 'Should return correct prefix when Class B address provided' { - $IPaddress = Get-IPAddressPrefix -IPAddress '172.16.2.3' - - $IPaddress.IPaddress | Should -Be '172.16.2.3' - $IPaddress.PrefixLength | Should -Be 16 - } - } - - Context 'IPv4 Class C address with no CIDR notation' { - it 'Should return correct prefix when Class C address provided' { - $IPaddress = Get-IPAddressPrefix -IPAddress '192.168.20.3' - - $IPaddress.IPaddress | Should -Be '192.168.20.3' - $IPaddress.PrefixLength | Should -Be 24 - } - } - - Context 'IPv6 CIDR notation provided' { - it 'Should return provided IP and prefix as separate properties' { - $IPaddress = Get-IPAddressPrefix -IPAddress 'FF12::12::123/64' -AddressFamily IPv6 - - $IPaddress.IPaddress | Should -Be 'FF12::12::123' - $IPaddress.PrefixLength | Should -Be 64 - } - } - - Context 'IPv6 with no CIDR notation provided' { - it 'Should return provided IP and correct IPv6 prefix' { - $IPaddress = Get-IPAddressPrefix -IPAddress 'FF12::12::123' -AddressFamily IPv6 - - $IPaddress.IPaddress | Should -Be 'FF12::12::123' - $IPaddress.PrefixLength | Should -Be 64 - } - } - } - - Describe 'NetworkingDsc.Common\Get-WinsClientServerStaticAddress' { - - # Generate the adapter data to be used for Mocking - $interfaceAlias = 'Adapter' - $interfaceGuid = [Guid]::NewGuid().ToString() - $nomatchAdapter = $null - $matchAdapter = @{ - InterfaceGuid = $interfaceGuid - } - $parameters = @{ - InterfaceAlias = $interfaceAlias - } - $noIpStaticAddressString = '' - $oneIpStaticAddressString = '8.8.8.8' - $secondIpStaticAddressString = '4.4.4.4' - $twoIpStaticAddressString = $oneIpStaticAddressString, $secondIpStaticAddressString - - Context 'When interface alias does not match adapter in system' { - Mock Get-NetAdapter -MockWith { $nomatchAdapter } - - $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.InterfaceAliasNotFoundError -f $interfaceAlias) - - It 'Should throw exception' { - { $script:result = Get-WinsClientServerStaticAddress @parameters -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'When interface alias was found in system and WINS server is empty' { - Mock Get-NetAdapter -MockWith { $matchAdapter } - Mock Get-ItemProperty -MockWith { - @{ - NameServer = $noIpStaticAddressString - } - } - - It 'Should not throw exception' { - { $script:result = Get-WinsClientServerStaticAddress @parameters -Verbose } | Should -Not -Throw - } - - It 'Should return null' { - $script:result | Should -BeNullOrEmpty - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 - } - } - - Context 'When interface alias was found in system and WINS server list contains one entry' { - Mock Get-NetAdapter -MockWith { $matchAdapter } - Mock Get-ItemProperty -MockWith { - @{ - NameServerList = $oneIpStaticAddressString - } - } - - It 'Should not throw exception' { - { $script:result = Get-WinsClientServerStaticAddress @parameters -Verbose } | Should -Not -Throw - } - - It 'Should return expected address' { - $script:result | Should -Be $oneIpStaticAddressString - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 - } - } - - Context 'When interface alias was found in system and WINS server list contains two entries' { - Mock Get-NetAdapter -MockWith { $matchAdapter } - Mock Get-ItemProperty -MockWith { - @{ - NameServerList = $twoIpStaticAddressString - } - } - - It 'Should not throw exception' { - { $script:result = Get-WinsClientServerStaticAddress @parameters -Verbose } | Should -Not -Throw - } - - It 'Should return two expected addresses' { - $script:result[0] | Should -Be $oneIpStaticAddressString - $script:result[1] | Should -Be $secondIpStaticAddressString - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 - } - } - } - - Describe 'NetworkingDsc.Common\Set-WinsClientServerStaticAddress' { - - # Generate the adapter data to be used for Mocking - $interfaceAlias = 'Adapter' - $interfaceGuid = [Guid]::NewGuid().ToString() - $nomatchAdapter = $null - $matchAdapter = @{ - InterfaceGuid = $interfaceGuid - } - $parameters = @{ - InterfaceAlias = $interfaceAlias - } - $noIpStaticAddressString = '' - $oneIpStaticAddressString = '8.8.8.8' - $secondIpStaticAddressString = '4.4.4.4' - $twoIpStaticAddressString = $oneIpStaticAddressString, $secondIpStaticAddressString - - Context 'When interface alias does not match adapter in system' { - Mock Get-NetAdapter -MockWith { $nomatchAdapter } - - $parameters.Address = @() - - $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.InterfaceAliasNotFoundError -f $interfaceAlias) - - It 'Should throw exception' { - { $script:result = Set-WinsClientServerStaticAddress @parameters -Verbose } | Should -Throw $errorRecord - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - } - } - - Context 'When interface alias was found in system and WINS server address is set to $null' { - Mock Get-NetAdapter -MockWith { $matchAdapter } - Mock Set-ItemProperty -MockWith { } - - $parameters.Address = @() - - It 'Should not throw exception' { - { $script:result = Set-WinsClientServerStaticAddress @parameters -Verbose } | Should -Not -Throw - } - - It 'Should return null' { - $script:result | Should -BeNullOrEmpty - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Set-ItemProperty -Exactly -Times 1 - } - } - - Context 'When interface alias was found in system and WINS server address is set to a single entry' { - Mock Get-NetAdapter -MockWith { $matchAdapter } - Mock Set-ItemProperty -MockWith { } - - $parameters.Address = $oneIpStaticAddressString - - It 'Should not throw exception' { - { $script:result = Set-WinsClientServerStaticAddress @parameters -Verbose } | Should -Not -Throw - } - - It 'Should return null' { - $script:result | Should -BeNullOrEmpty - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Set-ItemProperty -Exactly -Times 1 - } - } - - Context 'When interface alias was found in system and WINS server address is set to two enties' { - Mock Get-NetAdapter -MockWith { $matchAdapter } - Mock Set-ItemProperty -MockWith { } - - $parameters.Address = $twoIpStaticAddressString - - It 'Should not throw exception' { - { $script:result = Set-WinsClientServerStaticAddress @parameters -Verbose } | Should -Not -Throw - } - - It 'Should return null' { - $script:result | Should -BeNullOrEmpty - } - - It 'Should call expected mocks' { - Assert-MockCalled -CommandName Get-NetAdapter -Exactly -Times 1 - Assert-MockCalled -CommandName Set-ItemProperty -Exactly -Times 1 - } - } - } - - Describe 'NetworkingDsc.Common\Format-Win32NetworkADapterFilterByNetConnectionID' { - Context 'When interface alias has an ''*''' { - $interfaceAlias = 'Ether*' - - It 'Should convert the ''*'' to a ''%''' { - (Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias).Contains('%') -eq $True -and - (Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias).Contains('*') -eq $False | Should -Be $True - } - - It 'Should change the operator to ''LIKE''' { - (Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias) | Should -BeExactly 'NetConnectionID LIKE "Ether%"' - } - - It 'Should look like a usable filter' { - Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias | Should -BeExactly 'NetConnectionID LIKE "Ether%"' - } - } - - Context 'When interface alias has a ''%''' { - $interfaceAlias = 'Ether%' - - It 'Should change the operator to ''LIKE''' { - (Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias) | Should -BeExactly 'NetConnectionID LIKE "Ether%"' - } - - It 'Should look like a usable filter' { - Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias | Should -BeExactly 'NetConnectionID LIKE "Ether%"' - } - } - - Context 'When interface alias has no wildcards' { - $interfaceAlias = 'Ethernet' - - It 'Should look like a usable filter' { - Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias | Should -BeExactly 'NetConnectionID="Ethernet"' - } - } - } -} diff --git a/tests/Unit/Public/Convert-CIDRToSubnetMask.Tests.ps1 b/tests/Unit/Public/Convert-CIDRToSubnetMask.Tests.ps1 new file mode 100644 index 00000000..16d08801 --- /dev/null +++ b/tests/Unit/Public/Convert-CIDRToSubnetMask.Tests.ps1 @@ -0,0 +1,117 @@ +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + + Import-Module -Name $script:dscModuleName + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscModuleName +} + +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscModuleName -All | Remove-Module -Force +} + +Describe 'Convert-CIDRToSubnetMask' { + Context 'Subnet Mask Notation Used "192.168.0.0/255.255.0.0"' { + It 'Should Return "192.168.0.0/255.255.0.0"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Convert-CIDRToSubnetMask -Address @('192.168.0.0/255.255.0.0') | Should -Be '192.168.0.0/255.255.0.0' + } + } + } + + Context 'Subnet Mask Notation Used "192.168.0.10/255.255.0.0" resulting in source bits masked' { + It 'Should Return "192.168.0.0/255.255.0.0" with source bits masked' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Convert-CIDRToSubnetMask -Address @('192.168.0.10/255.255.0.0') | Should -Be '192.168.0.0/255.255.0.0' + } + } + } + + Context 'CIDR Notation Used "192.168.0.0/16"' { + It 'Should Return "192.168.0.0/255.255.0.0"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Convert-CIDRToSubnetMask -Address @('192.168.0.0/16') | Should -Be '192.168.0.0/255.255.0.0' + } + } + } + + Context 'CIDR Notation Used "192.168.0.10/16" resulting in source bits masked' { + It 'Should Return "192.168.0.0/255.255.0.0" with source bits masked' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Convert-CIDRToSubnetMask -Address @('192.168.0.10/16') | Should -Be '192.168.0.0/255.255.0.0' + } + } + } + + Context 'Multiple Notations Used "192.168.0.0/16,10.0.0.24/255.255.255.0"' { + It 'Should Return "192.168.0.0/255.255.0.0,10.0.0.0/255.255.255.0"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $Result = Convert-CIDRToSubnetMask -Address @('192.168.0.0/16', '10.0.0.24/255.255.255.0') + $Result[0] | Should -Be '192.168.0.0/255.255.0.0' + $Result[1] | Should -Be '10.0.0.0/255.255.255.0' + } + } + } + + Context 'Range Used "192.168.1.0-192.168.1.128"' { + It 'Should Return "192.168.1.0-192.168.1.128"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Convert-CIDRToSubnetMask -Address @('192.168.1.0-192.168.1.128') | Should -Be '192.168.1.0-192.168.1.128' + } + } + } + + Context 'IPv6 Used "fe80::/112"' { + It 'Should Return "fe80::/112"' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Convert-CIDRToSubnetMask -Address @('fe80::/112') | Should -Be 'fe80::/112' + } + } + } +} diff --git a/tests/Unit/Public/Find-NetworkAdapter.Tests.ps1 b/tests/Unit/Public/Find-NetworkAdapter.Tests.ps1 new file mode 100644 index 00000000..10b0e881 --- /dev/null +++ b/tests/Unit/Public/Find-NetworkAdapter.Tests.ps1 @@ -0,0 +1,585 @@ +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + + Import-Module -Name $script:dscModuleName + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscModuleName +} + +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscModuleName -All | Remove-Module -Force +} + +Describe 'Public\Find-NetworkAdapter' { + BeforeAll { + # Generate the adapter data to be used for Mocking + $adapterName = 'Adapter' + $adapterPhysicalMediaType = '802.3' + $adapterStatus = 'Up' + $adapterMacAddress = '11-22-33-44-55-66' + $adapterInterfaceDescription = 'Hyper-V Virtual Ethernet Adapter #2' + $adapterInterfaceIndex = 2 + $adapterInterfaceGuid = '75670D9B-5879-4DBA-BC99-86CDD33EB66A' + $adapterDriverDescription = 'Hyper-V Virtual Ethernet Adapter' + + $nomatchAdapter = [PSObject]@{ + Name = 'No Match Adapter' + PhysicalMediaType = '802.11' + Status = 'Disconnected' + MacAddress = '66-55-44-33-22-11' + InterfaceDescription = 'Some Other Interface #2' + InterfaceIndex = 3 + InterfaceGuid = 'FFFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF' + DriverDescription = 'Some Other Interface' + } + + $matchAdapter = [PSObject]@{ + Name = $adapterName + PhysicalMediaType = $adapterPhysicalMediaType + Status = $adapterStatus + MacAddress = $adapterMacAddress + InterfaceDescription = $adapterInterfaceDescription + InterfaceIndex = $adapterInterfaceIndex + InterfaceGuid = $adapterInterfaceGuid + DriverDescription = $adapterDriverDescription + } + + $script:adapterArray = @( $nomatchAdapter, $matchAdapter ) + $script:multipleMatchingAdapterArray = @( $matchAdapter, $matchAdapter ) + + InModuleScope -Parameters @{ + adapterName = $adapterName + adapterPhysicalMediaType = $adapterPhysicalMediaType + adapterStatus = $adapterStatus + adapterMacAddress = $adapterMacAddress + adapterInterfaceDescription = $adapterInterfaceDescription + adapterInterfaceIndex = $adapterInterfaceIndex + adapterInterfaceGuid = $adapterInterfaceGuid + adapterDriverDescription = $adapterDriverDescription + } -ScriptBlock { + Set-StrictMode -Version 1.0 + $script:adapterName = $adapterName + $script:adapterPhysicalMediaType = $adapterPhysicalMediaType + $script:adapterStatus = $adapterStatus + $script:adapterMacAddress = $adapterMacAddress + $script:adapterInterfaceDescription = $adapterInterfaceDescription + $script:adapterInterfaceIndex = $adapterInterfaceIndex + $script:adapterInterfaceGuid = $adapterInterfaceGuid + $script:adapterDriverDescription = $adapterDriverDescription + } + } + + Context 'Name is passed and one adapter matches' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Find-NetworkAdapter -Name $adapterName } | Should -Not -Throw + } + } + + It 'Should return expected adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Name | Should -Be $adapterName + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'Name is passed and no adapters match' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.NetAdapterNotFoundError) + + { $script:result = Find-NetworkAdapter -Name 'NOMATCH' } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'PhysicalMediaType is passed and one adapter matches' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Find-NetworkAdapter -PhysicalMediaType $adapterPhysicalMediaType } | Should -Not -Throw + } + } + + It 'Should return expected adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Name | Should -Be $adapterName + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'PhysicalMediaType is passed and no adapters match' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.NetAdapterNotFoundError) + + { $script:result = Find-NetworkAdapter -PhysicalMediaType 'NOMATCH' } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'Status is passed and one adapter matches' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Find-NetworkAdapter -Status $adapterStatus } | Should -Not -Throw + } + } + + It 'Should return expected adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Name | Should -Be $adapterName + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'Status is passed and no adapters match' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.NetAdapterNotFoundError) + + { $script:result = Find-NetworkAdapter -Status 'Disabled' } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'MacAddress is passed and one adapter matches' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Find-NetworkAdapter -MacAddress $adapterMacAddress } | Should -Not -Throw + } + } + + It 'Should return expected adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Name | Should -Be $adapterName + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'MacAddress is passed and no adapters match' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.NetAdapterNotFoundError) + + { $script:result = Find-NetworkAdapter -MacAddress '00-00-00-00-00-00' } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'InterfaceDescription is passed and one adapter matches' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Find-NetworkAdapter -InterfaceDescription $adapterInterfaceDescription } | Should -Not -Throw + } + } + + It 'Should return expected adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Name | Should -Be $adapterName + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'InterfaceDescription is passed and no adapters match' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.NetAdapterNotFoundError) + + { $script:result = Find-NetworkAdapter -InterfaceDescription 'NOMATCH' } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'InterfaceIndex is passed and one adapter matches' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Find-NetworkAdapter -InterfaceIndex $adapterInterfaceIndex } | Should -Not -Throw + } + } + + It 'Should return expected adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Name | Should -Be $adapterName + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'InterfaceIndex is passed and no adapters match' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.NetAdapterNotFoundError) + + { $script:result = Find-NetworkAdapter -InterfaceIndex 99 } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'InterfaceGuid is passed and one adapter matches' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Find-NetworkAdapter -InterfaceGuid $adapterInterfaceGuid } | Should -Not -Throw + } + } + + It 'Should return expected adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Name | Should -Be $adapterName + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'InterfaceGuid is passed and no adapters match' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.NetAdapterNotFoundError) + + { $script:result = Find-NetworkAdapter -InterfaceGuid 'NOMATCH' } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'DriverDescription is passed and one adapter matches' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Find-NetworkAdapter -DriverDescription $adapterDriverDescription } | Should -Not -Throw + } + } + + It 'Should return expected adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Name | Should -Be $adapterName + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'DriverDescription is passed and no adapters match' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.NetAdapterNotFoundError) + + { $script:result = Find-NetworkAdapter -DriverDescription 'NOMATCH' } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'No parameters are passed and multiple Adapters adapters match but IgnoreMultipleMatchingAdapters is not set' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.MultipleMatchingNetAdapterFound -f 2) + + { $script:result = Find-NetworkAdapter } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'No parameters are passed and multiple Adapters adapters match and IgnoreMultipleMatchingAdapters is set and interface number is 2' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:adapterArray } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Find-NetworkAdapter -IgnoreMultipleMatchingAdapters:$true -InterfaceNumber 2 } | Should -Not -Throw + } + } + + It 'Should return expected adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Name | Should -Be $adapterName + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'Multiple Adapters adapters match but IgnoreMultipleMatchingAdapters is not set' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:multipleMatchingAdapterArray } + } + + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.MultipleMatchingNetAdapterFound -f 2) + + { $script:result = Find-NetworkAdapter -PhysicalMediaType $adapterPhysicalMediaType } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'Multiple Adapters adapters match and IgnoreMultipleMatchingAdapters is set' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:multipleMatchingAdapterArray } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Find-NetworkAdapter -PhysicalMediaType $adapterPhysicalMediaType -IgnoreMultipleMatchingAdapters:$true } | Should -Not -Throw + } + } + + It 'Should return expected adapter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result.Name | Should -Be $adapterName + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'Multiple Adapters adapters match and IgnoreMultipleMatchingAdapters is set and InterfaceNumber is greater than matching adapters' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:multipleMatchingAdapterArray } + } + + It 'Should throw the correct exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.InvalidNetAdapterNumberError -f 2, 3) + + { $script:result = Find-NetworkAdapter -PhysicalMediaType $adapterPhysicalMediaType -IgnoreMultipleMatchingAdapters:$true -InterfaceNumber 3 } | Should -Throw $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } +} diff --git a/tests/Unit/Public/Format-Win32NetworkADapterFilterByNetConnectionID.Tests.ps1 b/tests/Unit/Public/Format-Win32NetworkADapterFilterByNetConnectionID.Tests.ps1 new file mode 100644 index 00000000..cc5e968b --- /dev/null +++ b/tests/Unit/Public/Format-Win32NetworkADapterFilterByNetConnectionID.Tests.ps1 @@ -0,0 +1,118 @@ +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + + Import-Module -Name $script:dscModuleName + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscModuleName +} + +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscModuleName -All | Remove-Module -Force +} + +Describe 'Public\Format-Win32NetworkADapterFilterByNetConnectionID' { + Context 'When interface alias has an ''*''' { + BeforeAll { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:interfaceAlias = 'Ether*' + } + } + + It 'Should convert the ''*'' to a ''%''' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + (Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias).Contains('%') -eq $true -and + (Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias).Contains('*') -eq $false | Should -BeTrue + } + } + + It 'Should change the operator to ''LIKE''' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + (Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias) | Should -BeExactly 'NetConnectionID LIKE "Ether%"' + } + } + + It 'Should look like a usable filter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias | Should -BeExactly 'NetConnectionID LIKE "Ether%"' + } + } + } + + Context 'When interface alias has a ''%''' { + BeforeAll { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $interfaceAlias = 'Ether%' + } + } + + It 'Should change the operator to ''LIKE''' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + (Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias) | Should -BeExactly 'NetConnectionID LIKE "Ether%"' + } + } + + It 'Should look like a usable filter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias | Should -BeExactly 'NetConnectionID LIKE "Ether%"' + } + } + } + + Context 'When interface alias has no wildcards' { + It 'Should look like a usable filter' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $interfaceAlias = 'Ethernet' + + Format-Win32NetworkADapterFilterByNetConnectionID -InterfaceAlias $interfaceAlias | Should -BeExactly 'NetConnectionID="Ethernet"' + } + } + } +} diff --git a/tests/Unit/Public/Get-DnsClientServerStaticAddress.Tests.ps1 b/tests/Unit/Public/Get-DnsClientServerStaticAddress.Tests.ps1 new file mode 100644 index 00000000..0c4ca3f4 --- /dev/null +++ b/tests/Unit/Public/Get-DnsClientServerStaticAddress.Tests.ps1 @@ -0,0 +1,377 @@ +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + + Import-Module -Name $script:dscModuleName + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscModuleName +} + +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscModuleName -All | Remove-Module -Force +} + +Describe 'Public\Get-DnsClientServerStaticAddress' { + BeforeAll { + # Generate the adapter data to be used for Mocking + $interfaceAlias = 'Adapter' + $interfaceGuid = [Guid]::NewGuid().ToString() + $script:nomatchAdapter = $null + $script:matchAdapter = [PSObject]@{ + InterfaceGuid = $interfaceGuid + } + $ipv4Parameters = @{ + InterfaceAlias = $interfaceAlias + AddressFamily = 'IPv4' + } + $ipv6Parameters = @{ + InterfaceAlias = $interfaceAlias + AddressFamily = 'IPv6' + } + $script:noIpv4StaticAddressString = '' + $script:oneIpv4StaticAddressString = '8.8.8.8' + $secondIpv4StaticAddressString = '4.4.4.4' + $script:twoIpv4StaticAddressString = "$oneIpv4StaticAddressString,$secondIpv4StaticAddressString" + $script:noIpv6StaticAddressString = '' + $script:oneIpv6StaticAddressString = '::1' + $secondIpv6StaticAddressString = '::2' + $script:twoIpv6StaticAddressString = "$oneIpv6StaticAddressString,$secondIpv6StaticAddressString" + + InModuleScope -Parameters @{ + interfaceAlias = $interfaceAlias + ipv4Parameters = $ipv4Parameters + ipv6Parameters = $ipv6Parameters + oneIpv4StaticAddressString = $oneIpv4StaticAddressString + secondIpv4StaticAddressString = $secondIpv4StaticAddressString + oneIpv6StaticAddressString = $oneIpv6StaticAddressString + secondIpv6StaticAddressString = $secondIpv6StaticAddressString + } -ScriptBlock { + Set-StrictMode -Version 1.0 + $script:interfaceAlias = $interfaceAlias + $script:ipv4Parameters = $ipv4Parameters + $script:ipv6Parameters = $ipv6Parameters + $script:oneIpv4StaticAddressString = $oneIpv4StaticAddressString + $script:secondIpv4StaticAddressString = $secondIpv4StaticAddressString + $script:oneIpv6StaticAddressString = $oneIpv6StaticAddressString + $script:secondIpv6StaticAddressString = $secondIpv6StaticAddressString + + } + } + + Context 'Interface Alias does not match adapter in system' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:nomatchAdapter } + } + + It 'Should throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.InterfaceAliasNotFoundError -f $interfaceAlias) + + { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'Interface Alias was found in system but IPv4 NameServer is empty' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:matchAdapter } + + Mock -CommandName Get-ItemProperty -MockWith { + [psobject] @{ + NameServer = $script:noIpv4StaticAddressString + } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters } | Should -Not -Throw + } + } + + It 'Should return null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -BeNullOrEmpty + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'Interface Alias was found in system but IPv4 NameServer property does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:matchAdapter } + + Mock -CommandName Get-ItemProperty -MockWith { + [psobject] @{ + Dummy = '' + } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters } | Should -Not -Throw + } + } + + It 'Should return null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -BeNullOrEmpty + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'Interface Alias was found in system but IPv4 NameServer contains one DNS entry' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:matchAdapter } + + Mock -CommandName Get-ItemProperty -MockWith { + [psobject] @{ + NameServer = $script:oneIpv4StaticAddressString + } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters } | Should -Not -Throw + } + } + + It 'Should return expected address' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -Be $oneIpv4StaticAddressString + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'Interface Alias was found in system but IPv4 NameServer contains two DNS entries' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:matchAdapter } + + Mock -CommandName Get-ItemProperty -MockWith { + [psobject] @{ + NameServer = $script:twoIpv4StaticAddressString + } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters } | Should -Not -Throw + } + } + + It 'Should return two expected addresses' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result[0] | Should -Be $oneIpv4StaticAddressString + $script:result[1] | Should -Be $secondIpv4StaticAddressString + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'Interface Alias was found in system but IPv6 NameServer is empty' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:matchAdapter } + + Mock -CommandName Get-ItemProperty -MockWith { + [psobject] @{ + NameServer = $script:noIpv6StaticAddressString + } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters } | Should -Not -Throw + } + } + + It 'Should return null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -BeNullOrEmpty + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'Interface Alias was found in system but IPv6 NameServer property does not exist' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:matchAdapter } + + Mock -CommandName Get-ItemProperty -MockWith { + [psobject] @{ + Dummy = '' + } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters } | Should -Not -Throw + } + } + + It 'Should return null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -BeNullOrEmpty + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'Interface Alias was found in system but IPv6 NameServer contains one DNS entry' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:matchAdapter } + + Mock -CommandName Get-ItemProperty -MockWith { + [psobject] @{ + NameServer = $script:oneIpv6StaticAddressString + } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters } | Should -Not -Throw + } + } + + It 'Should return expected address' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -Be $script:oneIpv6StaticAddressString + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'Interface Alias was found in system but IPv6 NameServer contains two DNS entries' { + BeforeAll { + Mock -CommandName Get-NetAdapter -MockWith { $script:matchAdapter } + + Mock -CommandName Get-ItemProperty -MockWith { + [psobject] @{ + NameServer = $script:twoIpv6StaticAddressString + } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters } | Should -Not -Throw + } + } + + It 'Should return two expected addresses' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result[0] | Should -Be $script:oneIpv6StaticAddressString + $script:result[1] | Should -Be $script:secondIpv6StaticAddressString + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } +} diff --git a/tests/Unit/Public/Get-IPAddressPrefix.Tests.ps1 b/tests/Unit/Public/Get-IPAddressPrefix.Tests.ps1 new file mode 100644 index 00000000..625fc1a5 --- /dev/null +++ b/tests/Unit/Public/Get-IPAddressPrefix.Tests.ps1 @@ -0,0 +1,123 @@ +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + + Import-Module -Name $script:dscModuleName + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscModuleName +} + +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscModuleName -All | Remove-Module -Force +} + +Describe 'Public\Get-IPAddressPrefix' { + Context 'IPv4 CIDR notation provided' { + It 'Should return the provided IP and prefix as separate properties' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $IPaddress = Get-IPAddressPrefix -IPAddress '192.168.10.0/24' + + $IPaddress.IPaddress | Should -Be '192.168.10.0' + $IPaddress.PrefixLength | Should -Be 24 + } + } + } + + Context 'IPv4 Class A address with no CIDR notation' { + It 'Should return correct prefix when Class A address provided' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $IPaddress = Get-IPAddressPrefix -IPAddress '10.1.2.3' + + $IPaddress.IPaddress | Should -Be '10.1.2.3' + $IPaddress.PrefixLength | Should -Be 8 + } + } + } + + Context 'IPv4 Class B address with no CIDR notation' { + It 'Should return correct prefix when Class B address provided' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $IPaddress = Get-IPAddressPrefix -IPAddress '172.16.2.3' + + $IPaddress.IPaddress | Should -Be '172.16.2.3' + $IPaddress.PrefixLength | Should -Be 16 + } + } + } + + Context 'IPv4 Class C address with no CIDR notation' { + It 'Should return correct prefix when Class C address provided' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $IPaddress = Get-IPAddressPrefix -IPAddress '192.168.20.3' + + $IPaddress.IPaddress | Should -Be '192.168.20.3' + $IPaddress.PrefixLength | Should -Be 24 + } + } + } + + Context 'IPv6 CIDR notation provided' { + It 'Should return provided IP and prefix as separate properties' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $IPaddress = Get-IPAddressPrefix -IPAddress 'FF12::12::123/64' -AddressFamily IPv6 + + $IPaddress.IPaddress | Should -Be 'FF12::12::123' + $IPaddress.PrefixLength | Should -Be 64 + } + } + } + + Context 'IPv6 with no CIDR notation provided' { + It 'Should return provided IP and correct IPv6 prefix' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $IPaddress = Get-IPAddressPrefix -IPAddress 'FF12::12::123' -AddressFamily IPv6 + + $IPaddress.IPaddress | Should -Be 'FF12::12::123' + $IPaddress.PrefixLength | Should -Be 64 + } + } + } +} diff --git a/tests/Unit/Public/Get-WinsClientServerStaticAddress.Tests.ps1 b/tests/Unit/Public/Get-WinsClientServerStaticAddress.Tests.ps1 new file mode 100644 index 00000000..307e8fee --- /dev/null +++ b/tests/Unit/Public/Get-WinsClientServerStaticAddress.Tests.ps1 @@ -0,0 +1,193 @@ +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + + Import-Module -Name $script:dscModuleName + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscModuleName +} + +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscModuleName -All | Remove-Module -Force +} + +Describe 'Public\Get-WinsClientServerStaticAddress' { + BeforeAll { + # Generate the adapter data to be used for Mocking + $interfaceAlias = 'Adapter' + $interfaceGuid = [Guid]::NewGuid().ToString() + $script:nomatchAdapter = $null + $script:matchAdapter = @{ + InterfaceGuid = $interfaceGuid + } + $parameters = @{ + InterfaceAlias = $interfaceAlias + } + $noIpStaticAddressString = '' + $oneIpStaticAddressString = '8.8.8.8' + $secondIpStaticAddressString = '4.4.4.4' + $twoIpStaticAddressString = $oneIpStaticAddressString, $secondIpStaticAddressString + + InModuleScope -Parameters @{ + interfaceAlias = $interfaceAlias + parameters = $parameters + oneIpStaticAddressString = $oneIpStaticAddressString + secondIpStaticAddressString = $secondIpStaticAddressString + } -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:interfaceAlias = $interfaceAlias + $script:parameters = $parameters + $script:oneIpStaticAddressString = $oneIpStaticAddressString + $script:secondIpStaticAddressString = $secondIpStaticAddressString + } + } + + Context 'When interface alias does not match adapter in system' { + BeforeAll { + Mock Get-NetAdapter -MockWith { $nomatchAdapter } + } + + It 'Should throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.InterfaceAliasNotFoundError -f $interfaceAlias) + + { $script:result = Get-WinsClientServerStaticAddress @parameters } | Should -Throw -ExpectedMessage $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'When interface alias was found in system and WINS server is empty' { + BeforeAll { + Mock Get-NetAdapter -MockWith { $matchAdapter } + Mock Get-ItemProperty -MockWith { + @{ + NameServer = $noIpStaticAddressString + } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Get-WinsClientServerStaticAddress @parameters } | Should -Not -Throw + } + } + + It 'Should return null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -BeNullOrEmpty + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'When interface alias was found in system and WINS server list contains one entry' { + BeforeAll { + Mock Get-NetAdapter -MockWith { $matchAdapter } + Mock Get-ItemProperty -MockWith { + @{ + NameServerList = $oneIpStaticAddressString + } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Get-WinsClientServerStaticAddress @parameters } | Should -Not -Throw + } + } + + It 'Should return expected address' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -Be $oneIpStaticAddressString + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'When interface alias was found in system and WINS server list contains two entries' { + BeforeAll { + Mock Get-NetAdapter -MockWith { $matchAdapter } + Mock Get-ItemProperty -MockWith { + @{ + NameServerList = $twoIpStaticAddressString + } + } + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + { $script:result = Get-WinsClientServerStaticAddress @parameters } | Should -Not -Throw + } + } + + It 'Should return two expected addresses' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result[0] | Should -Be $oneIpStaticAddressString + $script:result[1] | Should -Be $secondIpStaticAddressString + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Get-ItemProperty -Exactly -Times 1 -Scope Context + } + } +} diff --git a/tests/Unit/Public/Set-WinsClientServerStaticAddress.Tests.ps1 b/tests/Unit/Public/Set-WinsClientServerStaticAddress.Tests.ps1 new file mode 100644 index 00000000..acaf62e7 --- /dev/null +++ b/tests/Unit/Public/Set-WinsClientServerStaticAddress.Tests.ps1 @@ -0,0 +1,186 @@ +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] +param () + +BeforeDiscovery { + try + { + if (-not (Get-Module -Name 'DscResource.Test')) + { + # Assumes dependencies has been resolved, so if this module is not available, run 'noop' task. + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) + { + # Redirect all streams to $null, except the error stream (stream 2) + & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null + } + + # If the dependencies has not been resolved, this will throw an error. + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' + } + } + catch [System.IO.FileNotFoundException] + { + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks build" first.' + } +} + +BeforeAll { + $script:dscModuleName = 'NetworkingDsc' + + Import-Module -Name $script:dscModuleName + + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Mock:ModuleName'] = $script:dscModuleName + $PSDefaultParameterValues['Should:ModuleName'] = $script:dscModuleName +} + +AfterAll { + $PSDefaultParameterValues.Remove('InModuleScope:ModuleName') + $PSDefaultParameterValues.Remove('Mock:ModuleName') + $PSDefaultParameterValues.Remove('Should:ModuleName') + + # Unload the module being tested so that it doesn't impact any other tests. + Get-Module -Name $script:dscModuleName -All | Remove-Module -Force +} + +Describe 'Public\Set-WinsClientServerStaticAddress' { + BeforeAll { + # Generate the adapter data to be used for Mocking + $interfaceAlias = 'Adapter' + $interfaceGuid = [Guid]::NewGuid().ToString() + $script:nomatchAdapter = $null + $script:matchAdapter = @{ + InterfaceGuid = $interfaceGuid + } + $parameters = @{ + InterfaceAlias = $interfaceAlias + } + $noIpStaticAddressString = '' + $oneIpStaticAddressString = '8.8.8.8' + $secondIpStaticAddressString = '4.4.4.4' + $twoIpStaticAddressString = $oneIpStaticAddressString, $secondIpStaticAddressString + + InModuleScope -Parameters @{ + interfaceAlias = $interfaceAlias + parameters = $parameters + oneIpStaticAddressString = $oneIpStaticAddressString + twoIpStaticAddressString = $twoIpStaticAddressString + } -ScriptBlock { + Set-StrictMode -Version 1.0 + $script:interfaceAlias = $interfaceAlias + $script:parameters = $parameters + $script:oneIpStaticAddressString = $oneIpStaticAddressString + $script:twoIpStaticAddressString = $twoIpStaticAddressString + } + } + + Context 'When interface alias does not match adapter in system' { + BeforeAll { + Mock Get-NetAdapter -MockWith { $nomatchAdapter } + } + + It 'Should throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $parameters.Address = @() + + $errorRecord = Get-InvalidOperationRecord -Message ($script:localizedData.InterfaceAliasNotFoundError -f $interfaceAlias) + + { $script:result = Set-WinsClientServerStaticAddress @parameters } | Should -Throw $errorRecord + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + } + } + + Context 'When interface alias was found in system and WINS server address is set to $null' { + BeforeAll { + Mock Get-NetAdapter -MockWith { $matchAdapter } + Mock Set-ItemProperty + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $parameters.Address = @() + + { $script:result = Set-WinsClientServerStaticAddress @parameters } | Should -Not -Throw + } + } + + It 'Should return null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -BeNullOrEmpty + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'When interface alias was found in system and WINS server address is set to a single entry' { + BeforeAll { + Mock Get-NetAdapter -MockWith { $matchAdapter } + Mock Set-ItemProperty + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $parameters.Address = $oneIpStaticAddressString + { $script:result = Set-WinsClientServerStaticAddress @parameters } | Should -Not -Throw + } + } + + It 'Should return null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -BeNullOrEmpty + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-ItemProperty -Exactly -Times 1 -Scope Context + } + } + + Context 'When interface alias was found in system and WINS server address is set to two entries' { + BeforeAll { + Mock Get-NetAdapter -MockWith { $matchAdapter } + Mock Set-ItemProperty + } + + It 'Should not throw exception' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $parameters.Address = $twoIpStaticAddressString + + { $script:result = Set-WinsClientServerStaticAddress @parameters } | Should -Not -Throw + } + } + + It 'Should return null' { + InModuleScope -ScriptBlock { + Set-StrictMode -Version 1.0 + + $script:result | Should -BeNullOrEmpty + } + } + + It 'Should call expected mocks' { + Should -Invoke -CommandName Get-NetAdapter -Exactly -Times 1 -Scope Context + Should -Invoke -CommandName Set-ItemProperty -Exactly -Times 1 -Scope Context + } + } +}