diff --git a/CHANGELOG.md b/CHANGELOG.md index f75f4e5b..3b68cde9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,37 @@ ## Unreleased +## 5.5.0.0 + +- MSFT_xNetAdapterAdvancedProperty: + - Created new resource configuring AdvancedProperties for NetAdapter +- MSFT_xNetAdapterLso: + - Corrected style and formatting to meet HQRM guidelines. + - Updated tests to meet Pester v4 guidelines. +- MSFT_xNetAdapterName: + - Corrected style and formatting to meet HQRM guidelines. + - Updated tests to meet Pester v4 guidelines. +- MSFT_xNetAdapterRDMA: + - Corrected style and formatting to meet HQRM guidelines. + - Updated tests to meet Pester v4 guidelines. + - Converted exceptions to use ResourceHelper functions. + - Improved integration tests to preserve system status and run in more + scenarios. +- MSFT_xNetBIOS: + - Corrected style and formatting to meet HQRM guidelines. + - Updated tests to meet Pester v4 guidelines. + - Converted exceptions to use ResourceHelper functions. + - Improved integration tests to preserve system status, run in more + scenarios and more effectively test the resource. + - Changed to report back error if unable to set NetBIOS setting. +- MSFT_xWinsSetting: + - Created new resource for enabling/disabling LMHOSTS lookup and + enabling/disabling WINS name resoluton using DNS. +- MSFT_xNetworkTeam: + - Corrected style and formatting to meet HQRM guidelines. + - Updated tests to meet Pester v4 guidelines. + - Converted exceptions to use ResourceHelper functions. + ## 5.4.0.0 - MSFT_xIPAddressOption: diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/MSFT_xNetAdapterAdvancedProperty.psm1 b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/MSFT_xNetAdapterAdvancedProperty.psm1 new file mode 100644 index 00000000..736b2092 --- /dev/null +++ b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/MSFT_xNetAdapterAdvancedProperty.psm1 @@ -0,0 +1,217 @@ +$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 the Networking Resource Helper Module +Import-Module -Name (Join-Path -Path $modulePath ` + -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` + -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) + +# Import Localization Strings +$localizedData = Get-LocalizedData ` + -ResourceName 'MSFT_xNetAdapterAdvancedProperty' ` + -ResourcePath (Split-Path -Parent $Script:MyInvocation.MyCommand.Path) + +<# +.SYNOPSIS + Gets the current value of an advanced property. + +.PARAMETER NetworkAdapterName + Specifies the Name of the network adapter to get the advanced property for. + +.PARAMETER RegistryKeyword + Specifies the settings registrykeyword that should be in desired state. + +.PARAMETER RegistryValue + Specifies the value of the settings. +#> +function Get-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $NetworkAdapterName, + + [Parameter(Mandatory = $true)] + [ValidateSet("*FlowControl","*InterruptModeration","*IPChecksumOffloadIPv4","*JumboPacket","*LsoV2IPv4","*LsoV2IPv6","*MaxRssProcessors","*NumaNodeId","*NumRssQueues","*PriorityVLANTag","*ReceiveBuffers","*RSS","*RssBaseProcNumber","*RssMaxProcNumber","*RSSProfile","*SpeedDuplex","*TCPChecksumOffloadIPv4","*TCPChecksumOffloadIPv6","*TransmitBuffers","*UDPChecksumOffloadIPv4","*UDPChecksumOffloadIPv6","AdaptiveIFS","ITR","LogLinkStateEvent","MasterSlave","NetworkAddress","WaitAutoNegComplete")] + [System.String] + $RegistryKeyword, + + [Parameter(Mandatory = $true)] + [System.String] + $RegistryValue + ) + + Write-Verbose -Message ( @( + "$($MyInvocation.MyCommand): " + $localizedData.CheckingNetAdapterMessage + ) -join '') + + try + { + $netAdapterAdvancedProperty = Get-NetAdapterAdvancedProperty -Name $networkAdapterName -RegistryKeyword $RegistryKeyword -ErrorAction Stop + } + catch + { + New-InvalidOperationException ` + -Message ($LocalizedData.NetAdapterNotFoundMessage) + } + + if ($netAdapterAdvancedProperty) + { + Write-Verbose -Message ( @( + "$($MyInvocation.MyCommand): " + $($LocalizedData.NetAdapterTestingStateMessage -f $NetworkAdapterName, $RegistryKeyword) + ) -join '') + + $result = @{ + Name = $NetworkAdapterName + RegistryKeyword = $RegistryKeyword + DisplayValue = $netAdapterAdvancedProperty.DisplayValue + RegistryValue = $netAdapterAdvancedProperty.RegistryValue + } + + return $result + } +} + +<# +.SYNOPSIS + Gets the current value of an advanced property. + +.PARAMETER NetworkAdapterName + Specifies the Name of the network adapter to get the advanced property for. + +.PARAMETER RegistryKeyword + Specifies the settings registrykeyword that should be in desired state. + +.PARAMETER RegistryValue + Specifies the value of the settings. +#> +function Set-TargetResource +{ + [CmdletBinding()] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $NetworkAdapterName, + + [Parameter(Mandatory = $true)] + [ValidateSet("*FlowControl","*InterruptModeration","*IPChecksumOffloadIPv4","*JumboPacket","*LsoV2IPv4","*LsoV2IPv6","*MaxRssProcessors","*NumaNodeId","*NumRssQueues","*PriorityVLANTag","*ReceiveBuffers","*RSS","*RssBaseProcNumber","*RssMaxProcNumber","*RSSProfile","*SpeedDuplex","*TCPChecksumOffloadIPv4","*TCPChecksumOffloadIPv6","*TransmitBuffers","*UDPChecksumOffloadIPv4","*UDPChecksumOffloadIPv6","AdaptiveIFS","ITR","LogLinkStateEvent","MasterSlave","NetworkAddress","WaitAutoNegComplete")] + [System.String] + $RegistryKeyword, + + [Parameter(Mandatory = $true)] + [System.String] + $RegistryValue + ) + + Write-Verbose -Message ( @( + "$($MyInvocation.MyCommand): " + $localizedData.CheckingNetAdapterMessage + ) -join '') + + try + { + $netAdapterAdvancedProperty = Get-NetAdapterAdvancedProperty -Name $networkAdapterName -RegistryKeyword $RegistryKeyword -ErrorAction Stop + } + catch + { + New-InvalidOperationException ` + -Message ($LocalizedData.NetAdapterNotFoundMessage) + } + + if ($netAdapterAdvancedProperty) + { + Write-Verbose -Message ( @( + "$($MyInvocation.MyCommand): " + $($LocalizedData.NetAdapterTestingStateMessage -f $NetworkAdapterName, $RegistryKeyword) + ) -join '') + + if ($RegistryValue -ne $netAdapterAdvancedProperty.RegistryValue) + { + $netadapterRegistryValue = $netAdapterAdvancedProperty.RegistryValue + Write-Verbose -Message ( @( + "$($MyInvocation.MyCommand): " + $($LocalizedData.NetAdapterApplyingChangesMessage -f ` + $NetworkAdapterName, $RegistryKeyword, "$netadapterRegistryValue", $RegistryValue ) + ) -join '') + + Set-NetAdapterAdvancedProperty -RegistryValue $RegistryValue -Name $networkAdapterName -RegistryKeyword $RegistryKeyword + } + } +} + +<# +.SYNOPSIS + Sets the current value of an advanced property. + +.PARAMETER NetworkAdapterName + Specifies the Name of the network adapter to get the advanced property for. + +.PARAMETER RegistryKeyword + Specifies the settings registrykeyword that should be in desired state. + +.PARAMETER RegistryValue + Specifies the value of the settings. +#> +function Test-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Boolean])] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $NetworkAdapterName, + + [Parameter(Mandatory = $true)] + [ValidateSet("*FlowControl","*InterruptModeration","*IPChecksumOffloadIPv4","*JumboPacket","*LsoV2IPv4","*LsoV2IPv6","*MaxRssProcessors","*NumaNodeId","*NumRssQueues","*PriorityVLANTag","*ReceiveBuffers","*RSS","*RssBaseProcNumber","*RssMaxProcNumber","*RSSProfile","*SpeedDuplex","*TCPChecksumOffloadIPv4","*TCPChecksumOffloadIPv6","*TransmitBuffers","*UDPChecksumOffloadIPv4","*UDPChecksumOffloadIPv6","AdaptiveIFS","ITR","LogLinkStateEvent","MasterSlave","NetworkAddress","WaitAutoNegComplete")] + [System.String] + $RegistryKeyword, + + [Parameter(Mandatory = $true)] + [System.String] + $RegistryValue + ) + + Write-Verbose -Message ( @( + "$($MyInvocation.MyCommand): " + $localizedData.CheckingNetAdapterMessage + ) -join '') + + try + { + $netAdapterAdvancedProperty = Get-NetAdapterAdvancedProperty -Name $networkAdapterName -RegistryKeyword $RegistryKeyword -ErrorAction Stop + } + catch + { + New-InvalidOperationException ` + -Message ($LocalizedData.NetAdapterNotFoundMessage) + } + + if ($netAdapterAdvancedProperty) + { + Write-Verbose -Message ( @( + "$($MyInvocation.MyCommand): " + $localizedData.NetAdapterTestingStateMessage -f ` + $NetworkAdapterName, $RegistryKeyword + ) -join '') + + if ($RegistryValue -eq $netAdapterAdvancedProperty.RegistryValue) + { + return $true + } + else + { + return $false + } + } +} diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/MSFT_xNetAdapterAdvancedProperty.schema.mof b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/MSFT_xNetAdapterAdvancedProperty.schema.mof new file mode 100644 index 00000000..85b343fc --- /dev/null +++ b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/MSFT_xNetAdapterAdvancedProperty.schema.mof @@ -0,0 +1,8 @@ +[ClassVersion("1.0.0.0"), FriendlyName("xNetAdapterAdvancedProperty")] +class MSFT_xNetAdapterAdvancedProperty : OMI_BaseResource +{ + [Key,ValueMap{"*FlowControl","*InterruptModeration","*IPChecksumOffloadIPv4","*JumboPacket","*LsoV2IPv4","*LsoV2IPv6","*MaxRssProcessors","*NumaNodeId","*NumRssQueues","*PriorityVLANTag","*ReceiveBuffers","*RSS","*RssBaseProcNumber","*RssMaxProcNumber","*RSSProfile","*SpeedDuplex","*TCPChecksumOffloadIPv4","*TCPChecksumOffloadIPv6","*TransmitBuffers","*UDPChecksumOffloadIPv4","*UDPChecksumOffloadIPv6","AdaptiveIFS","ITR","LogLinkStateEvent","MasterSlave","NetworkAddress","WaitAutoNegComplete"},Values{"*FlowControl","*InterruptModeration","*IPChecksumOffloadIPv4","*JumboPacket","*LsoV2IPv4","*LsoV2IPv6","*MaxRssProcessors","*NumaNodeId","*NumRssQueues","*PriorityVLANTag","*ReceiveBuffers","*RSS","*RssBaseProcNumber","*RssMaxProcNumber","*RSSProfile","*SpeedDuplex","*TCPChecksumOffloadIPv4","*TCPChecksumOffloadIPv6","*TransmitBuffers","*UDPChecksumOffloadIPv4","*UDPChecksumOffloadIPv6","AdaptiveIFS","ITR","LogLinkStateEvent","MasterSlave","NetworkAddress","WaitAutoNegComplete"},Description("Specifies the registrykeyword of the property that should be in desired state.")] String RegistryKeyword; + [Required, Description("Specifies the network adapter name.")] String NetworkAdapterName; + [Required, Description("Specifies the registryvalue.")] String RegistryValue; + [Read, Description("Output Display value of selected RegistryKeyword.")] String DisplayValue; +}; diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/README.MD b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/README.MD new file mode 100644 index 00000000..40344cec --- /dev/null +++ b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/README.MD @@ -0,0 +1,5 @@ +# Description + +This resource is used to change advanced properties on a network adapter. +Please check the supported registry values before creating a configuration. + diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/en-US/MSFT_xNetAdapterAdvancedProperty.strings.psd1 b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/en-US/MSFT_xNetAdapterAdvancedProperty.strings.psd1 new file mode 100644 index 00000000..8d5715d1 --- /dev/null +++ b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterAdvancedProperty/en-US/MSFT_xNetAdapterAdvancedProperty.strings.psd1 @@ -0,0 +1,9 @@ +# Localized resources for MSFT_xNetAdapterAdvancedProperty + +ConvertFrom-StringData @' + CheckingNetAdapterMessage = Checking if network adapter exists or not. + NetAdapterNotFoundMessage = Network adapter not found. + NetAdapterTestingStateMessage = Checking if adapter {0} '{1}' is in desired state. + NetAdapterIsInDesiredStateMessage = Network adapter {0} '{1}' is in desired state '{2}'. + NetAdapterApplyingChangesMessage = Network adapter {0} '{1}' was '{2}', should be '{3}', applying changes. +'@ diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/MSFT_xNetAdapterLso.psm1 b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/MSFT_xNetAdapterLso.psm1 index 389d4d93..ec49ef00 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/MSFT_xNetAdapterLso.psm1 +++ b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/MSFT_xNetAdapterLso.psm1 @@ -2,13 +2,13 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot # Import the Networking Common Modules Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) + -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` + -ChildPath 'NetworkingDsc.Common.psm1')) # Import the Networking Resource Helper Module Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` - -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) + -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` + -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) # Import Localization Strings $localizedData = Get-LocalizedData ` @@ -35,63 +35,66 @@ function Get-TargetResource param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] - [ValidateSet("V1IPv4","IPv4","IPv6")] - [String] + [ValidateSet('V1IPv4', 'IPv4', 'IPv6')] + [System.String] $Protocol, [Parameter(Mandatory = $true)] - [Boolean] + [System.Boolean] $State ) - - Write-Verbose -Message ( @( + + Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " $localizedData.CheckingNetAdapterMessage ) -join '') - try + try { $netAdapter = Get-NetAdapterLso -Name $Name -ErrorAction Stop } - catch + catch { New-InvalidOperationException ` -Message ($LocalizedData.NetAdapterNotFoundMessage) } - if ($netAdapter) - { - Write-Verbose -Message ( @( + if ($netAdapter) + { + Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " $($LocalizedData.NetAdapterTestingStateMessage -f $Name, $Protocol) ) -join '') - $result = @{ - Name = $Name - Protocol = $Protocol + $result = @{ + Name = $Name + Protocol = $Protocol + } + + switch ($Protocol) + { + 'V1IPv4' + { + $result.add('State', $netAdapter.V1IPv4Enabled) } - switch ($Protocol) + + 'IPv4' { - "V1IPv4" - { - $result.add('State', $netAdapter.V1IPv4Enabled) - } - "IPv4" - { - $result.add('State', $netAdapter.IPv4Enabled) - } - "IPv6" - { - $result.add('State', $netAdapter.IPv6Enabled) - } + $result.add('State', $netAdapter.IPv4Enabled) + } + 'IPv6' + { + $result.add('State', $netAdapter.IPv6Enabled) } - return $result } + + return $result + } } <# @@ -113,72 +116,72 @@ function Set-TargetResource param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] - [ValidateSet("V1IPv4","IPv4","IPv6")] - [String] + [ValidateSet('V1IPv4', 'IPv4', 'IPv6')] + [System.String] $Protocol, [Parameter(Mandatory = $true)] - [Boolean] + [System.Boolean] $State ) - Write-Verbose -Message ( @( + Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " $localizedData.CheckingNetAdapterMessage ) -join '') - try + try { $netAdapter = Get-NetAdapterLso -Name $Name -ErrorAction Stop } - catch + catch { New-InvalidOperationException ` -Message ($LocalizedData.NetAdapterNotFoundMessage) } - if ($netAdapter) - { - Write-Verbose -Message ( @( + if ($netAdapter) + { + Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " $($LocalizedData.NetAdapterTestingStateMessage -f $Name, $Protocol) ) -join '') - if ($Protocol -eq "V1IPv4" -and $State -ne $netAdapter.V1IPv4Enabled) - { - Write-Verbose -Message ( @( + if ($Protocol -eq 'V1IPv4' -and $State -ne $netAdapter.V1IPv4Enabled) + { + Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " $($LocalizedData.NetAdapterApplyingChangesMessage -f ` - $Name, $Protocol, $($netAdapter.V1IPv4Enabled.ToString()), $($State.ToString()) ) - ) -join '') - - Set-NetAdapterLso -Name $Name -V1IPv4Enabled $State - } - elseif ($Protocol -eq "IPv4" -and $State -ne $netAdapter.IPv4Enabled) - { - Write-Verbose -Message ( @( + $Name, $Protocol, $($netAdapter.V1IPv4Enabled.ToString()), $($State.ToString()) ) + ) -join '') + + Set-NetAdapterLso -Name $Name -V1IPv4Enabled $State + } + elseif ($Protocol -eq 'IPv4' -and $State -ne $netAdapter.IPv4Enabled) + { + Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " $($LocalizedData.NetAdapterApplyingChangesMessage -f ` - $Name, $Protocol, $($netAdapter.IPv4Enabled.ToString()), $($State.ToString()) ) + $Name, $Protocol, $($netAdapter.IPv4Enabled.ToString()), $($State.ToString()) ) ) -join '') - Set-NetAdapterLso -Name $Name -IPv4Enabled $State - } - elseif ($Protocol -eq "IPv6" -and $State -ne $netAdapter.IPv6Enabled) - { - Write-Verbose -Message ( @( + Set-NetAdapterLso -Name $Name -IPv4Enabled $State + } + elseif ($Protocol -eq 'IPv6' -and $State -ne $netAdapter.IPv6Enabled) + { + Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " $($LocalizedData.NetAdapterApplyingChangesMessage -f ` - $Name, $Protocol, $($netAdapter.IPv6Enabled.ToString()), $($State.ToString()) ) + $Name, $Protocol, $($netAdapter.IPv6Enabled.ToString()), $($State.ToString()) ) ) -join '') - Set-NetAdapterLso -Name $Name -IPv6Enabled $State - } + Set-NetAdapterLso -Name $Name -IPv6Enabled $State } + } } <# @@ -201,57 +204,58 @@ function Test-TargetResource param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] - [ValidateSet("V1IPv4","IPv4","IPv6")] - [String] + [ValidateSet('V1IPv4', 'IPv4', 'IPv6')] + [System.String] $Protocol, [Parameter(Mandatory = $true)] - [Boolean] + [System.Boolean] $State ) - - Write-Verbose -Message ( @( + Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " $localizedData.CheckingNetAdapterMessage ) -join '') - try + try { $netAdapter = Get-NetAdapterLso -Name $Name -ErrorAction Stop } - catch + catch { New-InvalidOperationException ` -Message ($LocalizedData.NetAdapterNotFoundMessage) } - if ($netAdapter) - { - Write-Verbose -Message ( @( + if ($netAdapter) + { + Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " $localizedData.NetAdapterTestingStateMessage -f ` - $Name, $Protocol + $Name, $Protocol ) -join '') - switch ($Protocol) + switch ($Protocol) + { + 'V1IPv4' + { + return ($State -eq $netAdapter.V1IPv4Enabled) + } + + 'IPv4' + { + return ($State -eq $netAdapter.IPv4Enabled) + } + + 'IPv6' { - "V1IPv4" - { - return ($State -eq $netAdapter.V1IPv4Enabled) - } - "IPv4" - { - return ($State -eq $netAdapter.IPv4Enabled) - } - "IPv6" - { - return ($State -eq $netAdapter.IPv6Enabled) - } + return ($State -eq $netAdapter.IPv6Enabled) } } + } } diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/README.MD b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/README.MD index f56d8d71..5a4f4730 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/README.MD +++ b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/README.MD @@ -1,3 +1,4 @@ # Description -This resource is used to enable or disable LSO for specific protocols on a network adapter. +This resource is used to enable or disable LSO for specific protocols on a +network adapter. diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/en-US/MSFT_xNetAdapterLso.strings.psd1 b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/en-US/MSFT_xNetAdapterLso.strings.psd1 index 65f0c682..052bba06 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/en-US/MSFT_xNetAdapterLso.strings.psd1 +++ b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterLso/en-US/MSFT_xNetAdapterLso.strings.psd1 @@ -2,8 +2,8 @@ ConvertFrom-StringData @' CheckingNetAdapterMessage = Checking if network adapter exists or not. - NetAdapterNotFoundMessage = Network adapter not found - NetAdapterTestingStateMessage = Checking if adapter {0} {1} is in desired state. - NetAdapterIsInDesiredStateMessage = Network adapter {0} {1} is in desired state {2}. - NetAdapterApplyingChangesMessage = Network adapter {0} {1} was {2}, should be {3}, applying changes. + NetAdapterNotFoundMessage = Network adapter not found. + NetAdapterTestingStateMessage = Checking if adapter '{0}' '{1}' is in desired state. + NetAdapterIsInDesiredStateMessage = Network adapter '{0}' '{1}' is in desired state '{2}'. + NetAdapterApplyingChangesMessage = Network adapter '{0}' '{1}' was '{2}', should be '{3}', applying changes. '@ diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterName/MSFT_xNetAdapterName.psm1 b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterName/MSFT_xNetAdapterName.psm1 index 3d207318..c545dcdd 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterName/MSFT_xNetAdapterName.psm1 +++ b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterName/MSFT_xNetAdapterName.psm1 @@ -2,13 +2,13 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot # Import the Networking Common Modules Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) + -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` + -ChildPath 'NetworkingDsc.Common.psm1')) # Import the Networking Resource Helper Module Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` - -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) + -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` + -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) # Import Localization Strings $localizedData = Get-LocalizedData ` @@ -66,6 +66,7 @@ function Get-TargetResource [System.String] $NewName, + [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $Name, @@ -76,7 +77,7 @@ function Get-TargetResource [Parameter()] [ValidateNotNullOrEmpty()] - [ValidateSet('Up','Disconnected','Disabled')] + [ValidateSet('Up', 'Disconnected', 'Disabled')] [System.String] $Status = 'Up', @@ -110,7 +111,7 @@ function Get-TargetResource ) Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($LocalizedData.GettingNetAdapterNameMessage -f $NewName) + $($LocalizedData.GettingNetAdapterNameMessage -f $NewName) ) -join '') $adapter = Find-NetworkAdapter ` @@ -120,7 +121,7 @@ function Get-TargetResource if (-not $adapter) { Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " - $($LocalizedData.FindNetAdapterMessage) + $($LocalizedData.FindNetAdapterMessage) ) -join '') $null = $PSBoundParameters.Remove('NewName') @@ -131,7 +132,7 @@ function Get-TargetResource } Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " - $($LocalizedData.NetAdapterNameFoundMessage -f $adapter.Name) + $($LocalizedData.NetAdapterNameFoundMessage -f $adapter.Name) ) -join '') $returnValue = @{ @@ -199,6 +200,7 @@ function Set-TargetResource [System.String] $NewName, + [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $Name, @@ -209,7 +211,7 @@ function Set-TargetResource [Parameter()] [ValidateNotNullOrEmpty()] - [ValidateSet('Up','Disconnected','Disabled')] + [ValidateSet('Up', 'Disconnected', 'Disabled')] [System.String] $Status = 'Up', @@ -243,7 +245,7 @@ function Set-TargetResource ) Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " - $($LocalizedData.SettingNetAdapterNameMessage -f $NewName) + $($LocalizedData.SettingNetAdapterNameMessage -f $NewName) ) -join '') $null = $PSBoundParameters.Remove('NewName') @@ -253,13 +255,13 @@ function Set-TargetResource -ErrorAction Stop Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " - $($LocalizedData.RenamingNetAdapterNameMessage -f $adapter.Name,$NewName) + $($LocalizedData.RenamingNetAdapterNameMessage -f $adapter.Name, $NewName) ) -join '') $adapter | Rename-NetAdapter -NewName $NewName Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " - $($LocalizedData.NetAdapterNameRenamedMessage -f $NewName) + $($LocalizedData.NetAdapterNameRenamedMessage -f $NewName) ) -join '') } # Set-TargetResource @@ -314,6 +316,7 @@ function Test-TargetResource [System.String] $NewName, + [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $Name, @@ -324,7 +327,7 @@ function Test-TargetResource [Parameter()] [ValidateNotNullOrEmpty()] - [ValidateSet('Up','Disconnected','Disabled')] + [ValidateSet('Up', 'Disconnected', 'Disabled')] [System.String] $Status = 'Up', @@ -358,7 +361,7 @@ function Test-TargetResource ) Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($LocalizedData.TestingNetAdapterNameMessage -f $NewName) + $($LocalizedData.TestingNetAdapterNameMessage -f $NewName) ) -join '') $null = $PSBoundParameters.Remove('NewName') @@ -373,15 +376,16 @@ function Test-TargetResource { # An adapter was found matching the new name Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($LocalizedData.NetAdapterWithNewNameExistsMessage -f $adapterWithNewName.Name) + $($LocalizedData.NetAdapterWithNewNameExistsMessage -f $adapterWithNewName.Name) ) -join '') + return $true } else { # Find an adapter matching the parameters - throw if none can be found Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): " - $($LocalizedData.FindNetAdapterMessage) + $($LocalizedData.FindNetAdapterMessage) ) -join '') $adapter = Find-NetworkAdapter ` @@ -390,8 +394,9 @@ function Test-TargetResource # An adapter was found that needs to be changed to the new name Write-Verbose -Message ( @("$($MyInvocation.MyCommand): " - $($LocalizedData.NetAdapterNameNotMatchMessage -f $adapter.Name,$NewName) + $($LocalizedData.NetAdapterNameNotMatchMessage -f $adapter.Name, $NewName) ) -join '') + return $false } # if } # Test-TargetResource diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/MSFT_xNetAdapterRDMA.psm1 b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/MSFT_xNetAdapterRDMA.psm1 index 144d1104..0704c777 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/MSFT_xNetAdapterRDMA.psm1 +++ b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/MSFT_xNetAdapterRDMA.psm1 @@ -2,13 +2,13 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot # Import the Networking Common Modules Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) + -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` + -ChildPath 'NetworkingDsc.Common.psm1')) # Import the Networking Resource Helper Module Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` - -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) + -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` + -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) # Import Localization Strings $localizedData = Get-LocalizedData ` @@ -17,10 +17,11 @@ $localizedData = Get-LocalizedData ` <# .SYNOPSIS - Gets MSFT_xVMNetAdapterRDMA resource current state. + Gets the state of the network adapter RDMA. .PARAMETER Name - Specifies the name of the network adapter for which the RDMA configuration needs to be retrieved. + Specifies the name of network adapter for which RDMA needs + to be configured. #> function Get-TargetResource { @@ -28,8 +29,8 @@ function Get-TargetResource [OutputType([Hashtable])] param ( - [parameter(Mandatory = $true)] - [String] + [Parameter(Mandatory = $true)] + [System.String] $Name ) @@ -39,43 +40,49 @@ function Get-TargetResource try { - Write-Verbose -Message $localizedData.CheckNetAdapter - $netAdapter = Get-NetAdapterRdma -Name $Name -ErrorAction Stop - if ($netAdapter) - { - Write-Verbose -Message $localizedData.CheckNetAdapterRDMA - $configuration.Add('Enabled',$netAdapter.Enabled) - return $configuration - } + Write-Verbose -Message ($localizedData.GetNetAdapterRDMAMessage -f $Name) + + $netAdapterRdma = Get-NetAdapterRdma -Name $Name -ErrorAction Stop } catch { - throw $localizedData.NetAdapterNotFound + New-InvalidOperationException ` + -Message ($LocalizedData.NetAdapterNotFoundError -f $Name) + } + + if ($netAdapterRdma) + { + Write-Verbose -Message ($localizedData.CheckNetAdapterRDMAMessage -f $Name) + + $configuration.Add('Enabled', $netAdapterRdma.Enabled) } + + return $configuration } <# .SYNOPSIS - Sets MSFT_xVMNetAdapterRDMA resource state. + Sets the state of the network adapter RDMA. .PARAMETER Name - Specifies the name of the network adapter for which the - RDMA configuration needs to be retrieved. + Specifies the name of network adapter for which RDMA needs + to be configured. .PARAMETER Enabled Specifies if the RDMA configuration should be enabled or disabled. - This is a boolean value and the default is $true. + Defaults to $true. #> function Set-TargetResource { [CmdletBinding()] param ( - [parameter(Mandatory = $true)] - [String] + [Parameter(Mandatory = $true)] + [System.String] $Name, - [Boolean] + [Parameter()] + [System.Boolean] $Enabled = $true ) @@ -85,36 +92,40 @@ function Set-TargetResource try { - Write-Verbose -Message $localizedData.CheckNetAdapter - $netAdapter = Get-NetAdapterRdma -Name $Name -ErrorAction Stop - if ($netAdapter) - { - Write-Verbose -Message $localizedData.CheckNetAdapterRDMA - if ($netAdapter.Enabled -ne $Enabled) - { - Write-Verbose -Message $localizedData.NetAdapterRDMADifferent - Write-Verbose -Message $localizedData.SetNetAdapterRDMA - Set-NetAdapterRdma -Name $Name -Enabled $Enabled - } - } + Write-Verbose -Message ($localizedData.GetNetAdapterRDMAMessage -f $Name) + + $netAdapterRdma = Get-NetAdapterRdma -Name $Name -ErrorAction Stop } catch { - throw $localizedData.NetAdapterNotFound + New-InvalidOperationException ` + -Message ($LocalizedData.NetAdapterNotFoundError -f $Name) + } + + if ($netAdapterRdma) + { + Write-Verbose -Message ($localizedData.CheckNetAdapterRDMAMessage -f $Name) + + if ($netAdapterRdma.Enabled -ne $Enabled) + { + Write-Verbose -Message ($localizedData.SetNetAdapterRDMAMessage -f $Name, $Enabled) + + Set-NetAdapterRdma -Name $Name -Enabled $Enabled + } } } <# .SYNOPSIS - Tests if MSFT_xVMNetAdapterRDMA resource state is indeed desired state or not. + Tests the state of the network adapter RDMA. .PARAMETER Name - Specifies the name of the network adapter for which the - RDMA configuration needs to be retrieved. + Specifies the name of network adapter for which RDMA needs + to be configured. .PARAMETER Enabled Specifies if the RDMA configuration should be enabled or disabled. - This is a boolean value and the default is $true. + Defaults to $true. #> function Test-TargetResource { @@ -122,35 +133,42 @@ function Test-TargetResource [OutputType([System.Boolean])] param ( - [parameter(Mandatory = $true)] - [String] + [Parameter(Mandatory = $true)] + [System.String] $Name, - [Boolean] + [Parameter()] + [System.Boolean] $Enabled = $true ) try { - Write-Verbose -Message $localizedData.CheckNetAdapter - $netAdapter = Get-NetAdapterRdma -Name $Name -ErrorAction Stop - if ($netAdapter) - { - Write-Verbose -Message $localizedData.CheckNetAdapterRDMA - if ($netAdapter.Enabled -ne $Enabled) - { - Write-Verbose -Message $localizedData.NetAdapterRDMADifferent - return $false - } - else - { - Write-Verbose -Message $localizedData.NetAdapterRDMAMatches - return $true - } - } + Write-Verbose -Message ($localizedData.GetNetAdapterRDMAMessage -f $Name) + + $netAdapterRdma = Get-NetAdapterRdma -Name $Name -ErrorAction Stop } catch { - throw $localizedData.NetAdapterNotFound + New-InvalidOperationException ` + -Message ($LocalizedData.NetAdapterNotFoundError -f $Name) + } + + if ($netAdapterRdma) + { + Write-Verbose -Message ($localizedData.CheckNetAdapterRDMAMessage -f $Name) + + if ($netAdapterRdma.Enabled -ne $Enabled) + { + Write-Verbose -Message ($localizedData.NetAdapterRDMADifferentMessage -f $Name) + + return $false + } + else + { + Write-Verbose -Message ($localizedData.NetAdapterRDMAMatchesMessage -f $Name) + + return $true + } } } diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/MSFT_xNetAdapterRDMA.schema.mof b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/MSFT_xNetAdapterRDMA.schema.mof index 8883f754..ab17bd0d 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/MSFT_xNetAdapterRDMA.schema.mof +++ b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/MSFT_xNetAdapterRDMA.schema.mof @@ -2,5 +2,5 @@ class MSFT_xNetAdapterRDMA : OMI_BaseResource { [Key, Description("Specifies the name of network adapter for which RDMA needs to be configured.")] String Name; - [Write, Description("Specifies whether RDMA is enabled or disabled.")] Boolean Enabled; + [Write, Description("Specifies if the RDMA configuration should be enabled or disabled. Defaults to $true.")] Boolean Enabled; }; diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/en-US/MSFT_xNetAdapterRDMA.strings.psd1 b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/en-US/MSFT_xNetAdapterRDMA.strings.psd1 index db6e32d3..acd7c587 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/en-US/MSFT_xNetAdapterRDMA.strings.psd1 +++ b/Modules/xNetworking/DSCResources/MSFT_xNetAdapterRDMA/en-US/MSFT_xNetAdapterRDMA.strings.psd1 @@ -1,10 +1,10 @@ # Localized resources for MSFT_xNetAdapterRDMA ConvertFrom-StringData @' - CheckNetAdapter = Checking if network adapter exists or not. - CheckNetAdapterRDMA = Checking if RDMA is enabled and in desired state for this adapter. - NetAdapterNotFound = Network Adapter not found. - NetAdapterRDMADifferent = Network adapter RDMA setting is not in desired state. This will be configured. - SetNetAdapterRDMA = Setting network adapter RDMA configuration to desired state. - NetAdapterRDMAMatches = Network adapter RDMA configuration is in desired state. No action needed. + GetNetAdapterRDMAMessage = Getting network adapter '{0}' RDMA setting. + NetAdapterNotFoundError = Network adapter '{0}' not found. + CheckNetAdapterRDMAMessage = Checking the RDMA enabled state for network adapter '{0}'. + SetNetAdapterRDMAMessage = Setting network adapter '{0}' RDMA enabled to '{1}'. + NetAdapterRDMADifferentMessage = RDMA setting for network adapter '{0}' is not in desired state. This will be configured. + NetAdapterRDMAMatchesMessage = RDMA setting for network adapter '{0}' is in desired state. No action needed. '@ diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/MSFT_xNetBIOS.psm1 b/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/MSFT_xNetBIOS.psm1 index 290716ee..a85ca391 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/MSFT_xNetBIOS.psm1 +++ b/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/MSFT_xNetBIOS.psm1 @@ -2,13 +2,13 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot # Import the Networking Common Modules Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) + -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` + -ChildPath 'NetworkingDsc.Common.psm1')) # Import the Networking Resource Helper Module Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` - -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) + -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` + -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) # Import Localization Strings $localizedData = Get-LocalizedData ` @@ -18,7 +18,7 @@ $localizedData = Get-LocalizedData ` #region check NetBIOSSetting enum loaded, if not load try { - [void][reflection.assembly]::GetAssembly([NetBIOSSetting]) + [void][System.Reflection.Assembly]::GetAssembly([NetBiosSetting]) } catch { @@ -34,14 +34,17 @@ catch #endregion <# - .SYNOPSIS +.SYNOPSIS Returns the current state of the Net Bios on an interface. - .PARAMETER InterfaceAlias +.PARAMETER InterfaceAlias Specifies the alias of a network interface. Supports the use of '*'. - .PARAMETER Setting - Default - Use NetBios settings from the DHCP server. If static IP, Enable NetBIOS. +.PARAMETER Setting + Specifies if NetBIOS should be enabled or disabled or obtained from + the DHCP server (Default). If static IP, Enable NetBIOS. + + Parameter value is ignored. #> function Get-TargetResource { @@ -54,38 +57,57 @@ function Get-TargetResource $InterfaceAlias, [parameter(Mandatory = $true)] - [ValidateSet("Default","Enable","Disable")] + [ValidateSet("Default", "Enable", "Disable")] [System.String] $Setting ) - Write-Verbose -Message ($LocalizedData.GettingNetBiosSetting -f $InterfaceAlias) + Write-Verbose -Message ($LocalizedData.GettingNetBiosSettingMessage -f $InterfaceAlias) + + $netAdapter = Get-CimInstance ` + -ClassName Win32_NetworkAdapter ` + -Filter ('Name="{0}"' -f $InterfaceAlias) - $netadapterparams = @{ - ClassName = 'Win32_NetworkAdapter' - Filter = 'NetConnectionID="{0}"' -f $InterfaceAlias + if ($netAdapter) + { + Write-Verbose -Message ($localizedData.InterfaceDetectedMessage -f $InterfaceAlias, $netAdapter.InterfaceIndex) + } + else + { + New-InvalidOperationException ` + -Message ($localizedData.InterfaceNotFoundError -f $InterfaceAlias) } - $netAdapterConfig = Get-CimInstance @netadapterparams -ErrorAction Stop | - Get-CimAssociatedInstance ` - -ResultClassName Win32_NetworkAdapterConfiguration ` - -ErrorAction Stop + $netAdapterConfig = $netAdapter | Get-CimAssociatedInstance ` + -ResultClassName Win32_NetworkAdapterConfiguration ` + -ErrorAction Stop + + $tcpipNetbiosOptions = $netAdapterConfig.TcpipNetbiosOptions + if ($tcpipNetbiosOptions) + { + $Setting = $([NetBiosSetting].GetEnumValues()[$tcpipNetbiosOptions]) + } + else + { + $Setting = 'Default' + } return @{ InterfaceAlias = $InterfaceAlias - Setting = $([NETBIOSSetting].GetEnumValues()[$netAdapterConfig.TcpipNetbiosOptions]) + Setting = $Setting } } <# - .SYNOPSIS +.SYNOPSIS Sets the state of the Net Bios on an interface. - .PARAMETER InterfaceAlias +.PARAMETER InterfaceAlias Specifies the alias of a network interface. Supports the use of '*'. - .PARAMETER Setting - Default - Use NetBios settings from the DHCP server. If static IP, Enable NetBIOS. +.PARAMETER Setting + Specifies if NetBIOS should be enabled or disabled or obtained from + the DHCP server (Default). If static IP, Enable NetBIOS. #> function Set-TargetResource { @@ -97,50 +119,73 @@ function Set-TargetResource $InterfaceAlias, [parameter(Mandatory = $true)] - [ValidateSet("Default","Enable","Disable")] + [ValidateSet("Default", "Enable", "Disable")] [System.String] $Setting ) - $netadapterparams = @{ - ClassName = 'Win32_NetworkAdapter' - Filter = 'NetConnectionID="{0}"' -f $InterfaceAlias + Write-Verbose -Message ($LocalizedData.SettingNetBiosSettingMessage -f $InterfaceAlias) + + $netAdapter = Get-CimInstance ` + -ClassName Win32_NetworkAdapter ` + -Filter ('Name="{0}"' -f $InterfaceAlias) + + if ($netAdapter) + { + Write-Verbose -Message ($localizedData.InterfaceDetectedMessage -f $InterfaceAlias, $netAdapter.InterfaceIndex) } - $netAdapterConfig = Get-CimInstance @netadapterparams -ErrorAction Stop | - Get-CimAssociatedInstance ` - -ResultClassName Win32_NetworkAdapterConfiguration ` - -ErrorAction Stop + else + { + New-InvalidOperationException ` + -Message ($localizedData.InterfaceNotFoundError -f $InterfaceAlias) + } + + $netAdapterConfig = $netAdapter | Get-CimAssociatedInstance ` + -ResultClassName Win32_NetworkAdapterConfiguration ` + -ErrorAction Stop - if ($Setting -eq [NETBIOSSetting]::Default) + if ($Setting -eq [NetBiosSetting]::Default) { - Write-Verbose -Message $LocalizedData.ResetToDefaut - #If DHCP is not enabled, settcpipnetbios CIM Method won't take 0 so overwrite registry entry instead. - $regParam = @{ - Path = "HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters\Interfaces\Tcpip_$($NetAdapterConfig.SettingID)" - Name = 'NetbiosOptions' + Write-Verbose -Message $LocalizedData.ResetToDefautMessage + + # If DHCP is not enabled, SetTcpipNetbios CIM Method won't take 0 so overwrite registry entry instead. + $setItemPropertyParameters = @{ + Path = "HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters\Interfaces\Tcpip_$($NetAdapterConfig.SettingID)" + Name = 'NetbiosOptions' Value = 0 } - $null = Set-ItemProperty @regParam + $null = Set-ItemProperty @setItemPropertyParameters } else { - Write-Verbose -Message ($LocalizedData.SetNetBIOS -f $Setting) - $null = $netAdapterConfig | - Invoke-CimMethod -MethodName SetTcpipNetbios -ErrorAction Stop -Arguments @{ - TcpipNetbiosOptions = [uint32][NETBIOSSetting]::$Setting.value__ - } + Write-Verbose -Message ($LocalizedData.SetNetBiosMessage -f $Setting) + + $result = $netAdapterConfig | + Invoke-CimMethod ` + -MethodName SetTcpipNetbios ` + -ErrorAction Stop ` + -Arguments @{ + TcpipNetbiosOptions = [uint32][NetBiosSetting]::$Setting.value__ + } + + if ($result.ReturnValue -ne 0) + { + New-InvalidOperationException ` + -Message ($localizedData.FailedUpdatingNetBiosError -f $result.ReturnValue, $Setting) + } } } <# - .SYNOPSIS +.SYNOPSIS Tests the current state the Net Bios on an interface. - .PARAMETER InterfaceAlias +.PARAMETER InterfaceAlias Specifies the alias of a network interface. Supports the use of '*'. - .PARAMETER Setting - Default - Use NetBios settings from the DHCP server. If static IP, Enable NetBIOS. +.PARAMETER Setting + Specifies if NetBIOS should be enabled or disabled or obtained from + the DHCP server (Default). If static IP, Enable NetBIOS. #> function Test-TargetResource { @@ -153,44 +198,30 @@ function Test-TargetResource $InterfaceAlias, [parameter(Mandatory = $true)] - [ValidateSet("Default","Enable","Disable")] + [ValidateSet("Default", "Enable", "Disable")] [System.String] $Setting ) - $nic = Get-CimInstance ` + Write-Verbose -Message ($LocalizedData.TestingNetBiosSettingMessage -f $InterfaceAlias) + + $netAdapter = Get-CimInstance ` -ClassName Win32_NetworkAdapter ` - -Filter "NetConnectionID=`"$InterfaceAlias`"" - if ($null -ne $nic) + -Filter ('Name="{0}"' -f $InterfaceAlias) + + if ($netAdapter) { - Write-Verbose -Message ($LocalizedData.InterfaceDetected -f $InterfaceAlias,$nic.InterfaceIndex) + Write-Verbose -Message ($localizedData.InterfaceDetectedMessage -f $InterfaceAlias, $netAdapter.InterfaceIndex) } else { - $errorParam = @{ - Message = ($LocalizedData.NICNotFound -f $InterfaceAlias) - ArgumentName = 'InterfaceAlias' - } - New-InvalidArgumentException @errorParam + New-InvalidOperationException ` + -Message ($localizedData.InterfaceNotFoundError -f $InterfaceAlias) } - $nicConfig = $NIC | Get-CimAssociatedInstance -ResultClassName Win32_NetworkAdapterConfiguration - - Write-Verbose -Message ($LocalizedData.CurrentNetBiosSetting -f [NETBIOSSetting].GetEnumValues()[$NICConfig.TcpipNetbiosOptions]) + $currentState = Get-TargetResource @PSBoundParameters - $desiredSetting = ([NETBIOSSetting]::$($Setting)).value__ - Write-Verbose -Message ($LocalizedData.DesiredSetting -f $Setting) - - if ($nicConfig.TcpipNetbiosOptions -eq $desiredSetting) - { - Write-Verbose -Message $LocalizedData.InDesiredState - return $true - } - else - { - Write-Verbose -Message $LocalizedData.NotInDesiredState - return $false - } + return Test-DscParameterState -CurrentValues $currentState -DesiredValues $PSBoundParameters } Export-ModuleMember -Function *-TargetResource diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/MSFT_xNetBIOS.schema.mof b/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/MSFT_xNetBIOS.schema.mof index d9e516a0..cb6ffa40 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/MSFT_xNetBIOS.schema.mof +++ b/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/MSFT_xNetBIOS.schema.mof @@ -3,5 +3,5 @@ class MSFT_xNetBIOS : OMI_BaseResource { [Key, Description("Specifies the alias of a network interface.")] String InterfaceAlias; - [Required, Description("Default - Use NetBios settings from the DHCP server. If static IP, Enable NetBIOS."), ValueMap{"Default","Enable","Disable"}, Values{"Default","Enable","Disable"}] String Setting; + [Required, Description("Specifies if NetBIOS should be enabled or disabled or obtained from the DHCP server (Default). If static IP, Enable NetBIOS."), ValueMap{"Default","Enable","Disable"}, Values{"Default","Enable","Disable"}] String Setting; }; diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/en-US/MSFT_xNetBIOS.strings.psd1 b/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/en-US/MSFT_xNetBIOS.strings.psd1 index e5e3db0b..444eed49 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/en-US/MSFT_xNetBIOS.strings.psd1 +++ b/Modules/xNetworking/DSCResources/MSFT_xNetBIOS/en-US/MSFT_xNetBIOS.strings.psd1 @@ -1,13 +1,16 @@ # Localized resources for MSFT_xNetBIOS ConvertFrom-StringData @' - GettingNetBiosSetting = Getting NetBIOS Configuration for Interface {0}. - InterfaceDetected = Interface {0} detected with Index number: {1}. - CurrentNetBiosSetting = Current NetBIOS Configuration: {0}. - DesiredSetting = Desired NetBIOS Configuration: {0}. - InDesiredState = NetBIOS configuration is in desired state. - NotInDesiredState = NetBIOS configuration is not in desired state. - ResetToDefaut = NetBIOS configuration will be reset to default. - SetNetBIOS = NetBIOS configuration will be set to: {0}. - NICNotFound = Interface {0} was not found. + GettingNetBiosSettingMessage = Getting NetBIOS configuration for Interface '{0}'. + InterfaceDetectedMessage = Interface '{0}' detected with Index number {1}. + SettingNetBiosSettingMessage = Setting NetBIOS configuration for Interface '{0}'. + ResetToDefautMessage = NetBIOS configuration will be reset to default. + SetNetBiosMessage = NetBIOS configuration will be set to '{0}'. + TestingNetBiosSettingMessage = Testing NetBIOS configuration for Interface '{0}'. + CurrentNetBiosSettingMessage = Current NetBIOS configuration is '{0}'. + DesiredSettingMessage = Desired NetBIOS configuration is '{0}'. + InDesiredStateMessage = NetBIOS configuration is in desired state. + NotInDesiredStateMessage = NetBIOS configuration is not in desired state. + InterfaceNotFoundError = Interface '{0}' was not found. + FailedUpdatingNetBiosError = An error result of '{0}' was returned when attemting to set NetBIOS configuration to '{1}'. '@ diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetworkTeam/MSFT_xNetworkTeam.psm1 b/Modules/xNetworking/DSCResources/MSFT_xNetworkTeam/MSFT_xNetworkTeam.psm1 index 310dc602..28bc219b 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetworkTeam/MSFT_xNetworkTeam.psm1 +++ b/Modules/xNetworking/DSCResources/MSFT_xNetworkTeam/MSFT_xNetworkTeam.psm1 @@ -2,13 +2,13 @@ $modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot # Import the Networking Common Modules Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` - -ChildPath 'NetworkingDsc.Common.psm1')) + -ChildPath (Join-Path -Path 'NetworkingDsc.Common' ` + -ChildPath 'NetworkingDsc.Common.psm1')) # Import the Networking Resource Helper Module Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` - -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) + -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` + -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) # Import Localization Strings $localizedData = Get-LocalizedData ` @@ -33,17 +33,17 @@ Function Get-TargetResource Param ( [Parameter(Mandatory = $true)] - [string] + [System.String] $Name, [Parameter(Mandatory = $true)] - [String[]] + [System.String[]] $TeamMembers ) $configuration = @{ - name = $Name - teamMembers = $TeamMembers + Name = $Name + TeamMembers = $TeamMembers } Write-Verbose -Message ($localizedData.GetTeamInfo -f $Name) @@ -54,16 +54,16 @@ Function Get-TargetResource Write-Verbose -Message ($localizedData.FoundTeam -f $Name) if ($null -eq (Compare-Object -ReferenceObject $TeamMembers -DifferenceObject $networkTeam.Members)) { - Write-Verbose -Message ($localizedData.teamMembersExist -f $Name) - $configuration.Add('loadBalancingAlgorithm', $networkTeam.loadBalancingAlgorithm) - $configuration.Add('teamingMode', $networkTeam.teamingMode) - $configuration.Add('ensure','Present') + Write-Verbose -Message ($localizedData.TeamMembersExist -f $Name) + $configuration.Add('LoadBalancingAlgorithm', $networkTeam.loadBalancingAlgorithm) + $configuration.Add('TeamingMode', $networkTeam.teamingMode) + $configuration.Add('Ensure', 'Present') } } else { Write-Verbose -Message ($localizedData.TeamNotFound -f $Name) - $configuration.Add('ensure','Absent') + $configuration.Add('Ensure', 'Absent') } return $configuration @@ -95,119 +95,130 @@ Function Set-TargetResource Param ( [Parameter(Mandatory = $true)] - [string] + [System.String] $Name, [Parameter(Mandatory = $true)] - [String[]] + [System.String[]] $TeamMembers, [Parameter()] - [ValidateSet("SwitchIndependent", "LACP", "Static")] - [String] - $TeamingMode = "SwitchIndependent", + [ValidateSet('SwitchIndependent', 'LACP', 'Static')] + [System.String] + $TeamingMode = 'SwitchIndependent', [Parameter()] - [ValidateSet("Dynamic", "HyperVPort", "IPAddresses", "MacAddresses", "TransportPorts")] - [String] - $LoadBalancingAlgorithm = "HyperVPort", + [ValidateSet('Dynamic', 'HyperVPort', 'IPAddresses', 'MacAddresses', 'TransportPorts')] + [System.String] + $LoadBalancingAlgorithm = 'HyperVPort', [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present' ) + Write-Verbose -Message ($localizedData.GetTeamInfo -f $Name) + $networkTeam = Get-NetLBFOTeam -Name $Name -ErrorAction SilentlyContinue if ($Ensure -eq 'Present') { if ($networkTeam) { - Write-Verbose -Message ($localizedData.foundTeam -f $Name) + Write-Verbose -Message ($localizedData.FoundTeam -f $Name) + $setArguments = @{ - 'name' = $Name + Name = $Name } if ($networkTeam.loadBalancingAlgorithm -ne $LoadBalancingAlgorithm) { - Write-Verbose -Message ($localizedData.lbAlgoDifferent -f $LoadBalancingAlgorithm) - $setArguments.Add('loadBalancingAlgorithm', $LoadBalancingAlgorithm) + Write-Verbose -Message ($localizedData.LoadBalancingAlgorithmDifferent -f $LoadBalancingAlgorithm) + + $setArguments.Add('LoadBalancingAlgorithm', $LoadBalancingAlgorithm) $isNetModifyRequired = $true } if ($networkTeam.TeamingMode -ne $TeamingMode) { - Write-Verbose -Message ($localizedData.teamingModeDifferent -f $TeamingMode) - $setArguments.Add('teamingMode', $TeamingMode) + Write-Verbose -Message ($localizedData.TeamingModeDifferent -f $TeamingMode) + + $setArguments.Add('TeamingMode', $TeamingMode) $isNetModifyRequired = $true } if ($isNetModifyRequired) { - Write-Verbose -Message ($localizedData.modifyTeam -f $Name) + Write-Verbose -Message ($localizedData.ModifyTeam -f $Name) + Set-NetLbfoTeam @setArguments -ErrorAction Stop -Confirm:$false } $netTeamMembers = Compare-Object ` - -ReferenceObject $TeamMembers ` - -DifferenceObject $networkTeam.Members + -ReferenceObject $TeamMembers ` + -DifferenceObject $networkTeam.Members + if ($null -ne $netTeamMembers) { - Write-Verbose -Message ($localizedData.membersDifferent -f $Name) - $membersToRemove = ($netTeamMembers | Where-Object {$_.SideIndicator -eq '=>'}).InputObject + Write-Verbose -Message ($localizedData.MembersDifferent -f $Name) + + $membersToRemove = ($netTeamMembers | Where-Object -FilterScript { + $_.SideIndicator -eq '=>' + }).InputObject + if ($membersToRemove) { - Write-Verbose -Message ($localizedData.removingMembers -f ($membersToRemove -join ',')) + Write-Verbose -Message ($localizedData.RemovingMembers -f ($membersToRemove -join ',')) + $null = Remove-NetLbfoTeamMember -Name $membersToRemove ` - -Team $Name ` - -ErrorAction Stop ` - -Confirm:$false + -Team $Name ` + -ErrorAction Stop ` + -Confirm:$false } - $membersToAdd = ($netTeamMembers | Where-Object {$_.SideIndicator -eq '<='}).InputObject + $membersToAdd = ($netTeamMembers | Where-Object -FilterScript { + $_.SideIndicator -eq '<=' + }).InputObject + if ($membersToAdd) { - Write-Verbose -Message ($localizedData.addingMembers -f ($membersToAdd -join ',')) + Write-Verbose -Message ($localizedData.AddingMembers -f ($membersToAdd -join ',')) + $null = Add-NetLbfoTeamMember -Name $membersToAdd ` - -Team $Name ` - -ErrorAction Stop ` - -Confirm:$false + -Team $Name ` + -ErrorAction Stop ` + -Confirm:$false } } - } else { - Write-Verbose -Message ($localizedData.createTeam -f $Name) + Write-Verbose -Message ($localizedData.CreateTeam -f $Name) + try { $null = New-NetLbfoTeam ` - -Name $Name ` - -TeamMembers $teamMembers ` - -TeamingMode $TeamingMode ` - -LoadBalancingAlgorithm $loadBalancingAlgorithm ` - -ErrorAction Stop ` - -Confirm:$false - Write-Verbose -Message $localizedData.createdNetTeam + -Name $Name ` + -TeamMembers $teamMembers ` + -TeamingMode $TeamingMode ` + -LoadBalancingAlgorithm $loadBalancingAlgorithm ` + -ErrorAction Stop ` + -Confirm:$false + + Write-Verbose -Message $localizedData.CreatedNetTeam } catch { - $errorId = 'TeamCreateError' - $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation - $errorMessage = $localizedData.failedToCreateTeam - $exception = New-Object -TypeName System.InvalidOperationException ` - -ArgumentList $errorMessage - $errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord ` - -ArgumentList $exception, $errorId, $errorCategory, $null - - $PSCmdlet.ThrowTerminatingError($errorRecord) + New-InvalidOperationException ` + -Message ($localizedData.failedToCreateTeam -f $_.Exception.Message) } } } else { - Write-Verbose -Message ($localizedData.removeTeam -f $Name) + Write-Verbose -Message ($localizedData.RemoveTeam -f $Name) + $null = Remove-NetLbfoTeam -Name $name -ErrorAction Stop -Confirm:$false } } @@ -239,54 +250,59 @@ Function Test-TargetResource Param ( [Parameter(Mandatory = $true)] - [string] + [System.String] $Name, [Parameter(Mandatory = $true)] - [String[]] + [System.String[]] $TeamMembers, [Parameter()] - [ValidateSet("SwitchIndependent", "LACP", "Static")] - [String] - $TeamingMode = "SwitchIndependent", + [ValidateSet('SwitchIndependent', 'LACP', 'Static')] + [System.String] + $TeamingMode = 'SwitchIndependent', [Parameter()] - [ValidateSet("Dynamic", "HyperVPort", "IPAddresses", "MacAddresses", "TransportPorts")] - [String] - $LoadBalancingAlgorithm = "HyperVPort", + [ValidateSet('Dynamic', 'HyperVPort', 'IPAddresses', 'MacAddresses', 'TransportPorts')] + [System.String] + $LoadBalancingAlgorithm = 'HyperVPort', [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present' ) Write-Verbose -Message ($localizedData.GetTeamInfo -f $Name) + $networkTeam = Get-NetLbfoTeam -Name $Name -ErrorAction SilentlyContinue if ($ensure -eq 'Present') { if ($networkTeam) { - Write-Verbose -Message ($localizedData.foundTeam -f $Name) + Write-Verbose -Message ($localizedData.FoundTeam -f $Name) + if ( ($networkTeam.LoadBalancingAlgorithm -eq $LoadBalancingAlgorithm) -and ($networkTeam.teamingMode -eq $TeamingMode) -and ($null -eq (Compare-Object -ReferenceObject $TeamMembers -DifferenceObject $networkTeam.Members)) ) { - Write-Verbose -Message ($localizedData.teamExistsNoAction -f $Name) + Write-Verbose -Message ($localizedData.TeamExistsNoAction -f $Name) + return $true } else { - Write-Verbose -Message ($localizedData.teamExistsWithDifferentConfig -f $Name) + Write-Verbose -Message ($localizedData.TeamExistsWithDifferentConfig -f $Name) + return $false } } else { - Write-Verbose -Message ($localizedData.teamDoesNotExistShouldCreate -f $Name) + Write-Verbose -Message ($localizedData.TeamDoesNotExistShouldCreate -f $Name) + return $false } } @@ -294,12 +310,14 @@ Function Test-TargetResource { if ($networkTeam) { - Write-Verbose -Message ($localizedData.teamExistsShouldRemove -f $Name) + Write-Verbose -Message ($localizedData.TeamExistsShouldRemove -f $Name) + return $false } else { - Write-Verbose -Message ($localizedData.teamDoesNotExistNoAction -f $Name) + Write-Verbose -Message ($localizedData.TeamDoesNotExistNoAction -f $Name) + return $true } } diff --git a/Modules/xNetworking/DSCResources/MSFT_xNetworkTeam/en-US/MSFT_xNetworkTeam.strings.psd1 b/Modules/xNetworking/DSCResources/MSFT_xNetworkTeam/en-US/MSFT_xNetworkTeam.strings.psd1 index a4a4b3b2..669c6bf4 100644 --- a/Modules/xNetworking/DSCResources/MSFT_xNetworkTeam/en-US/MSFT_xNetworkTeam.strings.psd1 +++ b/Modules/xNetworking/DSCResources/MSFT_xNetworkTeam/en-US/MSFT_xNetworkTeam.strings.psd1 @@ -1,24 +1,24 @@ # Localized resources for MSFT_xNetworkTeam ConvertFrom-StringData @' - getTeamInfo = Getting network team information for {0}. - foundTeam = Found a network team with name {0}. - teamMembersExist = Members in the network team {0} exist as per the configuration. - teamNotFound = Network team with name {0} not found. - lbAlgoDifferent = Load Balancing Algo is different from the requested {0} algo. - teamingModeDifferent = Teaming mode is different from the requested {0} mode. - modifyTeam = Modifying the network team named {0}. - membersDifferent = Members within the team named {0} are different from that requested in the configuration. - removingMembers = Removing members {0} not specified in the configuration. - addingMembers = Adding members {0} that are not a part of the team configuration. - createTeam = Creating a network team with the name {0}. - removeTeam = Removing a network team with the name {0}. - teamExistsNoAction = Network team with name {0} exists. No action needed. - teamExistsWithDifferentConfig = Network team with name {0} exists but with different configuration. This will be modified. - teamDoesNotExistShouldCreate = Network team with name {0} does not exist. It will be created. - teamExistsShouldRemove = Network team with name {0} exists. It will be removed. - teamDoesNotExistNoAction = Network team with name {0} does not exist. No action needed. - waitingForTeam = Waiting for network team status to change to up. - createdNetTeam = Network Team was created successfully. - failedToCreateTeam = Failed to create the network team with specific configuration. + GetTeamInfo = Getting network team information for '{0}'. + FoundTeam = Found a network team with name '{0}'. + TeamMembersExist = Members in the network team '{0}' exist as per the configuration. + TeamNotFound = Network team with name '{0}' not found. + LoadBalancingAlgorithmDifferent = Load Balancing algorithm is different from the requested '{0}' algorithm. + TeamingModeDifferent = Teaming mode is different from the requested '{0}' mode. + ModifyTeam = Modifying the network team named '{0}'. + MembersDifferent = Members within the team named '{0}' are different from that requested in the configuration. + RemovingMembers = Removing members '{0}' not specified in the configuration. + AddingMembers = Adding members '{0}' that are not a part of the team configuration. + CreateTeam = Creating a network team with the name '{0}'. + RemoveTeam = Removing a network team with the name '{0}'. + TeamExistsNoAction = Network team with name '{0}' exists. No action needed. + TeamExistsWithDifferentConfig = Network team with name '{0}' exists but with different configuration. This will be modified. + TeamDoesNotExistShouldCreate = Network team with name '{0}' does not exist. It will be created. + TeamExistsShouldRemove = Network team with name '{0}' exists. It will be removed. + TeamDoesNotExistNoAction = Network team with name '{0}' does not exist. No action needed. + WaitingForTeam = Waiting for network team status to change to up. + CreatedNetTeam = Network Team was created successfully. + FailedToCreateTeam = Failed to create the network team with specific configuration: {0}. '@ diff --git a/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/MSFT_xWINSSetting.psm1 b/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/MSFT_xWINSSetting.psm1 new file mode 100644 index 00000000..fd6ab630 --- /dev/null +++ b/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/MSFT_xWINSSetting.psm1 @@ -0,0 +1,191 @@ +$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 the Networking Resource Helper Module +Import-Module -Name (Join-Path -Path $modulePath ` + -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' ` + -ChildPath 'NetworkingDsc.ResourceHelper.psm1')) + +# Import Localization Strings +$LocalizedData = Get-LocalizedData ` + -ResourceName 'MSFT_xWINSSetting' ` + -ResourcePath (Split-Path -Parent $Script:MyInvocation.MyCommand.Path) + +<# + .SYNOPSIS + Returns the current WINS settings. + + .PARAMETER IsSingleInstance + Specifies the resource is a single instance, the value must be 'Yes'. +#> +function Get-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] + param + ( + [Parameter(Mandatory = $true)] + [ValidateSet('Yes')] + [System.String] + $IsSingleInstance + ) + + Write-Verbose -Message ( @( + "$($MyInvocation.MyCommand): " + $($LocalizedData.GettingWinsSettingMessage) + ) -join '' ) + + # 0 equals off, 1 equals on + $enableLmHostsRegistryKey = Get-ItemProperty ` + -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' ` + -Name EnableLMHOSTS ` + -ErrorAction SilentlyContinue + + $enableLmHosts = ($enableLmHostsRegistryKey.EnableLMHOSTS -eq 1) + + # 0 equals off, 1 equals on + $enableDnsRegistryKey = Get-ItemProperty ` + -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' ` + -Name EnableDNS ` + -ErrorAction SilentlyContinue + + if ($enableDnsRegistryKey) + { + $enableDns = ($enableDnsRegistryKey.EnableDNS -eq 1) + } + else + { + # if the key does not exist, then set the default which is enabled. + $enableDns = $true + } + + return @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $enableLmHosts + EnableDns = $enableDns + } +} # Get-TargetResource + +<# + .SYNOPSIS + Sets the current configuration for the LMHOSTS Lookup setting. + + .PARAMETER IsSingleInstance + Specifies the resource is a single instance, the value must be 'Yes'. + + .PARAMETER EnableLmHosts + Specifies if LMHOSTS lookup should be enabled for all network + adapters with TCP/IP enabled. + + .PARAMETER EnableDns + Specifies if DNS is enabled for name resolution over WINS for + all network adapters with TCP/IP enabled. +#> +function Set-TargetResource +{ + [CmdletBinding()] + param + ( + [Parameter(Mandatory = $true)] + [ValidateSet('Yes')] + [System.String] + $IsSingleInstance, + + [Parameter()] + [System.Boolean] + $EnableLmHosts, + + [Parameter()] + [System.Boolean] + $EnableDns + ) + + Write-Verbose -Message ( @( + "$($MyInvocation.MyCommand): " + $($LocalizedData.SettingWinsSettingMessage) + ) -join '' ) + + # Get the current values of the WINS settings + $currentState = Get-TargetResource -IsSingleInstance 'Yes' + + if (-not $PSBoundParameters.ContainsKey('EnableLmHosts')) + { + $EnableLmHosts = $currentState.EnableLmHosts + } + + if (-not $PSBoundParameters.ContainsKey('EnableDns')) + { + $EnableDns = $currentState.EnableDNS + } + + $result = Invoke-CimMethod ` + -ClassName Win32_NetworkAdapterConfiguration ` + -MethodName EnableWins ` + -Arguments @{ + DNSEnabledForWINSResolution = $EnableDns + WINSEnableLMHostsLookup = $EnableLmHosts + } + + if ($result.ReturnValue -ne 0) + { + New-InvalidOperationException ` + -Message ($localizedData.FailedUpdatingWinsSettingError -f $result.ReturnValue) + } + + Write-Verbose -Message ( @( + "$($MyInvocation.MyCommand): " + $($LocalizedData.WinsSettingUpdatedMessage) + ) -join '' ) +} # Set-TargetResource + +<# + .SYNOPSIS + Tests the current configuration for the LMHOSTS Lookup setting. + + .PARAMETER IsSingleInstance + Specifies the resource is a single instance, the value must be 'Yes'. + + .PARAMETER EnableLmHosts + Specifies if LMHOSTS lookup should be enabled for all network + adapters with TCP/IP enabled. + + .PARAMETER EnableDns + Specifies if DNS is enabled for name resolution over WINS for + all network adapters with TCP/IP enabled. +#> +function Test-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Boolean])] + param + ( + [Parameter(Mandatory = $true)] + [ValidateSet('Yes')] + [System.String] + $IsSingleInstance, + + [Parameter()] + [System.Boolean] + $EnableLmHosts, + + [Parameter()] + [System.Boolean] + $EnableDns + ) + + Write-Verbose -Message ( @( + "$($MyInvocation.MyCommand): " + $($LocalizedData.TestingWinsSettingMessage) + ) -join '' ) + + # Get the current values of the WINS settings + $currentState = Get-TargetResource -IsSingleInstance 'Yes' + + return Test-DscParameterState -CurrentValues $currentState -DesiredValues $PSBoundParameters +} # Test-TargetResource + +Export-ModuleMember -Function *-TargetResource diff --git a/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/MSFT_xWINSSetting.schema.mof b/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/MSFT_xWINSSetting.schema.mof new file mode 100644 index 00000000..93757cb0 --- /dev/null +++ b/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/MSFT_xWINSSetting.schema.mof @@ -0,0 +1,7 @@ +[ClassVersion("1.0.0.0"), FriendlyName("xWINSSetting")] +class MSFT_xWINSSetting : OMI_BaseResource +{ + [Key, Description("Specifies the resource is a single instance, the value must be 'Yes'."), ValueMap{"Yes"}, Values{"Yes"}] String IsSingleInstance; + [Write, Description("Specifies if LMHOSTS lookup should be enabled for all network adapters with TCP/IP enabled.")] Boolean EnableLmHosts; + [Write, Description("Specifies if DNS is enabled for name resolution over WINS for all network adapters with TCP/IP enabled.")] Boolean EnableDns; +}; diff --git a/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/README.MD b/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/README.MD new file mode 100644 index 00000000..1cd6db57 --- /dev/null +++ b/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/README.MD @@ -0,0 +1,4 @@ +# Description + +This resource is used to configure the WINS settings that enable or disable +LMHOSTS lookups and enable or disable DNS for name resolution over WINS. diff --git a/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/en-US/MSFT_xWINSSetting.strings.psd1 b/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/en-US/MSFT_xWINSSetting.strings.psd1 new file mode 100644 index 00000000..f741ad77 --- /dev/null +++ b/Modules/xNetworking/DSCResources/MSFT_xWinsSetting/en-US/MSFT_xWINSSetting.strings.psd1 @@ -0,0 +1,9 @@ +# Localized resources for MSFT_xWinsSetting + +ConvertFrom-StringData @' + GettingWinsSettingMessage = Getting WINS settings. + SettingWinsSettingMessage = Setting WINS settings. + WinsSettingUpdatedMessage = WINS settings updated. + TestingWinsSettingMessage = Testing WINS settings. + FailedUpdatingWinsSettingError = An error code of '{0}' was returned when attemting to update WINS settings. +'@ diff --git a/Modules/xNetworking/Examples/Resources/xNetAdapterAdvancedProperty/1-JumboPacket.ps1 b/Modules/xNetworking/Examples/Resources/xNetAdapterAdvancedProperty/1-JumboPacket.ps1 new file mode 100644 index 00000000..c2679460 --- /dev/null +++ b/Modules/xNetworking/Examples/Resources/xNetAdapterAdvancedProperty/1-JumboPacket.ps1 @@ -0,0 +1,25 @@ +<# + .EXAMPLE + This configuration changes the JumboPacket Size. +#> +Configuration Example +{ + param + ( + [Parameter()] + [System.String[]] + $NodeName = 'localhost' + ) + + Import-DSCResource -ModuleName xNetworking + + Node $NodeName + { + xNetAdapterAdvancedProperty JumboPacket9014 + { + NetworkAdapterName = 'Ethernet' + RegistryKeyword = "*JumboPacket" + RegistryValue = 9014 + } + } +} diff --git a/Modules/xNetworking/Examples/Resources/xNetAdapterLso/1-DisableLsoIPv6.ps1 b/Modules/xNetworking/Examples/Resources/xNetAdapterLso/1-DisableLsoIPv6.ps1 index ab95ef2d..87063c1e 100644 --- a/Modules/xNetworking/Examples/Resources/xNetAdapterLso/1-DisableLsoIPv6.ps1 +++ b/Modules/xNetworking/Examples/Resources/xNetAdapterLso/1-DisableLsoIPv6.ps1 @@ -7,7 +7,7 @@ Configuration Example param ( [Parameter()] - [System.String[]] + [System.String[]] $NodeName = 'localhost' ) @@ -17,9 +17,9 @@ Configuration Example { xNetAdapterLso DisableLsoIPv6 { - Name = 'Ethernet' + Name = 'Ethernet' Protocol = 'IPv6' - State = $false + State = $false } } } diff --git a/Modules/xNetworking/Examples/Resources/xNetAdapterLso/2-DisableLsoIPv4.ps1 b/Modules/xNetworking/Examples/Resources/xNetAdapterLso/2-DisableLsoIPv4.ps1 index f562a596..790db771 100644 --- a/Modules/xNetworking/Examples/Resources/xNetAdapterLso/2-DisableLsoIPv4.ps1 +++ b/Modules/xNetworking/Examples/Resources/xNetAdapterLso/2-DisableLsoIPv4.ps1 @@ -7,7 +7,7 @@ Configuration Example param ( [Parameter()] - [System.String[]] + [System.String[]] $NodeName = 'localhost' ) @@ -17,9 +17,9 @@ Configuration Example { xNetAdapterLso DisableLsoIPv4 { - Name = 'Ethernet' + Name = 'Ethernet' Protocol = 'IPv4' - State = $false + State = $false } } } diff --git a/Modules/xNetworking/Examples/Resources/xNetAdapterName/1-RenameNetAdapterMacAddress.ps1 b/Modules/xNetworking/Examples/Resources/xNetAdapterName/1-RenameNetAdapterMacAddress.ps1 index 28391c2a..874ad086 100644 --- a/Modules/xNetworking/Examples/Resources/xNetAdapterName/1-RenameNetAdapterMacAddress.ps1 +++ b/Modules/xNetworking/Examples/Resources/xNetAdapterName/1-RenameNetAdapterMacAddress.ps1 @@ -18,8 +18,8 @@ Configuration Example { xNetAdapterName RenameNetAdapterCluster { - NewName = 'Cluster' - MacAddress = '9C-D2-1E-61-B5-DA' + NewName = 'Cluster' + MacAddress = '9C-D2-1E-61-B5-DA' } xDhcpClient EnableDhcpClientCluster @@ -31,8 +31,8 @@ Configuration Example xNetAdapterName RenameNetAdapterManagement { - NewName = 'Management' - MacAddress = '9C-D2-1E-61-B5-DB' + NewName = 'Management' + MacAddress = '9C-D2-1E-61-B5-DB' } xDhcpClient EnableDhcpClientManagement @@ -44,8 +44,8 @@ Configuration Example xNetAdapterName RenameNetAdapterSMB { - NewName = 'SMB' - MacAddress = '9C-D2-1E-61-B5-DC' + NewName = 'SMB' + MacAddress = '9C-D2-1E-61-B5-DC' } xDhcpClient EnableDhcpClientSMB diff --git a/Modules/xNetworking/Examples/Resources/xNetworkTeam/1-AddNetworkTeam.ps1 b/Modules/xNetworking/Examples/Resources/xNetworkTeam/1-AddNetworkTeam.ps1 index 5a5ce7d5..4ee91a27 100644 --- a/Modules/xNetworking/Examples/Resources/xNetworkTeam/1-AddNetworkTeam.ps1 +++ b/Modules/xNetworking/Examples/Resources/xNetworkTeam/1-AddNetworkTeam.ps1 @@ -1,6 +1,7 @@ <# .EXAMPLE - Creates the Host Team with the NIC1 and NIC2 Interfaces + Creates the switch independent Network Team 'HostTeam' using the NIC1 + and NIC2 interfaces. It sets the load balacing algorithm to 'HyperVPort'. #> Configuration Example { @@ -17,11 +18,11 @@ Configuration Example { xNetworkTeam HostTeam { - Name = 'HostTeam' - TeamingMode = 'SwitchIndependent' + Name = 'HostTeam' + TeamingMode = 'SwitchIndependent' LoadBalancingAlgorithm = 'HyperVPort' - TeamMembers = 'NIC1','NIC2' - Ensure = 'Present' + TeamMembers = 'NIC1', 'NIC2' + Ensure = 'Present' } } } diff --git a/Modules/xNetworking/Examples/Resources/xNetworkTeam/2-RemoveTeam.ps1 b/Modules/xNetworking/Examples/Resources/xNetworkTeam/2-RemoveTeam.ps1 index a0f3b4f6..1bfb5028 100644 --- a/Modules/xNetworking/Examples/Resources/xNetworkTeam/2-RemoveTeam.ps1 +++ b/Modules/xNetworking/Examples/Resources/xNetworkTeam/2-RemoveTeam.ps1 @@ -1,6 +1,6 @@ <# .EXAMPLE - Removes the NIC Team for the listed interfacess. + Removes the NIC Team 'HostTeam' from the interfaces NIC1, NIC2 and NIC3. #> Configuration Example { @@ -17,9 +17,9 @@ Configuration Example { xNetworkTeam HostTeam { - Name = 'HostTeam' - Ensure = 'Absent' - TeamMembers = 'NIC1','NIC2','NIC3' + Name = 'HostTeam' + Ensure = 'Absent' + TeamMembers = 'NIC1', 'NIC2', 'NIC3' } } } diff --git a/Modules/xNetworking/Examples/Resources/xWinsSetting/1-ConfigureWinsSetting.ps1 b/Modules/xNetworking/Examples/Resources/xWinsSetting/1-ConfigureWinsSetting.ps1 new file mode 100644 index 00000000..2fe23dc7 --- /dev/null +++ b/Modules/xNetworking/Examples/Resources/xWinsSetting/1-ConfigureWinsSetting.ps1 @@ -0,0 +1,25 @@ +<# + .EXAMPLE + Disable LMHOSTS lookup and disable using DNS for WINS name resolution. +#> +Configuration Example +{ + param + ( + [Parameter()] + [System.String[]] + $NodeName = 'localhost' + ) + + Import-DscResource -Module xNetworking + + Node $NodeName + { + xWinsSetting ConfigureWinsSettings + { + IsSingleInstance = 'Yes' + EnableLMHOSTS = $false + EnableDNS = $false + } + } +} diff --git a/Modules/xNetworking/Modules/NetworkingDsc.Common/NetworkingDsc.Common.psm1 b/Modules/xNetworking/Modules/NetworkingDsc.Common/NetworkingDsc.Common.psm1 index 5b7521ff..8e80f423 100644 --- a/Modules/xNetworking/Modules/NetworkingDsc.Common/NetworkingDsc.Common.psm1 +++ b/Modules/xNetworking/Modules/NetworkingDsc.Common/NetworkingDsc.Common.psm1 @@ -421,8 +421,312 @@ function Get-IPAddressPrefix } } +<# + .SYNOPSIS + Removes common parameters from a hashtable + + .DESCRIPTION + This function serves the purpose of removing common parameters and option common parameters from a parameter hashtable + + .PARAMETER Hashtable + The parameter hashtable that should be pruned +#> +function Remove-CommonParameter +{ + [OutputType([System.Collections.Hashtable])] + [cmdletbinding()] + param + ( + [Parameter(Mandatory = $true)] + [System.Collections.Hashtable] + $Hashtable + ) + + $inputClone = $Hashtable.Clone() + $commonParameters = [System.Management.Automation.PSCmdlet]::CommonParameters + $commonParameters += [System.Management.Automation.PSCmdlet]::OptionalCommonParameters + + $Hashtable.Keys | Where-Object { $_ -in $commonParameters } | ForEach-Object { + $inputClone.Remove($_) + } + + return $inputClone +} + +<# + .SYNOPSIS + Tests the status of DSC resource parameters + + .DESCRIPTION + This function tests the parameter status of DSC resource parameters against the current values present on the system + + .PARAMETER CurrentValues + A hashtable with the current values on the system, obtained by e.g. Get-TargetResource + + .PARAMETER DesiredValues + The hashtable of desired values + + .PARAMETER ValuesToCheck + The values to check if not all values should be checked + + .PARAMETER TurnOffTypeChecking + Indicates that the type of the parameter should not be checked +#> +function Test-DscParameterState +{ + [CmdletBinding()] + param + ( + [Parameter(Mandatory = $true)] + [System.Collections.Hashtable] + $CurrentValues, + + [Parameter(Mandatory = $true)] + [System.Object] + $DesiredValues, + + [Parameter()] + [System.String[]] + $ValuesToCheck, + + [Parameter()] + [switch] + $TurnOffTypeChecking + ) + + $returnValue = $true + + $types = 'System.Management.Automation.PSBoundParametersDictionary', 'System.Collections.Hashtable', 'Microsoft.Management.Infrastructure.CimInstance' + + if ($DesiredValues.GetType().FullName -notin $types) + { + New-InvalidArgumentException ` + -Message ($script:localizedData.InvalidDesiredValuesError -f $DesiredValues.GetType().FullName) ` + -ArgumentName 'DesiredValues' + } + + if ($DesiredValues -is [Microsoft.Management.Infrastructure.CimInstance] -and -not $ValuesToCheck) + { + New-InvalidArgumentException ` + -Message $script:localizedData.InvalidValuesToCheckError ` + -ArgumentName 'ValuesToCheck' + } + + $desiredValuesClean = Remove-CommonParameter -Hashtable $DesiredValues + + if (-not $ValuesToCheck) + { + $keyList = $desiredValuesClean.Keys + } + else + { + $keyList = $ValuesToCheck + } + + foreach ($key in $keyList) + { + if ($null -ne $desiredValuesClean.$key) + { + $desiredType = $desiredValuesClean.$key.GetType() + } + else + { + $desiredType = [psobject] @{ + Name = 'Unknown' + } + } + + if ($null -ne $CurrentValues.$key) + { + $currentType = $CurrentValues.$key.GetType() + } + else + { + $currentType = [psobject] @{ + Name = 'Unknown' + } + } + + if ($currentType.Name -ne 'Unknown' -and $desiredType.Name -eq 'PSCredential') + { + # This is a credential object. Compare only the user name + if ($currentType.Name -eq 'PSCredential' -and $CurrentValues.$key.UserName -eq $desiredValuesClean.$key.UserName) + { + Write-Verbose -Message ($script:localizedData.MatchPsCredentialUsernameMessage -f $CurrentValues.$key.UserName, $desiredValuesClean.$key.UserName) + continue + } + else + { + Write-Verbose -Message ($script:localizedData.NoMatchPsCredentialUsernameMessage -f $CurrentValues.$key.UserName, $desiredValuesClean.$key.UserName) + $returnValue = $false + } + + # Assume the string is our username when the matching desired value is actually a credential + if ($currentType.Name -eq 'string' -and $CurrentValues.$key -eq $desiredValuesClean.$key.UserName) + { + Write-Verbose -Message ($script:localizedData.MatchPsCredentialUsernameMessage -f $CurrentValues.$key, $desiredValuesClean.$key.UserName) + continue + } + else + { + Write-Verbose -Message ($script:localizedData.NoMatchPsCredentialUsernameMessage -f $CurrentValues.$key, $desiredValuesClean.$key.UserName) + $returnValue = $false + } + } + + if (-not $TurnOffTypeChecking) + { + if (($desiredType.Name -ne 'Unknown' -and $currentType.Name -ne 'Unknown') -and + $desiredType.FullName -ne $currentType.FullName) + { + Write-Verbose -Message ($script:localizedData.NoMatchTypeMismatchMessage -f $key, $currentType.Name, $desiredType.Name) + continue + } + } + + if ($CurrentValues.$key -eq $desiredValuesClean.$key -and -not $desiredType.IsArray) + { + Write-Verbose -Message ($script:localizedData.MatchValueMessage -f $desiredType.Name, $key, $CurrentValues.$key, $desiredValuesClean.$key) + continue + } + + if ($desiredValuesClean.GetType().Name -in 'HashTable', 'PSBoundParametersDictionary') + { + $checkDesiredValue = $desiredValuesClean.ContainsKey($key) + } + else + { + $checkDesiredValue = Test-DscObjectHasProperty -Object $desiredValuesClean -PropertyName $key + } + + if (-not $checkDesiredValue) + { + Write-Verbose -Message ($script:localizedData.MatchValueMessage -f $desiredType.Name, $key, $CurrentValues.$key, $desiredValuesClean.$key) + continue + } + + if ($desiredType.IsArray) + { + Write-Verbose -Message ($script:localizedData.TestDscParameterCompareMessage -f $key) + + if (-not $CurrentValues.ContainsKey($key) -or -not $CurrentValues.$key) + { + Write-Verbose -Message ($script:localizedData.NoMatchValueMessage -f $desiredType.Name, $key, $CurrentValues.$key, $desiredValuesClean.$key) + $returnValue = $false + continue + } + elseif ($CurrentValues.$key.Count -ne $DesiredValues.$key.Count) + { + Write-Verbose -Message ($script:localizedData.NoMatchValueDifferentCountMessage -f $desiredType.Name, $key, $CurrentValues.$key.Count, $desiredValuesClean.$key.Count) + $returnValue = $false + continue + } + else + { + $desiredArrayValues = $DesiredValues.$key + $currentArrayValues = $CurrentValues.$key + + for ($i = 0; $i -lt $desiredArrayValues.Count; $i++) + { + if ($null -ne $desiredArrayValues[$i]) + { + $desiredType = $desiredArrayValues[$i].GetType() + } + else + { + $desiredType = [psobject]@{ + Name = 'Unknown' + } + } + + if ($null -ne $currentArrayValues[$i]) + { + $currentType = $currentArrayValues[$i].GetType() + } + else + { + $currentType = [psobject]@{ + Name = 'Unknown' + } + } + + if (-not $TurnOffTypeChecking) + { + if (($desiredType.Name -ne 'Unknown' -and $currentType.Name -ne 'Unknown') -and + $desiredType.FullName -ne $currentType.FullName) + { + Write-Verbose -Message ($script:localizedData.NoMatchElementTypeMismatchMessage -f $key, $i, $currentType.Name, $desiredType.Name) + $returnValue = $false + continue + } + } + + if ($desiredArrayValues[$i] -ne $currentArrayValues[$i]) + { + Write-Verbose -Message ($script:localizedData.NoMatchElementValueMismatchMessage -f $i, $desiredType.Name, $key, $currentArrayValues[$i], $desiredArrayValues[$i]) + $returnValue = $false + continue + } + else + { + Write-Verbose -Message ($script:localizedData.MatchElementValueMessage -f $i, $desiredType.Name, $key, $currentArrayValues[$i], $desiredArrayValues[$i]) + continue + } + } + + } + } + else + { + if ($desiredValuesClean.$key -ne $CurrentValues.$key) + { + Write-Verbose -Message ($script:localizedData.NoMatchValueMessage -f $desiredType.Name, $key, $CurrentValues.$key, $desiredValuesClean.$key) + $returnValue = $false + } + } + } + + Write-Verbose -Message ($script:localizedData.TestDscParameterResultMessage -f $returnValue) + return $returnValue +} + +<# + .SYNOPSIS + Tests of an object has a property + + .PARAMETER Object + The object to test + + .PARAMETER PropertyName + The property name +#> +function Test-DscObjectHasProperty +{ + [CmdletBinding()] + [OutputType([System.Boolean])] + param + ( + [Parameter(Mandatory = $true)] + [System.Object] + $Object, + + [Parameter(Mandatory = $true)] + [System.String] + $PropertyName + ) + + if ($Object.PSObject.Properties.Name -contains $PropertyName) + { + return [System.Boolean] $Object.$PropertyName + } + + return $false +} + Export-ModuleMember -Function ` Convert-CIDRToSubhetMask, ` - Find-NetworkAdapter, - Get-DnsClientServerStaticAddress, - Get-IPAddressPrefix + Find-NetworkAdapter, ` + Get-DnsClientServerStaticAddress, ` + Get-IPAddressPrefix, ` + Test-DscParameterState, ` + Test-DscObjectHasProperty diff --git a/Modules/xNetworking/Modules/NetworkingDsc.Common/en-us/NetworkingDsc.Common.strings.psd1 b/Modules/xNetworking/Modules/NetworkingDsc.Common/en-us/NetworkingDsc.Common.strings.psd1 index d9d14cd7..21a82ef4 100644 --- a/Modules/xNetworking/Modules/NetworkingDsc.Common/en-us/NetworkingDsc.Common.strings.psd1 +++ b/Modules/xNetworking/Modules/NetworkingDsc.Common/en-us/NetworkingDsc.Common.strings.psd1 @@ -1,12 +1,25 @@ 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. + 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}'. - DNSServerStaticAddressNotSetMessage = Statically assigned DNS server {0} address for interface alias '{1}' is not set. - DNSServerStaticAddressFoundMessage = Statically assigned DNS server {0} address for interface alias '{1}' is '{2}'. + DNSServerStaticAddressNotSetMessage = Statically assigned DNS server {0} address for interface alias '{1}' is not set. + DNSServerStaticAddressFoundMessage = Statically assigned DNS server {0} address for interface alias '{1}' is '{2}'. + InvalidDesiredValuesError = Property 'DesiredValues' in Test-DscParameterState must be either a Hashtable or CimInstance. Type detected was '{0}'. + InvalidValuesToCheckError = If 'DesiredValues' is a CimInstance then property 'ValuesToCheck' must contain a value. + TestDscParameterCompareMessage = Comparing values in property '{0}'. + MatchPsCredentialUsernameMessage = MATCH: PSCredential username match. Current state is '{0}' and desired state is '{1}'. + NoMatchPsCredentialUsernameMessage = NOTMATCH: PSCredential username mismatch. Current state is '{0}' and desired state is '{1}'. + NoMatchTypeMismatchMessage = NOTMATCH: Type mismatch for property '{0}' Current state type is '{1}' and desired type is '{2}'. + MatchValueMessage = MATCH: Value (type '{0}') for property '{1}' does match. Current state is '{2}' and desired state is '{3}'. + NoMatchValueMessage = NOTMATCH: Value (type '{0}') for property '{1}' does not match. Current state is '{2}' and desired state is '{3}'. + NoMatchValueDifferentCountMessage = NOTMATCH: Value (type '{0}') for property '{1}' does have a different count. Current state count is '{2}' and desired state count is '{3}'. + NoMatchElementTypeMismatchMessage = NOTMATCH: Type mismatch for property '{0}' Current state type of element [{1}] is '{2}' and desired type is '{3}'. + NoMatchElementValueMismatchMessage = NOTMATCH: Value [{0}] (type '{1}') for property '{2}' does match. Current state is '{3}' and desired state is '{4}'. + MatchElementValueMessage = MATCH: Value [{0}] (type '{1}') for property '{2}' does match. Current state is '{3}' and desired state is '{4}'. + TestDscParameterResultMessage = Test-DscParameter result is '{0}'. '@ diff --git a/Modules/xNetworking/xNetworking.psd1 b/Modules/xNetworking/xNetworking.psd1 index 99f40eab..ea2e3a46 100644 --- a/Modules/xNetworking/xNetworking.psd1 +++ b/Modules/xNetworking/xNetworking.psd1 @@ -1,6 +1,6 @@ @{ # Version number of this module. -ModuleVersion = '5.4.0.0' +ModuleVersion = '5.5.0.0' # ID used to uniquely identify this module GUID = 'e6647cc3-ce9c-4c86-9eb8-2ee8919bf358' @@ -50,19 +50,34 @@ PrivateData = @{ # IconUri = '' # ReleaseNotes of this module - ReleaseNotes = '- MSFT_xIPAddressOption: - - Added a new resource to set the SkipAsSource option for an IP address. -- MSFT_xWeakHostSend: - - Created the new Weak Host Send resource. -- MSFT_xWeakHostReceive: - - Created the new Weak Host Receive resource. -- MSFT_xRoute: + ReleaseNotes = '- MSFT_xNetAdapterAdvancedProperty: + - Created new resource configuring AdvancedProperties for NetAdapter +- MSFT_xNetAdapterLso: - Corrected style and formatting to meet HQRM guidelines. + - Updated tests to meet Pester v4 guidelines. +- MSFT_xNetAdapterName: + - Corrected style and formatting to meet HQRM guidelines. + - Updated tests to meet Pester v4 guidelines. +- MSFT_xNetAdapterRDMA: + - Corrected style and formatting to meet HQRM guidelines. + - Updated tests to meet Pester v4 guidelines. + - Converted exceptions to use ResourceHelper functions. + - Improved integration tests to preserve system status and run in more + scenarios. +- MSFT_xNetBIOS: + - Corrected style and formatting to meet HQRM guidelines. + - Updated tests to meet Pester v4 guidelines. + - Converted exceptions to use ResourceHelper functions. + - Improved integration tests to preserve system status, run in more + scenarios and more effectively test the resource. + - Changed to report back error if unable to set NetBIOS setting. +- MSFT_xWinsSetting: + - Created new resource for enabling/disabling LMHOSTS lookup and + enabling/disabling WINS name resoluton using DNS. +- MSFT_xNetworkTeam: + - Corrected style and formatting to meet HQRM guidelines. + - Updated tests to meet Pester v4 guidelines. - Converted exceptions to use ResourceHelper functions. - - Changed unit tests so that they can be run in any order. - - Included default values in MOF file so that they are displayed - in Wiki documentation. - - Converted tests to meet Pester V4 standards. ' @@ -82,3 +97,4 @@ PrivateData = @{ + diff --git a/README.md b/README.md index 1091b815..27aa32ef 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ The **xNetworking** module contains the following resources: - **xWeakHostSend**: Enable or disable the Weak Host Send setting on a network adapter. - **xWeakHostReceive**: Enable or disable the Weak Host Receive setting on a network adapter. +- **xWinsSetting**: Configure the WINS settings that enable or disable LMHOSTS lookups + and enable or disable DNS for name resolution over WINS. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) diff --git a/Tests/Integration/MSFT_xNetAdapterBinding.Integration.Tests.ps1 b/Tests/Integration/MSFT_xNetAdapterBinding.Integration.Tests.ps1 index ae5df175..d436c094 100644 --- a/Tests/Integration/MSFT_xNetAdapterBinding.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_xNetAdapterBinding.Integration.Tests.ps1 @@ -30,7 +30,6 @@ try . $ConfigFile -Verbose -ErrorAction Stop Describe "$($script:DSCResourceName)_Integration" { - #region DEFAULT TESTS It 'Should compile and apply the MOF without throwing' { { & "$($script:DSCResourceName)_Config" -OutputPath $TestDrive @@ -42,21 +41,20 @@ try -Verbose ` -Force ` -ErrorAction Stop - } | Should Not Throw + } | 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 } - #endregion 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 + $current.InterfaceAlias | Should -Be $TestDisableIPv4.InterfaceAlias + $current.ComponentId | Should -Be $TestDisableIPv4.ComponentId + $current.State | Should -Be $TestDisableIPv4.State } } #endregion diff --git a/Tests/Integration/MSFT_xNetAdapterLso.Integration.Tests.ps1 b/Tests/Integration/MSFT_xNetAdapterLso.Integration.Tests.ps1 index ea70fa14..bab1fbbe 100644 --- a/Tests/Integration/MSFT_xNetAdapterLso.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_xNetAdapterLso.Integration.Tests.ps1 @@ -1,14 +1,14 @@ -$script:DSCModuleName = 'xNetworking' -$script:DSCResourceName = 'MSFT_xNetAdapterLso' +$script:DSCModuleName = 'xNetworking' +$script:DSCResourceName = 'MSFT_xNetAdapterLso' #region HEADER # Integration Test Template Version: 1.1.0 [string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -26,25 +26,31 @@ try . $ConfigFile -Verbose -ErrorAction Stop Describe "$($script:DSCResourceName)_Integration" { - - #region DEFAULT TESTS - It 'Should compile without throwing' { + 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 + + 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 } - #endregion It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object {$_.ConfigurationName -eq "$($script:DSCResourceName)_Config"} - $current.Name | Should Be $TestEnableLsoIPv6.Name - $current.Protocol | Should Be $TestEnableLsoIPv6.Protocol - $current.State | Should Be $TestEnableLsoIPv6.State + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:DSCResourceName)_Config" + } + $current.Name | Should -Be $TestEnableLsoIPv6.Name + $current.Protocol | Should -Be $TestEnableLsoIPv6.Protocol + $current.State | Should -Be $TestEnableLsoIPv6.State } } #endregion diff --git a/Tests/Integration/MSFT_xNetAdapterLso.config.ps1 b/Tests/Integration/MSFT_xNetAdapterLso.config.ps1 index d1fe3cb4..eafa3aeb 100644 --- a/Tests/Integration/MSFT_xNetAdapterLso.config.ps1 +++ b/Tests/Integration/MSFT_xNetAdapterLso.config.ps1 @@ -8,10 +8,11 @@ $TestEnableLsoIPv6 = [PSObject]@{ configuration MSFT_xNetAdapterLso_Config { Import-DscResource -ModuleName xNetworking node localhost { - xNetAdapterLso Integration_Test { - Name = $TestEnableLsoIPv6.Name - Protocol = $TestEnableLsoIPv6.Protocol - State = $TestEnableLsoIPv6.State + xNetAdapterLso Integration_Test + { + Name = $TestEnableLsoIPv6.Name + Protocol = $TestEnableLsoIPv6.Protocol + State = $TestEnableLsoIPv6.State } } } diff --git a/Tests/Integration/MSFT_xNetAdapterName.Integration.Tests.ps1 b/Tests/Integration/MSFT_xNetAdapterName.Integration.Tests.ps1 index 649808d4..122ade8d 100644 --- a/Tests/Integration/MSFT_xNetAdapterName.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_xNetAdapterName.Integration.Tests.ps1 @@ -1,14 +1,14 @@ -$script:DSCModuleName = 'xNetworking' -$script:DSCResourceName = 'MSFT_xNetAdapterName' +$script:DSCModuleName = 'xNetworking' +$script:DSCResourceName = 'MSFT_xNetAdapterName' #region HEADER # Integration Test Template Version: 1.1.0 [string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -60,24 +60,40 @@ try -OutputPath $TestDrive ` -ConfigurationData $configData - Start-DscConfiguration -Path $TestDrive ` - -ComputerName localhost -Wait -Verbose -Force - } | Should Not Throw + 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 } | 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 + { + Get-DscConfiguration -Verbose -ErrorAction Stop + } | Should -Not -Throw } #endregion It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object {$_.ConfigurationName -eq "$($script:DSCResourceName)_Config_All"} - $current.Name | Should Be $newAdapterName + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:DSCResourceName)_Config_All" + } + $current.Name | Should -Be $newAdapterName } AfterAll { @@ -107,9 +123,9 @@ try $configData = @{ AllNodes = @( @{ - NodeName = 'localhost' - NewName = $newAdapterName - Name = $adapter.Name + NodeName = 'localhost' + NewName = $newAdapterName + Name = $adapter.Name } ) } @@ -118,24 +134,40 @@ try -OutputPath $TestDrive ` -ConfigurationData $configData - Start-DscConfiguration -Path $TestDrive ` - -ComputerName localhost -Wait -Verbose -Force - } | Should Not Throw + 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 } | 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 + { + Get-DscConfiguration -Verbose -ErrorAction Stop + } | Should -Not -Throw } #endregion It 'Should have set the resource and all the parameters should match' { - $current = Get-DscConfiguration | Where-Object {$_.ConfigurationName -eq "$($script:DSCResourceName)_Config_NameOnly"} - $current.Name | Should Be $newAdapterName + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:DSCResourceName)_Config_NameOnly" + } + $current.Name | Should -Be $newAdapterName } AfterAll { diff --git a/Tests/Integration/MSFT_xNetAdapterRDMA.Integration.Tests.ps1 b/Tests/Integration/MSFT_xNetAdapterRDMA.Integration.Tests.ps1 index f5b179cd..3d764bf1 100644 --- a/Tests/Integration/MSFT_xNetAdapterRDMA.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_xNetAdapterRDMA.Integration.Tests.ps1 @@ -1,16 +1,38 @@ -#Remove this following line before using this integration test script -return +<# + To execute integration tests an RDMA compatible adapter is required in the host + The Microsoft Loopback Adapter is not RDMA compatible so can not be used for + test automation. -$script:DSCModuleName = 'xNetworking' -$script:DSCResourceName = 'MSFT_xNetAdapterRDMA' + To run the this test on a machine with a compatible RDMA adapter, set the value of + the `$script:AdapterName` variable to the name of the adapter to test. The RDMA status + of the adapter should be restored after test completion. + + Important: this test will disrupt network connectivity to the adapter selected for + 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 = 'xNetworking' +$script:DSCResourceName = 'MSFT_xNetAdapterRDMA' +$script:AdapterName = 'vEthernet (Default Switch)' + +# Check the adapter selected for use in testing is RDMA compatible and preserve state +$adapterRDMAStatus = Get-NetAdapterRdma -Name $script:AdapterName -ErrorAction SilentlyContinue +if (-not $adapterRDMAStatus) +{ + Write-Verbose -Message ('The network adapter selected for RDMA integration testing is not RDMA compatible. Integration tests will be skipped.') + return +} + +# Make sure RDMA is disabled on the selected adapter before running tests +Set-NetAdapterRdma -Name $script:AdapterName -Enabled $false #region HEADER [string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -18,7 +40,7 @@ Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\ $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:DSCModuleName ` -DSCResourceName $script:DSCResourceName ` - -TestType Integration + -TestType Integration #endregion # Using try/finally to always cleanup even if something awful happens. @@ -28,36 +50,56 @@ try $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 + } + ) + } + Describe "$($script:DSCResourceName)_Integration" { - #region DEFAULT TESTS - It 'Should compile without throwing' { + 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 + & "$($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' { + It 'Should be able to call Get-DscConfiguration without throwing' { { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw } - #endregion It 'Should have set the resource and all the parameters should match' { - $result = Get-DscConfiguration | Where-Object {$_.ConfigurationName -eq "$($script:DSCResourceName)_Config"} - $result.Name | Should Be $TestAdapter.Name - $result.Enabled | Should Be $TestAdapter.Enabled + $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 } Set-NetAdapterRDMA ` - -Name $TestAdapter.Name ` + -Name $configData.AllNodes[0].Name ` -Enabled $false } - #endregion } finally { #region FOOTER Restore-TestEnvironment -TestEnvironment $TestEnvironment + + Set-NetAdapterRdma -Name $script:AdapterName -Enabled $adapterRDMAStatus.Enabled #endregion } diff --git a/Tests/Integration/MSFT_xNetAdapterRDMA.config.ps1 b/Tests/Integration/MSFT_xNetAdapterRDMA.config.ps1 index 36f8ada6..52bb8b5c 100644 --- a/Tests/Integration/MSFT_xNetAdapterRDMA.config.ps1 +++ b/Tests/Integration/MSFT_xNetAdapterRDMA.config.ps1 @@ -1,24 +1,10 @@ -$TestAdapter = [PSObject]@{ - Name = 'SMB1_1' - Enabled = $true -} - -#This configuration enables RDMA setting on the network adapter. -configuration MSFT_xNetAdapterRDMA_Config -{ - param - ( - [string[]]$NodeName = 'localhost' - ) - - Import-DSCResource -ModuleName xNetworking -Name xNetAdapterRDMA +configuration MSFT_xNetAdapterRDMA_Config { + Import-DSCResource -ModuleName xNetworking - Node $NodeName - { - xNetAdapterRDMA SMB1 - { - Name = $TestAdapter.Name - Enabled = $TestAdapter.Enabled + node localhost { + xNetAdapterRDMA ConfigureRDMA { + Name = $Node.Name + Enabled = $Node.Enabled } } } diff --git a/Tests/Integration/MSFT_xNetBIOS.Integration.Tests.ps1 b/Tests/Integration/MSFT_xNetBIOS.Integration.Tests.ps1 index 3ed734a0..781dc656 100644 --- a/Tests/Integration/MSFT_xNetBIOS.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_xNetBIOS.Integration.Tests.ps1 @@ -1,14 +1,41 @@ -$script:DSCModuleName = 'xNetworking' -$script:DSCResourceName = 'MSFT_xNetBIOS' +$script:DSCModuleName = 'xNetworking' +$script:DSCResourceName = 'MSFT_xNetBIOS' + +# 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 +} + +foreach ($netAdapter in $netAdapterEnabled) +{ + $netAdapterConfig = $netAdapter | + Get-CimAssociatedInstance -ResultClassName Win32_NetworkAdapterConfiguration | + Where-Object -FilterScript { $_.IPEnabled -eq $True } + if ($netAdapterConfig) + { + break + } +} +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 +} +Write-Verbose -Message ('A network adapter ({0}) was found in this system that meets requirements for integration testing.' -f $netAdapter.Name) -Verbose #region HEADER # Integration Test Template Version: 1.1.0 [string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -21,34 +48,159 @@ $TestEnvironment = Initialize-TestEnvironment ` # Using try/finally to always cleanup even if something awful happens. try { - #region Integration Tests $ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" . $ConfigFile -Verbose -ErrorAction Stop + $tcpipNetbiosOptions = $netAdapterConfig.TcpipNetbiosOptions + + # Store the current Net Bios setting + if ($null -eq $tcpipNetbiosOptions) + { + $currentNetBiosSetting = [NetBiosSetting]::Default + } + else + { + $currentNetBiosSetting = [NetBiosSetting].GetEnumValues()[$tcpipNetbiosOptions] + } + + # Ensure the Net Bios setting is in a known state (enabled) + $null = $netAdapterConfig | Invoke-CimMethod ` + -MethodName SetTcpipNetbios ` + -ErrorAction Stop ` + -Arguments @{ + TcpipNetbiosOptions = [uint32][NetBiosSetting]::Enable + } + Describe "$($script:DSCResourceName)_Integration" { - #region DEFAULT TESTS - It 'Should compile without throwing' { - { - & "$($script:DSCResourceName)_Config" -OutputPath $TestDrive - Start-DscConfiguration -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force - } | Should not throw + Context 'Disable NetBIOS over TCP/IP' { + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = $netAdapter.Name + 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 + } + + 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 'Disable' + } } - It 'should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw + Context 'Enable NetBIOS over TCP/IP' { + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = $netAdapter.Name + 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 + } + + 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 'Enable' + } } - #endregion - It 'Should have set the resource and all setting should match current state' { - $Live = Get-DscConfiguration | Where-Object {$_.ConfigurationName -eq "$($script:DSCResourceName)_Config"} - $Live.Setting | should be $Current #Current is defined in MSFT_NetBIOS.config.ps1 + Context 'Default NetBIOS over TCP/IP' { + $configData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + InterfaceAlias = $netAdapter.Name + Setting = 'Default' + } + ) + } + + 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 setting should match current state' { + $result = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq "$($script:DSCResourceName)_Config" + } + $result.Setting | Should -Be 'Default' + } } } - #endregion } finally { #region FOOTER + # Restore the Net Bios setting + $null = $netAdapterConfig | Invoke-CimMethod ` + -MethodName SetTcpipNetbios ` + -ErrorAction Stop ` + -Arguments @{ + TcpipNetbiosOptions = $currentNetBiosSetting + } + Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion } diff --git a/Tests/Integration/MSFT_xNetBIOS.config.ps1 b/Tests/Integration/MSFT_xNetBIOS.config.ps1 index 3cb35143..8a858aa7 100644 --- a/Tests/Integration/MSFT_xNetBIOS.config.ps1 +++ b/Tests/Integration/MSFT_xNetBIOS.config.ps1 @@ -1,36 +1,10 @@ -try -{ - [void][reflection.assembly]::GetAssembly([NetBIOSSetting]) -} -catch -{ - Add-Type -TypeDefinition @' - public enum NetBiosSetting - { - Default, - Enable, - Disable - } -'@ -} - -$adapter = ( - Get-CimInstance -ClassName Win32_NetworkAdapter ` - -Filter 'NetEnabled="True"' -)[0] - -$Current = [NETBIOSSetting].GetEnumValues()[( - $adapter | - Get-CimAssociatedInstance ` - -ResultClassName Win32_NetworkAdapterConfiguration -).TcpipNetbiosOptions] - configuration MSFT_xNetBIOS_Config { Import-DscResource -ModuleName xNetworking + node localhost { xNetBIOS Integration_Test { - InterfaceAlias = $adapter.NetConnectionID - Setting = $Current + InterfaceAlias = $Node.InterfaceAlias + Setting = $Node.Setting } } } diff --git a/Tests/Integration/MSFT_xNetworkTeam.Integration.Tests.ps1 b/Tests/Integration/MSFT_xNetworkTeam.Integration.Tests.ps1 index 5072bc8b..1a47a688 100644 --- a/Tests/Integration/MSFT_xNetworkTeam.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_xNetworkTeam.Integration.Tests.ps1 @@ -1,17 +1,27 @@ -#Remove this following line before using this integration test script +<# + These tests can not be run in AppVeyor as this will cause the network + adapter to disconnect and terminate the build. + + They can be run by commenting out the return below. All the physical + adapters in the machine will be used to create the team. The team will + be removed when tests are complete. + + Loopback adapters can not be used for NIC teaming and only server OS + SKU machines will support it. +#> return -$script:DSCModuleName = 'xNetworking' -$script:DSCResourceName = 'MSFT_xNetworkTeam' +$script:DSCModuleName = 'xNetworking' +$script:DSCResourceName = 'MSFT_xNetworkTeam' #region HEADER # Integration Test Template Version: 1.1.0 [string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -24,44 +34,128 @@ $TestEnvironment = Initialize-TestEnvironment ` # Using try/finally to always cleanup even if something awful happens. try { - #region Integration Tests - $teamMembers = (Get-NetAdapter -Physical).Name - $ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" . $ConfigFile -Verbose -ErrorAction Stop Describe "$($script:DSCResourceName)_Integration" { - #region DEFAULT TESTS - It 'Should compile without throwing' { - { - & "$($script:DSCResourceName)_Config" -OutputPath $TestDrive - Start-DscConfiguration -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force - } | Should not throw - } + $teamMembers = (Get-NetAdapter -Physical).Name - It 'should be able to call Get-DscConfiguration without throwing' { - Start-Sleep -Seconds 30 - { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw + $configurationData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + Name = 'TestTeam' + Members = $teamMembers + LoadBalancingAlgorithm = 'MacAddresses' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' + } + ) } - #endregion - - It 'Should have set the resource and all the parameters should match' { - $result = Get-DscConfiguration | Where-Object {$_.ConfigurationName -eq "$($script:DSCResourceName)_Config"} - $result.Ensure | Should Be $TestTeam.Ensure - $result.Name | Should Be $TestTeam.Name - $result.TeamMembers | Should Be $teamMembers - $result.loadBalancingAlgorithm | Should Be $TestTeam.loadBalancingAlgorithm - $result.teamingMode | Should Be $TestTeam.teamingMode + + Context 'When the network team is 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 + + # 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) + { + break + } + + $count++ + } + } | 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 + $result.LoadBalancingAlgorithm | Should -Be $configurationData.AllNodes[0].LoadBalancingAlgorithm + $result.TeamingMode | Should -Be $configurationData.AllNodes[0].TeamingMode + } } - Remove-NetLbfoTeam ` - -Name $TestTeam.Name ` - -Confirm:$false + $configurationData.AllNodes[0].Ensure = 'Absent' + + Context 'When the network team is deleted' { + 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 removed + $count = 0 + While (Get-NetLbfoTeam -Name 'TestTeam' -ErrorAction SilentlyContinue) + { + Start-Sleep -Seconds 1 + + if ($count -ge 60) + { + break + } + + $count++ + } + } | 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 + } + } } - #endregion } finally { + # Remove the team just in case it wasn't removed correctly + Remove-NetLbfoTeam ` + -Name 'TestTeam' ` + -Confirm:$false ` + -ErrorAction SilentlyContinue + #region FOOTER Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion diff --git a/Tests/Integration/MSFT_xNetworkTeam.config.ps1 b/Tests/Integration/MSFT_xNetworkTeam.config.ps1 index 90e06108..3e7b188c 100644 --- a/Tests/Integration/MSFT_xNetworkTeam.config.ps1 +++ b/Tests/Integration/MSFT_xNetworkTeam.config.ps1 @@ -1,29 +1,17 @@ -$TestTeam = [PSObject]@{ - Name = 'TestTeam' - Members = (Get-NetAdapter -Physical).Name - loadBalancingAlgorithm = 'Dynamic' - teamingMode = 'SwitchIndependent' - Ensure = 'Present' -} configuration MSFT_xNetworkTeam_Config { - param - ( - [string[]]$NodeName = 'localhost' - ) - Import-DSCResource -ModuleName xNetworking - Node $NodeName + node localhost { xNetworkTeam HostTeam { - Name = $TestTeam.Name - TeamingMode = $TestTeam.teamingMode - LoadBalancingAlgorithm = $TestTeam.loadBalancingAlgorithm - TeamMembers = $TestTeam.Members - Ensure = $TestTeam.Ensure + Name = $Node.Name + TeamingMode = $Node.teamingMode + LoadBalancingAlgorithm = $Node.loadBalancingAlgorithm + TeamMembers = $Node.Members + Ensure = $Node.Ensure } } } diff --git a/Tests/Integration/MSFT_xWinsSetting.Integration.Tests.ps1 b/Tests/Integration/MSFT_xWinsSetting.Integration.Tests.ps1 new file mode 100644 index 00000000..ee76a21b --- /dev/null +++ b/Tests/Integration/MSFT_xWinsSetting.Integration.Tests.ps1 @@ -0,0 +1,182 @@ +$script:DSCModuleName = 'xNetworking' +$script:DSCResourceName = 'MSFT_xWinsSetting' + +# 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 +} + +foreach ($netAdapter in $netAdapterEnabled) +{ + $netAdapterConfig = $netAdapter | + Get-CimAssociatedInstance -ResultClassName Win32_NetworkAdapterConfiguration | + Where-Object -FilterScript { $_.IPEnabled -eq $True } + if ($netAdapterConfig) + { + break + } +} +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 +} +Write-Verbose -Message ('A network adapter ({0}) was found in this system that meets requirements for integration testing.' -f $netAdapter.Name) -Verbose + +#region HEADER +# Integration Test Template Version: 1.1.0 +[string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' + +if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) +{ + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) +} + +Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force +$TestEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:DSCModuleName ` + -DSCResourceName $script:DSCResourceName ` + -TestType Integration +#endregion + +# Using try/finally to always cleanup even if something awful happens. +try +{ + $ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" + . $ConfigFile + + # Store the current WINS settings + $enableDnsRegistryKey = Get-ItemProperty ` + -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' ` + -Name EnableDNS ` + -ErrorAction SilentlyContinue + + if ($enableDnsRegistryKey) + { + $currentEnableDNS = ($enableDnsRegistryKey.EnableDNS -eq 1) + } + else + { + # if the key does not exist, then set the default which is enabled. + $currentEnableDNS = $true + } + + $enableLMHostsRegistryKey = Get-ItemProperty ` + -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' ` + -Name EnableLMHOSTS ` + -ErrorAction SilentlyContinue + + $currentEnableLmHosts = ($enableLMHOSTSRegistryKey.EnableLMHOSTS -eq 1) + + # Set the WINS settings to known values + $null = Invoke-CimMethod ` + -ClassName Win32_NetworkAdapterConfiguration ` + -MethodName EnableWins ` + -Arguments @{ + DNSEnabledForWINSResolution = $true + WINSEnableLMHostsLookup = $true + } + + Describe "$($script:DSCResourceName)_Integration" { + Context 'Disable all settings' { + $configurationData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + EnableLmHosts = $false + EnableDns = $false + } + ) + } + + 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 + } + } + + Context 'Enable all settings' { + $configurationData = @{ + AllNodes = @( + @{ + NodeName = 'localhost' + EnableLmHosts = $true + EnableDns = $true + } + ) + } + + 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 $true + $result.EnableDns | Should -Be $true + } + } + } +} +finally +{ + # Restore the WINS settings + $null = Invoke-CimMethod ` + -ClassName Win32_NetworkAdapterConfiguration ` + -MethodName EnableWins ` + -Arguments @{ + DNSEnabledForWINSResolution = $currentEnableDns + WINSEnableLMHostsLookup = $currentEnableLmHosts + } + + #region FOOTER + Restore-TestEnvironment -TestEnvironment $TestEnvironment + #endregion +} diff --git a/Tests/Integration/MSFT_xWinsSetting.config.ps1 b/Tests/Integration/MSFT_xWinsSetting.config.ps1 new file mode 100644 index 00000000..37f67b89 --- /dev/null +++ b/Tests/Integration/MSFT_xWinsSetting.config.ps1 @@ -0,0 +1,12 @@ +Configuration MSFT_xWinsSetting_Config { + Import-DscResource -ModuleName xNetworking + + node localhost { + xWinsSetting Integration_Test + { + IsSingleInstance = 'Yes' + EnableLmHosts = $Node.EnableLmHosts + EnableDns = $Node.EnableDns + } + } +} diff --git a/Tests/Unit/MSFT_xDefaultGatewayAddress.Tests.ps1 b/Tests/Unit/MSFT_xDefaultGatewayAddress.Tests.ps1 index 17da6337..4c0be6aa 100644 --- a/Tests/Unit/MSFT_xDefaultGatewayAddress.Tests.ps1 +++ b/Tests/Unit/MSFT_xDefaultGatewayAddress.Tests.ps1 @@ -153,7 +153,7 @@ try AddressFamily = 'IPv4' } - Test-TargetResource @testTargetResourceParameters | Should Be $True + Test-TargetResource @testTargetResourceParameters | Should Be $true } } @@ -207,7 +207,7 @@ try AddressFamily = 'IPv4' } - Test-TargetResource @testTargetResourceParameters | Should Be $True + Test-TargetResource @testTargetResourceParameters | Should Be $true } } } diff --git a/Tests/Unit/MSFT_xDhcpClient.Tests.ps1 b/Tests/Unit/MSFT_xDhcpClient.Tests.ps1 index 9c4671f3..f127bfa0 100644 --- a/Tests/Unit/MSFT_xDhcpClient.Tests.ps1 +++ b/Tests/Unit/MSFT_xDhcpClient.Tests.ps1 @@ -182,7 +182,7 @@ try Mock -CommandName Get-NetIPInterface -MockWith { $mockNetIPInterfaceDisabled } It 'Should return true' { - Test-TargetResource @testNetIPInterfaceDisabled | Should Be $True + Test-TargetResource @testNetIPInterfaceDisabled | Should Be $true } It 'Should call expected mocks' { @@ -195,7 +195,7 @@ try Mock -CommandName Get-NetIPInterface -MockWith { $mockNetIPInterfaceEnabled } It 'Should return true' { - Test-TargetResource @testNetIPInterfaceEnabled | Should Be $True + Test-TargetResource @testNetIPInterfaceEnabled | Should Be $true } It 'Should call expected mocks' { diff --git a/Tests/Unit/MSFT_xDnsClientGlobalSetting.Tests.ps1 b/Tests/Unit/MSFT_xDnsClientGlobalSetting.Tests.ps1 index c3550880..1a8bfd99 100644 --- a/Tests/Unit/MSFT_xDnsClientGlobalSetting.Tests.ps1 +++ b/Tests/Unit/MSFT_xDnsClientGlobalSetting.Tests.ps1 @@ -27,13 +27,13 @@ try $dnsClientGlobalSettings = [PSObject]@{ SuffixSearchList = 'contoso.com' DevolutionLevel = 1 - UseDevolution = $True + UseDevolution = $true } $dnsClientGlobalMultiSuffixSettings = [PSObject]@{ SuffixSearchList = @('fabrikam.com', 'fourthcoffee.com') DevolutionLevel = 1 - UseDevolution = $True + UseDevolution = $true } $dnsClientGlobalSettingsSplat = [PSObject]@{ @@ -167,7 +167,7 @@ try Context 'DNS Client Global Settings all parameters are the same' { It 'Should return true' { $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() - Test-TargetResource @testTargetResourceParameters | Should Be $True + Test-TargetResource @testTargetResourceParameters | Should Be $true } It 'Should call expected Mocks' { @@ -233,7 +233,7 @@ try It 'Should return true' { $testTargetResourceParameters = $dnsClientGlobalSettingsSplat.Clone() $testTargetResourceParameters.SuffixSearchList = @('fabrikam.com', 'fourthcoffee.com') - Test-TargetResource @testTargetResourceParameters | Should Be $True + Test-TargetResource @testTargetResourceParameters | Should Be $true } It 'Should call expected Mocks' { diff --git a/Tests/Unit/MSFT_xFirewall.Tests.ps1 b/Tests/Unit/MSFT_xFirewall.Tests.ps1 index 83fa1b2a..e9400283 100644 --- a/Tests/Unit/MSFT_xFirewall.Tests.ps1 +++ b/Tests/Unit/MSFT_xFirewall.Tests.ps1 @@ -748,7 +748,7 @@ try It "Should return True on firewall rule $($firewallRule.Name)" { $result = Test-RuleProperties -FirewallRule $firewallRule @compareRule - $result | Should be $True + $result | Should be $true } } diff --git a/Tests/Unit/MSFT_xFirewallProfile.Tests.ps1 b/Tests/Unit/MSFT_xFirewallProfile.Tests.ps1 index b875339c..5fc3f99c 100644 --- a/Tests/Unit/MSFT_xFirewallProfile.Tests.ps1 +++ b/Tests/Unit/MSFT_xFirewallProfile.Tests.ps1 @@ -237,7 +237,7 @@ try Context 'Firewall Profile all parameters are the same' { It 'Should return true' { $testTargetResourceParameters = $firewallProfileSplat.Clone() - Test-TargetResource @testTargetResourceParameters | Should Be $True + Test-TargetResource @testTargetResourceParameters | Should Be $true } It 'Should call expected Mocks' { diff --git a/Tests/Unit/MSFT_xNetAdapterAdvancedProperty.Tests.ps1 b/Tests/Unit/MSFT_xNetAdapterAdvancedProperty.Tests.ps1 new file mode 100644 index 00000000..e43b6451 --- /dev/null +++ b/Tests/Unit/MSFT_xNetAdapterAdvancedProperty.Tests.ps1 @@ -0,0 +1,236 @@ +$script:DSCModuleName = 'xNetworking' +$script:DSCResourceName = 'MSFT_xNetAdapterAdvancedProperty' + +#region HEADER +# Unit Test Template Version: 1.1.0 +[string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' +if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) +{ + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) +} + +Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force +$TestEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:DSCModuleName ` + -DSCResourceName $script:DSCResourceName ` + -TestType Unit +#endregion HEADER + +# Begin Testing +try +{ + #region Pester Tests + InModuleScope $script:DSCResourceName { + + $TestJumboPacket9014 = @{ + NetworkAdapterName = 'Ethernet' + RegistryKeyword = "*JumboPacket" + RegistryValue = 9014 + } + + $TestJumboPacket1514 = @{ + NetworkAdapterName = 'Ethernet' + RegistryKeyword = '*JumboPacket' + RegistryValue = 1514 + } + + $TestAdapterNotFound = @{ + NetworkAdapterName = 'Ethe' + RegistryKeyword = "*JumboPacket" + RegistryValue = 1514 + } + + function Get-NetAdapterAdvancedProperty { } + + Describe "$($script:DSCResourceName)\Get-TargetResource" -Tag 'Get' { + + Context 'Adapter exist and JumboPacket is enabled 9014' { + Mock Get-NetAdapterAdvancedProperty -Verbose -MockWith { + @{ + RegistryValue = $TestJumboPacket9014.RegistryValue + RegistryKeyword = $TestJumboPacket9014.RegistryKeyword + } + } + + It 'Should return the JumboPacket size' { + $result = Get-TargetResource @TestJumboPacket9014 + $result.RegistryValue | Should -Be $TestJumboPacket9014.RegistryValue + } + + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 + } + } + + Context 'Adapter exist and JumboPacket is 1514' { + Mock Get-NetAdapterAdvancedProperty -Verbose -MockWith { + @{ + RegistryValue = $TestJumboPacket1514.RegistryValue + RegistryKeyword = $TestJumboPacket1514.RegistryKeyword + } + } + + It 'Should return the JumboPacket size' { + $result = Get-TargetResource @TestJumboPacket1514 + $result.RegistryValue | Should -Be $TestJumboPacket1514.RegistryValue + } + + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 + } + } + + Context 'Adapter does not exist' { + + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { throw 'Network adapter not found' } + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.NetAdapterNotFoundMessage) + + It 'Should throw an exception' { + { Get-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord + } + + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 + } + } + + Describe "$($script:DSCResourceName)\Set-TargetResource" { + + Context 'Adapter exist, JumboPacket is 9014, no action required' { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { + @{ + RegistryValue = $TestJumboPacket9014.RegistryValue + RegistryKeyword = $TestJumboPacket9014.RegistryKeyword + } + } + Mock -CommandName Set-NetAdapterAdvancedProperty + + It 'Should not throw an exception' { + { Set-TargetResource @TestJumboPacket9014 } | Should -Not -Throw + } + + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 + Assert-MockCalled -CommandName Set-NetAdapterAdvancedProperty -Exactly -Time 0 + } + } + + 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 not throw an exception' { + { Set-TargetResource @TestJumboPacket1514 } | Should -Not -Throw + } + + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 + Assert-MockCalled -CommandName Set-NetAdapterAdvancedProperty -Exactly -Time 1 + } + } + + 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 not throw an exception' { + { Set-TargetResource @TestJumboPacket9014 } | Should -Not -Throw + } + + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 + Assert-MockCalled -CommandName Set-NetAdapterAdvancedProperty -Exactly -Time 1 + } + } + + # Adapter + Context 'Adapter does not exist' { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { throw 'Network adapter not found' } + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.NetAdapterNotFoundMessage) + + It 'Should throw an exception' { + { Set-TargetResource @TestAdapterNotFound } | Should -Throw $errorRecord + } + + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly -Time 1 + } + } + } + } + + Describe "$($script:DSCResourceName)\Test-TargetResource" { + + # JumboPacket + Context 'Adapter exist, JumboPacket is 9014, no action required' { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { + @{ + RegistryValue = $TestJumboPacket9014.RegistryValue + RegistryKeyword = $TestJumboPacket9014.RegistryKeyword + } + } + + It 'Should return true' { + Test-TargetResource @TestJumboPacket9014 | Should -Be $true + } + + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly 1 + } + } + + Context 'Adapter exist, JumboPacket is 9014 should be 1514' { + Mock -CommandName Get-NetAdapterAdvancedProperty -MockWith { + @{ + RegistryValue = $TestJumboPacket9014.RegistryValue + RegistryKeyword = $TestJumboPacket9014.RegistryKeyword + } + } + + It 'Should return false' { + Test-TargetResource @TestJumboPacket1514 | Should -Be $false + } + + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly 1 + } + } + + + # 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 + } + + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterAdvancedProperty -Exactly 1 + } + } + } + } + #endregion +} +finally +{ + #region FOOTER + Restore-TestEnvironment -TestEnvironment $TestEnvironment + #endregion +} diff --git a/Tests/Unit/MSFT_xNetAdapterBinding.Tests.ps1 b/Tests/Unit/MSFT_xNetAdapterBinding.Tests.ps1 index f05be420..c6c57064 100644 --- a/Tests/Unit/MSFT_xNetAdapterBinding.Tests.ps1 +++ b/Tests/Unit/MSFT_xNetAdapterBinding.Tests.ps1 @@ -47,7 +47,7 @@ try $mockBindingEnabled = @{ InterfaceAlias = 'Ethernet' ComponentId = 'ms_tcpip63' - Enabled = $True + Enabled = $true } $mockBindingDisabled = @{ @@ -65,7 +65,7 @@ try @{ InterfaceAlias = 'Ethernet2' ComponentId = 'ms_tcpip63' - Enabled = $True + Enabled = $true } ) @@ -183,7 +183,7 @@ try Mock -CommandName Get-Binding -MockWith { $mockBindingEnabled } It 'Should return true' { - Test-TargetResource @testBindingEnabled | Should Be $True + Test-TargetResource @testBindingEnabled | Should Be $true } It 'Should call all the mocks' { @@ -195,7 +195,7 @@ try Mock -CommandName Get-Binding -MockWith { $mockBindingDisabled } It 'Should return true' { - Test-TargetResource @testBindingDisabled | Should Be $True + Test-TargetResource @testBindingDisabled | Should Be $true } It 'Should call all the mocks' { diff --git a/Tests/Unit/MSFT_xNetAdapterLso.Tests.ps1 b/Tests/Unit/MSFT_xNetAdapterLso.Tests.ps1 index 4a3897e7..10a21d34 100644 --- a/Tests/Unit/MSFT_xNetAdapterLso.Tests.ps1 +++ b/Tests/Unit/MSFT_xNetAdapterLso.Tests.ps1 @@ -1,13 +1,13 @@ -$script:DSCModuleName = 'xNetworking' +$script:DSCModuleName = 'xNetworking' $script:DSCResourceName = 'MSFT_xNetAdapterLso' #region HEADER # Unit Test Template Version: 1.1.0 [string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -22,44 +22,43 @@ try { #region Pester Tests InModuleScope $script:DSCResourceName { - - $TestV1IPv4LsoEnabled = @{ + $testV1IPv4LsoEnabled = @{ Name = 'Ethernet' Protocol = 'V1IPv4' State = $true } - $TestV1IPv4LsoDisabled = @{ + $testV1IPv4LsoDisabled = @{ Name = 'Ethernet' Protocol = 'V1IPv4' State = $false } - $TestIPv4LsoEnabled = @{ + $testIPv4LsoEnabled = @{ Name = 'Ethernet' Protocol = 'IPv4' State = $true } - $TestIPv4LsoDisabled = @{ + $testIPv4LsoDisabled = @{ Name = 'Ethernet' Protocol = 'IPv4' State = $false } - $TestIPv6LsoEnabled = @{ + $testIPv6LsoEnabled = @{ Name = 'Ethernet' Protocol = 'IPv6' State = $true } - $TestIPv6LsoDisabled = @{ + $testIPv6LsoDisabled = @{ Name = 'Ethernet' Protocol = 'IPv6' State = $false } - $TestAdapterNotFound = @{ + $testAdapterNotFound = @{ Name = 'Eth' Protocol = 'IPv4' State = $true @@ -68,302 +67,304 @@ try Describe "$($script:DSCResourceName)\Get-TargetResource" { Context 'Adapter exist and LSO for V1IPv4 is enabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $TestV1IPv4LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ V1IPv4Enabled = $testV1IPv4LsoEnabled.State } } - + It 'Should return the LSO state of V1IPv4' { - $result = Get-TargetResource @TestV1IPv4LsoEnabled - $result.State | Should Be $TestV1IPv4LsoEnabled.State + $result = Get-TargetResource @testV1IPv4LsoEnabled + $result.State | Should -Be $testV1IPv4LsoEnabled.State } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist and LSO for V1IPv4 is disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $TestV1IPv4LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ V1IPv4Enabled = $testV1IPv4LsoDisabled.State } } It 'Should return the LSO state of V1IPv4' { - $result = Get-TargetResource @TestV1IPv4LsoDisabled - $result.State | Should Be $TestV1IPv4LsoDisabled.State + $result = Get-TargetResource @testV1IPv4LsoDisabled + $result.State | Should -Be $testV1IPv4LsoDisabled.State } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist and LSO for IPv4 is enabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $TestIPv4LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv4Enabled = $testIPv4LsoEnabled.State } } It 'Should return the LSO state of IPv4' { - $result = Get-TargetResource @TestIPv4LsoEnabled - $result.State | Should Be $TestIPv4LsoEnabled.State + $result = Get-TargetResource @testIPv4LsoEnabled + $result.State | Should -Be $testIPv4LsoEnabled.State } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist and LSO for IPv4 is disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $TestIPv4LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv4Enabled = $testIPv4LsoDisabled.State } } It 'Should return the LSO state of IPv4' { - $result = Get-TargetResource @TestIPv4LsoDisabled - $result.State | Should Be $TestIPv4LsoDisabled.State + $result = Get-TargetResource @testIPv4LsoDisabled + $result.State | Should -Be $testIPv4LsoDisabled.State } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist and LSO for IPv6 is enabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $TestIPv6LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv6Enabled = $testIPv6LsoEnabled.State } } It 'Should return the LSO state of IPv6' { - $result = Get-TargetResource @TestIPv6LsoEnabled - $result.State | Should Be $TestIPv6LsoEnabled.State + $result = Get-TargetResource @testIPv6LsoEnabled + $result.State | Should -Be $testIPv6LsoEnabled.State } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist and LSO for IPv6 is disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $TestIPv6LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv6Enabled = $testIPv6LsoDisabled.State } } It 'Should return the LSO state of IPv6' { - $result = Get-TargetResource @TestIPv6LsoDisabled - $result.State | Should Be $TestIPv6LsoDisabled.State + $result = Get-TargetResource @testIPv6LsoDisabled + $result.State | Should -Be $testIPv6LsoDisabled.State } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter does not exist' { Mock -CommandName Get-NetAdapterLso -MockWith { throw 'Network adapter not found' } - It 'Should throw an exception' { - { Get-TargetResource @TestAdapterNotFound } | Should throw + It 'Should throw the correct exception' { + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.NetAdapterNotFoundMessage) + + { Get-TargetResource @testAdapterNotFound } | Should -Throw $errorRecord } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } } Describe "$($script:DSCResourceName)\Set-TargetResource" { - # V1IPv4 Context 'Adapter exist, LSO is enabled for V1IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $TestV1IPv4LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ V1IPv4Enabled = $testV1IPv4LsoEnabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestV1IPv4LsoEnabled } | Should Not Throw + { Set-TargetResource @testV1IPv4LsoEnabled } | Should -Not -Throw } - + It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 0 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 } } Context 'Adapter exist, LSO is enabled for V1IPv4, should be disabled' { Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $TestV1IPv4LsoEnabled.State } + @{ V1IPv4Enabled = $testV1IPv4LsoEnabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestV1IPv4LsoDisabled } | Should Not Throw + { Set-TargetResource @testV1IPv4LsoDisabled } | Should -Not -Throw } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is disabled for V1IPv4, no action required' { Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $TestV1IPv4LsoDisabled.State } + @{ V1IPv4Enabled = $testV1IPv4LsoDisabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestV1IPv4LsoDisabled } | Should Not Throw + { Set-TargetResource @testV1IPv4LsoDisabled } | Should -Not -Throw } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 0 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 } } Context 'Adapter exist, LSO is disabled for V1IPv4, should be enabled.' { Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $TestV1IPv4LsoDisabled.State } + @{ V1IPv4Enabled = $testV1IPv4LsoDisabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestV1IPv4LsoEnabled } | Should Not Throw + { Set-TargetResource @testV1IPv4LsoEnabled } | Should -Not -Throw } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 } } # IPv4 Context 'Adapter exist, LSO is enabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $TestIPv4LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv4Enabled = $testIPv4LsoEnabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestIPv4LsoEnabled } | Should Not Throw + { Set-TargetResource @testIPv4LsoEnabled } | Should -Not -Throw } - + It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 0 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 } } Context 'Adapter exist, LSO is enabled for IPv4, should be disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $TestIPv4LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv4Enabled = $testIPv4LsoEnabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestIPv4LsoDisabled } | Should Not Throw + { Set-TargetResource @testIPv4LsoDisabled } | Should -Not -Throw } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is disabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $TestIPv4LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv4Enabled = $testIPv4LsoDisabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestIPv4LsoDisabled } | Should Not Throw + { Set-TargetResource @testIPv4LsoDisabled } | Should -Not -Throw } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 0 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 } } Context 'Adapter exist, LSO is disabled for IPv4, should be enabled.' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $TestIPv4LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv4Enabled = $testIPv4LsoDisabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestIPv4LsoEnabled } | Should Not Throw + { Set-TargetResource @testIPv4LsoEnabled } | Should -Not -Throw } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 } } # IPv6 Context 'Adapter exist, LSO is enabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $TestIPv6LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv6Enabled = $testIPv6LsoEnabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestIPv6LsoEnabled } | Should Not Throw + { Set-TargetResource @testIPv6LsoEnabled } | Should -Not -Throw } - + It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 0 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 } } Context 'Adapter exist, LSO is enabled for IPv6, should be disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $TestIPv6LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv6Enabled = $testIPv6LsoEnabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestIPv6LsoDisabled } | Should Not Throw + { Set-TargetResource @testIPv6LsoDisabled } | Should -Not -Throw } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is disabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $TestIPv6LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv6Enabled = $testIPv6LsoDisabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestIPv6LsoDisabled } | Should Not Throw + { Set-TargetResource @testIPv6LsoDisabled } | Should -Not -Throw } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 0 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 0 } } Context 'Adapter exist, LSO is disabled for IPv6, should be enabled.' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $TestIPv6LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv6Enabled = $testIPv6LsoDisabled.State } } Mock -CommandName Set-NetAdapterLso It 'Should not throw an exception' { - { Set-TargetResource @TestIPv6LsoEnabled } | Should Not Throw + { Set-TargetResource @testIPv6LsoEnabled } | Should -Not -Throw } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 - Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterLso -Exactly -Times 1 } } @@ -371,12 +372,15 @@ try Context 'Adapter does not exist' { Mock -CommandName Get-NetAdapterLso -MockWith { throw 'Network adapter not found' } - It 'Should throw an exception' { - { Set-TargetResource @TestAdapterNotFound } | Should throw + It 'Should throw the correct exception' { + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.NetAdapterNotFoundMessage) + + { Set-TargetResource @testAdapterNotFound } | Should -Throw $errorRecord } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } @@ -385,172 +389,172 @@ try Describe "$($script:DSCResourceName)\Test-TargetResource" { # V1IPv4 Context 'Adapter exist, LSO is enabled for V1IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $TestV1IPv4LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ V1IPv4Enabled = $testV1IPv4LsoEnabled.State } } - + It 'Should return true' { - Test-TargetResource @TestV1IPv4LsoEnabled | Should Be $true + Test-TargetResource @testV1IPv4LsoEnabled | Should -Be $true } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is enabled for V1IPv4, should be disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $TestV1IPv4LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ V1IPv4Enabled = $testV1IPv4LsoEnabled.State } } - + It 'Should return false' { - Test-TargetResource @TestV1IPv4LsoDisabled | Should Be $false + Test-TargetResource @testV1IPv4LsoDisabled | Should -Be $false } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is disabled for V1IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $TestV1IPv4LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ V1IPv4Enabled = $testV1IPv4LsoDisabled.State } } - + It 'Should return true' { - Test-TargetResource @TestV1IPv4LsoDisabled | Should Be $true + Test-TargetResource @testV1IPv4LsoDisabled | Should -Be $true } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is disabled for V1IPv4, should be enabled.' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ V1IPv4Enabled = $TestV1IPv4LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ V1IPv4Enabled = $testV1IPv4LsoDisabled.State } } - + It 'Should return false' { - Test-TargetResource @TestV1IPv4LsoEnabled | Should Be $false + Test-TargetResource @testV1IPv4LsoEnabled | Should -Be $false } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } # IPv4 Context 'Adapter exist, LSO is enabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $TestIPv4LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv4Enabled = $testIPv4LsoEnabled.State } } - + It 'Should return true' { - Test-TargetResource @TestIPv4LsoEnabled | Should Be $true + Test-TargetResource @testIPv4LsoEnabled | Should -Be $true } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is enabled for IPv4, should be disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $TestIPv4LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv4Enabled = $testIPv4LsoEnabled.State } } - + It 'Should return false' { - Test-TargetResource @TestIPv4LsoDisabled | Should Be $false + Test-TargetResource @testIPv4LsoDisabled | Should -Be $false } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is disabled for IPv4, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $TestIPv4LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv4Enabled = $testIPv4LsoDisabled.State } } - + It 'Should return true' { - Test-TargetResource @TestIPv4LsoDisabled | Should Be $true + Test-TargetResource @testIPv4LsoDisabled | Should -Be $true } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is disabled for IPv4, should be enabled.' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv4Enabled = $TestIPv4LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv4Enabled = $testIPv4LsoDisabled.State } } - + It 'Should return false' { - Test-TargetResource @TestIPv4LsoEnabled | Should Be $false + Test-TargetResource @testIPv4LsoEnabled | Should -Be $false } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } # IPv6 Context 'Adapter exist, LSO is enabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $TestIPv6LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv6Enabled = $testIPv6LsoEnabled.State } } - + It 'Should return true' { - Test-TargetResource @TestIPv6LsoEnabled | Should Be $true + Test-TargetResource @testIPv6LsoEnabled | Should -Be $true } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is enabled for IPv6, should be disabled' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $TestIPv6LsoEnabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv6Enabled = $testIPv6LsoEnabled.State } } - + It 'Should return false' { - Test-TargetResource @TestIPv6LsoDisabled | Should Be $false + Test-TargetResource @testIPv6LsoDisabled | Should -Be $false } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is disabled for IPv6, no action required' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $TestIPv6LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv6Enabled = $testIPv6LsoDisabled.State } } - + It 'Should return true' { - Test-TargetResource @TestIPv6LsoDisabled | Should Be $true + Test-TargetResource @testIPv6LsoDisabled | Should -Be $true } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } Context 'Adapter exist, LSO is disabled for IPv6, should be enabled.' { - Mock -CommandName Get-NetAdapterLso -MockWith { - @{ IPv6Enabled = $TestIPv6LsoDisabled.State } + Mock -CommandName Get-NetAdapterLso -MockWith { + @{ IPv6Enabled = $testIPv6LsoDisabled.State } } - + It 'Should return false' { - Test-TargetResource @TestIPv6LsoEnabled | Should Be $false + Test-TargetResource @testIPv6LsoEnabled | Should -Be $false } - it 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + It 'Should call all mocks' { + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } @@ -558,12 +562,15 @@ try Context 'Adapter does not exist' { Mock -CommandName Get-NetAdapterLso -MockWith { throw 'Network adapter not found' } - It 'Should throw an exception' { - { Test-TargetResource @TestAdapterNotFound } | Should throw + It 'Should throw the correct exception' { + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.NetAdapterNotFoundMessage) + + { Test-TargetResource @testAdapterNotFound } | Should -Throw $errorRecord } It 'Should call all mocks' { - Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly 1 + Assert-MockCalled -CommandName Get-NetAdapterLso -Exactly -Times 1 } } } diff --git a/Tests/Unit/MSFT_xNetAdapterName.Tests.ps1 b/Tests/Unit/MSFT_xNetAdapterName.Tests.ps1 index e31906bb..33c79d10 100644 --- a/Tests/Unit/MSFT_xNetAdapterName.Tests.ps1 +++ b/Tests/Unit/MSFT_xNetAdapterName.Tests.ps1 @@ -1,13 +1,13 @@ -$script:DSCModuleName = 'xNetworking' -$script:DSCResourceName = 'MSFT_xNetAdapterName' +$script:DSCModuleName = 'xNetworking' +$script:DSCResourceName = 'MSFT_xNetAdapterName' #region HEADER # Unit Test Template Version: 1.1.0 [string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -21,7 +21,6 @@ $TestEnvironment = Initialize-TestEnvironment ` try { InModuleScope $script:DSCResourceName { - # Generate the adapter data to be used for Mocking $script:adapterName = 'Adapter' $script:newAdapterName = 'NewAdapter' @@ -32,6 +31,7 @@ try $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 @@ -43,6 +43,7 @@ try InterfaceGuid = $script:adapterInterfaceGuid DriverDescription = $script:adapterDriverDescription } + $script:mockAdapter = [PSObject]@{ Name = $script:adapterName PhysicalMediaType = $script:adapterPhysicalMediaType @@ -53,6 +54,7 @@ try InterfaceGuid = $script:adapterInterfaceGuid DriverDescription = $script:adapterDriverDescription } + $script:mockRenamedAdapter = [PSObject]@{ Name = $script:newAdapterName PhysicalMediaType = $script:adapterPhysicalMediaType @@ -64,105 +66,120 @@ try DriverDescription = $script:adapterDriverDescription } - function Rename-NetAdapter { + function Rename-NetAdapter + { [CmdletBinding()] param ( - [Parameter(ValueFromPipeline)] + [Parameter(ValueFromPipeline = $true)] $InputObject, + [Parameter()] [System.String] $NewName ) } - Describe "MSFT_xNetAdapterName\Get-TargetResource" { + Describe 'MSFT_xNetAdapterName\Get-TargetResource' { Context 'Renamed adapter can be found' { - Mock -CommandName Find-NetworkAdapter -MockWith { $script:mockRenamedAdapter } ` + Mock ` + -CommandName Find-NetworkAdapter ` + -MockWith { $script:mockRenamedAdapter } ` -ParameterFilter { $Name -eq $script:newAdapterName } It 'Should not throw' { - { $script:result = Get-TargetResource @adapterParameters -Verbose } | Should Not Throw + { $script:result = Get-TargetResource @adapterParameters -Verbose } | Should -Not -Throw } 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 + $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 call all the mocks' { - Assert-MockCalled -commandName Find-NetworkAdapter -Exactly -Times 1 ` + Assert-MockCalled ` + -CommandName Find-NetworkAdapter -Exactly -Times 1 ` -ParameterFilter { $Name -eq $script:newAdapterName } } } Context 'Renamed adapter not found but matching adapter can be found' { - Mock -CommandName Find-NetworkAdapter ` + Mock ` + -CommandName Find-NetworkAdapter ` -ParameterFilter { $Name -eq $script:newAdapterName } - Mock -CommandName Find-NetworkAdapter -MockWith { $script:mockAdapter } ` + + Mock ` + -CommandName Find-NetworkAdapter -MockWith { $script:mockAdapter } ` -ParameterFilter { $Name -eq $script:adapterName } - It 'Should not throw' { - { $script:result = Get-TargetResource -Name $script:adapterName -NewName $script:newAdapterName -Verbose } | Should Not Throw + It 'Should not throw exception' { + { $script:result = Get-TargetResource -Name $script:adapterName -NewName $script:newAdapterName -Verbose } | Should -Not -Throw } 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 + $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 } It 'Should call all the mocks' { - Assert-MockCalled -commandName Find-NetworkAdapter -Exactly -Times 1 ` + Assert-MockCalled ` + -CommandName Find-NetworkAdapter -Exactly -Times 1 ` -ParameterFilter { $Name -eq $script:adapterName } - Assert-MockCalled -commandName Find-NetworkAdapter -Exactly -Times 1 ` + + Assert-MockCalled ` + -CommandName Find-NetworkAdapter -Exactly -Times 1 ` -ParameterFilter { $Name -eq $script:newAdapterName } } } } - Describe "MSFT_xNetAdapterName\Set-TargetResource" { + Describe 'MSFT_xNetAdapterName\Set-TargetResource' { Context 'Matching adapter can be found' { - Mock -CommandName Find-NetworkAdapter -MockWith { $script:mockAdapter } + Mock ` + -CommandName Find-NetworkAdapter ` + -MockWith { $script:mockAdapter } + Mock ` -CommandName Rename-NetAdapter ` -ParameterFilter { $NewName -eq $script:newAdapterName } ` -MockWith { $script:mockRenamedAdapter } - It 'Should not throw' { - { Set-TargetResource @adapterParameters -Verbose } | Should Not Throw + It 'Should not throw exception' { + { Set-TargetResource @adapterParameters -Verbose } | Should -Not -Throw } It 'Should call all the mocks' { - Assert-MockCalled -commandName Find-NetworkAdapter -Exactly -Times 1 Assert-MockCalled ` - -commandName Rename-NetAdapter ` - -ParameterFilter { $NewName -eq $script:newAdapterName } ` - -Exactly -Times 1 + -CommandName Find-NetworkAdapter -Exactly -Times 1 + + Assert-MockCalled ` + -CommandName Rename-NetAdapter -Exactly -Times 1 ` + -ParameterFilter { $NewName -eq $script:newAdapterName } } } } - Describe "MSFT_xNetAdapterName\Test-TargetResource" { + Describe 'MSFT_xNetAdapterName\Test-TargetResource' { Context 'Matching adapter can be found and has correct Name' { Mock -CommandName Find-NetworkAdapter -MockWith { $script:mockRenamedAdapter } - It 'Should not throw' { - { $script:result = Test-TargetResource @adapterParameters -Verbose } | Should Not Throw + It 'Should not throw exception' { + { $script:result = Test-TargetResource @adapterParameters -Verbose } | Should -Not -Throw } It 'Should return true' { - $script:result | Should Be $true + $script:result | Should -Be $true } It 'Should call all the mocks' { @@ -171,42 +188,52 @@ try } 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 -MockWith { } ` - -ParameterFilter {$Name -and $Name -eq $script:newAdapterName} + Mock ` + -CommandName Find-NetworkAdapter ` + -MockWith { $script:mockAdapter } ` + -ParameterFilter { $Name -and $Name -eq $script:AdapterName } - It 'Should not throw' { - { $script:result = Test-TargetResource @adapterParameters -Verbose } | Should Not Throw + Mock ` + -CommandName Find-NetworkAdapter ` + -ParameterFilter { $Name -and $Name -eq $script:newAdapterName } + + It 'Should not throw exception' { + { $script:result = Test-TargetResource @adapterParameters -Verbose } | Should -Not -Throw } It 'Should return false' { - $script:result | Should Be $false + $script:result | Should -Be $false } It 'Should call all the mocks' { - Assert-MockCalled -commandName Find-NetworkAdapter -Exactly -Times 1 ` - -ParameterFilter {$Name -and $Name -eq $script:AdapterName} - Assert-MockCalled -commandName Find-NetworkAdapter -Exactly -Times 1 ` - -ParameterFilter {$Name -and $Name -eq $script:newAdapterName} + Assert-MockCalled ` + -CommandName Find-NetworkAdapter -Exactly -Times 1 ` + -ParameterFilter { $Name -and $Name -eq $script:AdapterName } + + Assert-MockCalled ` + -CommandName Find-NetworkAdapter -Exactly -Times 1 ` + -ParameterFilter { $Name -and $Name -eq $script:newAdapterName } } } Context 'Adapter name changed by Set-TargetResource' { - Mock -CommandName Find-NetworkAdapter -MockWith { $script:mockRenamedAdapter } ` - -ParameterFilter {$Name -and $Name -eq $script:newAdapterName} + Mock ` + -CommandName Find-NetworkAdapter ` + -MockWith { $script:mockRenamedAdapter } ` + -ParameterFilter { $Name -and $Name -eq $script:newAdapterName } - It 'Should not throw' { - { $script:result = Test-TargetResource @adapterParameters -Verbose } | Should Not Throw + It 'Should not throw exception' { + { $script:result = Test-TargetResource @adapterParameters -Verbose } | Should -Not -Throw } It 'Should return false' { - $script:result | Should Be $True + $script:result | Should -Be $true } It 'Should call all the mocks' { - Assert-MockCalled -commandName Find-NetworkAdapter -Exactly -Times 1 ` - -ParameterFilter {$Name -and $Name -eq $script:newAdapterName} + Assert-MockCalled ` + -CommandName Find-NetworkAdapter -Exactly -Times 1 ` + -ParameterFilter { $Name -and $Name -eq $script:newAdapterName } } } } diff --git a/Tests/Unit/MSFT_xNetAdapterRDMA.Tests.ps1 b/Tests/Unit/MSFT_xNetAdapterRDMA.Tests.ps1 index 1dcbb8d2..3acfe3dd 100644 --- a/Tests/Unit/MSFT_xNetAdapterRDMA.Tests.ps1 +++ b/Tests/Unit/MSFT_xNetAdapterRDMA.Tests.ps1 @@ -1,13 +1,15 @@ -$script:DSCModuleName = 'xNetworking' +$script:DSCModuleName = 'xNetworking' $script:DSCResourceName = 'MSFT_xNetAdapterRDMA' +Import-Module -Name (Join-Path -Path (Join-Path -Path (Split-Path $PSScriptRoot -Parent) -ChildPath 'TestHelpers') -ChildPath 'CommonTestHelper.psm1') -Global + #region HEADER # Unit Test Template Version: 1.1.0 [string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -22,229 +24,256 @@ try { #region Pester Tests InModuleScope $script:DSCResourceName { - # Create the Mock Objects that will be used for running tests - $MockNetAdapterRDMA = [PSCustomObject] @{ - Name = 'SMB1_1' - Enabled = $true + # Create the Mock -CommandName Objects that will be used for running tests + $testAdapterName = 'SMB1_1' + $targetParameters = [PSObject] @{ + Name = $testAdapterName + } + + $mockNetAdapterRDMAEnabled = [PSCustomObject] @{ + Name = $testAdapterName + Enabled = $true } - $TestAdapter = [PSObject]@{ - Name = $MockNetAdapterRDMA.Name + $mockNetAdapterRDMADisabled = [PSCustomObject] @{ + Name = $testAdapterName + Enabled = $false } Describe "$($script:DSCResourceName)\Get-TargetResource" { - function Get-NetAdapterRdma { } + function Get-NetAdapterRdma + { + } + Context 'Network adapter does not exist' { - It 'should throw error' { - Mock Get-NetAdapterRdma -MockWith { - throw 'Network adapter not found' - } - { Get-TargetResource @TestAdapter } | should throw + Mock -CommandName Get-NetAdapterRdma -MockWith { + throw 'Network adapter not found' } - It 'should call the expected mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 + + It 'Should throw expected exception' { + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.NetAdapterNotFoundError -f $testAdapterName) + + { + Get-TargetResource @targetParameters + } | Should -Throw $errorRecord + } + + It 'Should call the expected mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 } } Context 'Network Team exists' { - Mock Get-NetAdapterRdma -MockWith { $MockNetAdapterRDMA } - It 'should return network adapter RDMA properties' { - $Result = Get-TargetResource @TestAdapter - $Result.Name | Should Be $TestAdapter.Name + Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRDMAEnabled } + + It 'Should return network adapter RDMA properties' { + $Result = Get-TargetResource @targetParameters + $Result.Name | Should Be $targetParameters.Name $Result.Enabled | Should Be $true } - It 'should call the expected mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 + + It 'Should call the expected mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 } } } Describe "$($script:DSCResourceName)\Set-TargetResource" { - function Get-NetAdapterRdma { } - function Set-NetAdapterRdma { + function Get-NetAdapterRdma + { + } + function Set-NetAdapterRdma + { param ( - [String] $Name, - [Boolean] $Enabled = $true + [Parameter(Mandatory = $true)] + [System.String] + $Name, + + [Parameter(Mandatory = $true)] + [System.Boolean] + $Enabled = $true ) } Context 'Net Adapter does not exist' { - Mock Set-NetAdapterRdma - - It 'should throw error' { - Mock Get-NetAdapterRdma -MockWith { - throw 'Network adapter not found' - } - $updateAdapter = $TestAdapter.Clone() - $updateAdapter['Enabled'] = $true - { Set-TargetResource @updateAdapter } | Should throw + Mock -CommandName Set-NetAdapterRdma + Mock -CommandName Get-NetAdapterRdma -MockWith { + throw 'Network adapter not found' + } + + It 'Should throw expected exception' { + $setTargetResourceParameters = $targetParameters.Clone() + $setTargetResourceParameters['Enabled'] = $true + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.NetAdapterNotFoundError -f $testAdapterName) + + { + Set-TargetResource @setTargetResourceParameters + } | Should -Throw $errorRecord } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 - Assert-MockCalled -commandName Set-NetAdapterRdma -Exactly 0 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterRdma -Exactly -Times 0 } } Context 'Net Adapter RDMA is already enabled and no action needed' { - Mock Set-NetAdapterRdma + Mock -CommandName Set-NetAdapterRdma + Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRDMAEnabled } - It 'should not throw error' { - Mock Get-NetAdapterRdma -MockWith { $MockNetAdapterRDMA } - $updateAdapter = $TestAdapter.Clone() - $updateAdapter['Enabled'] = $true - { Set-TargetResource @updateAdapter } | Should not throw + It 'Should not throw exception' { + $setTargetResourceParameters = $targetParameters.Clone() + $setTargetResourceParameters['Enabled'] = $true + { + Set-TargetResource @setTargetResourceParameters + } | Should -Not -Throw } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 - Assert-MockCalled -commandName Set-NetAdapterRdma -Exactly 0 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterRdma -Exactly -Times 0 } } Context 'Net Adapter RDMA is disabled and should be enabled' { - Mock Set-NetAdapterRdma - - It 'should not throw error' { - Mock Get-NetAdapterRdma -MockWith { - $configuration = [PSCustomObject] @{ - Name = 'SMB1_1' - Enabled = $false - } - return $configuration - } - $updateAdapter = $TestAdapter.Clone() - $updateAdapter['Enabled'] = $true - { Set-TargetResource @updateAdapter } | Should not throw + Mock -CommandName Set-NetAdapterRdma + Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRDMADisabled } + + It 'Should not throw exception' { + $setTargetResourceParameters = $targetParameters.Clone() + $setTargetResourceParameters['Enabled'] = $true + { + Set-TargetResource @setTargetResourceParameters + } | Should -Not -Throw } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 - Assert-MockCalled -commandName Set-NetAdapterRdma -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterRdma -Exactly -Times 1 } } Context 'Net Adapter RDMA is enabled and should be disabled' { - Mock Set-NetAdapterRdma - - It 'should not throw error' { - Mock Get-NetAdapterRdma -MockWith { - $configuration = [PSCustomObject] @{ - Name = 'SMB1_1' - Enabled = $true - } - return $configuration - } - $updateAdapter = $TestAdapter.Clone() - $updateAdapter['Enabled'] = $false - { Set-TargetResource @updateAdapter } | Should not throw + Mock -CommandName Set-NetAdapterRdma + Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRDMAEnabled } + + It 'Should not throw exception' { + $setTargetResourceParameters = $targetParameters.Clone() + $setTargetResourceParameters['Enabled'] = $false + { + Set-TargetResource @setTargetResourceParameters + } | Should -Not -Throw } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 - Assert-MockCalled -commandName Set-NetAdapterRdma -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterRdma -Exactly -Times 1 } } Context 'Net Adapter RDMA is already disabled and no action needed' { - Mock Set-NetAdapterRdma - - It 'should not throw error' { - Mock Get-NetAdapterRdma -MockWith { - $configuration = [PSCustomObject] @{ - Name = 'SMB1_1' - Enabled = $false - } - return $configuration - } - $updateAdapter = $TestAdapter.Clone() - $updateAdapter['Enabled'] = $false - { Set-TargetResource @updateAdapter } | Should not throw + Mock -CommandName Set-NetAdapterRdma + Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRDMADisabled } + + It 'Should not throw exception' { + $setTargetResourceParameters = $targetParameters.Clone() + $setTargetResourceParameters['Enabled'] = $false + { + Set-TargetResource @setTargetResourceParameters + } | Should -Not -Throw } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 - Assert-MockCalled -commandName Set-NetAdapterRdma -Exactly 0 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 + Assert-MockCalled -CommandName Set-NetAdapterRdma -Exactly -Times 0 } } } Describe "$($script:DSCResourceName)\Test-TargetResource" { - function Get-NetAdapterRdma { } + function Get-NetAdapterRdma + { + } Context 'Net Adapter does not exist' { - It 'should throw error' { - Mock Get-NetAdapterRdma -MockWith { - throw 'Network adapter not found' - } - $updateAdapter = $TestAdapter.Clone() - $updateAdapter['Enabled'] = $true - { Test-TargetResource @updateAdapter } | Should throw + Mock -CommandName Get-NetAdapterRdma -MockWith { + throw 'Network adapter not found' } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 + + It 'Should throw expected exception' { + $testTargetResourceParameters = $targetParameters.Clone() + $testTargetResourceParameters['Enabled'] = $true + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.NetAdapterNotFoundError -f $testAdapterName) + + { + Test-TargetResource @testTargetResourceParameters + } | Should -Throw $errorRecord + } + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 } } Context 'Net Adapter RDMA is already enabled and no action needed' { - It 'should return true' { - Mock Get-NetAdapterRdma -MockWith { $MockNetAdapterRDMA } - $updateAdapter = $TestAdapter.Clone() - $updateAdapter['Enabled'] = $true - Test-TargetResource @updateAdapter | Should be $true + Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRDMAEnabled } + + It 'Should return true' { + $testTargetResourceParameters = $targetParameters.Clone() + $testTargetResourceParameters['Enabled'] = $true + Test-TargetResource @testTargetResourceParameters | Should -Be $true } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 } } Context 'Net Adapter RDMA is disabled and should be enabled' { - It 'should return false' { - Mock Get-NetAdapterRdma -MockWith { - $configuration = [PSCustomObject] @{ - Name = 'SMB1_1' - Enabled = $false - } - return $configuration - } - $updateAdapter = $TestAdapter.Clone() - $updateAdapter['Enabled'] = $true - Test-TargetResource @updateAdapter | Should be $false + Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRDMADisabled } + + It 'Should return false' { + $testTargetResourceParameters = $targetParameters.Clone() + $testTargetResourceParameters['Enabled'] = $true + Test-TargetResource @testTargetResourceParameters | Should -Be $false } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 } } Context 'Net Adapter RDMA is enabled and should be disabled' { - It 'should return false' { - Mock Get-NetAdapterRdma -MockWith { - $configuration = [PSCustomObject] @{ - Name = 'SMB1_1' - Enabled = $true - } - return $configuration - } - $updateAdapter = $TestAdapter.Clone() - $updateAdapter['Enabled'] = $false - Test-TargetResource @updateAdapter | Should be $false + Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRDMAEnabled } + + It 'Should return false' { + $testTargetResourceParameters = $targetParameters.Clone() + $testTargetResourceParameters['Enabled'] = $false + Test-TargetResource @testTargetResourceParameters | Should -Be $false } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 } } Context 'Net Adapter RDMA is already disabled and no action needed' { - It 'should return true' { - Mock Get-NetAdapterRdma -MockWith { - $configuration = [PSCustomObject] @{ - Name = 'SMB1_1' - Enabled = $false - } - return $configuration - } - $updateAdapter = $TestAdapter.Clone() - $updateAdapter['Enabled'] = $false - Test-TargetResource @updateAdapter | Should be $true + Mock -CommandName Get-NetAdapterRdma -MockWith { $mockNetAdapterRDMADisabled } + + It 'Should return true' { + $testTargetResourceParameters = $targetParameters.Clone() + $testTargetResourceParameters['Enabled'] = $false + Test-TargetResource @testTargetResourceParameters | Should -Be $true } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetAdapterRdma -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetAdapterRdma -Exactly -Times 1 } } } diff --git a/Tests/Unit/MSFT_xNetBIOS.Tests.ps1 b/Tests/Unit/MSFT_xNetBIOS.Tests.ps1 index f110555e..6c1482e1 100644 --- a/Tests/Unit/MSFT_xNetBIOS.Tests.ps1 +++ b/Tests/Unit/MSFT_xNetBIOS.Tests.ps1 @@ -1,13 +1,13 @@ -$script:DSCModuleName = 'xNetworking' +$script:DSCModuleName = 'xNetworking' $script:DSCResourceName = 'MSFT_xNetBIOS' #region HEADER # Unit Test Template Version: 1.1.0 [string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -22,113 +22,265 @@ try { #region Pester Tests InModuleScope $script:DSCResourceName { + $interfaceAlias = 'Test Adapter' - $InterfaceAlias = (Get-NetAdapter -Physical | Select-Object -First 1).Name + $mockNetadapter = New-Object ` + -TypeName CimInstance ` + -ArgumentList 'Win32_NetworkAdapter' | + Add-Member ` + -MemberType NoteProperty ` + -Name Name ` + -Value $interfaceAlias ` + -PassThru - $MockNetadapterSettingsDefault = New-Object -TypeName CimInstance -ArgumentList 'Win32_NetworkAdapterConfiguration' | Add-Member -MemberType NoteProperty -Name TcpipNetbiosOptions -Value 0 -PassThru - $MockNetadapterSettingsEnable = New-Object -TypeName CimInstance -ArgumentList 'Win32_NetworkAdapterConfiguration' | Add-Member -MemberType NoteProperty -Name TcpipNetbiosOptions -Value 1 -PassThru - $MockNetadapterSettingsDisable = New-Object -TypeName CimInstance -ArgumentList 'Win32_NetworkAdapterConfiguration' | Add-Member -MemberType NoteProperty -Name TcpipNetbiosOptions -Value 2 -PassThru + $mockNetadapterSettingsDefault = New-Object ` + -TypeName CimInstance ` + -ArgumentList 'Win32_NetworkAdapterConfiguration' | + Add-Member ` + -MemberType NoteProperty ` + -Name TcpipNetbiosOptions ` + -Value 0 ` + -PassThru + + $mockNetadapterSettingsEnable = New-Object ` + -TypeName CimInstance ` + -ArgumentList 'Win32_NetworkAdapterConfiguration' | + Add-Member ` + -MemberType NoteProperty ` + -Name TcpipNetbiosOptions ` + -Value 1 ` + -PassThru + + $mockNetadapterSettingsDisable = New-Object ` + -TypeName CimInstance ` + -ArgumentList 'Win32_NetworkAdapterConfiguration' | + Add-Member ` + -MemberType NoteProperty ` + -Name TcpipNetbiosOptions ` + -Value 2 ` + -PassThru #region Function Get-TargetResource - Describe "MSFT_xNetBIOS\Get-TargetResource" { + Describe 'MSFT_xNetBIOS\Get-TargetResource' { + Context 'NetBIOS over TCP/IP is set to "Default"' { + Mock -CommandName Get-CimInstance -MockWith { $mockNetadapter } + Mock -CommandName Get-CimAssociatedInstance -MockWith { $mockNetadapterSettingsDefault} + + It 'Should not throw exception' { + { + $script:result = Get-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Default' -Verbose + } | Should -Not -Throw + } - Mock -CommandName Get-CimAssociatedInstance -MockWith {return $MockNetadapterSettingsDefault} + It 'Returns a hashtable' { + $script:result -is [System.Collections.Hashtable] | Should -Be $true + } - It 'Returns a hashtable' { - $targetResource = Get-TargetResource -InterfaceAlias $InterfaceAlias -Setting 'Default' - $targetResource -is [System.Collections.Hashtable] | Should Be $true + It 'Setting should return "Default"' { + $script:result.Setting | Should -Be 'Default' + } } - It 'NetBIOS over TCP/IP numerical setting "0" should translate to "Default"' { - $Result = Get-TargetResource -InterfaceAlias $InterfaceAlias -Setting 'Default' - $Result.Setting | should be 'Default' + Context 'NetBIOS over TCP/IP is set to "Enable"' { + Mock -CommandName Get-CimInstance -MockWith { $mockNetadapter } + Mock -CommandName Get-CimAssociatedInstance -MockWith { $mockNetadapterSettingsEnable } + + It 'Should not throw exception' { + { + $script:result = Get-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Default' -Verbose + } | Should -Not -Throw + } + + It 'Returns a hashtable' { + $script:result -is [System.Collections.Hashtable] | Should -Be $true + } + + It 'Setting should return "Enable"' { + $script:result.Setting | Should -Be 'Enable' + } + } + + Context 'NetBIOS over TCP/IP is set to "Disable"' { + Mock -CommandName Get-CimInstance -MockWith { $mockNetadapter } + Mock -CommandName Get-CimAssociatedInstance -MockWith { $mockNetadapterSettingsDisable } + + It 'Should not throw exception' { + { + $script:result = Get-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Default' -Verbose + } | Should -Not -Throw + } + + It 'Returns a hashtable' { + $script:result -is [System.Collections.Hashtable] | Should -Be $true + } + + It 'Setting should return "Disable"' { + $script:result.Setting | Should -Be 'Disable' + } } - It 'NetBIOS over TCP/IP setting should return real value "Default", not parameter value "Enable"' { - $Result = Get-TargetResource -InterfaceAlias $InterfaceAlias -Setting 'Enable' - $Result.Setting | should be 'Default' + Context 'Interface does not exist' { + Mock -CommandName Get-CimInstance -MockWith { } + Mock -CommandName Get-CimAssociatedInstance -MockWith { $mockNetadapterSettingsDisable } + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.InterfaceNotFoundError -f $interfaceAlias) + + It 'Should throw expected exception' { + { + $script:result = Get-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Default' -Verbose + } | Should -Throw $errorRecord + } } } #endregion - #region Function Test-TargetResource - Describe "MSFT_xNetBIOS\Test-TargetResource" { - Context 'invoking with NetBIOS over TCP/IP set to default' { - - Mock -CommandName Get-CimAssociatedInstance -MockWith {return $MockNetadapterSettingsDefault} + Describe 'MSFT_xNetBIOS\Test-TargetResource' { + Context 'NetBIOS over TCP/IP is set to "Default"' { + Mock -CommandName Get-CimInstance -MockWith { $mockNetadapter } + Mock -CommandName Get-CimAssociatedInstance -MockWith { $mockNetadapterSettingsDefault } - It 'should return true when value "Default" is set' { - Test-TargetResource -InterfaceAlias $InterfaceAlias -Setting 'Default' | Should Be $true + It 'Should return true when value "Default" is set' { + Test-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Default' -Verbose | Should -Be $true } - It 'should return false when value "Disable" is set' { - Test-TargetResource -InterfaceAlias $InterfaceAlias -Setting 'Disable' | Should Be $false + + It 'Should return false when value "Disable" is set' { + Test-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Disable' -Verbose | Should -Be $false } } - Context 'invoking with NetBIOS over TCP/IP set to Disable' { - - Mock -CommandName Get-CimAssociatedInstance -MockWith {return $MockNetadapterSettingsDisable} + Context 'NetBIOS over TCP/IP is set to "Disable"' { + Mock -CommandName Get-CimInstance -MockWith { $mockNetadapter } + Mock -CommandName Get-CimAssociatedInstance -MockWith { $mockNetadapterSettingsDisable } - It 'should return true when value "Disable" is set' { - Test-TargetResource -InterfaceAlias $InterfaceAlias -Setting 'Disable' | Should Be $true + It 'Should return true when value "Disable" is set' { + Test-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Disable' -Verbose | Should -Be $true } - It 'should return false when value "Enable" is set' { - Test-TargetResource -InterfaceAlias $InterfaceAlias -Setting 'Enable' | Should Be $false + + It 'Should return false when value "Enable" is set' { + Test-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Enable' -Verbose | Should -Be $false } } - Context 'invoking with NetBIOS over TCP/IP set to Enable' { - - Mock -CommandName Get-CimAssociatedInstance -MockWith {return $MockNetadapterSettingsEnable} + Context 'NetBIOS over TCP/IP is set to "Enable"' { + Mock -CommandName Get-CimInstance -MockWith { $mockNetadapter } + Mock -CommandName Get-CimAssociatedInstance -MockWith { $mockNetadapterSettingsEnable } - It 'should return true when value "Enable" is set' { - Test-TargetResource -InterfaceAlias $InterfaceAlias -Setting 'Enable' | Should Be $true + It 'Should return true when value "Enable" is set' { + Test-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Enable' -Verbose | Should -Be $true } - It 'should return false when value "Disable" is set' { - Test-TargetResource -InterfaceAlias $InterfaceAlias -Setting 'Disable' | Should Be $false + + It 'Should return false when value "Disable" is set' { + Test-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Disable' -Verbose | Should -Be $false } } - Context 'Invoking with NonExisting Network Adapter' { - Mock -CommandName Get-CimAssociatedInstance -MockWith { } - $errorMessage = ($LocalizedData.NICNotFound -f 'BogusAdapter') - It 'should throw ObjectNotFound exception' { - {Test-TargetResource -InterfaceAlias 'BogusAdapter' -Setting 'Enable'} | Should Throw $errorMessage + Context 'Interface does not exist' { + Mock -CommandName Get-CimInstance -MockWith { } + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.InterfaceNotFoundError -f $interfaceAlias) + + It 'Should throw expected exception' { + { + Test-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Enable' -Verbose + } | Should -Throw $errorRecord } } } #endregion #region Function Set-TargetResource - Describe "MSFT_xNetBIOS\Set-TargetResource" { - Mock Set-ItemProperty - Mock Invoke-CimMethod + Describe 'MSFT_xNetBIOS\Set-TargetResource' { + Context 'NetBIOS over TCP/IP should be set to "Default"' { + Mock -CommandName Get-CimInstance -MockWith { $mockNetadapter } + Mock -CommandName Get-CimAssociatedInstance -MockWith { $mockNetadapterSettingsEnable } + Mock -CommandName Set-ItemProperty + Mock -CommandName Invoke-CimMethod -MockWith { @{ ReturnValue = 0 } } - Context '"Setting" is "Default"' { - - Mock -CommandName Get-CimAssociatedInstance -MockWith {return $MockNetadapterSettingsEnable} + It 'Should not throw exception' { + { + Set-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Default' -Verbose + } | Should -Not -Throw + } It 'Should call "Set-ItemProperty" instead of "Invoke-CimMethod"' { - $Null = Set-TargetResource -InterfaceAlias $InterfaceAlias -Setting 'Default' - Assert-MockCalled -CommandName Set-ItemProperty -Exactly -Times 1 Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 0 } } - Context '"Setting" is "Disable"' { + Context 'NetBIOS over TCP/IP should be set to "Disable"' { + Mock -CommandName Get-CimInstance -MockWith { $mockNetadapter } + Mock -CommandName Get-CimAssociatedInstance -MockWith { $mockNetadapterSettingsEnable } + Mock -CommandName Set-ItemProperty + Mock -CommandName Invoke-CimMethod -MockWith { @{ ReturnValue = 0 } } + + It 'Should not throw exception' { + { + Set-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Disable' -Verbose + } | Should -Not -Throw + } + + It 'Should call "Invoke-CimMethod" instead of "Set-ItemProperty"' { + Assert-MockCalled -CommandName Set-ItemProperty -Exactly -Times 0 + Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 + } + } + + Context 'NetBIOS over TCP/IP should be set to "Enable"' { + Mock -CommandName Get-CimInstance -MockWith { $mockNetadapter } + Mock -CommandName Get-CimAssociatedInstance -MockWith { $mockNetadapterSettingsDisable } + Mock -CommandName Set-ItemProperty + Mock -CommandName Invoke-CimMethod -MockWith { @{ ReturnValue = 0 } } + + It 'Should not throw exception' { + { + Set-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Enable' -Verbose + } | Should -Not -Throw + } It 'Should call "Invoke-CimMethod" instead of "Set-ItemProperty"' { - Mock -CommandName Get-CimAssociatedInstance -MockWith {return $MockNetadapterSettingsEnable} - Mock Invoke-CimMethod - $Null = Set-TargetResource -InterfaceAlias $InterfaceAlias -Setting 'Disable' + Assert-MockCalled -CommandName Set-ItemProperty -Exactly -Times 0 + Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 + } + } + + Context 'NetBIOS over TCP/IP should be set to "Enable" but error returned from "Invoke-CimMethod"' { + Mock -CommandName Get-CimInstance -MockWith { $mockNetadapter } + Mock -CommandName Get-CimAssociatedInstance -MockWith { $mockNetadapterSettingsDisable } + Mock -CommandName Invoke-CimMethod -MockWith { @{ ReturnValue = 74 } } + Mock -CommandName Set-ItemProperty + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.FailedUpdatingNetBiosError -f 74, 'Enable') + + It 'Should throw expected exception' { + { + Set-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Enable' -Verbose + } | Should -Throw $errorRecord + } + + It 'Should call "Invoke-CimMethod" instead of "Set-ItemProperty"' { Assert-MockCalled -CommandName Set-ItemProperty -Exactly -Times 0 Assert-MockCalled -CommandName Invoke-CimMethod -Exactly -Times 1 } } + + Context 'Interface does not exist' { + Mock -CommandName Get-CimInstance -MockWith { } + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.InterfaceNotFoundError -f $interfaceAlias) + + It 'Should throw expected exception' { + { + Set-TargetResource -InterfaceAlias $interfaceAlias -Setting 'Enable' -Verbose + } | Should -Throw $errorRecord + } + } } #endregion } diff --git a/Tests/Unit/MSFT_xNetworkTeam.Tests.ps1 b/Tests/Unit/MSFT_xNetworkTeam.Tests.ps1 index a2de0cfb..5578fee4 100644 --- a/Tests/Unit/MSFT_xNetworkTeam.Tests.ps1 +++ b/Tests/Unit/MSFT_xNetworkTeam.Tests.ps1 @@ -1,13 +1,13 @@ -$script:DSCModuleName = 'xNetworking' +$script:DSCModuleName = 'xNetworking' $script:DSCResourceName = 'MSFT_xNetworkTeam' #region HEADER # Unit Test Template Version: 1.1.0 [string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -22,311 +22,325 @@ try { #region Pester Tests InModuleScope $script:DSCResourceName { - - # Create the Mock Objects that will be used for running tests - $MockNetTeam = [PSCustomObject] @{ - Name = 'HostTeam' - Members = @('NIC1','NIC2') + # Create the Mock -CommandName Objects that will be used for running tests + $mockNetTeam = [PSCustomObject] @{ + Name = 'HostTeam' + Members = @('NIC1', 'NIC2') } - $TestTeam = [PSObject]@{ - Name = $MockNetTeam.Name - TeamMembers = $MockNetTeam.Members + $testTeam = [PSObject] @{ + Name = $mockNetTeam.Name + TeamMembers = $mockNetTeam.Members } - $MockTeam = [PSObject]@{ - Name = $TestTeam.Name - Members = $TestTeam.TeamMembers - loadBalancingAlgorithm = 'Dynamic' - teamingMode = 'SwitchIndependent' - Ensure = 'Present' + $mockTeam = [PSObject] @{ + Name = $testTeam.Name + Members = $testTeam.TeamMembers + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } - Describe "MSFT_xNetworkTeam\Get-TargetResource" { - + Describe 'MSFT_xNetworkTeam\Get-TargetResource' { Context 'Team does not exist' { - Mock Get-NetLbfoTeam - It 'should return ensure as absent' { - $Result = Get-TargetResource ` - @TestTeam - $Result.Ensure | Should Be 'Absent' + Mock -CommandName Get-NetLbfoTeam + + It 'Should return ensure as absent' { + $result = Get-TargetResource ` + @testTeam + $result.Ensure | Should -Be 'Absent' } - It 'should call the expected mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 + + It 'Should call the expected mocks' { + Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 } } Context 'Network Team exists' { - Mock Get-NetLbfoTeam -MockWith { $MockTeam } - It 'should return team properties' { - $Result = Get-TargetResource @TestTeam - $Result.Ensure | Should Be 'Present' - $Result.Name | Should Be $TestTeam.Name - $Result.TeamMembers | Should Be $TestTeam.TeamMembers - $Result.loadBalancingAlgorithm | Should Be 'Dynamic' - $Result.teamingMode | Should Be 'SwitchIndependent' - } - It 'should call the expected mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 + Mock -CommandName Get-NetLbfoTeam -MockWith { $mockTeam } + + It 'Should return team properties' { + $result = Get-TargetResource @testTeam + $result.Ensure | Should -Be 'Present' + $result.Name | Should -Be $testTeam.Name + $result.TeamMembers | Should -Be $testTeam.TeamMembers + $result.LoadBalancingAlgorithm | Should -Be 'Dynamic' + $result.TeamingMode | Should -Be 'SwitchIndependent' + } + + It 'Should call the expected mocks' { + Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 } } } - Describe "MSFT_xNetworkTeam\Set-TargetResource" { - $newTeam = [PSObject]@{ - Name = $TestTeam.Name - TeamMembers = $TestTeam.TeamMembers - loadBalancingAlgorithm = 'Dynamic' - teamingMode = 'SwitchIndependent' - Ensure = 'Present' + Describe 'MSFT_xNetworkTeam\Set-TargetResource' { + $newTeam = [PSObject] @{ + Name = $testTeam.Name + TeamMembers = $testTeam.TeamMembers + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } Context '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 - Mock Get-NetLbfoTeam - Mock New-NetLbfoTeam - Mock Set-NetLbfoTeam - Mock Remove-NetLbfoTeamMember - Mock Add-NetLbfoTeamMember - - It 'should not throw error' { + It 'Should not throw error' { { Set-TargetResource @newTeam - } | Should Not Throw + } | Should -Not -Throw } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 - Assert-MockCalled -commandName New-NetLbfoTeam -Exactly 1 - Assert-MockCalled -commandName Set-NetLbfoTeam -Exactly 0 - Assert-MockCalled -commandName Remove-NetLbfoTeamMember -Exactly 0 - Assert-MockCalled -commandName Add-NetLbfoTeamMember -Exactly 0 + + 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 } } - Context 'team exists but needs a different teaming mode' { - - Mock Get-NetLbfoTeam -MockWith { $MockTeam } - Mock New-NetLbfoTeam - Mock Set-NetLbfoTeam - Mock Remove-NetLbfoTeam + Context '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 not throw error' { + It 'Should not throw error' { { $updateTeam = $newTeam.Clone() - $updateTeam.teamingMode = 'LACP' + $updateTeam.TeamingMode = 'LACP' Set-TargetResource @updateTeam - } | Should Not Throw + } | Should -Not -Throw } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 - Assert-MockCalled -commandName New-NetLbfoTeam -Exactly 0 - Assert-MockCalled -commandName Set-NetLbfoTeam -Exactly 1 - Assert-MockCalled -commandName Remove-NetLbfoTeam -Exactly 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 1 + Assert-MockCalled -CommandName Remove-NetLbfoTeam -Exactly -Times 0 } } - Context 'team exists but needs a different load balacing algorithm' { - Mock Get-NetLbfoTeam -MockWith { $MockTeam } - Mock New-NetLbfoTeam - Mock Set-NetLbfoTeam - Mock Remove-NetLbfoTeam + Context '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 not throw error' { + It 'Should not throw error' { { $updateTeam = $newTeam.Clone() - $updateTeam.loadBalancingAlgorithm = 'HyperVPort' + $updateTeam.LoadBalancingAlgorithm = 'HyperVPort' Set-TargetResource @updateTeam - } | Should Not Throw + } | Should -Not -Throw } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 - Assert-MockCalled -commandName New-NetLbfoTeam -Exactly 0 - Assert-MockCalled -commandName Set-NetLbfoTeam -Exactly 1 - Assert-MockCalled -commandName Remove-NetLbfoTeam -Exactly 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 1 + Assert-MockCalled -CommandName Remove-NetLbfoTeam -Exactly -Times 0 } } - Context 'team exists but has to remove a member adapter' { - Mock Get-NetLbfoTeam -MockWith { $MockTeam } - Mock New-NetLbfoTeam - Mock Set-NetLbfoTeam - Mock Remove-NetLbfoTeam - Mock Remove-NetLbfoTeamMember + Context '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 not throw error' { + It 'Should not throw error' { { $updateTeam = $newTeam.Clone() $updateTeam.TeamMembers = $newTeam.TeamMembers[0] Set-TargetResource @updateTeam - } | Should Not Throw + } | Should -Not -Throw } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 - Assert-MockCalled -commandName New-NetLbfoTeam -Exactly 0 - Assert-MockCalled -commandName Set-NetLbfoTeam -Exactly 0 - Assert-MockCalled -commandName Remove-NetLbfoTeam -Exactly 0 - Assert-MockCalled -commandName Remove-NetLbfoTeamMember -Exactly 1 + + 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 } } - Context 'team exists but has to add a member adapter' { - Mock Get-NetLbfoTeam -MockWith { $MockTeam } - Mock New-NetLbfoTeam - Mock Set-NetLbfoTeam - Mock Remove-NetLbfoTeam - Mock Remove-NetLbfoTeamMember - Mock Add-NetLbfoTeamMember + Context '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' { + It 'Should not throw error' { { $updateTeam = $newTeam.Clone() $updateTeam.TeamMembers += 'NIC3' Set-TargetResource @updateTeam - } | Should Not Throw + } | Should -Not -Throw } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 - Assert-MockCalled -commandName New-NetLbfoTeam -Exactly 0 - Assert-MockCalled -commandName Set-NetLbfoTeam -Exactly 0 - Assert-MockCalled -commandName Remove-NetLbfoTeam -Exactly 0 - Assert-MockCalled -commandName Remove-NetLbfoTeamMember -Exactly 0 - Assert-MockCalled -commandName Add-NetLbfoTeamMember -Exactly 1 + + 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 'team exists but should not exist' { - Mock Get-NetLbfoTeam -MockWith { $MockTeam } - Mock New-NetLbfoTeam - Mock Set-NetLbfoTeam - Mock Remove-NetLbfoTeam - Mock Remove-NetLbfoTeamMember - Mock Add-NetLbfoTeamMember + Context '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' { + It 'Should not throw error' { { $updateTeam = $newTeam.Clone() - $updateTeam.Ensure = 'absent' + $updateTeam.Ensure = 'Absent' Set-TargetResource @updateTeam - } | Should Not Throw + } | Should -Not -Throw } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 - Assert-MockCalled -commandName New-NetLbfoTeam -Exactly 0 - Assert-MockCalled -commandName Set-NetLbfoTeam -Exactly 0 - Assert-MockCalled -commandName Remove-NetLbfoTeam -Exactly 1 - Assert-MockCalled -commandName Remove-NetLbfoTeamMember -Exactly 0 - Assert-MockCalled -commandName Add-NetLbfoTeamMember -Exactly 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 } } } - Describe "MSFT_xNetworkTeam\Test-TargetResource" { - $newTeam = [PSObject]@{ - Name = $TestTeam.Name - TeamMembers = $TestTeam.TeamMembers - loadBalancingAlgorithm = 'Dynamic' - teamingMode = 'SwitchIndependent' - Ensure = 'Present' + Describe 'MSFT_xNetworkTeam\Test-TargetResource' { + $newTeam = [PSObject] @{ + Name = $testTeam.Name + TeamMembers = $testTeam.TeamMembers + LoadBalancingAlgorithm = 'Dynamic' + TeamingMode = 'SwitchIndependent' + Ensure = 'Present' } Context 'Team does not exist but should' { - Mock Get-NetLbfoTeam + Mock -CommandName Get-NetLbfoTeam - It 'should return false' { - Test-TargetResource @newTeam | Should be $false + It 'Should return false' { + Test-TargetResource @newTeam | Should -Be $false } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 } } - Context 'team exists but needs a different teaming mode' { - Mock Get-NetLbfoTeam -MockWith { $MockTeam } + Context 'Team exists but needs a different teaming mode' { + Mock -CommandName Get-NetLbfoTeam -MockWith { $mockTeam } - It 'should return false' { + It 'Should return false' { $updateTeam = $newTeam.Clone() - $updateTeam.teamingMode = 'LACP' - Test-TargetResource @updateTeam | Should Be $false + $updateTeam.TeamingMode = 'LACP' + Test-TargetResource @updateTeam | Should -Be $false } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 } } Context 'team exists but needs a different load balacing algorithm' { - Mock Get-NetLbfoTeam -MockWith { $MockTeam } + Mock -CommandName Get-NetLbfoTeam -MockWith { $mockTeam } - It 'should return false' { + It 'Should return false' { $updateTeam = $newTeam.Clone() - $updateTeam.loadBalancingAlgorithm = 'HyperVPort' - Test-TargetResource @updateTeam | Should Be $false + $updateTeam.LoadBalancingAlgorithm = 'HyperVPort' + Test-TargetResource @updateTeam | Should -Be $false } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 } } - Context 'team exists but has to remove a member adapter' { - Mock Get-NetLbfoTeam -MockWith { $MockTeam } + Context 'Team exists but has to remove a member adapter' { + Mock -CommandName Get-NetLbfoTeam -MockWith { $mockTeam } - It 'should return false' { + It 'Should return false' { $updateTeam = $newTeam.Clone() $updateTeam.TeamMembers = $newTeam.TeamMembers[0] - Test-TargetResource @updateTeam | Should Be $false + Test-TargetResource @updateTeam | Should -Be $false } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 } } - Context 'team exists but has to add a member adapter' { - Mock Get-NetLbfoTeam -MockWith { $MockTeam } + Context 'Team exists but has to add a member adapter' { + Mock -CommandName Get-NetLbfoTeam -MockWith { $mockTeam } - It 'should return false' { + It 'Should return false' { $updateTeam = $newTeam.Clone() $updateTeam.TeamMembers += 'NIC3' - Test-TargetResource @updateTeam | Should Be $false + Test-TargetResource @updateTeam | Should -Be $false } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 } } - Context 'team exists but should not exist' { - Mock Get-NetLbfoTeam -MockWith { $MockTeam } + Context 'Team exists but should not exist' { + Mock -CommandName Get-NetLbfoTeam -MockWith { $mockTeam } - It 'should return $false' { + It 'Should return $false' { $updateTeam = $newTeam.Clone() - $updateTeam.Ensure = 'absent' - Test-TargetResource @updateTeam | Should Be $false + $updateTeam.Ensure = 'Absent' + Test-TargetResource @updateTeam | Should -Be $false } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 } } - Context 'team exists and no action needed' { - Mock Get-NetLbfoTeam -MockWith { $MockTeam } + Context 'Team exists and no action needed' { + Mock -CommandName Get-NetLbfoTeam -MockWith { $mockTeam } - It 'should return true' { + It 'Should return true' { $updateTeam = $newTeam.Clone() - Test-TargetResource @updateTeam | Should Be $true + Test-TargetResource @updateTeam | Should -Be $true } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 } } - Context 'team does not and no action needed' { - Mock Get-NetLbfoTeam + Context 'Team does not and no action needed' { + Mock -CommandName Get-NetLbfoTeam - It 'should return true' { + It 'Should return true' { $updateTeam = $newTeam.Clone() $updateTeam.Ensure = 'Absent' - Test-TargetResource @updateTeam | Should Be $true + Test-TargetResource @updateTeam | Should -Be $true } - It 'should call expected Mocks' { - Assert-MockCalled -commandName Get-NetLbfoTeam -Exactly 1 + + It 'Should call expected Mocks' { + Assert-MockCalled -CommandName Get-NetLbfoTeam -Exactly -Times 1 } } } diff --git a/Tests/Unit/MSFT_xWinsSetting.Tests.ps1 b/Tests/Unit/MSFT_xWinsSetting.Tests.ps1 new file mode 100644 index 00000000..0aa1b950 --- /dev/null +++ b/Tests/Unit/MSFT_xWinsSetting.Tests.ps1 @@ -0,0 +1,335 @@ +$script:DSCModuleName = 'xNetworking' +$script:DSCResourceName = 'MSFT_xWinsSetting' +Import-Module -Name (Join-Path -Path (Join-Path -Path (Split-Path $PSScriptRoot -Parent) -ChildPath 'TestHelpers') -ChildPath 'CommonTestHelper.psm1') -Global + +#region HEADER +# Unit Test Template Version: 1.1.0 +[string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' +if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) +{ + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) +} + +Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force +$TestEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:DSCModuleName ` + -DSCResourceName $script:DSCResourceName ` + -TestType Unit +#endregion HEADER + +# Begin Testing +try +{ + #region Pester Tests + InModuleScope $script:DSCResourceName { + # Create the Mock Objects that will be used for running tests + $mockEnabledLmHostsRegistryKey = { + [PSObject] @{ + EnableLMHOSTS = 1 + } + } + + $mockDisabledLmHostsRegistryKey = { + [PSObject] @{ + EnableLMHOSTS = 0 + } + } + + $mockEnabledDNSRegistryKey = { + [PSObject] @{ + EnableDNS = 1 + } + } + + $mockDisabledDNSRegistryKey = { + [PSObject] @{ + EnableDNS = 0 + } + } + + $mockGetTargetResourceAllEnabled = { + [PSObject] @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $true + EnableDns = $true + } + } + + $mockGetTargetResourceAllDisabled = { + [PSObject] @{ + IsSingleInstance = 'Yes' + EnableLmHosts = $false + EnableDns = $false + } + } + + $mockInvokeCimMethodReturnValueOK = { + @{ + ReturnValue = 0 + } + } + + $mockInvokeCimMethodReturnValueError = { + @{ + ReturnValue = 74 + } + } + + $getItemProperty_EnableLmHosts_ParameterFilter = { + $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableLMHOSTS' + } + + $getItemProperty_EnableDns_ParameterFilter = { + $Path -eq 'HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' -and $Name -eq 'EnableDNS' + } + + $invokeCimMethod_EnableAll_ParameterFilter = { + $ClassName -eq 'Win32_NetworkAdapterConfiguration' ` + -and $MethodName -eq 'EnableWins' ` + -and $Arguments.DNSEnabledForWINSResolution -eq $true ` + -and $Arguments.WINSEnableLMHostsLookup -eq $true + } + + $invokeCimMethod_DisableAll_ParameterFilter = { + $ClassName -eq 'Win32_NetworkAdapterConfiguration' ` + -and $MethodName -eq 'EnableWins' ` + -and $Arguments.DNSEnabledForWINSResolution -eq $false ` + -and $Arguments.WINSEnableLMHostsLookup -eq $false + } + + Describe 'MSFT_xWinsSetting\Get-TargetResource' { + Context 'EnableLmHosts is enabled and EnableDns is enabled' { + Mock ` + -CommandName Get-ItemProperty ` + -ParameterFilter $getItemProperty_EnableLmHosts_ParameterFilter ` + -MockWith $mockEnabledLmHostsRegistryKey + + Mock ` + -CommandName Get-ItemProperty ` + -ParameterFilter $getItemProperty_EnableDns_ParameterFilter ` + -MockWith $mockEnabledDNSRegistryKey + + It 'Should not throw an exception' { + { $script:result = Get-TargetResource -IsSingleInstance 'Yes' -Verbose } | Should -Not -Throw + } + + It 'Should return expected results' { + $script:result.EnableLmHosts | Should Be $true + $script:result.EnableDns | Should Be $true + } + + It 'Should call the expected mocks' { + Assert-MockCalled ` + -CommandName Get-ItemProperty ` + -ParameterFilter $getItemProperty_EnableLmHosts_ParameterFilter ` + -Exactly -Times 1 + + Assert-MockCalled ` + -CommandName Get-ItemProperty ` + -ParameterFilter $getItemProperty_EnableDns_ParameterFilter ` + -Exactly -Times 1 + } + } + + Context 'EnableLmHosts is disabled and EnableDns is disabled' { + Mock ` + -CommandName Get-ItemProperty ` + -ParameterFilter $getItemProperty_EnableLmHosts_ParameterFilter ` + -MockWith $mockDisabledLmHostsRegistryKey + + Mock ` + -CommandName Get-ItemProperty ` + -ParameterFilter $getItemProperty_EnableDns_ParameterFilter ` + -MockWith $mockDisabledDNSRegistryKey + + It 'Should not throw an exception' { + { $script:result = Get-TargetResource -IsSingleInstance 'Yes' -Verbose } | Should -Not -Throw + } + + It 'Should return expected results' { + $script:result.EnableLmHosts | Should Be $false + $script:result.EnableDns | Should Be $false + } + + It 'Should call the expected mocks' { + Assert-MockCalled ` + -CommandName Get-ItemProperty ` + -ParameterFilter $getItemProperty_EnableLmHosts_ParameterFilter ` + -Exactly -Times 1 + + Assert-MockCalled ` + -CommandName Get-ItemProperty ` + -ParameterFilter $getItemProperty_EnableDns_ParameterFilter ` + -Exactly -Times 1 + } + } + } + + Describe 'MSFT_xDnsClientGlobalSetting\Set-TargetResource' { + BeforeEach { + Mock -CommandName Get-TargetResource -MockWith { $mockGetTargetResourceAllEnabled } + } + + Context 'Set EnableLmHosts to enabled and EnableDns to enabled' { + Mock ` + -CommandName Invoke-CimMethod ` + -ParameterFilter $invokeCimMethod_EnableAll_ParameterFilter ` + -MockWith $mockInvokeCimMethodReturnValueOK + + It 'Should not throw an exception' { + { + Set-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $true -EnableDns $true -Verbose + } | Should -Not -Throw + } + + It 'Should call expected Mocks' { + Assert-MockCalled ` + -CommandName Invoke-CimMethod ` + -ParameterFilter $invokeCimMethod_EnableAll_ParameterFilter ` + -Exactly -Times 1 + } + } + + Context 'Set EnableLmHosts to disabled and EnableDns to disabled' { + Mock ` + -CommandName Invoke-CimMethod ` + -ParameterFilter $invokeCimMethod_DisableAll_ParameterFilter ` + -MockWith $mockInvokeCimMethodReturnValueOK + + It 'Should not throw an exception' { + { + Set-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $false -EnableDns $false -Verbose + } | Should -Not -Throw + } + + It 'Should call expected Mocks' { + Assert-MockCalled ` + -CommandName Invoke-CimMethod ` + -ParameterFilter $invokeCimMethod_DisableAll_ParameterFilter ` ` + -Exactly -Times 1 + } + } + + Context 'Set EnableLmHosts and EnableDNS but Invoke-CimMethod returns error' { + Mock ` + -CommandName Invoke-CimMethod ` + -ParameterFilter $invokeCimMethod_EnableAll_ParameterFilter ` ` + -MockWith $mockInvokeCimMethodReturnValueError + + $errorRecord = Get-InvalidOperationRecord ` + -Message ($LocalizedData.FailedUpdatingWinsSettingError -f 74, 'Enable') + + It 'Should throw an exception' { + { + Set-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $true -EnableDns $true -Verbose + } | Should -Throw $errorRecord + } + + It 'Should call expected Mocks' { + Assert-MockCalled ` + -CommandName Invoke-CimMethod ` + -ParameterFilter $invokeCimMethod_EnableAll_ParameterFilter ` ` + -Exactly -Times 1 + } + } + } + + Describe 'MSFT_xDnsClientGlobalSetting\Test-TargetResource' { + Context 'EnableLmHosts is enabled and EnableDns is enabled' { + Context 'Set EnableLmHosts to true and EnableDns to true' { + Mock -CommandName Get-TargetResource -MockWith $mockGetTargetResourceAllEnabled + + It 'Should not throw an exception' { + { + $script:result = Test-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $true -EnableDns $true -Verbose + } | Should -Not -Throw + } + + It 'Should return true' { + $script:result | Should -Be $true + } + } + + Context 'Set EnableLmHosts to false' { + Mock -CommandName Get-TargetResource -MockWith $mockGetTargetResourceAllEnabled + + It 'Should not throw an exception' { + { + $script:result = Test-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $false -Verbose + } | Should -Not -Throw + } + + It 'Should return false' { + $script:result | Should -Be $false + } + } + + Context 'Set EnableDns to false' { + Mock -CommandName Get-TargetResource -MockWith $mockGetTargetResourceAllEnabled + + It 'Should not throw an exception' { + { + $script:result = Test-TargetResource -IsSingleInstance 'Yes' -EnableDns $false -Verbose + } | Should -Not -Throw + } + + It 'Should return false' { + $script:result | Should -Be $false + } + } + } + + 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 true' { + $script:result | Should -Be $true + } + } + + Context 'Set EnableLmHosts to true' { + Mock -CommandName Get-TargetResource -MockWith $mockGetTargetResourceAllDisabled + + It 'Should not throw an exception' { + { + $script:result = Test-TargetResource -IsSingleInstance 'Yes' -EnableLmHosts $true -Verbose + } | Should -Not -Throw + } + + It 'Should return false' { + $script:result | Should -Be $false + } + } + + 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' { + $script:result | Should -Be $false + } + } + } + } + } + #endregion +} +finally +{ + #region FOOTER + Restore-TestEnvironment -TestEnvironment $TestEnvironment + #endregion +} diff --git a/Tests/Unit/NetworkingDsc.Common.tests.ps1 b/Tests/Unit/NetworkingDsc.Common.tests.ps1 index 07036cef..0eba1662 100644 --- a/Tests/Unit/NetworkingDsc.Common.tests.ps1 +++ b/Tests/Unit/NetworkingDsc.Common.tests.ps1 @@ -6,9 +6,9 @@ Import-Module -Name (Join-Path -Path (Join-Path -Path (Split-Path $PSScriptRoot # Unit Test Template Version: 1.1.0 [string] $script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xNetworking' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -47,7 +47,7 @@ try } } 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') + $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' @@ -462,7 +462,7 @@ try -MockWith { $multipleMatchingAdapterArray } $errorRecord = Get-InvalidOperationRecord ` - -Message ($LocalizedData.InvalidNetAdapterNumberError -f 2,3) + -Message ($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 @@ -483,14 +483,14 @@ try an exception because the GetAdapter module has no manifest #> InModuleScope $script:ModuleName { - Describe "NetworkingDsc.Common\Get-DnsClientServerStaticAddress" { + 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 + InterfaceGuid = $interfaceGuid } $ipv4Parameters = @{ InterfaceAlias = $interfaceAlias @@ -534,10 +534,10 @@ try Mock ` -CommandName Get-ItemProperty ` -MockWith { - [psobject] @{ - NameServer = $noIpv4StaticAddressString - } + [psobject] @{ + NameServer = $noIpv4StaticAddressString } + } It 'Should not throw exception' { { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters -Verbose } | Should Not Throw @@ -561,10 +561,10 @@ try Mock ` -CommandName Get-ItemProperty ` -MockWith { - [psobject] @{ - Dummy = '' - } + [psobject] @{ + Dummy = '' } + } It 'Should not throw exception' { { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters -Verbose } | Should Not Throw @@ -588,10 +588,10 @@ try Mock ` -CommandName Get-ItemProperty ` -MockWith { - [psobject] @{ - NameServer = $oneIpv4StaticAddressString - } + [psobject] @{ + NameServer = $oneIpv4StaticAddressString } + } It 'Should not throw exception' { { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters -Verbose } | Should Not Throw @@ -615,10 +615,10 @@ try Mock ` -CommandName Get-ItemProperty ` -MockWith { - [psobject] @{ - NameServer = $twoIpv4StaticAddressString - } + [psobject] @{ + NameServer = $twoIpv4StaticAddressString } + } It 'Should not throw exception' { { $script:result = Get-DnsClientServerStaticAddress @ipv4Parameters -Verbose } | Should Not Throw @@ -643,10 +643,10 @@ try Mock ` -CommandName Get-ItemProperty ` -MockWith { - [psobject] @{ - NameServer = $noIpv6StaticAddressString - } + [psobject] @{ + NameServer = $noIpv6StaticAddressString } + } It 'Should not throw exception' { { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters -Verbose } | Should Not Throw @@ -670,10 +670,10 @@ try Mock ` -CommandName Get-ItemProperty ` -MockWith { - [psobject] @{ - Dummy = '' - } + [psobject] @{ + Dummy = '' } + } It 'Should not throw exception' { { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters -Verbose } | Should Not Throw @@ -697,10 +697,10 @@ try Mock ` -CommandName Get-ItemProperty ` -MockWith { - [psobject] @{ - NameServer = $oneIpv6StaticAddressString - } + [psobject] @{ + NameServer = $oneIpv6StaticAddressString } + } It 'Should not throw exception' { { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters -Verbose } | Should Not Throw @@ -724,10 +724,10 @@ try Mock ` -CommandName Get-ItemProperty ` -MockWith { - [psobject] @{ - NameServer = $twoIpv6StaticAddressString - } + [psobject] @{ + NameServer = $twoIpv6StaticAddressString } + } It 'Should not throw exception' { { $script:result = Get-DnsClientServerStaticAddress @ipv6Parameters -Verbose } | Should Not Throw @@ -748,7 +748,7 @@ try #endregion #region Function Get-IPAddressPrefix - Describe "NetworkingDsc.Common\Get-IPAddressPrefix" { + 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' @@ -803,6 +803,431 @@ try } } } + + InModuleScope $script:ModuleName { + Describe 'NetworkingDsc.Common\Remove-CommonParameter' { + $removeCommonParameter = @{ + Parameter1 = 'value1' + Parameter2 = 'value2' + Verbose = $true + Debug = $true + ErrorAction = 'Stop' + WarningAction = 'Stop' + InformationAction = 'Stop' + ErrorVariable = 'errorVariable' + WarningVariable = 'warningVariable' + OutVariable = 'outVariable' + OutBuffer = 'outBuffer' + PipelineVariable = 'pipelineVariable' + InformationVariable = 'informationVariable' + WhatIf = $true + Confirm = $true + UseTransaction = $true + } + + Context 'Hashtable contains all common parameters' { + It 'Should not throw exception' { + { $script:result = Remove-CommonParameter -Hashtable $removeCommonParameter -Verbose } | Should -Not -Throw + } + + It 'Should have retained parameters in the hashtable' { + $script:result.Contains('Parameter1') | Should -Be $true + $script:result.Contains('Parameter2') | Should -Be $true + } + + It 'Should have removed the common parameters from the hashtable' { + $script:result.Contains('Verbose') | Should -Be $false + $script:result.Contains('Debug') | Should -Be $false + $script:result.Contains('ErrorAction') | Should -Be $false + $script:result.Contains('WarningAction') | Should -Be $false + $script:result.Contains('InformationAction') | Should -Be $false + $script:result.Contains('ErrorVariable') | Should -Be $false + $script:result.Contains('WarningVariable') | Should -Be $false + $script:result.Contains('OutVariable') | Should -Be $false + $script:result.Contains('OutBuffer') | Should -Be $false + $script:result.Contains('PipelineVariable') | Should -Be $false + $script:result.Contains('InformationVariable') | Should -Be $false + $script:result.Contains('WhatIf') | Should -Be $false + $script:result.Contains('Confirm') | Should -Be $false + $script:result.Contains('UseTransaction') | Should -Be $false + } + } + } + + Describe 'NetworkingDsc.Common\Test-DscParameterState' { + Context 'All current parameters match desired parameters' { + $currentValues = @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $desiredValues = [PSObject] @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $valuesToCheck = @( + 'parameterString' + 'parameterBool' + 'ParameterInt' + 'ParameterArray' + ) + + It 'Should not throw exception' { + { $script:result = Test-DscParameterState ` + -CurrentValues $currentValues ` + -DesiredValues $desiredValues ` + -ValuesToCheck $valuesToCheck ` + -Verbose } | Should -Not -Throw + } + + It 'Should return $true' { + $script:result | Should -Be $true + } + } + + Context 'The current parameters do not match desired parameters because a string mismatches' { + $currentValues = @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $desiredValues = [PSObject] @{ + parameterString = 'different string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $valuesToCheck = @( + 'parameterString' + 'parameterBool' + 'ParameterInt' + 'ParameterArray' + ) + + It 'Should not throw exception' { + { $script:result = Test-DscParameterState ` + -CurrentValues $currentValues ` + -DesiredValues $desiredValues ` + -ValuesToCheck $valuesToCheck ` + -Verbose } | Should -Not -Throw + } + + It 'Should return $false' { + $script:result | Should -Be $false + } + } + + Context 'The current parameters do not match desired parameters because a boolean mismatches' { + $currentValues = @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $desiredValues = [PSObject] @{ + parameterString = 'a string' + parameterBool = $false + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $valuesToCheck = @( + 'parameterString' + 'parameterBool' + 'ParameterInt' + 'ParameterArray' + ) + + It 'Should not throw exception' { + { $script:result = Test-DscParameterState ` + -CurrentValues $currentValues ` + -DesiredValues $desiredValues ` + -ValuesToCheck $valuesToCheck ` + -Verbose } | Should -Not -Throw + } + + It 'Should return $false' { + $script:result | Should -Be $false + } + } + + Context 'The current parameters do not match desired parameters because a int mismatches' { + $currentValues = @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $desiredValues = [PSObject] @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 1 + parameterArray = @( 'a', 'b', 'c' ) + } + + $valuesToCheck = @( + 'parameterString' + 'parameterBool' + 'ParameterInt' + 'ParameterArray' + ) + + It 'Should not throw exception' { + { $script:result = Test-DscParameterState ` + -CurrentValues $currentValues ` + -DesiredValues $desiredValues ` + -ValuesToCheck $valuesToCheck ` + -Verbose } | Should -Not -Throw + } + + It 'Should return $false' { + $script:result | Should -Be $false + } + } + + Context 'The current parameters do not match desired parameters because an array is missing a value' { + $currentValues = @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $desiredValues = [PSObject] @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 1 + parameterArray = @( 'a', 'b' ) + } + + $valuesToCheck = @( + 'parameterString' + 'parameterBool' + 'ParameterInt' + 'ParameterArray' + ) + + It 'Should not throw exception' { + { $script:result = Test-DscParameterState ` + -CurrentValues $currentValues ` + -DesiredValues $desiredValues ` + -ValuesToCheck $valuesToCheck ` + -Verbose } | Should -Not -Throw + } + + It 'Should return $false' { + $script:result | Should -Be $false + } + } + + Context 'The current parameters do not match desired parameters because an array has an additional value' { + $currentValues = @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $desiredValues = [PSObject] @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 1 + parameterArray = @( 'a', 'b', 'c', 'd' ) + } + + $valuesToCheck = @( + 'parameterString' + 'parameterBool' + 'ParameterInt' + 'ParameterArray' + ) + + It 'Should not throw exception' { + { $script:result = Test-DscParameterState ` + -CurrentValues $currentValues ` + -DesiredValues $desiredValues ` + -ValuesToCheck $valuesToCheck ` + -Verbose } | Should -Not -Throw + } + + It 'Should return $false' { + $script:result | Should -Be $false + } + } + + Context 'The current parameters do not match desired parameters because an array has a different value' { + $currentValues = @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $desiredValues = [PSObject] @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 1 + parameterArray = @( 'a', 'd', 'c' ) + } + + $valuesToCheck = @( + 'parameterString' + 'parameterBool' + 'ParameterInt' + 'ParameterArray' + ) + + It 'Should not throw exception' { + { $script:result = Test-DscParameterState ` + -CurrentValues $currentValues ` + -DesiredValues $desiredValues ` + -ValuesToCheck $valuesToCheck ` + -Verbose } | Should -Not -Throw + } + + It 'Should return $false' { + $script:result | Should -Be $false + } + } + + Context 'The current parameters do not match desired parameters because an array has a different type' { + $currentValues = @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $desiredValues = [PSObject] @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 1 + parameterArray = @( 'a', 1, 'c' ) + } + + $valuesToCheck = @( + 'parameterString' + 'parameterBool' + 'ParameterInt' + 'ParameterArray' + ) + + It 'Should not throw exception' { + { $script:result = Test-DscParameterState ` + -CurrentValues $currentValues ` + -DesiredValues $desiredValues ` + -ValuesToCheck $valuesToCheck ` + -Verbose } | Should -Not -Throw + } + + It 'Should return $false' { + $script:result | Should -Be $false + } + } + + Context 'The current parameters do not match desired parameters because a parameter has a different type' { + $currentValues = @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $desiredValues = [PSObject] @{ + parameterString = $false + parameterBool = $true + parameterInt = 1 + parameterArray = @( 'a', 'b', 'c' ) + } + + $valuesToCheck = @( + 'parameterString' + 'parameterBool' + 'ParameterInt' + 'ParameterArray' + ) + + It 'Should not throw exception' { + { $script:result = Test-DscParameterState ` + -CurrentValues $currentValues ` + -DesiredValues $desiredValues ` + -ValuesToCheck $valuesToCheck ` + -Verbose } | Should -Not -Throw + } + + It 'Should return $false' { + $script:result | Should -Be $false + } + } + + Context 'Some of the current parameters do not match desired parameters but only matching parameter is compared' { + $currentValues = @{ + parameterString = 'a string' + parameterBool = $true + parameterInt = 99 + parameterArray = @( 'a', 'b', 'c' ) + } + + $desiredValues = [PSObject] @{ + parameterString = 'a string' + parameterBool = $false + parameterInt = 1 + parameterArray = @( 'a', 'b' ) + } + + $valuesToCheck = @( + 'parameterString' + ) + + It 'Should not throw exception' { + { $script:result = Test-DscParameterState ` + -CurrentValues $currentValues ` + -DesiredValues $desiredValues ` + -ValuesToCheck $valuesToCheck ` + -Verbose } | Should -Not -Throw + } + + It 'Should return $true' { + $script:result | Should -Be $true + } + } + + Describe 'NetworkingDsc.Common\Test-DscObjectHasProperty' { + # Use the Get-Verb cmdlet to just get a simple object fast + $testDscObject = (Get-Verb)[0] + + Context 'The object contains the expected property' { + It 'Should not throw exception' { + { $script:result = Test-DscObjectHasProperty -Object $testDscObject -PropertyName 'Verb' -Verbose } | Should -Not -Throw + } + + It 'Should return $true' { + $script:result | Should -Be $true + } + } + + Context 'The object does not contain the expected property' { + It 'Should not throw exception' { + { $script:result = Test-DscObjectHasProperty -Object $testDscObject -PropertyName 'Missing' -Verbose } | Should -Not -Throw + } + + It 'Should return $false' { + $script:result | Should -Be $false + } + } + } + } + } } finally {