diff options
author | Jordan Borean <jborean93@gmail.com> | 2021-11-11 02:04:39 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-11-11 02:04:39 +0100 |
commit | 9985b8a9756c570811d0f221bc11ffc9354f291f (patch) | |
tree | 63c9ade93cd52a860a7537d0f1f7aab53fcad67f /test/integration/targets | |
parent | Docs: Link to valid data types for role parameters (#76276) (diff) | |
download | ansible-9985b8a9756c570811d0f221bc11ffc9354f291f.tar.xz ansible-9985b8a9756c570811d0f221bc11ffc9354f291f.zip |
ansible-test pssa update and new rules (#76256)
Diffstat (limited to 'test/integration/targets')
32 files changed, 2261 insertions, 2078 deletions
diff --git a/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/module_utils/PSUtil.psm1 b/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/module_utils/PSUtil.psm1 index d37e681a8a..f23b99e7f9 100644 --- a/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/module_utils/PSUtil.psm1 +++ b/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/module_utils/PSUtil.psm1 @@ -8,7 +8,7 @@ Function Get-PSUtilSpec { #> @{ options = @{ - option1 = @{ type = 'str'; required = $true; aliases = 'alias1' } + option1 = @{ type = 'str'; required = $true; aliases = 'alias1' } } } } diff --git a/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/win_util_args.ps1 b/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/win_util_args.ps1 index 9dab99da92..69922cd617 100644 --- a/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/win_util_args.ps1 +++ b/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/win_util_args.ps1 @@ -8,7 +8,7 @@ $spec = @{ options = @{ - my_opt = @{ type = "str"; required = $true } + my_opt = @{ type = "str"; required = $true } } } diff --git a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/win_selfcontained.ps1 b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/win_selfcontained.ps1 index 661bc0f6fe..986d5157ed 100644 --- a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/win_selfcontained.ps1 +++ b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/win_selfcontained.ps1 @@ -1,9 +1,9 @@ #!powershell $res = @{ - changed = $false - source = "user" - msg = "hi from selfcontained.ps1" + changed = $false + source = "user" + msg = "hi from selfcontained.ps1" } ConvertTo-Json $res
\ No newline at end of file diff --git a/test/integration/targets/module_utils_Ansible.AccessToken/library/ansible_access_token_tests.ps1 b/test/integration/targets/module_utils_Ansible.AccessToken/library/ansible_access_token_tests.ps1 index 5e3a0af5a1..a1de2b4e9e 100644 --- a/test/integration/targets/module_utils_Ansible.AccessToken/library/ansible_access_token_tests.ps1 +++ b/test/integration/targets/module_utils_Ansible.AccessToken/library/ansible_access_token_tests.ps1 @@ -15,38 +15,41 @@ $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec) $test_username = $module.Params.test_username $test_password = $module.Params.test_password -Function Assert-Equals { +Function Assert-Equal { param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected + [Parameter(Mandatory = $true, ValueFromPipeline = $true)][AllowNull()]$Actual, + [Parameter(Mandatory = $true, Position = 0)][AllowNull()]$Expected ) - $matched = $false - if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { - $Actual.Count | Assert-Equals -Expected $Expected.Count - for ($i = 0; $i -lt $Actual.Count; $i++) { - $actual_value = $Actual[$i] - $expected_value = $Expected[$i] - Assert-Equals -Actual $actual_value -Expected $expected_value + process { + $matched = $false + if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { + $Actual.Count | Assert-Equal -Expected $Expected.Count + for ($i = 0; $i -lt $Actual.Count; $i++) { + $actual_value = $Actual[$i] + $expected_value = $Expected[$i] + Assert-Equal -Actual $actual_value -Expected $expected_value + } + $matched = $true } - $matched = $true - } else { - $matched = $Actual -ceq $Expected - } - - if (-not $matched) { - if ($Actual -is [PSObject]) { - $Actual = $Actual.ToString() + else { + $matched = $Actual -ceq $Expected } - $call_stack = (Get-PSCallStack)[1] - $module.Result.test = $test - $module.Result.actual = $Actual - $module.Result.expected = $Expected - $module.Result.line = $call_stack.ScriptLineNumber - $module.Result.method = $call_stack.Position.Text + if (-not $matched) { + if ($Actual -is [PSObject]) { + $Actual = $Actual.ToString() + } + + $call_stack = (Get-PSCallStack)[1] + $module.Result.test = $test + $module.Result.actual = $Actual + $module.Result.expected = $Expected + $module.Result.line = $call_stack.ScriptLineNumber + $module.Result.method = $call_stack.Position.Text - $module.FailJson("AssertionError: actual != expected") + $module.FailJson("AssertionError: actual != expected") + } } } @@ -58,15 +61,16 @@ $tests = [Ordered]@{ $h_token = [Ansible.AccessToken.TokenUtil]::OpenProcessToken($h_process, "Query") try { - $h_token.IsClosed | Assert-Equals -Expected $false - $h_token.IsInvalid | Assert-Equals -Expected $false + $h_token.IsClosed | Assert-Equal -Expected $false + $h_token.IsInvalid | Assert-Equal -Expected $false $actual_user = [Ansible.AccessToken.TokenUtil]::GetTokenUser($h_token) - $actual_user | Assert-Equals -Expected $current_user - } finally { + $actual_user | Assert-Equal -Expected $current_user + } + finally { $h_token.Dispose() } - $h_token.IsClosed | Assert-Equals -Expected $true + $h_token.IsClosed | Assert-Equal -Expected $true } "Open process token of another process" = { @@ -74,21 +78,24 @@ $tests = [Ordered]@{ try { $h_process = [Ansible.AccessToken.TokenUtil]::OpenProcess($proc_info.Id, "QueryInformation", $false) try { - $h_process.IsClosed | Assert-Equals -Expected $false - $h_process.IsInvalid | Assert-Equals -Expected $false + $h_process.IsClosed | Assert-Equal -Expected $false + $h_process.IsInvalid | Assert-Equal -Expected $false $h_token = [Ansible.AccessToken.TokenUtil]::OpenProcessToken($h_process, "Query") try { $actual_user = [Ansible.AccessToken.TokenUtil]::GetTokenUser($h_token) - $actual_user | Assert-Equals -Expected $current_user - } finally { + $actual_user | Assert-Equal -Expected $current_user + } + finally { $h_token.Dispose() } - } finally { + } + finally { $h_process.Dispose() } - $h_process.IsClosed | Assert-Equals -Expected $true - } finally { + $h_process.IsClosed | Assert-Equal -Expected $true + } + finally { $proc_info | Stop-Process } } @@ -98,11 +105,13 @@ $tests = [Ordered]@{ try { $h_process = [Ansible.AccessToken.TokenUtil]::OpenProcess(4, "QueryInformation", $false) $h_process.Dispose() # Incase this doesn't fail, make sure we still dispose of it - } catch [Ansible.AccessToken.Win32Exception] { + } + catch [Ansible.AccessToken.Win32Exception] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "Failed to open process 4 with access QueryInformation (Access is denied, Win32ErrorCode 5 - 0x00000005)" + $msg = "Failed to open process 4 with access QueryInformation (Access is denied, Win32ErrorCode 5 - 0x00000005)" + $_.Exception.Message | Assert-Equal -Expected $msg } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "Duplicate access token primary" = { @@ -111,22 +120,24 @@ $tests = [Ordered]@{ try { $dup_token = [Ansible.AccessToken.TokenUtil]::DuplicateToken($h_token, "Query", "Anonymous", "Primary") try { - $dup_token.IsClosed | Assert-Equals -Expected $false - $dup_token.IsInvalid | Assert-Equals -Expected $false + $dup_token.IsClosed | Assert-Equal -Expected $false + $dup_token.IsInvalid | Assert-Equal -Expected $false $actual_user = [Ansible.AccessToken.TokenUtil]::GetTokenUser($dup_token) - $actual_user | Assert-Equals -Expected $current_user + $actual_user | Assert-Equal -Expected $current_user $actual_stat = [Ansible.AccessToken.TokenUtil]::GetTokenStatistics($dup_token) - $actual_stat.TokenType | Assert-Equals -Expected ([Ansible.AccessToken.TokenType]::Primary) - $actual_stat.ImpersonationLevel | Assert-Equals -Expected ([Ansible.AccessToken.SecurityImpersonationLevel]::Anonymous) - } finally { + $actual_stat.TokenType | Assert-Equal -Expected ([Ansible.AccessToken.TokenType]::Primary) + $actual_stat.ImpersonationLevel | Assert-Equal -Expected ([Ansible.AccessToken.SecurityImpersonationLevel]::Anonymous) + } + finally { $dup_token.Dispose() } - $dup_token.IsClosed | Assert-Equals -Expected $true - } finally { + $dup_token.IsClosed | Assert-Equal -Expected $true + } + finally { $h_token.Dispose() } } @@ -140,16 +151,18 @@ $tests = [Ordered]@{ try { $actual_user = [Ansible.AccessToken.TokenUtil]::GetTokenUser($dup_token) - $actual_user | Assert-Equals -Expected $current_user + $actual_user | Assert-Equal -Expected $current_user $actual_stat = [Ansible.AccessToken.TokenUtil]::GetTokenStatistics($dup_token) - $actual_stat.TokenType | Assert-Equals -Expected ([Ansible.AccessToken.TokenType]::Impersonation) - $actual_stat.ImpersonationLevel | Assert-Equals -Expected ([Ansible.AccessToken.SecurityImpersonationLevel]"$_") - } finally { + $actual_stat.TokenType | Assert-Equal -Expected ([Ansible.AccessToken.TokenType]::Impersonation) + $actual_stat.ImpersonationLevel | Assert-Equal -Expected ([Ansible.AccessToken.SecurityImpersonationLevel]"$_") + } + finally { $dup_token.Dispose() } } - } finally { + } + finally { $h_token.Dispose() } } @@ -162,25 +175,26 @@ $tests = [Ordered]@{ $tested = $false foreach ($h_token in [Ansible.AccessToken.TokenUtil]::EnumerateUserTokens($system_sid, "Duplicate, Impersonate, Query")) { $actual_user = [Ansible.AccessToken.TokenUtil]::GetTokenUser($h_token) - $actual_user | Assert-Equals -Expected $system_sid + $actual_user | Assert-Equal -Expected $system_sid [Ansible.AccessToken.TokenUtil]::ImpersonateToken($h_token) try { $current_sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User - $current_sid | Assert-Equals -Expected $system_sid - } finally { + $current_sid | Assert-Equal -Expected $system_sid + } + finally { [Ansible.AccessToken.TokenUtil]::RevertToSelf() } $current_sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User - $current_sid | Assert-Equals -Expected $current_user + $current_sid | Assert-Equal -Expected $current_user # Will keep on looping for each SYSTEM token it can retrieve, we only want to test 1 $tested = $true break } - $tested | Assert-Equals -Expected $true + $tested | Assert-Equal -Expected $true } "Get token privileges" = { @@ -191,8 +205,8 @@ $tests = [Ordered]@{ $actual_privs = [Ansible.AccessToken.Tokenutil]::GetTokenPrivileges($h_token) $actual_stat = [Ansible.AccessToken.TokenUtil]::GetTokenStatistics($h_token) - $actual_privs.Count | Assert-Equals -Expected $priv_info.Count - $actual_privs.Count | Assert-Equals -Expected $actual_stat.PrivilegeCount + $actual_privs.Count | Assert-Equal -Expected $priv_info.Count + $actual_privs.Count | Assert-Equal -Expected $actual_stat.PrivilegeCount foreach ($info in $priv_info) { $info_split = $info.Split(" ", [System.StringSplitOptions]::RemoveEmptyEntries) @@ -200,14 +214,16 @@ $tests = [Ordered]@{ $priv_enabled = $info_split[-1] -eq "Enabled" $actual_priv = $actual_privs | Where-Object { $_.Name -eq $priv_name } - $actual_priv -eq $null | Assert-Equals -Expected $false + $actual_priv -eq $null | Assert-Equal -Expected $false if ($priv_enabled) { - $actual_priv.Attributes.HasFlag([Ansible.AccessToken.PrivilegeAttributes]::Enabled) | Assert-Equals -Expected $true - } else { - $actual_priv.Attributes.HasFlag([Ansible.AccessToken.PrivilegeAttributes]::Disabled) | Assert-Equals -Expected $true + $actual_priv.Attributes.HasFlag([Ansible.AccessToken.PrivilegeAttributes]::Enabled) | Assert-Equal -Expected $true + } + else { + $actual_priv.Attributes.HasFlag([Ansible.AccessToken.PrivilegeAttributes]::Disabled) | Assert-Equal -Expected $true } } - } finally { + } + finally { $h_token.Dispose() } } @@ -219,25 +235,27 @@ $tests = [Ordered]@{ $actual_priv = [Ansible.AccessToken.Tokenutil]::GetTokenPrivileges($h_token) $actual_stat = [Ansible.AccessToken.TokenUtil]::GetTokenStatistics($h_token) - $actual_stat.TokenId.GetType().FullName | Assert-Equals -Expected "Ansible.AccessToken.Luid" - $actual_stat.AuthenticationId.GetType().FullName | Assert-Equals -Expected "Ansible.AccessToken.Luid" - $actual_stat.ExpirationTime.GetType().FullName | Assert-Equals -Expected "System.Int64" + $actual_stat.TokenId.GetType().FullName | Assert-Equal -Expected "Ansible.AccessToken.Luid" + $actual_stat.AuthenticationId.GetType().FullName | Assert-Equal -Expected "Ansible.AccessToken.Luid" + $actual_stat.ExpirationTime.GetType().FullName | Assert-Equal -Expected "System.Int64" - $actual_stat.TokenType | Assert-Equals -Expected ([Ansible.AccessToken.TokenType]::Primary) + $actual_stat.TokenType | Assert-Equal -Expected ([Ansible.AccessToken.TokenType]::Primary) $os_version = [Version](Get-Item -LiteralPath $env:SystemRoot\System32\kernel32.dll).VersionInfo.ProductVersion if ($os_version -lt [Version]"6.1") { # While the token is a primary token, Server 2008 reports the SecurityImpersonationLevel for a primary token as Impersonation - $actual_stat.ImpersonationLevel | Assert-Equals -Expected ([Ansible.AccessToken.SecurityImpersonationLevel]::Impersonation) - } else { - $actual_stat.ImpersonationLevel | Assert-Equals -Expected ([Ansible.AccessToken.SecurityImpersonationLevel]::Anonymous) + $actual_stat.ImpersonationLevel | Assert-Equal -Expected ([Ansible.AccessToken.SecurityImpersonationLevel]::Impersonation) + } + else { + $actual_stat.ImpersonationLevel | Assert-Equal -Expected ([Ansible.AccessToken.SecurityImpersonationLevel]::Anonymous) } - $actual_stat.DynamicCharged.GetType().FullName | Assert-Equals -Expected "System.UInt32" - $actual_stat.DynamicAvailable.GetType().FullName | Assert-Equals -Expected "System.UInt32" - $actual_stat.GroupCount.GetType().FullName | Assert-Equals -Expected "System.UInt32" - $actual_stat.PrivilegeCount | Assert-Equals -Expected $actual_priv.Count - $actual_stat.ModifiedId.GetType().FullName | Assert-Equals -Expected "Ansible.AccessToken.Luid" - } finally { + $actual_stat.DynamicCharged.GetType().FullName | Assert-Equal -Expected "System.UInt32" + $actual_stat.DynamicAvailable.GetType().FullName | Assert-Equal -Expected "System.UInt32" + $actual_stat.GroupCount.GetType().FullName | Assert-Equal -Expected "System.UInt32" + $actual_stat.PrivilegeCount | Assert-Equal -Expected $actual_priv.Count + $actual_stat.ModifiedId.GetType().FullName | Assert-Equal -Expected "Ansible.AccessToken.Luid" + } + finally { $h_token.Dispose() } } @@ -246,23 +264,25 @@ $tests = [Ordered]@{ $h_token = [Ansible.AccessToken.TokenUtil]::LogonUser($test_username, $null, $test_password, "Interactive", "Default") try { $actual_elevation_type = [Ansible.AccessToken.TokenUtil]::GetTokenElevationType($h_token) - $actual_elevation_type | Assert-Equals -Expected ([Ansible.AccessToken.TokenElevationType]::Limited) + $actual_elevation_type | Assert-Equal -Expected ([Ansible.AccessToken.TokenElevationType]::Limited) $actual_linked = [Ansible.AccessToken.TokenUtil]::GetTokenLinkedToken($h_token) try { - $actual_linked.IsClosed | Assert-Equals -Expected $false - $actual_linked.IsInvalid | Assert-Equals -Expected $false + $actual_linked.IsClosed | Assert-Equal -Expected $false + $actual_linked.IsInvalid | Assert-Equal -Expected $false $actual_elevation_type = [Ansible.AccessToken.TokenUtil]::GetTokenElevationType($actual_linked) - $actual_elevation_type | Assert-Equals -Expected ([Ansible.AccessToken.TokenElevationType]::Full) + $actual_elevation_type | Assert-Equal -Expected ([Ansible.AccessToken.TokenElevationType]::Full) $actual_stat = [Ansible.AccessToken.TokenUtil]::GetTokenStatistics($actual_linked) - $actual_stat.TokenType | Assert-Equals -Expected ([Ansible.AccessToken.TokenType]::Impersonation) - } finally { + $actual_stat.TokenType | Assert-Equal -Expected ([Ansible.AccessToken.TokenType]::Impersonation) + } + finally { $actual_linked.Dispose() } - $actual_linked.IsClosed | Assert-Equals -Expected $true - } finally { + $actual_linked.IsClosed | Assert-Equal -Expected $true + } + finally { $h_token.Dispose() } } @@ -286,29 +306,32 @@ $tests = [Ordered]@{ try { $actual_linked = [Ansible.AccessToken.TokenUtil]::GetTokenLinkedToken($h_token) try { - $actual_linked.IsClosed | Assert-Equals -Expected $false - $actual_linked.IsInvalid | Assert-Equals -Expected $false + $actual_linked.IsClosed | Assert-Equal -Expected $false + $actual_linked.IsInvalid | Assert-Equal -Expected $false $actual_elevation_type = [Ansible.AccessToken.TokenUtil]::GetTokenElevationType($actual_linked) - $actual_elevation_type | Assert-Equals -Expected ([Ansible.AccessToken.TokenElevationType]::Full) + $actual_elevation_type | Assert-Equal -Expected ([Ansible.AccessToken.TokenElevationType]::Full) $actual_stat = [Ansible.AccessToken.TokenUtil]::GetTokenStatistics($actual_linked) - $actual_stat.TokenType | Assert-Equals -Expected ([Ansible.AccessToken.TokenType]::Primary) - } finally { + $actual_stat.TokenType | Assert-Equal -Expected ([Ansible.AccessToken.TokenType]::Primary) + } + finally { $actual_linked.Dispose() } - $actual_linked.IsClosed | Assert-Equals -Expected $true - } finally { + $actual_linked.IsClosed | Assert-Equal -Expected $true + } + finally { [Ansible.AccessToken.TokenUtil]::RevertToSelf() } - } finally { + } + finally { $h_token.Dispose() } $tested = $true break } - $tested | Assert-Equals -Expected $true + $tested | Assert-Equal -Expected $true } "Failed to get token information" = { @@ -318,13 +341,16 @@ $tests = [Ordered]@{ $failed = $false try { [Ansible.AccessToken.TokenUtil]::GetTokenUser($h_token) - } catch [Ansible.AccessToken.Win32Exception] { + } + catch [Ansible.AccessToken.Win32Exception] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "GetTokenInformation(TokenUser) failed to get buffer length (Access is denied, Win32ErrorCode 5 - 0x00000005)" - } finally { + $msg = "GetTokenInformation(TokenUser) failed to get buffer length (Access is denied, Win32ErrorCode 5 - 0x00000005)" + $_.Exception.Message | Assert-Equal -Expected $msg + } + finally { $h_token.Dispose() } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "Logon with valid credentials" = { @@ -333,39 +359,42 @@ $tests = [Ordered]@{ $h_token = [Ansible.AccessToken.TokenUtil]::LogonUser($test_username, $null, $test_password, "Network", "Default") try { - $h_token.IsClosed | Assert-Equals -Expected $false - $h_token.IsInvalid | Assert-Equals -Expected $false + $h_token.IsClosed | Assert-Equal -Expected $false + $h_token.IsInvalid | Assert-Equal -Expected $false $actual_user = [Ansible.AccessToken.TokenUtil]::GetTokenUser($h_token) - $actual_user | Assert-Equals -Expected $expected_sid - } finally { + $actual_user | Assert-Equal -Expected $expected_sid + } + finally { $h_token.Dispose() } - $h_token.IsClosed | Assert-Equals -Expected $true + $h_token.IsClosed | Assert-Equal -Expected $true } "Logon with invalid credentials" = { $failed = $false try { [Ansible.AccessToken.TokenUtil]::LogonUser("fake-user", $null, "fake-pass", "Network", "Default") - } catch [Ansible.AccessToken.Win32Exception] { + } + catch [Ansible.AccessToken.Win32Exception] { $failed = $true - $_.Exception.Message.Contains("Failed to logon fake-user") | Assert-Equals -Expected $true - $_.Exception.Message.Contains("Win32ErrorCode 1326 - 0x0000052E)") | Assert-Equals -Expected $true + $_.Exception.Message.Contains("Failed to logon fake-user") | Assert-Equal -Expected $true + $_.Exception.Message.Contains("Win32ErrorCode 1326 - 0x0000052E)") | Assert-Equal -Expected $true } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "Logon with invalid credential with domain account" = { $failed = $false try { [Ansible.AccessToken.TokenUtil]::LogonUser("fake-user", "fake-domain", "fake-pass", "Network", "Default") - } catch [Ansible.AccessToken.Win32Exception] { + } + catch [Ansible.AccessToken.Win32Exception] { $failed = $true - $_.Exception.Message.Contains("Failed to logon fake-domain\fake-user") | Assert-Equals -Expected $true - $_.Exception.Message.Contains("Win32ErrorCode 1326 - 0x0000052E)") | Assert-Equals -Expected $true + $_.Exception.Message.Contains("Failed to logon fake-domain\fake-user") | Assert-Equal -Expected $true + $_.Exception.Message.Contains("Win32ErrorCode 1326 - 0x0000052E)") | Assert-Equal -Expected $true } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } } diff --git a/test/integration/targets/module_utils_Ansible.Basic/library/ansible_basic_tests.ps1 b/test/integration/targets/module_utils_Ansible.Basic/library/ansible_basic_tests.ps1 index 9278e38682..cfa73c60c2 100644 --- a/test/integration/targets/module_utils_Ansible.Basic/library/ansible_basic_tests.ps1 +++ b/test/integration/targets/module_utils_Ansible.Basic/library/ansible_basic_tests.ps1 @@ -4,76 +4,85 @@ $module = [Ansible.Basic.AnsibleModule]::Create($args, @{}) -Function Assert-Equals { +Function Assert-Equal { param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected + [Parameter(Mandatory = $true, ValueFromPipeline = $true)][AllowNull()]$Actual, + [Parameter(Mandatory = $true, Position = 0)][AllowNull()]$Expected ) - $matched = $false - if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { - $Actual.Count | Assert-Equals -Expected $Expected.Count - for ($i = 0; $i -lt $Actual.Count; $i++) { - $actual_value = $Actual[$i] - $expected_value = $Expected[$i] - Assert-Equals -Actual $actual_value -Expected $expected_value + process { + $matched = $false + if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { + $Actual.Count | Assert-Equal -Expected $Expected.Count + for ($i = 0; $i -lt $Actual.Count; $i++) { + $actual_value = $Actual[$i] + $expected_value = $Expected[$i] + Assert-Equal -Actual $actual_value -Expected $expected_value + } + $matched = $true } - $matched = $true - } else { - $matched = $Actual -ceq $Expected - } - - if (-not $matched) { - if ($Actual -is [PSObject]) { - $Actual = $Actual.ToString() + else { + $matched = $Actual -ceq $Expected } - $call_stack = (Get-PSCallStack)[1] - $module.Result.failed = $true - $module.Result.test = $test - $module.Result.actual = $Actual - $module.Result.expected = $Expected - $module.Result.line = $call_stack.ScriptLineNumber - $module.Result.method = $call_stack.Position.Text - $module.Result.msg = "AssertionError: actual != expected" + if (-not $matched) { + if ($Actual -is [PSObject]) { + $Actual = $Actual.ToString() + } - Exit-Module + $call_stack = (Get-PSCallStack)[1] + $module.Result.failed = $true + $module.Result.test = $test + $module.Result.actual = $Actual + $module.Result.expected = $Expected + $module.Result.line = $call_stack.ScriptLineNumber + $module.Result.method = $call_stack.Position.Text + $module.Result.msg = "AssertionError: actual != expected" + + Exit-Module + } } } -Function Assert-DictionaryEquals { +Function Assert-DictionaryEqual { param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected + [Parameter(Mandatory = $true, ValueFromPipeline = $true)][AllowNull()]$Actual, + [Parameter(Mandatory = $true, Position = 0)][AllowNull()]$Expected ) - $actual_keys = $Actual.Keys - $expected_keys = $Expected.Keys - - $actual_keys.Count | Assert-Equals -Expected $expected_keys.Count - foreach ($actual_entry in $Actual.GetEnumerator()) { - $actual_key = $actual_entry.Key - ($actual_key -cin $expected_keys) | Assert-Equals -Expected $true - $actual_value = $actual_entry.Value - $expected_value = $Expected.$actual_key - - if ($actual_value -is [System.Collections.IDictionary]) { - $actual_value | Assert-DictionaryEquals -Expected $expected_value - } elseif ($actual_value -is [System.Collections.ArrayList] -or $actual_value -is [Array]) { - for ($i = 0; $i -lt $actual_value.Count; $i++) { - $actual_entry = $actual_value[$i] - $expected_entry = $expected_value[$i] - if ($actual_entry -is [System.Collections.IDictionary]) { - $actual_entry | Assert-DictionaryEquals -Expected $expected_entry - } else { - Assert-Equals -Actual $actual_entry -Expected $expected_entry + + process { + $actual_keys = $Actual.Keys + $expected_keys = $Expected.Keys + + $actual_keys.Count | Assert-Equal -Expected $expected_keys.Count + foreach ($actual_entry in $Actual.GetEnumerator()) { + $actual_key = $actual_entry.Key + ($actual_key -cin $expected_keys) | Assert-Equal -Expected $true + $actual_value = $actual_entry.Value + $expected_value = $Expected.$actual_key + + if ($actual_value -is [System.Collections.IDictionary]) { + $actual_value | Assert-DictionaryEqual -Expected $expected_value + } + elseif ($actual_value -is [System.Collections.ArrayList] -or $actual_value -is [Array]) { + for ($i = 0; $i -lt $actual_value.Count; $i++) { + $actual_entry = $actual_value[$i] + $expected_entry = $expected_value[$i] + if ($actual_entry -is [System.Collections.IDictionary]) { + $actual_entry | Assert-DictionaryEqual -Expected $expected_entry + } + else { + Assert-Equal -Actual $actual_entry -Expected $expected_entry + } } } - } else { - Assert-Equals -Actual $actual_value -Expected $expected_value + else { + Assert-Equal -Actual $actual_value -Expected $expected_value + } + } + foreach ($expected_key in $expected_keys) { + ($expected_key -cin $actual_keys) | Assert-Equal -Expected $true } - } - foreach ($expected_key in $expected_keys) { - ($expected_key -cin $actual_keys) | Assert-Equals -Expected $true } } @@ -104,28 +113,28 @@ $tests = @{ [System.IO.File]::WriteAllText($args_file, '{ "ANSIBLE_MODULE_ARGS": {} }') $m = [Ansible.Basic.AnsibleModule]::Create(@($args_file), @{}) - $m.CheckMode | Assert-Equals -Expected $false - $m.DebugMode | Assert-Equals -Expected $false - $m.DiffMode | Assert-Equals -Expected $false - $m.KeepRemoteFiles | Assert-Equals -Expected $false - $m.ModuleName | Assert-Equals -Expected "undefined win module" - $m.NoLog | Assert-Equals -Expected $false - $m.Verbosity | Assert-Equals -Expected 0 - $m.AnsibleVersion | Assert-Equals -Expected $null + $m.CheckMode | Assert-Equal -Expected $false + $m.DebugMode | Assert-Equal -Expected $false + $m.DiffMode | Assert-Equal -Expected $false + $m.KeepRemoteFiles | Assert-Equal -Expected $false + $m.ModuleName | Assert-Equal -Expected "undefined win module" + $m.NoLog | Assert-Equal -Expected $false + $m.Verbosity | Assert-Equal -Expected 0 + $m.AnsibleVersion | Assert-Equal -Expected $null } "Empty spec and no options - complex_args" = { Set-Variable -Name complex_args -Scope Global -Value @{} $m = [Ansible.Basic.AnsibleModule]::Create(@(), @{}) - $m.CheckMode | Assert-Equals -Expected $false - $m.DebugMode | Assert-Equals -Expected $false - $m.DiffMode | Assert-Equals -Expected $false - $m.KeepRemoteFiles | Assert-Equals -Expected $false - $m.ModuleName | Assert-Equals -Expected "undefined win module" - $m.NoLog | Assert-Equals -Expected $false - $m.Verbosity | Assert-Equals -Expected 0 - $m.AnsibleVersion | Assert-Equals -Expected $null + $m.CheckMode | Assert-Equal -Expected $false + $m.DebugMode | Assert-Equal -Expected $false + $m.DiffMode | Assert-Equal -Expected $false + $m.KeepRemoteFiles | Assert-Equal -Expected $false + $m.ModuleName | Assert-Equal -Expected "undefined win module" + $m.NoLog | Assert-Equal -Expected $false + $m.Verbosity | Assert-Equal -Expected 0 + $m.AnsibleVersion | Assert-Equal -Expected $null } "Internal param changes - args file" = { @@ -152,16 +161,16 @@ $tests = @{ } } "@) - $m = [Ansible.Basic.AnsibleModule]::Create(@($args_file), @{supports_check_mode=$true}) - $m.CheckMode | Assert-Equals -Expected $true - $m.DebugMode | Assert-Equals -Expected $true - $m.DiffMode | Assert-Equals -Expected $true - $m.KeepRemoteFiles | Assert-Equals -Expected $true - $m.ModuleName | Assert-Equals -Expected "ansible_basic_tests" - $m.NoLog | Assert-Equals -Expected $true - $m.Verbosity | Assert-Equals -Expected 3 - $m.AnsibleVersion | Assert-Equals -Expected "2.8.0" - $m.Tmpdir | Assert-Equals -Expected $m_tmpdir + $m = [Ansible.Basic.AnsibleModule]::Create(@($args_file), @{supports_check_mode = $true }) + $m.CheckMode | Assert-Equal -Expected $true + $m.DebugMode | Assert-Equal -Expected $true + $m.DiffMode | Assert-Equal -Expected $true + $m.KeepRemoteFiles | Assert-Equal -Expected $true + $m.ModuleName | Assert-Equal -Expected "ansible_basic_tests" + $m.NoLog | Assert-Equal -Expected $true + $m.Verbosity | Assert-Equal -Expected 3 + $m.AnsibleVersion | Assert-Equal -Expected "2.8.0" + $m.Tmpdir | Assert-Equal -Expected $m_tmpdir } "Internal param changes - complex_args" = { @@ -187,15 +196,15 @@ $tests = @{ supports_check_mode = $true } $m = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - $m.CheckMode | Assert-Equals -Expected $true - $m.DebugMode | Assert-Equals -Expected $true - $m.DiffMode | Assert-Equals -Expected $true - $m.KeepRemoteFiles | Assert-Equals -Expected $true - $m.ModuleName | Assert-Equals -Expected "ansible_basic_tests" - $m.NoLog | Assert-Equals -Expected $true - $m.Verbosity | Assert-Equals -Expected 3 - $m.AnsibleVersion | Assert-Equals -Expected "2.8.0" - $m.Tmpdir | Assert-Equals -Expected $m_tmpdir + $m.CheckMode | Assert-Equal -Expected $true + $m.DebugMode | Assert-Equal -Expected $true + $m.DiffMode | Assert-Equal -Expected $true + $m.KeepRemoteFiles | Assert-Equal -Expected $true + $m.ModuleName | Assert-Equal -Expected "ansible_basic_tests" + $m.NoLog | Assert-Equal -Expected $true + $m.Verbosity | Assert-Equal -Expected 3 + $m.AnsibleVersion | Assert-Equal -Expected "2.8.0" + $m.Tmpdir | Assert-Equal -Expected $m_tmpdir } "Parse complex module options" = { @@ -203,65 +212,65 @@ $tests = @{ options = @{ option_default = @{} missing_option_default = @{} - string_option = @{type = "str"} - required_option = @{required = $true} - missing_choices = @{choices = "a", "b"} - choices = @{choices = "a", "b"} - one_choice = @{choices = ,"b"} - choice_with_default = @{choices = "a", "b"; default = "b"} - alias_direct = @{aliases = ,"alias_direct1"} - alias_as_alias = @{aliases = "alias_as_alias1", "alias_as_alias2"} - bool_type = @{type = "bool"} - bool_from_str = @{type = "bool"} + string_option = @{type = "str" } + required_option = @{required = $true } + missing_choices = @{choices = "a", "b" } + choices = @{choices = "a", "b" } + one_choice = @{choices = , "b" } + choice_with_default = @{choices = "a", "b"; default = "b" } + alias_direct = @{aliases = , "alias_direct1" } + alias_as_alias = @{aliases = "alias_as_alias1", "alias_as_alias2" } + bool_type = @{type = "bool" } + bool_from_str = @{type = "bool" } dict_type = @{ type = "dict" options = @{ - int_type = @{type = "int"} - str_type = @{type = "str"; default = "str_sub_type"} + int_type = @{type = "int" } + str_type = @{type = "str"; default = "str_sub_type" } } } dict_type_missing = @{ type = "dict" options = @{ - int_type = @{type = "int"} - str_type = @{type = "str"; default = "str_sub_type"} + int_type = @{type = "int" } + str_type = @{type = "str"; default = "str_sub_type" } } } dict_type_defaults = @{ type = "dict" apply_defaults = $true options = @{ - int_type = @{type = "int"} - str_type = @{type = "str"; default = "str_sub_type"} + int_type = @{type = "int" } + str_type = @{type = "str"; default = "str_sub_type" } } } - dict_type_json = @{type = "dict"} - dict_type_str = @{type = "dict"} - float_type = @{type = "float"} - int_type = @{type = "int"} - json_type = @{type = "json"} - json_type_dict = @{type = "json"} - list_type = @{type = "list"} - list_type_str = @{type = "list"} - list_with_int = @{type = "list"; elements = "int"} - list_type_single = @{type = "list"} + dict_type_json = @{type = "dict" } + dict_type_str = @{type = "dict" } + float_type = @{type = "float" } + int_type = @{type = "int" } + json_type = @{type = "json" } + json_type_dict = @{type = "json" } + list_type = @{type = "list" } + list_type_str = @{type = "list" } + list_with_int = @{type = "list"; elements = "int" } + list_type_single = @{type = "list" } list_with_dict = @{ type = "list" elements = "dict" options = @{ - int_type = @{type = "int"} - str_type = @{type = "str"; default = "str_sub_type"} + int_type = @{type = "int" } + str_type = @{type = "str"; default = "str_sub_type" } } } - path_type = @{type = "path"} - path_type_nt = @{type = "path"} - path_type_missing = @{type = "path"} - raw_type_str = @{type = "raw"} - raw_type_int = @{type = "raw"} - sid_type = @{type = "sid"} - sid_from_name = @{type = "sid"} - str_type = @{type = "str"} - delegate_type = @{type = [Func[[Object], [UInt64]]]{ [System.UInt64]::Parse($args[0]) }} + path_type = @{type = "path" } + path_type_nt = @{type = "path" } + path_type_missing = @{type = "path" } + raw_type_str = @{type = "raw" } + raw_type_int = @{type = "raw" } + sid_type = @{type = "sid" } + sid_from_name = @{type = "sid" } + str_type = @{type = "str" } + delegate_type = @{type = [Func[[Object], [UInt64]]] { [System.UInt64]::Parse($args[0]) } } } } Set-Variable -Name complex_args -Scope Global -Value @{ @@ -311,129 +320,131 @@ $tests = @{ } $m = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - $m.Params.option_default | Assert-Equals -Expected "1" - $m.Params.option_default.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.missing_option_default | Assert-Equals -Expected $null - $m.Params.string_option | Assert-Equals -Expected "1" - $m.Params.string_option.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.required_option | Assert-Equals -Expected "required" - $m.Params.required_option.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.missing_choices | Assert-Equals -Expected $null - $m.Params.choices | Assert-Equals -Expected "a" - $m.Params.choices.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.one_choice | Assert-Equals -Expected "b" - $m.Params.one_choice.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.choice_with_default | Assert-Equals -Expected "b" - $m.Params.choice_with_default.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.alias_direct | Assert-Equals -Expected "a" - $m.Params.alias_direct.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.alias_as_alias | Assert-Equals -Expected "a" - $m.Params.alias_as_alias.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.bool_type | Assert-Equals -Expected $true - $m.Params.bool_type.GetType().ToString() | Assert-Equals -Expected "System.Boolean" - $m.Params.bool_from_str | Assert-Equals -Expected $false - $m.Params.bool_from_str.GetType().ToString() | Assert-Equals -Expected "System.Boolean" - $m.Params.dict_type | Assert-DictionaryEquals -Expected @{int_type = 10; str_type = "str_sub_type"} - $m.Params.dict_type.GetType().ToString() | Assert-Equals -Expected "System.Collections.Generic.Dictionary``2[System.String,System.Object]" - $m.Params.dict_type.int_type.GetType().ToString() | Assert-Equals -Expected "System.Int32" - $m.Params.dict_type.str_type.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.dict_type_missing | Assert-Equals -Expected $null - $m.Params.dict_type_defaults | Assert-DictionaryEquals -Expected @{int_type = $null; str_type = "str_sub_type"} - $m.Params.dict_type_defaults.GetType().ToString() | Assert-Equals -Expected "System.Collections.Generic.Dictionary``2[System.String,System.Object]" - $m.Params.dict_type_defaults.str_type.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.dict_type_json | Assert-DictionaryEquals -Expected @{ + $m.Params.option_default | Assert-Equal -Expected "1" + $m.Params.option_default.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.missing_option_default | Assert-Equal -Expected $null + $m.Params.string_option | Assert-Equal -Expected "1" + $m.Params.string_option.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.required_option | Assert-Equal -Expected "required" + $m.Params.required_option.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.missing_choices | Assert-Equal -Expected $null + $m.Params.choices | Assert-Equal -Expected "a" + $m.Params.choices.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.one_choice | Assert-Equal -Expected "b" + $m.Params.one_choice.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.choice_with_default | Assert-Equal -Expected "b" + $m.Params.choice_with_default.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.alias_direct | Assert-Equal -Expected "a" + $m.Params.alias_direct.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.alias_as_alias | Assert-Equal -Expected "a" + $m.Params.alias_as_alias.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.bool_type | Assert-Equal -Expected $true + $m.Params.bool_type.GetType().ToString() | Assert-Equal -Expected "System.Boolean" + $m.Params.bool_from_str | Assert-Equal -Expected $false + $m.Params.bool_from_str.GetType().ToString() | Assert-Equal -Expected "System.Boolean" + $m.Params.dict_type | Assert-DictionaryEqual -Expected @{int_type = 10; str_type = "str_sub_type" } + $m.Params.dict_type.GetType().ToString() | Assert-Equal -Expected "System.Collections.Generic.Dictionary``2[System.String,System.Object]" + $m.Params.dict_type.int_type.GetType().ToString() | Assert-Equal -Expected "System.Int32" + $m.Params.dict_type.str_type.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.dict_type_missing | Assert-Equal -Expected $null + $m.Params.dict_type_defaults | Assert-DictionaryEqual -Expected @{int_type = $null; str_type = "str_sub_type" } + $m.Params.dict_type_defaults.GetType().ToString() | Assert-Equal -Expected "System.Collections.Generic.Dictionary``2[System.String,System.Object]" + $m.Params.dict_type_defaults.str_type.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.dict_type_json | Assert-DictionaryEqual -Expected @{ a = "a" b = 1 c = @("a", "b") } - $m.Params.dict_type_json.GetType().ToString() | Assert-Equals -Expected "System.Collections.Generic.Dictionary``2[System.String,System.Object]" - $m.Params.dict_type_json.a.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.dict_type_json.b.GetType().ToString() | Assert-Equals -Expected "System.Int32" - $m.Params.dict_type_json.c.GetType().ToString() | Assert-Equals -Expected "System.Collections.ArrayList" - $m.Params.dict_type_str | Assert-DictionaryEquals -Expected @{a = "a"; b = "b 2"; c = "c"} - $m.Params.dict_type_str.GetType().ToString() | Assert-Equals -Expected "System.Collections.Generic.Dictionary``2[System.String,System.Object]" - $m.Params.dict_type_str.a.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.dict_type_str.b.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.dict_type_str.c.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.float_type | Assert-Equals -Expected ([System.Single]3.14159) - $m.Params.float_type.GetType().ToString() | Assert-Equals -Expected "System.Single" - $m.Params.int_type | Assert-Equals -Expected 0 - $m.Params.int_type.GetType().ToString() | Assert-Equals -Expected "System.Int32" - $m.Params.json_type | Assert-Equals -Expected '{"a":"a","b":1,"c":["a","b"]}' - $m.Params.json_type.GetType().ToString() | Assert-Equals -Expected "System.String" - [Ansible.Basic.AnsibleModule]::FromJson($m.Params.json_type_dict) | Assert-DictionaryEquals -Expected ([Ansible.Basic.AnsibleModule]::FromJson('{"a":"a","b":1,"c":["a","b"]}')) - $m.Params.json_type_dict.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.list_type.GetType().ToString() | Assert-Equals -Expected "System.Collections.Generic.List``1[System.Object]" - $m.Params.list_type.Count | Assert-Equals -Expected 4 - $m.Params.list_type[0] | Assert-Equals -Expected "a" - $m.Params.list_type[0].GetType().FullName | Assert-Equals -Expected "System.String" - $m.Params.list_type[1] | Assert-Equals -Expected "b" - $m.Params.list_type[1].GetType().FullName | Assert-Equals -Expected "System.String" - $m.Params.list_type[2] | Assert-Equals -Expected 1 - $m.Params.list_type[2].GetType().FullName | Assert-Equals -Expected "System.Int32" - $m.Params.list_type[3] | Assert-Equals -Expected 2 - $m.Params.list_type[3].GetType().FullName | Assert-Equals -Expected "System.Int32" - $m.Params.list_type_str.GetType().ToString() | Assert-Equals -Expected "System.Collections.Generic.List``1[System.Object]" - $m.Params.list_type_str.Count | Assert-Equals -Expected 4 - $m.Params.list_type_str[0] | Assert-Equals -Expected "a" - $m.Params.list_type_str[0].GetType().FullName | Assert-Equals -Expected "System.String" - $m.Params.list_type_str[1] | Assert-Equals -Expected "b" - $m.Params.list_type_str[1].GetType().FullName | Assert-Equals -Expected "System.String" - $m.Params.list_type_str[2] | Assert-Equals -Expected "1" - $m.Params.list_type_str[2].GetType().FullName | Assert-Equals -Expected "System.String" - $m.Params.list_type_str[3] | Assert-Equals -Expected "2" - $m.Params.list_type_str[3].GetType().FullName | Assert-Equals -Expected "System.String" - $m.Params.list_with_int.GetType().ToString() | Assert-Equals -Expected "System.Collections.Generic.List``1[System.Object]" - $m.Params.list_with_int.Count | Assert-Equals -Expected 2 - $m.Params.list_with_int[0] | Assert-Equals -Expected 1 - $m.Params.list_with_int[0].GetType().FullName | Assert-Equals -Expected "System.Int32" - $m.Params.list_with_int[1] | Assert-Equals -Expected 2 - $m.Params.list_with_int[1].GetType().FullName | Assert-Equals -Expected "System.Int32" - $m.Params.list_type_single.GetType().ToString() | Assert-Equals -Expected "System.Collections.Generic.List``1[System.Object]" - $m.Params.list_type_single.Count | Assert-Equals -Expected 1 - $m.Params.list_type_single[0] | Assert-Equals -Expected "single" - $m.Params.list_type_single[0].GetType().FullName | Assert-Equals -Expected "System.String" - $m.Params.list_with_dict.GetType().FullName.StartsWith("System.Collections.Generic.List``1[[System.Object") | Assert-Equals -Expected $true - $m.Params.list_with_dict.Count | Assert-Equals -Expected 3 - $m.Params.list_with_dict[0].GetType().FullName.StartsWith("System.Collections.Generic.Dictionary``2[[System.String") | Assert-Equals -Expected $true - $m.Params.list_with_dict[0] | Assert-DictionaryEquals -Expected @{int_type = 2; str_type = "dict entry"} - $m.Params.list_with_dict[0].int_type.GetType().FullName.ToString() | Assert-Equals -Expected "System.Int32" - $m.Params.list_with_dict[0].str_type.GetType().FullName.ToString() | Assert-Equals -Expected "System.String" - $m.Params.list_with_dict[1].GetType().FullName.StartsWith("System.Collections.Generic.Dictionary``2[[System.String") | Assert-Equals -Expected $true - $m.Params.list_with_dict[1] | Assert-DictionaryEquals -Expected @{int_type = 1; str_type = "str_sub_type"} - $m.Params.list_with_dict[1].int_type.GetType().FullName.ToString() | Assert-Equals -Expected "System.Int32" - $m.Params.list_with_dict[1].str_type.GetType().FullName.ToString() | Assert-Equals -Expected "System.String" - $m.Params.list_with_dict[2].GetType().FullName.StartsWith("System.Collections.Generic.Dictionary``2[[System.String") | Assert-Equals -Expected $true - $m.Params.list_with_dict[2] | Assert-DictionaryEquals -Expected @{int_type = $null; str_type = "str_sub_type"} - $m.Params.list_with_dict[2].str_type.GetType().FullName.ToString() | Assert-Equals -Expected "System.String" - $m.Params.path_type | Assert-Equals -Expected "$($env:SystemRoot)\System32" - $m.Params.path_type.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.path_type_nt | Assert-Equals -Expected "\\?\%SystemRoot%\System32" - $m.Params.path_type_nt.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.path_type_missing | Assert-Equals -Expected "T:\missing\path" - $m.Params.path_type_missing.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.raw_type_str | Assert-Equals -Expected "str" - $m.Params.raw_type_str.GetType().FullName | Assert-Equals -Expected "System.String" - $m.Params.raw_type_int | Assert-Equals -Expected 1 - $m.Params.raw_type_int.GetType().FullName | Assert-Equals -Expected "System.Int32" - $m.Params.sid_type | Assert-Equals -Expected (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList "S-1-5-18") - $m.Params.sid_type.GetType().ToString() | Assert-Equals -Expected "System.Security.Principal.SecurityIdentifier" - $m.Params.sid_from_name | Assert-Equals -Expected (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList "S-1-5-18") - $m.Params.sid_from_name.GetType().ToString() | Assert-Equals -Expected "System.Security.Principal.SecurityIdentifier" - $m.Params.str_type | Assert-Equals -Expected "str" - $m.Params.str_type.GetType().ToString() | Assert-Equals -Expected "System.String" - $m.Params.delegate_type | Assert-Equals -Expected 1234 - $m.Params.delegate_type.GetType().ToString() | Assert-Equals -Expected "System.UInt64" + $m.Params.dict_type_json.GetType().ToString() | Assert-Equal -Expected "System.Collections.Generic.Dictionary``2[System.String,System.Object]" + $m.Params.dict_type_json.a.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.dict_type_json.b.GetType().ToString() | Assert-Equal -Expected "System.Int32" + $m.Params.dict_type_json.c.GetType().ToString() | Assert-Equal -Expected "System.Collections.ArrayList" + $m.Params.dict_type_str | Assert-DictionaryEqual -Expected @{a = "a"; b = "b 2"; c = "c" } + $m.Params.dict_type_str.GetType().ToString() | Assert-Equal -Expected "System.Collections.Generic.Dictionary``2[System.String,System.Object]" + $m.Params.dict_type_str.a.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.dict_type_str.b.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.dict_type_str.c.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.float_type | Assert-Equal -Expected ([System.Single]3.14159) + $m.Params.float_type.GetType().ToString() | Assert-Equal -Expected "System.Single" + $m.Params.int_type | Assert-Equal -Expected 0 + $m.Params.int_type.GetType().ToString() | Assert-Equal -Expected "System.Int32" + $m.Params.json_type | Assert-Equal -Expected '{"a":"a","b":1,"c":["a","b"]}' + $m.Params.json_type.GetType().ToString() | Assert-Equal -Expected "System.String" + $jsonValue = ([Ansible.Basic.AnsibleModule]::FromJson('{"a":"a","b":1,"c":["a","b"]}')) + [Ansible.Basic.AnsibleModule]::FromJson($m.Params.json_type_dict) | Assert-DictionaryEqual -Expected $jsonValue + $m.Params.json_type_dict.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.list_type.GetType().ToString() | Assert-Equal -Expected "System.Collections.Generic.List``1[System.Object]" + $m.Params.list_type.Count | Assert-Equal -Expected 4 + $m.Params.list_type[0] | Assert-Equal -Expected "a" + $m.Params.list_type[0].GetType().FullName | Assert-Equal -Expected "System.String" + $m.Params.list_type[1] | Assert-Equal -Expected "b" + $m.Params.list_type[1].GetType().FullName | Assert-Equal -Expected "System.String" + $m.Params.list_type[2] | Assert-Equal -Expected 1 + $m.Params.list_type[2].GetType().FullName | Assert-Equal -Expected "System.Int32" + $m.Params.list_type[3] | Assert-Equal -Expected 2 + $m.Params.list_type[3].GetType().FullName | Assert-Equal -Expected "System.Int32" + $m.Params.list_type_str.GetType().ToString() | Assert-Equal -Expected "System.Collections.Generic.List``1[System.Object]" + $m.Params.list_type_str.Count | Assert-Equal -Expected 4 + $m.Params.list_type_str[0] | Assert-Equal -Expected "a" + $m.Params.list_type_str[0].GetType().FullName | Assert-Equal -Expected "System.String" + $m.Params.list_type_str[1] | Assert-Equal -Expected "b" + $m.Params.list_type_str[1].GetType().FullName | Assert-Equal -Expected "System.String" + $m.Params.list_type_str[2] | Assert-Equal -Expected "1" + $m.Params.list_type_str[2].GetType().FullName | Assert-Equal -Expected "System.String" + $m.Params.list_type_str[3] | Assert-Equal -Expected "2" + $m.Params.list_type_str[3].GetType().FullName | Assert-Equal -Expected "System.String" + $m.Params.list_with_int.GetType().ToString() | Assert-Equal -Expected "System.Collections.Generic.List``1[System.Object]" + $m.Params.list_with_int.Count | Assert-Equal -Expected 2 + $m.Params.list_with_int[0] | Assert-Equal -Expected 1 + $m.Params.list_with_int[0].GetType().FullName | Assert-Equal -Expected "System.Int32" + $m.Params.list_with_int[1] | Assert-Equal -Expected 2 + $m.Params.list_with_int[1].GetType().FullName | Assert-Equal -Expected "System.Int32" + $m.Params.list_type_single.GetType().ToString() | Assert-Equal -Expected "System.Collections.Generic.List``1[System.Object]" + $m.Params.list_type_single.Count | Assert-Equal -Expected 1 + $m.Params.list_type_single[0] | Assert-Equal -Expected "single" + $m.Params.list_type_single[0].GetType().FullName | Assert-Equal -Expected "System.String" + $m.Params.list_with_dict.GetType().FullName.StartsWith("System.Collections.Generic.List``1[[System.Object") | Assert-Equal -Expected $true + $m.Params.list_with_dict.Count | Assert-Equal -Expected 3 + $m.Params.list_with_dict[0].GetType().FullName.StartsWith("System.Collections.Generic.Dictionary``2[[System.String") | Assert-Equal -Expected $true + $m.Params.list_with_dict[0] | Assert-DictionaryEqual -Expected @{int_type = 2; str_type = "dict entry" } + $m.Params.list_with_dict[0].int_type.GetType().FullName.ToString() | Assert-Equal -Expected "System.Int32" + $m.Params.list_with_dict[0].str_type.GetType().FullName.ToString() | Assert-Equal -Expected "System.String" + $m.Params.list_with_dict[1].GetType().FullName.StartsWith("System.Collections.Generic.Dictionary``2[[System.String") | Assert-Equal -Expected $true + $m.Params.list_with_dict[1] | Assert-DictionaryEqual -Expected @{int_type = 1; str_type = "str_sub_type" } + $m.Params.list_with_dict[1].int_type.GetType().FullName.ToString() | Assert-Equal -Expected "System.Int32" + $m.Params.list_with_dict[1].str_type.GetType().FullName.ToString() | Assert-Equal -Expected "System.String" + $m.Params.list_with_dict[2].GetType().FullName.StartsWith("System.Collections.Generic.Dictionary``2[[System.String") | Assert-Equal -Expected $true + $m.Params.list_with_dict[2] | Assert-DictionaryEqual -Expected @{int_type = $null; str_type = "str_sub_type" } + $m.Params.list_with_dict[2].str_type.GetType().FullName.ToString() | Assert-Equal -Expected "System.String" + $m.Params.path_type | Assert-Equal -Expected "$($env:SystemRoot)\System32" + $m.Params.path_type.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.path_type_nt | Assert-Equal -Expected "\\?\%SystemRoot%\System32" + $m.Params.path_type_nt.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.path_type_missing | Assert-Equal -Expected "T:\missing\path" + $m.Params.path_type_missing.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.raw_type_str | Assert-Equal -Expected "str" + $m.Params.raw_type_str.GetType().FullName | Assert-Equal -Expected "System.String" + $m.Params.raw_type_int | Assert-Equal -Expected 1 + $m.Params.raw_type_int.GetType().FullName | Assert-Equal -Expected "System.Int32" + $m.Params.sid_type | Assert-Equal -Expected (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList "S-1-5-18") + $m.Params.sid_type.GetType().ToString() | Assert-Equal -Expected "System.Security.Principal.SecurityIdentifier" + $m.Params.sid_from_name | Assert-Equal -Expected (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList "S-1-5-18") + $m.Params.sid_from_name.GetType().ToString() | Assert-Equal -Expected "System.Security.Principal.SecurityIdentifier" + $m.Params.str_type | Assert-Equal -Expected "str" + $m.Params.str_type.GetType().ToString() | Assert-Equal -Expected "System.String" + $m.Params.delegate_type | Assert-Equal -Expected 1234 + $m.Params.delegate_type.GetType().ToString() | Assert-Equal -Expected "System.UInt64" $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_module_args = @{ option_default = "1" @@ -500,9 +511,9 @@ $tests = @{ str_type = "str" delegate_type = 1234 } - $actual.Keys.Count | Assert-Equals -Expected 2 - $actual.changed | Assert-Equals -Expected $false - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $expected_module_args} + $actual.Keys.Count | Assert-Equal -Expected 2 + $actual.changed | Assert-Equal -Expected $false + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $expected_module_args } } "Parse module args with list elements and delegate type" = { @@ -510,7 +521,7 @@ $tests = @{ options = @{ list_delegate_type = @{ type = "list" - elements = [Func[[Object], [UInt16]]]{ [System.UInt16]::Parse($args[0]) } + elements = [Func[[Object], [UInt16]]] { [System.UInt16]::Parse($args[0]) } } } } @@ -521,19 +532,20 @@ $tests = @{ ) } $m = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - $m.Params.list_delegate_type.GetType().Name | Assert-Equals -Expected 'List`1' - $m.Params.list_delegate_type[0].GetType().FullName | Assert-Equals -Expected "System.UInt16" - $m.Params.list_delegate_Type[1].GetType().FullName | Assert-Equals -Expected "System.UInt16" + $m.Params.list_delegate_type.GetType().Name | Assert-Equal -Expected 'List`1' + $m.Params.list_delegate_type[0].GetType().FullName | Assert-Equal -Expected "System.UInt16" + $m.Params.list_delegate_Type[1].GetType().FullName | Assert-Equal -Expected "System.UInt16" $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_module_args = @{ list_delegate_type = @( @@ -541,9 +553,9 @@ $tests = @{ 4321 ) } - $actual.Keys.Count | Assert-Equals -Expected 2 - $actual.changed | Assert-Equals -Expected $false - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $expected_module_args} + $actual.Keys.Count | Assert-Equal -Expected 2 + $actual.changed | Assert-Equal -Expected $false + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $expected_module_args } } "Parse module args with case insensitive input" = { @@ -559,21 +571,22 @@ $tests = @{ $m = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) # Verifies the case of the params key is set to the module spec not actual input - $m.Params.Keys | Assert-Equals -Expected @("option1") - $m.Params.option1 | Assert-Equals -Expected 1 + $m.Params.Keys | Assert-Equal -Expected @("option1") + $m.Params.option1 | Assert-Equal -Expected 1 # Verifies the type conversion happens even on a case insensitive match - $m.Params.option1.GetType().FullName | Assert-Equals -Expected "System.Int32" + $m.Params.option1.GetType().FullName | Assert-Equal -Expected "System.Int32" $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_warnings = "Parameters for (win_test) was a case insensitive match: Option1. " $expected_warnings += "Module options will become case sensitive in a future Ansible release. " @@ -589,16 +602,16 @@ $tests = @{ # We have disabled the warning for now #warnings = @($expected_warnings) } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "No log values" = { $spec = @{ options = @{ - username = @{type = "str"} - password = @{type = "str"; no_log = $true} - password2 = @{type = "int"; no_log = $true} - dict = @{type = "dict"} + username = @{type = "str" } + password = @{type = "str"; no_log = $true } + password2 = @{type = "int"; no_log = $true } + dict = @{type = "dict" } } } Set-Variable -Name complex_args -Scope Global -Value @{ @@ -634,20 +647,21 @@ $tests = @{ $m.Result.data = $complex_args.dict # verify params internally aren't masked - $m.Params.username | Assert-Equals -Expected "user - pass - name" - $m.Params.password | Assert-Equals -Expected "pass" - $m.Params.password2 | Assert-Equals -Expected 1234 - $m.Params.dict.custom | Assert-Equals -Expected "pass" + $m.Params.username | Assert-Equal -Expected "user - pass - name" + $m.Params.password | Assert-Equal -Expected "pass" + $m.Params.password2 | Assert-Equal -Expected 1234 + $m.Params.dict.custom | Assert-Equal -Expected "pass" $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true # verify no_log params are masked in invocation $expected = @{ @@ -683,7 +697,7 @@ $tests = @{ changed = $false data = $complex_args.dict } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected $expected_event = @' test_no_log - Invoked with: @@ -707,14 +721,14 @@ test_no_log - Invoked with: password: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER '@ $actual_event = (Get-EventLog -LogName Application -Source Ansible -Newest 1).Message - $actual_event | Assert-DictionaryEquals -Expected $expected_event + $actual_event | Assert-DictionaryEqual -Expected $expected_event } "No log value with an empty string" = { $spec = @{ options = @{ - password1 = @{type = "str"; no_log = $true} - password2 = @{type = "str"; no_log = $true} + password1 = @{type = "str"; no_log = $true } + password2 = @{type = "str"; no_log = $true } } } Set-Variable -Name complex_args -Scope Global -Value @{ @@ -726,18 +740,19 @@ test_no_log - Invoked with: $m.Result.data = $complex_args.dict # verify params internally aren't masked - $m.Params.password1 | Assert-Equals -Expected "" - $m.Params.password2 | Assert-Equals -Expected $null + $m.Params.password1 | Assert-Equal -Expected "" + $m.Params.password2 | Assert-Equal -Expected $null $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected = @{ invocation = @{ @@ -749,15 +764,15 @@ test_no_log - Invoked with: changed = $false data = $complex_args.dict } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "Removed in version" = { $spec = @{ options = @{ - removed1 = @{removed_in_version = "2.1"} - removed2 = @{removed_in_version = "2.2"} - removed3 = @{removed_in_version = "2.3"; removed_from_collection = "ansible.builtin"} + removed1 = @{removed_in_version = "2.1" } + removed2 = @{removed_in_version = "2.2" } + removed3 = @{removed_in_version = "2.3"; removed_from_collection = "ansible.builtin" } } } Set-Variable -Name complex_args -Scope Global -Value @{ @@ -770,12 +785,13 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected = @{ changed = $false @@ -799,15 +815,15 @@ test_no_log - Invoked with: } ) } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "Removed at date" = { $spec = @{ options = @{ - removed1 = @{removed_at_date = [DateTime]"2020-03-10"} - removed2 = @{removed_at_date = [DateTime]"2020-03-11"} - removed3 = @{removed_at_date = [DateTime]"2020-06-07"; removed_from_collection = "ansible.builtin"} + removed1 = @{removed_at_date = [DateTime]"2020-03-10" } + removed2 = @{removed_at_date = [DateTime]"2020-03-11" } + removed3 = @{removed_at_date = [DateTime]"2020-06-07"; removed_from_collection = "ansible.builtin" } } } Set-Variable -Name complex_args -Scope Global -Value @{ @@ -820,12 +836,13 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected = @{ changed = $false @@ -849,29 +866,53 @@ test_no_log - Invoked with: } ) } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "Deprecated aliases" = { $spec = @{ options = @{ - option1 = @{ type = "str"; aliases = "alias1"; deprecated_aliases = @(@{name = "alias1"; version = "2.10"}) } - option2 = @{ type = "str"; aliases = "alias2"; deprecated_aliases = @(@{name = "alias2"; version = "2.11"}) } + option1 = @{ type = "str"; aliases = "alias1"; deprecated_aliases = @(@{name = "alias1"; version = "2.10" }) } + option2 = @{ type = "str"; aliases = "alias2"; deprecated_aliases = @(@{name = "alias2"; version = "2.11" }) } option3 = @{ type = "dict" options = @{ - option1 = @{ type = "str"; aliases = "alias1"; deprecated_aliases = @(@{name = "alias1"; version = "2.10"}) } - option2 = @{ type = "str"; aliases = "alias2"; deprecated_aliases = @(@{name = "alias2"; version = "2.11"}) } - option3 = @{ type = "str"; aliases = "alias3"; deprecated_aliases = @(@{name = "alias3"; version = "2.12"; collection_name = "ansible.builtin"}) } - option4 = @{ type = "str"; aliases = "alias4"; deprecated_aliases = @(@{name = "alias4"; date = [DateTime]"2020-03-11"}) } - option5 = @{ type = "str"; aliases = "alias5"; deprecated_aliases = @(@{name = "alias5"; date = [DateTime]"2020-03-09"}) } - option6 = @{ type = "str"; aliases = "alias6"; deprecated_aliases = @(@{name = "alias6"; date = [DateTime]"2020-06-01"; collection_name = "ansible.builtin"}) } + option1 = @{ type = "str"; aliases = "alias1"; deprecated_aliases = @(@{name = "alias1"; version = "2.10" }) } + option2 = @{ type = "str"; aliases = "alias2"; deprecated_aliases = @(@{name = "alias2"; version = "2.11" }) } + option3 = @{ + type = "str" + aliases = "alias3" + deprecated_aliases = @( + @{name = "alias3"; version = "2.12"; collection_name = "ansible.builtin" } + ) + } + option4 = @{ type = "str"; aliases = "alias4"; deprecated_aliases = @(@{name = "alias4"; date = [DateTime]"2020-03-11" }) } + option5 = @{ type = "str"; aliases = "alias5"; deprecated_aliases = @(@{name = "alias5"; date = [DateTime]"2020-03-09" }) } + option6 = @{ + type = "str" + aliases = "alias6" + deprecated_aliases = @( + @{name = "alias6"; date = [DateTime]"2020-06-01"; collection_name = "ansible.builtin" } + ) + } } } - option4 = @{ type = "str"; aliases = "alias4"; deprecated_aliases = @(@{name = "alias4"; date = [DateTime]"2020-03-10"}) } - option5 = @{ type = "str"; aliases = "alias5"; deprecated_aliases = @(@{name = "alias5"; date = [DateTime]"2020-03-12"}) } - option6 = @{ type = "str"; aliases = "alias6"; deprecated_aliases = @(@{name = "alias6"; version = "2.12"; collection_name = "ansible.builtin"}) } - option7 = @{ type = "str"; aliases = "alias7"; deprecated_aliases = @(@{name = "alias7"; date = [DateTime]"2020-06-07"; collection_name = "ansible.builtin"}) } + option4 = @{ type = "str"; aliases = "alias4"; deprecated_aliases = @(@{name = "alias4"; date = [DateTime]"2020-03-10" }) } + option5 = @{ type = "str"; aliases = "alias5"; deprecated_aliases = @(@{name = "alias5"; date = [DateTime]"2020-03-12" }) } + option6 = @{ + type = "str" + aliases = "alias6" + deprecated_aliases = @( + @{name = "alias6"; version = "2.12"; collection_name = "ansible.builtin" } + ) + } + option7 = @{ + type = "str" + aliases = "alias7" + deprecated_aliases = @( + @{name = "alias7"; date = [DateTime]"2020-06-07"; collection_name = "ansible.builtin" } + ) + } } } @@ -896,12 +937,13 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected = @{ changed = $false @@ -974,15 +1016,15 @@ test_no_log - Invoked with: } ) } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "Required by - single value" = { $spec = @{ options = @{ - option1 = @{type = "str"} - option2 = @{type = "str"} - option3 = @{type = "str"} + option1 = @{type = "str" } + option2 = @{type = "str" } + option3 = @{type = "str" } } required_by = @{ option1 = "option2" @@ -998,12 +1040,13 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected = @{ changed = $false @@ -1015,15 +1058,15 @@ test_no_log - Invoked with: } } } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "Required by - multiple values" = { $spec = @{ options = @{ - option1 = @{type = "str"} - option2 = @{type = "str"} - option3 = @{type = "str"} + option1 = @{type = "str" } + option2 = @{type = "str" } + option3 = @{type = "str" } } required_by = @{ option1 = "option2", "option3" @@ -1040,12 +1083,13 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected = @{ changed = $false @@ -1057,15 +1101,15 @@ test_no_log - Invoked with: } } } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "Required by explicit null" = { $spec = @{ options = @{ - option1 = @{type = "str"} - option2 = @{type = "str"} - option3 = @{type = "str"} + option1 = @{type = "str" } + option2 = @{type = "str" } + option3 = @{type = "str" } } required_by = @{ option1 = "option2" @@ -1081,12 +1125,13 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected = @{ changed = $false @@ -1098,15 +1143,15 @@ test_no_log - Invoked with: } } } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "Required by failed - single value" = { $spec = @{ options = @{ - option1 = @{type = "str"} - option2 = @{type = "str"} - option3 = @{type = "str"} + option1 = @{type = "str" } + option2 = @{type = "str" } + option3 = @{type = "str" } } required_by = @{ option1 = "option2" @@ -1119,12 +1164,13 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected = @{ changed = $false @@ -1136,15 +1182,15 @@ test_no_log - Invoked with: } msg = "missing parameter(s) required by 'option1': option2" } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "Required by failed - multiple values" = { $spec = @{ options = @{ - option1 = @{type = "str"} - option2 = @{type = "str"} - option3 = @{type = "str"} + option1 = @{type = "str" } + option2 = @{type = "str" } + option3 = @{type = "str" } } required_by = @{ option1 = "option2", "option3" @@ -1157,12 +1203,13 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected = @{ changed = $false @@ -1174,7 +1221,7 @@ test_no_log - Invoked with: } msg = "missing parameter(s) required by 'option1': option2, option3" } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "Debug without debug set" = { @@ -1184,7 +1231,7 @@ test_no_log - Invoked with: $m = [Ansible.Basic.AnsibleModule]::Create(@(), @{}) $m.Debug("debug message") $actual_event = (Get-EventLog -LogName Application -Source Ansible -Newest 1).Message - $actual_event | Assert-Equals -Expected "undefined win module - Invoked with:`r`n " + $actual_event | Assert-Equal -Expected "undefined win module - Invoked with:`r`n " } "Debug with debug set" = { @@ -1194,7 +1241,7 @@ test_no_log - Invoked with: $m = [Ansible.Basic.AnsibleModule]::Create(@(), @{}) $m.Debug("debug message") $actual_event = (Get-EventLog -LogName Application -Source Ansible -Newest 1).Message - $actual_event | Assert-Equals -Expected "undefined win module - [DEBUG] debug message" + $actual_event | Assert-Equal -Expected "undefined win module - [DEBUG] debug message" } "Deprecate and warn with version" = { @@ -1206,20 +1253,21 @@ test_no_log - Invoked with: $m.Warn("warning") $actual_warn_event = Get-EventLog -LogName Application -Source Ansible -Newest 1 - $actual_deprecate_event_1.Message | Assert-Equals -Expected "undefined win module - [DEPRECATION WARNING] message 2.7" - $actual_deprecate_event_2.Message | Assert-Equals -Expected "undefined win module - [DEPRECATION WARNING] message w collection 2.8" - $actual_warn_event.EntryType | Assert-Equals -Expected "Warning" - $actual_warn_event.Message | Assert-Equals -Expected "undefined win module - [WARNING] warning" + $actual_deprecate_event_1.Message | Assert-Equal -Expected "undefined win module - [DEPRECATION WARNING] message 2.7" + $actual_deprecate_event_2.Message | Assert-Equal -Expected "undefined win module - [DEPRECATION WARNING] message w collection 2.8" + $actual_warn_event.EntryType | Assert-Equal -Expected "Warning" + $actual_warn_event.Message | Assert-Equal -Expected "undefined win module - [WARNING] warning" $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected = @{ changed = $false @@ -1228,11 +1276,11 @@ test_no_log - Invoked with: } warnings = @("warning") deprecations = @( - @{msg = "message"; version = "2.7"; collection_name = $null}, - @{msg = "message w collection"; version = "2.8"; collection_name = "ansible.builtin"} + @{msg = "message"; version = "2.7"; collection_name = $null }, + @{msg = "message w collection"; version = "2.8"; collection_name = "ansible.builtin" } ) } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "Deprecate and warn with date" = { @@ -1244,20 +1292,21 @@ test_no_log - Invoked with: $m.Warn("warning") $actual_warn_event = Get-EventLog -LogName Application -Source Ansible -Newest 1 - $actual_deprecate_event_1.Message | Assert-Equals -Expected "undefined win module - [DEPRECATION WARNING] message 2020-01-01" - $actual_deprecate_event_2.Message | Assert-Equals -Expected "undefined win module - [DEPRECATION WARNING] message w collection 2020-01-02" - $actual_warn_event.EntryType | Assert-Equals -Expected "Warning" - $actual_warn_event.Message | Assert-Equals -Expected "undefined win module - [WARNING] warning" + $actual_deprecate_event_1.Message | Assert-Equal -Expected "undefined win module - [DEPRECATION WARNING] message 2020-01-01" + $actual_deprecate_event_2.Message | Assert-Equal -Expected "undefined win module - [DEPRECATION WARNING] message w collection 2020-01-02" + $actual_warn_event.EntryType | Assert-Equal -Expected "Warning" + $actual_warn_event.Message | Assert-Equal -Expected "undefined win module - [WARNING] warning" $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected = @{ changed = $false @@ -1266,11 +1315,11 @@ test_no_log - Invoked with: } warnings = @("warning") deprecations = @( - @{msg = "message"; date = "2020-01-01"; collection_name = $null}, - @{msg = "message w collection"; date = "2020-01-02"; collection_name = "ansible.builtin"} + @{msg = "message"; date = "2020-01-01"; collection_name = $null }, + @{msg = "message w collection"; date = "2020-01-02"; collection_name = "ansible.builtin" } ) } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "FailJson with message" = { @@ -1279,12 +1328,13 @@ test_no_log - Invoked with: $failed = $false try { $m.FailJson("fail message") - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $failed + $failed | Assert-Equal -Expected $failed $expected = @{ changed = $false @@ -1294,7 +1344,7 @@ test_no_log - Invoked with: failed = $true msg = "fail message" } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "FailJson with Exception" = { @@ -1302,19 +1352,21 @@ test_no_log - Invoked with: try { [System.IO.Path]::GetFullPath($null) - } catch { + } + catch { $excp = $_.Exception } $failed = $false try { $m.FailJson("fail message", $excp) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $failed + $failed | Assert-Equal -Expected $failed $expected = @{ changed = $false @@ -1324,7 +1376,7 @@ test_no_log - Invoked with: failed = $true msg = "fail message" } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "FailJson with ErrorRecord" = { @@ -1332,19 +1384,21 @@ test_no_log - Invoked with: try { Get-Item -LiteralPath $null - } catch { + } + catch { $error_record = $_ } $failed = $false try { $m.FailJson("fail message", $error_record) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $failed + $failed | Assert-Equal -Expected $failed $expected = @{ changed = $false @@ -1354,7 +1408,7 @@ test_no_log - Invoked with: failed = $true msg = "fail message" } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "FailJson with Exception and verbosity 3" = { @@ -1365,25 +1419,28 @@ test_no_log - Invoked with: try { [System.IO.Path]::GetFullPath($null) - } catch { + } + catch { $excp = $_.Exception } $failed = $false try { $m.FailJson("fail message", $excp) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $failed + $failed | Assert-Equal -Expected $failed - $actual.changed | Assert-Equals -Expected $false - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = @{}} - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected "fail message" - $actual.exception.Contains('System.Management.Automation.MethodInvocationException: Exception calling "GetFullPath" with "1" argument(s)') | Assert-Equals -Expected $true + $actual.changed | Assert-Equal -Expected $false + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = @{} } + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected "fail message" + $expected = 'System.Management.Automation.MethodInvocationException: Exception calling "GetFullPath" with "1" argument(s)' + $actual.exception.Contains($expected) | Assert-Equal -Expected $true } "FailJson with ErrorRecord and verbosity 3" = { @@ -1394,43 +1451,46 @@ test_no_log - Invoked with: try { Get-Item -LiteralPath $null - } catch { + } + catch { $error_record = $_ } $failed = $false try { $m.FailJson("fail message", $error_record) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $failed + $failed | Assert-Equal -Expected $failed - $actual.changed | Assert-Equals -Expected $false - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = @{}} - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected "fail message" - $actual.exception.Contains("Cannot bind argument to parameter 'LiteralPath' because it is null") | Assert-Equals -Expected $true - $actual.exception.Contains("+ Get-Item -LiteralPath `$null") | Assert-Equals -Expected $true - $actual.exception.Contains("ScriptStackTrace:") | Assert-Equals -Expected $true + $actual.changed | Assert-Equal -Expected $false + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = @{} } + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected "fail message" + $actual.exception.Contains("Cannot bind argument to parameter 'LiteralPath' because it is null") | Assert-Equal -Expected $true + $actual.exception.Contains("+ Get-Item -LiteralPath `$null") | Assert-Equal -Expected $true + $actual.exception.Contains("ScriptStackTrace:") | Assert-Equal -Expected $true } "Diff entry without diff set" = { $m = [Ansible.Basic.AnsibleModule]::Create(@(), @{}) - $m.Diff.before = @{a = "a"} - $m.Diff.after = @{b = "b"} + $m.Diff.before = @{a = "a" } + $m.Diff.after = @{b = "b" } $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $failed + $failed | Assert-Equal -Expected $failed $expected = @{ changed = $false @@ -1438,7 +1498,7 @@ test_no_log - Invoked with: module_args = @{} } } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "Diff entry with diff set" = { @@ -1446,18 +1506,19 @@ test_no_log - Invoked with: _ansible_diff = $true } $m = [Ansible.Basic.AnsibleModule]::Create(@(), @{}) - $m.Diff.before = @{a = "a"} - $m.Diff.after = @{b = "b"} + $m.Diff.before = @{a = "a" } + $m.Diff.after = @{b = "b" } $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $failed + $failed | Assert-Equal -Expected $failed $expected = @{ changed = $false @@ -1465,11 +1526,11 @@ test_no_log - Invoked with: module_args = @{} } diff = @{ - before = @{a = "a"} - after = @{b = "b"} + before = @{a = "a" } + after = @{b = "b" } } } - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } "ParseBool tests" = { @@ -1508,8 +1569,8 @@ test_no_log - Invoked with: foreach ($map in $mapping.GetEnumerator()) { $expected = $map.Value $actual = [Ansible.Basic.AnsibleModule]::ParseBool($map.Key) - $actual | Assert-Equals -Expected $expected - $actual.GetType().FullName | Assert-Equals -Expected "System.Boolean" + $actual | Assert-Equal -Expected $expected + $actual.GetType().FullName | Assert-Equal -Expected "System.Boolean" } $fail_bools = @( @@ -1523,11 +1584,12 @@ test_no_log - Invoked with: $failed = $false try { [Ansible.Basic.AnsibleModule]::ParseBool($fail_bool) - } catch { + } + catch { $failed = $true - $_.Exception.Message.Contains("The value '$fail_bool' is not a valid boolean") | Assert-Equals -Expected $true + $_.Exception.Message.Contains("The value '$fail_bool' is not a valid boolean") | Assert-Equal -Expected $true } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } } @@ -1538,9 +1600,10 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), @{}) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $expected = @{ invocation = @{ @@ -1553,9 +1616,9 @@ test_no_log - Invoked with: msg = "Unsupported parameters for (undefined win module) module: _ansible_invalid. Supported parameters include: " } $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) - $actual | Assert-DictionaryEquals -Expected $expected + $actual | Assert-DictionaryEqual -Expected $expected } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "Module tmpdir with present remote tmp" = { @@ -1577,29 +1640,30 @@ test_no_log - Invoked with: _ansible_remote_tmp = $remote_tmp.ToString() } $m = [Ansible.Basic.AnsibleModule]::Create(@(), @{}) - (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equals -Expected $true + (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equal -Expected $true $actual_tmpdir = $m.Tmpdir $parent_tmpdir = Split-Path -Path $actual_tmpdir -Parent $tmpdir_name = Split-Path -Path $actual_tmpdir -Leaf - $parent_tmpdir | Assert-Equals -Expected $remote_tmp - $tmpdir_name.StartSwith("ansible-moduletmp-") | Assert-Equals -Expected $true - (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equals -Expected $true - (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equals -Expected $true + $parent_tmpdir | Assert-Equal -Expected $remote_tmp + $tmpdir_name.StartSwith("ansible-moduletmp-") | Assert-Equal -Expected $true + (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equal -Expected $true + (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equal -Expected $true $children = [System.IO.Directory]::EnumerateDirectories($remote_tmp) - $children.Count | Assert-Equals -Expected 1 + $children.Count | Assert-Equal -Expected 1 $actual_tmpdir_sd = (Get-Acl -Path $actual_tmpdir).GetSecurityDescriptorSddlForm("Access, Owner") - $actual_tmpdir_sd | Assert-Equals -Expected $expected_sd + $actual_tmpdir_sd | Assert-Equal -Expected $expected_sd try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $output = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equals -Expected $false - (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equals -Expected $true - $output.warnings.Count | Assert-Equals -Expected 0 + (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equal -Expected $false + (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equal -Expected $true + $output.warnings.Count | Assert-Equal -Expected 0 } "Module tmpdir with missing remote_tmp" = { @@ -1620,36 +1684,37 @@ test_no_log - Invoked with: _ansible_remote_tmp = $remote_tmp.ToString() } $m = [Ansible.Basic.AnsibleModule]::Create(@(), @{}) - (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equals -Expected $false + (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equal -Expected $false $actual_tmpdir = $m.Tmpdir $parent_tmpdir = Split-Path -Path $actual_tmpdir -Parent $tmpdir_name = Split-Path -Path $actual_tmpdir -Leaf - $parent_tmpdir | Assert-Equals -Expected $remote_tmp - $tmpdir_name.StartSwith("ansible-moduletmp-") | Assert-Equals -Expected $true - (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equals -Expected $true - (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equals -Expected $true + $parent_tmpdir | Assert-Equal -Expected $remote_tmp + $tmpdir_name.StartSwith("ansible-moduletmp-") | Assert-Equal -Expected $true + (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equal -Expected $true + (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equal -Expected $true $children = [System.IO.Directory]::EnumerateDirectories($remote_tmp) - $children.Count | Assert-Equals -Expected 1 + $children.Count | Assert-Equal -Expected 1 $actual_remote_sd = (Get-Acl -Path $remote_tmp).GetSecurityDescriptorSddlForm("Access, Owner") $actual_tmpdir_sd = (Get-Acl -Path $actual_tmpdir).GetSecurityDescriptorSddlForm("Access, Owner") - $actual_remote_sd | Assert-Equals -Expected $expected_sd - $actual_tmpdir_sd | Assert-Equals -Expected $expected_sd + $actual_remote_sd | Assert-Equal -Expected $expected_sd + $actual_tmpdir_sd | Assert-Equal -Expected $expected_sd try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $output = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equals -Expected $false - (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equals -Expected $true - $output.warnings.Count | Assert-Equals -Expected 1 + (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equal -Expected $false + (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equal -Expected $true + $output.warnings.Count | Assert-Equal -Expected 1 $nt_account = $current_user.Translate([System.Security.Principal.NTAccount]) $actual_warning = "Module remote_tmp $remote_tmp did not exist and was created with FullControl to $nt_account, " $actual_warning += "this may cause issues when running as another user. To avoid this, " $actual_warning += "create the remote_tmp dir with the correct permissions manually" - $actual_warning | Assert-Equals -Expected $output.warnings[0] + $actual_warning | Assert-Equal -Expected $output.warnings[0] } "Module tmp, keep remote files" = { @@ -1665,19 +1730,20 @@ test_no_log - Invoked with: $parent_tmpdir = Split-Path -Path $actual_tmpdir -Parent $tmpdir_name = Split-Path -Path $actual_tmpdir -Leaf - $parent_tmpdir | Assert-Equals -Expected $remote_tmp - $tmpdir_name.StartSwith("ansible-moduletmp-") | Assert-Equals -Expected $true - (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equals -Expected $true - (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equals -Expected $true + $parent_tmpdir | Assert-Equal -Expected $remote_tmp + $tmpdir_name.StartSwith("ansible-moduletmp-") | Assert-Equal -Expected $true + (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equal -Expected $true + (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equal -Expected $true try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $output = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equals -Expected $true - (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equals -Expected $true - $output.warnings.Count | Assert-Equals -Expected 0 + (Test-Path -LiteralPath $actual_tmpdir -PathType Container) | Assert-Equal -Expected $true + (Test-Path -LiteralPath $remote_tmp -PathType Container) | Assert-Equal -Expected $true + $output.warnings.Count | Assert-Equal -Expected 0 Remove-Item -LiteralPath $actual_tmpdir -Force -Recurse } @@ -1688,22 +1754,23 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "internal error: argument spec entry contains an invalid key 'invalid', valid keys: apply_defaults, " $expected_msg += "aliases, choices, default, deprecated_aliases, elements, mutually_exclusive, no_log, options, " $expected_msg += "removed_in_version, removed_at_date, removed_from_collection, required, required_by, required_if, " $expected_msg += "required_one_of, required_together, supports_check_mode, type" - $actual.Keys.Count | Assert-Equals -Expected 3 - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - ("exception" -cin $actual.Keys) | Assert-Equals -Expected $true + $actual.Keys.Count | Assert-Equal -Expected 3 + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + ("exception" -cin $actual.Keys) | Assert-Equal -Expected $true } "Invalid argument spec key - nested" = { @@ -1721,22 +1788,23 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "internal error: argument spec entry contains an invalid key 'invalid', valid keys: apply_defaults, " $expected_msg += "aliases, choices, default, deprecated_aliases, elements, mutually_exclusive, no_log, options, " $expected_msg += "removed_in_version, removed_at_date, removed_from_collection, required, required_by, required_if, " $expected_msg += "required_one_of, required_together, supports_check_mode, type - found in option_key -> sub_option_key" - $actual.Keys.Count | Assert-Equals -Expected 3 - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - ("exception" -cin $actual.Keys) | Assert-Equals -Expected $true + $actual.Keys.Count | Assert-Equal -Expected 3 + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + ("exception" -cin $actual.Keys) | Assert-Equal -Expected $true } "Invalid argument spec value type" = { @@ -1746,20 +1814,21 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "internal error: argument spec for 'apply_defaults' did not match expected " $expected_msg += "type System.Boolean: actual type System.String" - $actual.Keys.Count | Assert-Equals -Expected 3 - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - ("exception" -cin $actual.Keys) | Assert-Equals -Expected $true + $actual.Keys.Count | Assert-Equal -Expected 3 + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + ("exception" -cin $actual.Keys) | Assert-Equal -Expected $true } "Invalid argument spec option type" = { @@ -1773,20 +1842,21 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "internal error: type 'invalid type' is unsupported - found in option_key. " $expected_msg += "Valid types are: bool, dict, float, int, json, list, path, raw, sid, str" - $actual.Keys.Count | Assert-Equals -Expected 3 - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - ("exception" -cin $actual.Keys) | Assert-Equals -Expected $true + $actual.Keys.Count | Assert-Equal -Expected 3 + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + ("exception" -cin $actual.Keys) | Assert-Equal -Expected $true } "Invalid argument spec option element type" = { @@ -1801,20 +1871,21 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "internal error: elements 'invalid type' is unsupported - found in option_key. " $expected_msg += "Valid types are: bool, dict, float, int, json, list, path, raw, sid, str" - $actual.Keys.Count | Assert-Equals -Expected 3 - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - ("exception" -cin $actual.Keys) | Assert-Equals -Expected $true + $actual.Keys.Count | Assert-Equal -Expected 3 + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + ("exception" -cin $actual.Keys) | Assert-Equal -Expected $true } "Invalid deprecated aliases entry - no version and date" = { @@ -1822,9 +1893,9 @@ test_no_log - Invoked with: options = @{ option_key = @{ type = "str" - aliases = ,"alias_name" + aliases = , "alias_name" deprecated_aliases = @( - @{name = "alias_name"} + @{name = "alias_name" } ) } } @@ -1833,19 +1904,20 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "internal error: One of version or date is required in a deprecated_aliases entry" - $actual.Keys.Count | Assert-Equals -Expected 3 - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - ("exception" -cin $actual.Keys) | Assert-Equals -Expected $true + $actual.Keys.Count | Assert-Equal -Expected 3 + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + ("exception" -cin $actual.Keys) | Assert-Equal -Expected $true } "Invalid deprecated aliases entry - no name (nested)" = { @@ -1856,9 +1928,9 @@ test_no_log - Invoked with: options = @{ sub_option_key = @{ type = "str" - aliases = ,"alias_name" + aliases = , "alias_name" deprecated_aliases = @( - @{version = "2.10"} + @{version = "2.10" } ) } } @@ -1875,12 +1947,13 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.ArgumentException] { + } + catch [System.ArgumentException] { $failed = $true $expected_msg = "name is required in a deprecated_aliases entry - found in option_key" - $_.Exception.Message | Assert-Equals -Expected $expected_msg + $_.Exception.Message | Assert-Equal -Expected $expected_msg } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "Invalid deprecated aliases entry - both version and date" = { @@ -1888,7 +1961,7 @@ test_no_log - Invoked with: options = @{ option_key = @{ type = "str" - aliases = ,"alias_name" + aliases = , "alias_name" deprecated_aliases = @( @{ name = "alias_name" @@ -1903,19 +1976,20 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "internal error: Only one of version or date is allowed in a deprecated_aliases entry" - $actual.Keys.Count | Assert-Equals -Expected 3 - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - ("exception" -cin $actual.Keys) | Assert-Equals -Expected $true + $actual.Keys.Count | Assert-Equal -Expected 3 + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + ("exception" -cin $actual.Keys) | Assert-Equal -Expected $true } "Invalid deprecated aliases entry - wrong date type" = { @@ -1923,7 +1997,7 @@ test_no_log - Invoked with: options = @{ option_key = @{ type = "str" - aliases = ,"alias_name" + aliases = , "alias_name" deprecated_aliases = @( @{ name = "alias_name" @@ -1937,19 +2011,20 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "internal error: A deprecated_aliases date must be a DateTime object" - $actual.Keys.Count | Assert-Equals -Expected 3 - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - ("exception" -cin $actual.Keys) | Assert-Equals -Expected $true + $actual.Keys.Count | Assert-Equal -Expected 3 + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + ("exception" -cin $actual.Keys) | Assert-Equal -Expected $true } "Spec required and default set at the same time" = { @@ -1965,19 +2040,20 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "internal error: required and default are mutually exclusive for option_key" - $actual.Keys.Count | Assert-Equals -Expected 3 - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - ("exception" -cin $actual.Keys) | Assert-Equals -Expected $true + $actual.Keys.Count | Assert-Equal -Expected 3 + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + ("exception" -cin $actual.Keys) | Assert-Equal -Expected $true } "Unsupported options" = { @@ -1997,21 +2073,22 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "Unsupported parameters for (undefined win module) module: another_key, invalid_key. " $expected_msg += "Supported parameters include: option_key" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Check mode and module doesn't support check mode" = { @@ -2030,20 +2107,21 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "remote module (undefined win module) does not support check mode" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.skipped | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = @{option_key = "abc"}} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.skipped | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = @{option_key = "abc" } } } "Check mode with suboption without supports_check_mode" = { @@ -2065,7 +2143,7 @@ test_no_log - Invoked with: } $m = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - $m.CheckMode | Assert-Equals -Expected $true + $m.CheckMode | Assert-Equal -Expected $true } "Type conversion error" = { @@ -2083,21 +2161,22 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "argument for option_key is of type System.String and we were unable to convert to int: " $expected_msg += "Input string was not in a correct format." - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Type conversion error - delegate" = { @@ -2107,7 +2186,7 @@ test_no_log - Invoked with: type = "dict" options = @{ sub_option_key = @{ - type = [Func[[Object], [UInt64]]]{ [System.UInt64]::Parse($args[0]) } + type = [Func[[Object], [UInt64]]] { [System.UInt64]::Parse($args[0]) } } } } @@ -2122,22 +2201,23 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "argument for sub_option_key is of type System.String and we were unable to convert to delegate: " $expected_msg += "Exception calling `"Parse`" with `"1`" argument(s): `"Input string was not in a correct format.`" " $expected_msg += "found in option_key" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Numeric choices" = { @@ -2156,12 +2236,13 @@ test_no_log - Invoked with: $m = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $output = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $output.Keys.Count | Assert-Equals -Expected 2 - $output.changed | Assert-Equals -Expected $false - $output.invocation | Assert-DictionaryEquals -Expected @{module_args = @{option_key = 2}} + $output.Keys.Count | Assert-Equal -Expected 2 + $output.changed | Assert-Equal -Expected $false + $output.invocation | Assert-DictionaryEqual -Expected @{module_args = @{option_key = 2 } } } "Case insensitive choice" = { @@ -2179,17 +2260,18 @@ test_no_log - Invoked with: $m = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $output = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } $expected_warning = "value of option_key was a case insensitive match of one of: abc, def. " $expected_warning += "Checking of choices will be case sensitive in a future Ansible release. " $expected_warning += "Case insensitive matches were: ABC" - $output.invocation | Assert-DictionaryEquals -Expected @{module_args = @{option_key = "ABC"}} + $output.invocation | Assert-DictionaryEqual -Expected @{module_args = @{option_key = "ABC" } } # We have disabled the warnings for now - #$output.warnings.Count | Assert-Equals -Expected 1 - #$output.warnings[0] | Assert-Equals -Expected $expected_warning + #$output.warnings.Count | Assert-Equal -Expected 1 + #$output.warnings[0] | Assert-Equal -Expected $expected_warning } "Case insensitive choice no_log" = { @@ -2208,17 +2290,18 @@ test_no_log - Invoked with: $m = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $output = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } $expected_warning = "value of option_key was a case insensitive match of one of: abc, def. " $expected_warning += "Checking of choices will be case sensitive in a future Ansible release. " $expected_warning += "Case insensitive matches were: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER" - $output.invocation | Assert-DictionaryEquals -Expected @{module_args = @{option_key = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"}} + $output.invocation | Assert-DictionaryEqual -Expected @{module_args = @{option_key = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER" } } # We have disabled the warnings for now - #$output.warnings.Count | Assert-Equals -Expected 1 - #$output.warnings[0] | Assert-Equals -Expected $expected_warning + #$output.warnings.Count | Assert-Equal -Expected 1 + #$output.warnings[0] | Assert-Equal -Expected $expected_warning } "Case insentitive choice as list" = { @@ -2238,17 +2321,18 @@ test_no_log - Invoked with: $m = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $output = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } $expected_warning = "value of option_key was a case insensitive match of one or more of: abc, def, ghi, JKL. " $expected_warning += "Checking of choices will be case sensitive in a future Ansible release. " $expected_warning += "Case insensitive matches were: AbC, jkl" - $output.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $output.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } # We have disabled the warnings for now - #$output.warnings.Count | Assert-Equals -Expected 1 - #$output.warnings[0] | Assert-Equals -Expected $expected_warning + #$output.warnings.Count | Assert-Equal -Expected 1 + #$output.warnings[0] | Assert-Equal -Expected $expected_warning } "Invalid choice" = { @@ -2266,20 +2350,21 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "value of option_key must be one of: a, b. Got no match for: c" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Invalid choice with no_log" = { @@ -2298,20 +2383,21 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "value of option_key must be one of: a, b. Got no match for: ********" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = @{option_key = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"}} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = @{option_key = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER" } } } "Invalid choice in list" = { @@ -2330,20 +2416,21 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "value of option_key must be one or more of: a, b. Got no match for: c" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Mutually exclusive options" = { @@ -2352,7 +2439,7 @@ test_no_log - Invoked with: option1 = @{} option2 = @{} } - mutually_exclusive = @(,@("option1", "option2")) + mutually_exclusive = @(, @("option1", "option2")) } Set-Variable -Name complex_args -Scope Global -Value @{ option1 = "a" @@ -2362,27 +2449,28 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "parameters are mutually exclusive: option1, option2" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Missing required argument" = { $spec = @{ options = @{ option1 = @{} - option2 = @{required = $true} + option2 = @{required = $true } } } Set-Variable -Name complex_args -Scope Global -Value @{ @@ -2392,20 +2480,21 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "missing required arguments: option2" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Missing required argument subspec - no value defined" = { @@ -2426,16 +2515,17 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true - $actual.Keys.Count | Assert-Equals -Expected 2 - $actual.changed | Assert-Equals -Expected $false - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 2 + $actual.changed | Assert-Equal -Expected $false + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Missing required argument subspec" = { @@ -2461,20 +2551,21 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "missing required arguments: sub_option_key found in option_key" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Required together not set" = { @@ -2483,7 +2574,7 @@ test_no_log - Invoked with: option1 = @{} option2 = @{} } - required_together = @(,@("option1", "option2")) + required_together = @(, @("option1", "option2")) } Set-Variable -Name complex_args -Scope Global -Value @{ option1 = "abc" @@ -2492,20 +2583,21 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "parameters are required together: option1, option2" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Required together not set - subspec" = { @@ -2517,11 +2609,11 @@ test_no_log - Invoked with: option1 = @{} option2 = @{} } - required_together = @(,@("option1", "option2")) + required_together = @(, @("option1", "option2")) } another_option = @{} } - required_together = @(,@("option_key", "another_option")) + required_together = @(, @("option_key", "another_option")) } Set-Variable -Name complex_args -Scope Global -Value @{ option_key = @{ @@ -2533,20 +2625,21 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "parameters are required together: option1, option2 found in option_key" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Required one of not set" = { @@ -2565,58 +2658,60 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "one of the following is required: option2, option3" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Required if invalid entries" = { $spec = @{ options = @{ - state = @{choices = "absent", "present"; default = "present"} - path = @{type = "path"} + state = @{choices = "absent", "present"; default = "present" } + path = @{type = "path" } } - required_if = @(,@("state", "absent")) + required_if = @(, @("state", "absent")) } $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "internal error: invalid required_if value count of 2, expecting 3 or 4 entries" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Required if no missing option" = { $spec = @{ options = @{ - state = @{choices = "absent", "present"; default = "present"} + state = @{choices = "absent", "present"; default = "present" } name = @{} - path = @{type = "path"} + path = @{type = "path" } } - required_if = @(,@("state", "absent", @("name", "path"))) + required_if = @(, @("state", "absent", @("name", "path"))) } Set-Variable -Name complex_args -Scope Global -Value @{ name = "abc" @@ -2626,26 +2721,27 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true - $actual.Keys.Count | Assert-Equals -Expected 2 - $actual.changed | Assert-Equals -Expected $false - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 2 + $actual.changed | Assert-Equal -Expected $false + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Required if missing option" = { $spec = @{ options = @{ - state = @{choices = "absent", "present"; default = "present"} + state = @{choices = "absent", "present"; default = "present" } name = @{} - path = @{type = "path"} + path = @{type = "path" } } - required_if = @(,@("state", "absent", @("name", "path"))) + required_if = @(, @("state", "absent", @("name", "path"))) } Set-Variable -Name complex_args -Scope Global -Value @{ state = "absent" @@ -2655,30 +2751,31 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "state is absent but all of the following are missing: path" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Required if missing option and required one is set" = { $spec = @{ options = @{ - state = @{choices = "absent", "present"; default = "present"} + state = @{choices = "absent", "present"; default = "present" } name = @{} - path = @{type = "path"} + path = @{type = "path" } } - required_if = @(,@("state", "absent", @("name", "path"), $true)) + required_if = @(, @("state", "absent", @("name", "path"), $true)) } Set-Variable -Name complex_args -Scope Global -Value @{ state = "absent" @@ -2687,30 +2784,31 @@ test_no_log - Invoked with: $failed = $false try { $null = [Ansible.Basic.AnsibleModule]::Create(@(), $spec) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $expected_msg = "state is absent but any of the following are missing: name, path" - $actual.Keys.Count | Assert-Equals -Expected 4 - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected $expected_msg - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 4 + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected $expected_msg + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Required if missing option but one required set" = { $spec = @{ options = @{ - state = @{choices = "absent", "present"; default = "present"} + state = @{choices = "absent", "present"; default = "present" } name = @{} - path = @{type = "path"} + path = @{type = "path" } } - required_if = @(,@("state", "absent", @("name", "path"), $true)) + required_if = @(, @("state", "absent", @("name", "path"), $true)) } Set-Variable -Name complex_args -Scope Global -Value @{ state = "absent" @@ -2721,16 +2819,17 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true - $actual.Keys.Count | Assert-Equals -Expected 2 - $actual.changed | Assert-Equals -Expected $false - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.Keys.Count | Assert-Equal -Expected 2 + $actual.changed | Assert-Equal -Expected $false + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "PS Object in return result" = { @@ -2738,38 +2837,39 @@ test_no_log - Invoked with: # JavaScriptSerializer struggles with PS Object like PSCustomObject due to circular references, this test makes # sure we can handle these types of objects without bombing - $m.Result.output = [PSCustomObject]@{a = "a"; b = "b"} + $m.Result.output = [PSCustomObject]@{a = "a"; b = "b" } $failed = $true try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true - $actual.Keys.Count | Assert-Equals -Expected 3 - $actual.changed | Assert-Equals -Expected $false - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = @{}} - $actual.output | Assert-DictionaryEquals -Expected @{a = "a"; b = "b"} + $actual.Keys.Count | Assert-Equal -Expected 3 + $actual.changed | Assert-Equal -Expected $false + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = @{} } + $actual.output | Assert-DictionaryEqual -Expected @{a = "a"; b = "b" } } "String json array to object" = { $input_json = '["abc", "def"]' $actual = [Ansible.Basic.AnsibleModule]::FromJson($input_json) - $actual -is [Array] | Assert-Equals -Expected $true - $actual.Length | Assert-Equals -Expected 2 - $actual[0] | Assert-Equals -Expected "abc" - $actual[1] | Assert-Equals -Expected "def" + $actual -is [Array] | Assert-Equal -Expected $true + $actual.Length | Assert-Equal -Expected 2 + $actual[0] | Assert-Equal -Expected "abc" + $actual[1] | Assert-Equal -Expected "def" } "String json array of dictionaries to object" = { $input_json = '[{"abc":"def"}]' $actual = [Ansible.Basic.AnsibleModule]::FromJson($input_json) - $actual -is [Array] | Assert-Equals -Expected $true - $actual.Length | Assert-Equals -Expected 1 - $actual[0] | Assert-DictionaryEquals -Expected @{"abc" = "def"} + $actual -is [Array] | Assert-Equal -Expected $true + $actual.Length | Assert-Equal -Expected 1 + $actual[0] | Assert-DictionaryEqual -Expected @{"abc" = "def" } } "Spec with fragments" = { @@ -2793,15 +2893,16 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true - $actual.changed | Assert-Equals -Expected $false - $actual.invocation | Assert-DictionaryEquals -Expected @{module_args = $complex_args} + $actual.changed | Assert-Equal -Expected $false + $actual.invocation | Assert-DictionaryEqual -Expected @{module_args = $complex_args } } "Fragment spec that with a deprecated alias" = { @@ -2811,13 +2912,13 @@ test_no_log - Invoked with: aliases = @("alias1_spec") type = "str" deprecated_aliases = @( - @{name = "alias1_spec"; version = "2.0"} + @{name = "alias1_spec"; version = "2.0" } ) } option2 = @{ aliases = @("alias2_spec") deprecated_aliases = @( - @{name = "alias2_spec"; version = "2.0"; collection_name = "ansible.builtin"} + @{name = "alias2_spec"; version = "2.0"; collection_name = "ansible.builtin" } ) } } @@ -2831,7 +2932,7 @@ test_no_log - Invoked with: option2 = @{ aliases = @("alias2") deprecated_aliases = @( - @{name = "alias2"; version = "2.0"; collection_name = "foo.bar"} + @{name = "alias2"; version = "2.0"; collection_name = "foo.bar" } ) type = "str" } @@ -2847,22 +2948,23 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true - $actual.deprecations.Count | Assert-Equals -Expected 2 - $actual.deprecations[0] | Assert-DictionaryEquals -Expected @{ + $actual.deprecations.Count | Assert-Equal -Expected 2 + $actual.deprecations[0] | Assert-DictionaryEqual -Expected @{ msg = "Alias 'alias1_spec' is deprecated. See the module docs for more information"; version = "2.0"; collection_name = $null } - $actual.deprecations[1] | Assert-DictionaryEquals -Expected @{ + $actual.deprecations[1] | Assert-DictionaryEqual -Expected @{ msg = "Alias 'alias2' is deprecated. See the module docs for more information"; version = "2.0"; collection_name = "foo.bar" } - $actual.changed | Assert-Equals -Expected $false - $actual.invocation | Assert-DictionaryEquals -Expected @{ + $actual.changed | Assert-Equal -Expected $false + $actual.invocation | Assert-DictionaryEqual -Expected @{ module_args = @{ option1 = "option1" alias1_spec = "option1" @@ -2879,7 +2981,7 @@ test_no_log - Invoked with: option2 = @{ type = "str" } } mutually_exclusive = @( - ,@('option1', 'option2') + , @('option1', 'option2') ) } $fragment1 = @{ @@ -2888,7 +2990,7 @@ test_no_log - Invoked with: fragment1_2 = @{ type = "str" } } mutually_exclusive = @( - ,@('fragment1_1', 'fragment1_2') + , @('fragment1_1', 'fragment1_2') ) } $fragment2 = @{ @@ -2907,17 +3009,18 @@ test_no_log - Invoked with: $failed = $false try { [Ansible.Basic.AnsibleModule]::Create(@(), $spec, @($fragment1, $fragment2)) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true - $actual.changed | Assert-Equals -Expected $false - $actual.failed | Assert-Equals -Expected $true - $actual.msg | Assert-Equals -Expected "parameters are mutually exclusive: fragment1_1, fragment1_2" - $actual.invocation | Assert-DictionaryEquals -Expected @{ module_args = $complex_args } + $actual.changed | Assert-Equal -Expected $false + $actual.failed | Assert-Equal -Expected $true + $actual.msg | Assert-Equal -Expected "parameters are mutually exclusive: fragment1_1, fragment1_2" + $actual.invocation | Assert-DictionaryEqual -Expected @{ module_args = $complex_args } } "Fragment spec with no_log" = { @@ -2945,15 +3048,16 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true - $actual.changed | Assert-Equals -Expected $false - $actual.invocation | Assert-DictionaryEquals -Expected @{ + $actual.changed | Assert-Equal -Expected $false + $actual.invocation | Assert-DictionaryEqual -Expected @{ module_args = @{ option1 = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER" alias = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER" @@ -2979,15 +3083,16 @@ test_no_log - Invoked with: $failed = $false try { [Ansible.Basic.AnsibleModule]::Create(@(), $spec, @($fragment)) - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 1" + $_.Exception.Message | Assert-Equal -Expected "exit: 1" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true - $actual.failed | Assert-Equals -Expected $true - $actual.msg.StartsWith("internal error: argument spec entry contains an invalid key 'invalid', valid keys: ") | Assert-Equals -Expected $true + $actual.failed | Assert-Equal -Expected $true + $actual.msg.StartsWith("internal error: argument spec entry contains an invalid key 'invalid', valid keys: ") | Assert-Equal -Expected $true } "Spec with different list types" = { @@ -2996,25 +3101,25 @@ test_no_log - Invoked with: # Single element of the same list type not in a list option1 = @{ aliases = "alias1" - deprecated_aliases = @{name="alias1";version="2.0";collection_name="foo.bar"} + deprecated_aliases = @{name = "alias1"; version = "2.0"; collection_name = "foo.bar" } } # Arrays option2 = @{ - aliases = ,"alias2" - deprecated_aliases = ,@{name="alias2";version="2.0";collection_name="foo.bar"} + aliases = , "alias2" + deprecated_aliases = , @{name = "alias2"; version = "2.0"; collection_name = "foo.bar" } } # ArrayList option3 = @{ aliases = [System.Collections.ArrayList]@("alias3") - deprecated_aliases = [System.Collections.ArrayList]@(@{name="alias3";version="2.0";collection_name="foo.bar"}) + deprecated_aliases = [System.Collections.ArrayList]@(@{name = "alias3"; version = "2.0"; collection_name = "foo.bar" }) } # Generic.List[Object] option4 = @{ aliases = [System.Collections.Generic.List[Object]]@("alias4") - deprecated_aliases = [System.Collections.Generic.List[Object]]@(@{name="alias4";version="2.0";collection_name="foo.bar"}) + deprecated_aliases = [System.Collections.Generic.List[Object]]@(@{name = "alias4"; version = "2.0"; collection_name = "foo.bar" }) } # Generic.List[T] @@ -3024,7 +3129,7 @@ test_no_log - Invoked with: } } } - $spec.options.option5.deprecated_aliases.Add(@{name="alias5";version="2.0";collection_name="foo.bar"}) + $spec.options.option5.deprecated_aliases.Add(@{name = "alias5"; version = "2.0"; collection_name = "foo.bar" }) Set-Variable -Name complex_args -Scope Global -Value @{ alias1 = "option1" @@ -3038,21 +3143,22 @@ test_no_log - Invoked with: $failed = $false try { $m.ExitJson() - } catch [System.Management.Automation.RuntimeException] { + } + catch [System.Management.Automation.RuntimeException] { $failed = $true - $_.Exception.Message | Assert-Equals -Expected "exit: 0" + $_.Exception.Message | Assert-Equal -Expected "exit: 0" $actual = [Ansible.Basic.AnsibleModule]::FromJson($_.Exception.InnerException.Output) } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true - $actual.changed | Assert-Equals -Expected $false - $actual.deprecations.Count | Assert-Equals -Expected 5 + $actual.changed | Assert-Equal -Expected $false + $actual.deprecations.Count | Assert-Equal -Expected 5 foreach ($dep in $actual.deprecations) { - $dep.msg -like "Alias 'alias?' is deprecated. See the module docs for more information" | Assert-Equals -Expected $true - $dep.version | Assert-Equals -Expected '2.0' - $dep.collection_name | Assert-Equals -Expected 'foo.bar' + $dep.msg -like "Alias 'alias?' is deprecated. See the module docs for more information" | Assert-Equal -Expected $true + $dep.version | Assert-Equal -Expected '2.0' + $dep.collection_name | Assert-Equal -Expected 'foo.bar' } - $actual.invocation | Assert-DictionaryEquals -Expected @{ + $actual.invocation | Assert-DictionaryEqual -Expected @{ module_args = @{ alias1 = "option1" option1 = "option1" @@ -3078,7 +3184,8 @@ try { &$test_impl.Value } $module.Result.data = "success" -} catch [System.Management.Automation.RuntimeException] { +} +catch [System.Management.Automation.RuntimeException] { $module.Result.failed = $true $module.Result.test = $test $module.Result.line = $_.InvocationInfo.ScriptLineNumber @@ -3088,7 +3195,8 @@ try { # The exception was caused by an unexpected Exit call, log that on the output $module.Result.output = (ConvertFrom-Json -InputObject $_.Exception.InnerException.Output) $module.Result.msg = "Uncaught AnsibleModule exit in tests, see output" - } else { + } + else { # Unrelated exception $module.Result.exception = $_.Exception.ToString() $module.Result.msg = "Uncaught exception: $(($_ | Out-String).ToString())" diff --git a/test/integration/targets/module_utils_Ansible.Become/library/ansible_become_tests.ps1 b/test/integration/targets/module_utils_Ansible.Become/library/ansible_become_tests.ps1 index 4d1f319b3f..6e36321154 100644 --- a/test/integration/targets/module_utils_Ansible.Become/library/ansible_become_tests.ps1 +++ b/test/integration/targets/module_utils_Ansible.Become/library/ansible_become_tests.ps1 @@ -5,37 +5,40 @@ $module = [Ansible.Basic.AnsibleModule]::Create($args, @{}) -Function Assert-Equals { +Function Assert-Equal { param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected + [Parameter(Mandatory = $true, ValueFromPipeline = $true)][AllowNull()]$Actual, + [Parameter(Mandatory = $true, Position = 0)][AllowNull()]$Expected ) - $matched = $false - if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { - $Actual.Count | Assert-Equals -Expected $Expected.Count - for ($i = 0; $i -lt $Actual.Count; $i++) { - $actual_value = $Actual[$i] - $expected_value = $Expected[$i] - Assert-Equals -Actual $actual_value -Expected $expected_value + process { + $matched = $false + if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { + $Actual.Count | Assert-Equal -Expected $Expected.Count + for ($i = 0; $i -lt $Actual.Count; $i++) { + $actual_value = $Actual[$i] + $expected_value = $Expected[$i] + Assert-Equal -Actual $actual_value -Expected $expected_value + } + $matched = $true } - $matched = $true - } else { - $matched = $Actual -ceq $Expected - } - - if (-not $matched) { - if ($Actual -is [PSObject]) { - $Actual = $Actual.ToString() + else { + $matched = $Actual -ceq $Expected } - $call_stack = (Get-PSCallStack)[1] - $module.Result.test = $test - $module.Result.actual = $Actual - $module.Result.expected = $Expected - $module.Result.line = $call_stack.ScriptLineNumber - $module.Result.method = $call_stack.Position.Text - $module.FailJson("AssertionError: actual != expected") + if (-not $matched) { + if ($Actual -is [PSObject]) { + $Actual = $Actual.ToString() + } + + $call_stack = (Get-PSCallStack)[1] + $module.Result.test = $test + $module.Result.actual = $Actual + $module.Result.expected = $Expected + $module.Result.line = $call_stack.ScriptLineNumber + $module.Result.method = $call_stack.Position.Text + $module.FailJson("AssertionError: actual != expected") + } } } @@ -437,101 +440,101 @@ $tests = @{ "Runas standard user" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($standard_user, $become_pass, "powershell.exe -NoProfile -ExecutionPolicy ByPass -File $tmp_script") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Interactive" - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.UserSid.Value | Assert-Equals -Expected $standard_user_sid - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $medium_integrity_sid + $stdout.LogonType | Assert-Equal -Expected "Interactive" + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.UserSid.Value | Assert-Equal -Expected $standard_user_sid + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $medium_integrity_sid } "Runas admin user" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, $become_pass, "powershell.exe -NoProfile -ExecutionPolicy ByPass -File $tmp_script") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Interactive" - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.UserSid.Value | Assert-Equals -Expected $admin_user_sid - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $high_integrity_sid + $stdout.LogonType | Assert-Equal -Expected "Interactive" + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.UserSid.Value | Assert-Equal -Expected $admin_user_sid + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $high_integrity_sid } "Runas SYSTEM" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("SYSTEM", $null, "powershell.exe -NoProfile -ExecutionPolicy ByPass -File $tmp_script") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "System" - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.UserSid.Value | Assert-Equals -Expected "S-1-5-18" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $system_integrity_sid + $stdout.LogonType | Assert-Equal -Expected "System" + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.UserSid.Value | Assert-Equal -Expected "S-1-5-18" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $system_integrity_sid $with_domain = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("NT AUTHORITY\System", $null, "whoami.exe") - $with_domain.StandardOut | Assert-Equals -Expected "nt authority\system`r`n" + $with_domain.StandardOut | Assert-Equal -Expected "nt authority\system`r`n" } "Runas LocalService" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("LocalService", $null, "powershell.exe -NoProfile -ExecutionPolicy ByPass -File $tmp_script") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Service" - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.UserSid.Value | Assert-Equals -Expected "S-1-5-19" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $system_integrity_sid + $stdout.LogonType | Assert-Equal -Expected "Service" + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.UserSid.Value | Assert-Equal -Expected "S-1-5-19" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $system_integrity_sid $with_domain = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("NT AUTHORITY\LocalService", $null, "whoami.exe") - $with_domain.StandardOut | Assert-Equals -Expected "nt authority\local service`r`n" + $with_domain.StandardOut | Assert-Equal -Expected "nt authority\local service`r`n" } "Runas NetworkService" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("NetworkService", $null, "powershell.exe -NoProfile -ExecutionPolicy ByPass -File $tmp_script") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Service" - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.UserSid.Value | Assert-Equals -Expected "S-1-5-20" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $system_integrity_sid + $stdout.LogonType | Assert-Equal -Expected "Service" + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.UserSid.Value | Assert-Equal -Expected "S-1-5-20" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $system_integrity_sid $with_domain = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("NT AUTHORITY\NetworkService", $null, "whoami.exe") - $with_domain.StandardOut | Assert-Equals -Expected "nt authority\network service`r`n" + $with_domain.StandardOut | Assert-Equal -Expected "nt authority\network service`r`n" } "Runas without working dir set" = { $expected = "$env:SystemRoot\system32`r`n" $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($standard_user, $become_pass, 0, "Interactive", $null, 'powershell.exe $pwd.Path', $null, $null, "") - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "Runas with working dir set" = { $expected = "$env:SystemRoot`r`n" $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($standard_user, $become_pass, 0, "Interactive", $null, 'powershell.exe $pwd.Path', $env:SystemRoot, $null, "") - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "Runas without environment set" = { $expected = "Windows_NT`r`n" $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($standard_user, $become_pass, 0, "Interactive", $null, 'powershell.exe $env:TEST; $env:OS', $null, $null, "") - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "Runas with environment set" = { @@ -541,52 +544,53 @@ $tests = @{ } $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, $become_pass, 0, "Interactive", $null, 'cmd.exe /c set', $null, $env_vars, "") - ("TEST=tesTing" -cin $actual.StandardOut.Split("`r`n")) | Assert-Equals -Expected $true - ("TEST2=Testing 2" -cin $actual.StandardOut.Split("`r`n")) | Assert-Equals -Expected $true - ("OS=Windows_NT" -cnotin $actual.StandardOut.Split("`r`n")) | Assert-Equals -Expected $true - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + ("TEST=tesTing" -cin $actual.StandardOut.Split("`r`n")) | Assert-Equal -Expected $true + ("TEST2=Testing 2" -cin $actual.StandardOut.Split("`r`n")) | Assert-Equal -Expected $true + ("OS=Windows_NT" -cnotin $actual.StandardOut.Split("`r`n")) | Assert-Equal -Expected $true + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "Runas with string stdin" = { $expected = "input value`r`n`r`n" $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, $become_pass, 0, "Interactive", $null, 'powershell.exe [System.Console]::In.ReadToEnd()', $null, $null, "input value") - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "Runas with string stdin and newline" = { $expected = "input value`r`n`r`n" $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, $become_pass, 0, "Interactive", $null, 'powershell.exe [System.Console]::In.ReadToEnd()', $null, $null, "input value`r`n") - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "Runas with byte stdin" = { $expected = "input value`r`n" $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, $become_pass, 0, "Interactive", $null, 'powershell.exe [System.Console]::In.ReadToEnd()', $null, $null, [System.Text.Encoding]::UTF8.GetBytes("input value")) - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "Missing executable" = { $failed = $false try { [Ansible.Become.BecomeUtil]::CreateProcessAsUser("SYSTEM", $null, "fake.exe") - } catch { + } + catch { $failed = $true - $_.Exception.InnerException.GetType().FullName | Assert-Equals -Expected "Ansible.Process.Win32Exception" + $_.Exception.InnerException.GetType().FullName | Assert-Equal -Expected "Ansible.Process.Win32Exception" $expected = 'Exception calling "CreateProcessAsUser" with "3" argument(s): "CreateProcessWithTokenW() failed ' $expected += '(The system cannot find the file specified, Win32ErrorCode 2)"' - $_.Exception.Message | Assert-Equals -Expected $expected + $_.Exception.Message | Assert-Equal -Expected $expected } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "CreateProcessAsUser with lpApplicationName" = { @@ -594,112 +598,114 @@ $tests = @{ $full_path = "$($env:SystemRoot)\System32\WindowsPowerShell\v1.0\powershell.exe" $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("SYSTEM", $null, 0, "Interactive", $full_path, "Write-Output 'abc'", $null, $null, "") - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("SYSTEM", $null, 0, "Interactive", $full_path, "powershell.exe Write-Output 'abc'", $null, $null, "") - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcessAsUser with stderr" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("SYSTEM", $null, 0, "Interactive", $null, "powershell.exe [System.Console]::Error.WriteLine('hi')", $null, $null, "") - $actual.StandardOut | Assert-Equals -Expected "" - $actual.StandardError | Assert-Equals -Expected "hi`r`n" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected "" + $actual.StandardError | Assert-Equal -Expected "hi`r`n" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcessAsUser with exit code" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("SYSTEM", $null, 0, "Interactive", $null, "powershell.exe exit 10", $null, $null, "") - $actual.StandardOut | Assert-Equals -Expected "" - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 10 + $actual.StandardOut | Assert-Equal -Expected "" + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 10 } "Local account with computer name" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("$env:COMPUTERNAME\$standard_user", $become_pass, "powershell.exe -NoProfile -ExecutionPolicy ByPass -File $tmp_script") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Interactive" - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.UserSid.Value | Assert-Equals -Expected $standard_user_sid - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $medium_integrity_sid + $stdout.LogonType | Assert-Equal -Expected "Interactive" + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.UserSid.Value | Assert-Equal -Expected $standard_user_sid + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $medium_integrity_sid } "Local account with computer as period" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser(".\$standard_user", $become_pass, "powershell.exe -NoProfile -ExecutionPolicy ByPass -File $tmp_script") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Interactive" - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.UserSid.Value | Assert-Equals -Expected $standard_user_sid - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $medium_integrity_sid + $stdout.LogonType | Assert-Equal -Expected "Interactive" + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.UserSid.Value | Assert-Equal -Expected $standard_user_sid + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $medium_integrity_sid } "Local account with invalid password" = { $failed = $false try { [Ansible.Become.BecomeUtil]::CreateProcessAsUser($standard_user, "incorrect", "powershell.exe Write-Output abc") - } catch { + } + catch { $failed = $true - $_.Exception.InnerException.GetType().FullName | Assert-Equals -Expected "Ansible.AccessToken.Win32Exception" + $_.Exception.InnerException.GetType().FullName | Assert-Equal -Expected "Ansible.AccessToken.Win32Exception" # Server 2008 has a slightly different error msg, just assert we get the error 1326 - ($_.Exception.Message.Contains("Win32ErrorCode 1326")) | Assert-Equals -Expected $true + ($_.Exception.Message.Contains("Win32ErrorCode 1326")) | Assert-Equal -Expected $true } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "Invalid account" = { $failed = $false try { [Ansible.Become.BecomeUtil]::CreateProcessAsUser("incorrect", "incorrect", "powershell.exe Write-Output abc") - } catch { + } + catch { $failed = $true - $_.Exception.InnerException.GetType().FullName | Assert-Equals -Expected "System.Security.Principal.IdentityNotMappedException" + $_.Exception.InnerException.GetType().FullName | Assert-Equal -Expected "System.Security.Principal.IdentityNotMappedException" $expected = 'Exception calling "CreateProcessAsUser" with "3" argument(s): "Some or all ' $expected += 'identity references could not be translated."' - $_.Exception.Message | Assert-Equals -Expected $expected + $_.Exception.Message | Assert-Equal -Expected $expected } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "Interactive logon with standard" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($standard_user, $become_pass, "WithProfile", "Interactive", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Interactive" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $medium_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.SourceName | Assert-Equals -Expected "Advapi" - $stdout.UserSid.Value | Assert-Equals -Expected $standard_user_sid + $stdout.LogonType | Assert-Equal -Expected "Interactive" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $medium_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.SourceName | Assert-Equal -Expected "Advapi" + $stdout.UserSid.Value | Assert-Equal -Expected $standard_user_sid } "Batch logon with standard" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($standard_user, $become_pass, "WithProfile", "Batch", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Batch" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $medium_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.SourceName | Assert-Equals -Expected "Advapi" - $stdout.UserSid.Value | Assert-Equals -Expected $standard_user_sid + $stdout.LogonType | Assert-Equal -Expected "Batch" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $medium_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.SourceName | Assert-Equal -Expected "Advapi" + $stdout.UserSid.Value | Assert-Equal -Expected $standard_user_sid } "Network logon with standard" = { @@ -709,15 +715,15 @@ $tests = @{ } $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($standard_user, $become_pass, "WithProfile", "Network", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Network" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $medium_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.SourceName | Assert-Equals -Expected "Advapi" - $stdout.UserSid.Value | Assert-Equals -Expected $standard_user_sid + $stdout.LogonType | Assert-Equal -Expected "Network" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $medium_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.SourceName | Assert-Equal -Expected "Advapi" + $stdout.UserSid.Value | Assert-Equal -Expected $standard_user_sid } "Network with cleartext logon with standard" = { @@ -727,31 +733,31 @@ $tests = @{ } $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($standard_user, $become_pass, "WithProfile", "NetworkCleartext", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "NetworkCleartext" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $medium_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.SourceName | Assert-Equals -Expected "Advapi" - $stdout.UserSid.Value | Assert-Equals -Expected $standard_user_sid + $stdout.LogonType | Assert-Equal -Expected "NetworkCleartext" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $medium_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.SourceName | Assert-Equal -Expected "Advapi" + $stdout.UserSid.Value | Assert-Equal -Expected $standard_user_sid } "Logon without password with standard" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($standard_user, [NullString]::Value, "WithProfile", "Interactive", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 # Too unstable, there might be another process still lingering which causes become to steal instead of using # S4U. Just don't check the type and source to verify we can become without a password $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - # $stdout.LogonType | Assert-Equals -Expected "Batch" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $medium_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - # $stdout.SourceName | Assert-Equals -Expected "ansible" - $stdout.UserSid.Value | Assert-Equals -Expected $standard_user_sid + # $stdout.LogonType | Assert-Equal -Expected "Batch" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $medium_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + # $stdout.SourceName | Assert-Equal -Expected "ansible" + $stdout.UserSid.Value | Assert-Equal -Expected $standard_user_sid } "Logon without password and network type with standard" = { @@ -761,45 +767,45 @@ $tests = @{ } $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($standard_user, [NullString]::Value, "WithProfile", "Network", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 # Too unstable, there might be another process still lingering which causes become to steal instead of using # S4U. Just don't check the type and source to verify we can become without a password $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - # $stdout.LogonType | Assert-Equals -Expected "Network" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $medium_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - # $stdout.SourceName | Assert-Equals -Expected "ansible" - $stdout.UserSid.Value | Assert-Equals -Expected $standard_user_sid + # $stdout.LogonType | Assert-Equal -Expected "Network" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $medium_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + # $stdout.SourceName | Assert-Equal -Expected "ansible" + $stdout.UserSid.Value | Assert-Equal -Expected $standard_user_sid } "Interactive logon with admin" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, $become_pass, "WithProfile", "Interactive", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Interactive" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $high_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.SourceName | Assert-Equals -Expected "Advapi" - $stdout.UserSid.Value | Assert-Equals -Expected $admin_user_sid + $stdout.LogonType | Assert-Equal -Expected "Interactive" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $high_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.SourceName | Assert-Equal -Expected "Advapi" + $stdout.UserSid.Value | Assert-Equal -Expected $admin_user_sid } "Batch logon with admin" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, $become_pass, "WithProfile", "Batch", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Batch" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $high_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.SourceName | Assert-Equals -Expected "Advapi" - $stdout.UserSid.Value | Assert-Equals -Expected $admin_user_sid + $stdout.LogonType | Assert-Equal -Expected "Batch" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $high_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.SourceName | Assert-Equal -Expected "Advapi" + $stdout.UserSid.Value | Assert-Equal -Expected $admin_user_sid } "Network logon with admin" = { @@ -809,15 +815,15 @@ $tests = @{ } $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, $become_pass, "WithProfile", "Network", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Network" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $high_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.SourceName | Assert-Equals -Expected "Advapi" - $stdout.UserSid.Value | Assert-Equals -Expected $admin_user_sid + $stdout.LogonType | Assert-Equal -Expected "Network" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $high_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.SourceName | Assert-Equal -Expected "Advapi" + $stdout.UserSid.Value | Assert-Equal -Expected $admin_user_sid } "Network with cleartext logon with admin" = { @@ -827,15 +833,15 @@ $tests = @{ } $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, $become_pass, "WithProfile", "NetworkCleartext", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "NetworkCleartext" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $high_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - $stdout.SourceName | Assert-Equals -Expected "Advapi" - $stdout.UserSid.Value | Assert-Equals -Expected $admin_user_sid + $stdout.LogonType | Assert-Equal -Expected "NetworkCleartext" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $high_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + $stdout.SourceName | Assert-Equal -Expected "Advapi" + $stdout.UserSid.Value | Assert-Equal -Expected $admin_user_sid } "Fail to logon with null or empty password" = { @@ -846,30 +852,31 @@ $tests = @{ # use [NullString]::Value instead if we want that behaviour. This just tests to see that an empty # string won't go the S4U route. [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, $null, "WithProfile", - "Interactive", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - } catch { + "Interactive", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") + } + catch { $failed = $true - $_.Exception.InnerException.GetType().FullName | Assert-Equals -Expected "Ansible.AccessToken.Win32Exception" + $_.Exception.InnerException.GetType().FullName | Assert-Equal -Expected "Ansible.AccessToken.Win32Exception" # Server 2008 has a slightly different error msg, just assert we get the error 1326 - ($_.Exception.Message.Contains("Win32ErrorCode 1326")) | Assert-Equals -Expected $true + ($_.Exception.Message.Contains("Win32ErrorCode 1326")) | Assert-Equal -Expected $true } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "Logon without password with admin" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, [NullString]::Value, "WithProfile", "Interactive", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 # Too unstable, there might be another process still lingering which causes become to steal instead of using # S4U. Just don't check the type and source to verify we can become without a password $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - # $stdout.LogonType | Assert-Equals -Expected "Batch" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $high_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - # $stdout.SourceName | Assert-Equals -Expected "ansible" - $stdout.UserSid.Value | Assert-Equals -Expected $admin_user_sid + # $stdout.LogonType | Assert-Equal -Expected "Batch" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $high_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + # $stdout.SourceName | Assert-Equal -Expected "ansible" + $stdout.UserSid.Value | Assert-Equal -Expected $admin_user_sid } "Logon without password and network type with admin" = { @@ -879,17 +886,17 @@ $tests = @{ } $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, [NullString]::Value, "WithProfile", "Network", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 # Too unstable, there might be another process still lingering which causes become to steal instead of using # S4U. Just don't check the type and source to verify we can become without a password $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - # $stdout.LogonType | Assert-Equals -Expected "Network" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $high_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $true - # $stdout.SourceName | Assert-Equals -Expected "ansible" - $stdout.UserSid.Value | Assert-Equals -Expected $admin_user_sid + # $stdout.LogonType | Assert-Equal -Expected "Network" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $high_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $true + # $stdout.SourceName | Assert-Equal -Expected "ansible" + $stdout.UserSid.Value | Assert-Equal -Expected $admin_user_sid } "Logon without profile with admin" = { @@ -900,45 +907,45 @@ $tests = @{ $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser($admin_user, $become_pass, 0, "Interactive", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "Interactive" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $high_integrity_sid - $stdout.ProfileLoaded | Assert-Equals -Expected $false - $stdout.SourceName | Assert-Equals -Expected "Advapi" - $stdout.UserSid.Value | Assert-Equals -Expected $admin_user_sid + $stdout.LogonType | Assert-Equal -Expected "Interactive" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $high_integrity_sid + $stdout.ProfileLoaded | Assert-Equal -Expected $false + $stdout.SourceName | Assert-Equal -Expected "Advapi" + $stdout.UserSid.Value | Assert-Equal -Expected $admin_user_sid } "Logon with network credentials and no profile" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("fakeuser", "fakepassword", "NetcredentialsOnly", "NewCredentials", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "NewCredentials" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $current_user.MandatoryLabelSid.Value + $stdout.LogonType | Assert-Equal -Expected "NewCredentials" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $current_user.MandatoryLabelSid.Value # while we didn't set WithProfile, the new process is based on the current process - $stdout.ProfileLoaded | Assert-Equals -Expected $current_user.ProfileLoaded - $stdout.SourceName | Assert-Equals -Expected "Advapi" - $stdout.UserSid.Value | Assert-Equals -Expected $current_user.UserSid.Value + $stdout.ProfileLoaded | Assert-Equal -Expected $current_user.ProfileLoaded + $stdout.SourceName | Assert-Equal -Expected "Advapi" + $stdout.UserSid.Value | Assert-Equal -Expected $current_user.UserSid.Value } "Logon with network credentials and with profile" = { $actual = [Ansible.Become.BecomeUtil]::CreateProcessAsUser("fakeuser", "fakepassword", "NetcredentialsOnly, WithProfile", "NewCredentials", $null, "powershell.exe -NoProfile -", $tmp_dir, $null, $test_whoami + "`r`n") - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $stdout = ConvertFrom-Json -InputObject $actual.StandardOut - $stdout.LogonType | Assert-Equals -Expected "NewCredentials" - $stdout.MandatoryLabelSid.Value | Assert-Equals -Expected $current_user.MandatoryLabelSid.Value - $stdout.ProfileLoaded | Assert-Equals -Expected $current_user.ProfileLoaded - $stdout.SourceName | Assert-Equals -Expected "Advapi" - $stdout.UserSid.Value | Assert-Equals -Expected $current_user.UserSid.Value + $stdout.LogonType | Assert-Equal -Expected "NewCredentials" + $stdout.MandatoryLabelSid.Value | Assert-Equal -Expected $current_user.MandatoryLabelSid.Value + $stdout.ProfileLoaded | Assert-Equal -Expected $current_user.ProfileLoaded + $stdout.SourceName | Assert-Equal -Expected "Advapi" + $stdout.UserSid.Value | Assert-Equal -Expected $current_user.UserSid.Value } } @@ -965,7 +972,8 @@ try { $user_obj = $adsi.Create("User", $user) $user_obj.SetPassword($become_pass) $user_obj.SetInfo() - } else { + } + else { $user_obj.SetPassword($become_pass) } $user_obj.RefreshCache() @@ -973,13 +981,17 @@ try { if ($user -eq $standard_user) { $standard_user_sid = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList @($user_obj.ObjectSid.Value, 0)).Value $group = [System.Security.Principal.WellKnownSidType]::BuiltinUsersSid - } else { + } + else { $admin_user_sid = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList @($user_obj.ObjectSid.Value, 0)).Value $group = [System.Security.Principal.WellKnownSidType]::BuiltinAdministratorsSid } $group = (New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList $group, $null).Value [string[]]$current_groups = $user_obj.Groups() | ForEach-Object { - New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList @($_.GetType().InvokeMember("objectSID", "GetProperty", $null, $_, $null), 0) + New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList @( + $_.GetType().InvokeMember("objectSID", "GetProperty", $null, $_, $null), + 0 + ) } if ($current_groups -notcontains $group) { $group_obj = $adsi.Children | Where-Object { @@ -995,7 +1007,8 @@ try { $test = $test_impl.Key &$test_impl.Value } -} finally { +} +finally { Remove-Item -LiteralPath $tmp_dir -Force -Recurse foreach ($user in $standard_user, $admin_user) { $user_obj = $adsi.Children | Where-Object { $_.SchemaClassName -eq "User" -and $_.Name -eq $user } diff --git a/test/integration/targets/module_utils_Ansible.ModuleUtils.AddType/library/add_type_test.ps1 b/test/integration/targets/module_utils_Ansible.ModuleUtils.AddType/library/add_type_test.ps1 index d6b0569119..d18c42d70f 100644 --- a/test/integration/targets/module_utils_Ansible.ModuleUtils.AddType/library/add_type_test.ps1 +++ b/test/integration/targets/module_utils_Ansible.ModuleUtils.AddType/library/add_type_test.ps1 @@ -9,10 +9,13 @@ $result = @{ changed = $false } -Function Assert-Equals($actual, $expected) { +Function Assert-Equal($actual, $expected) { if ($actual -cne $expected) { $call_stack = (Get-PSCallStack)[1] - $error_msg = "AssertionError:`r`nActual: `"$actual`" != Expected: `"$expected`"`r`nLine: $($call_stack.ScriptLineNumber), Method: $($call_stack.Position.Text)" + $error_msg = -join @( + "AssertionError:`r`nActual: `"$actual`" != Expected: `"$expected`"`r`nLine: " + "$($call_stack.ScriptLineNumber), Method: $($call_stack.Position.Text)" + ) Fail-Json -obj $result -message $error_msg } } @@ -34,15 +37,16 @@ namespace Namespace1 } '@ $res = Add-CSharpType -References $code -Assert-Equals -actual $res -expected $null +Assert-Equal -actual $res -expected $null $actual = [Namespace1.Class1]::GetString($false) -Assert-Equals $actual -expected "Hello World" +Assert-Equal $actual -expected "Hello World" try { [Namespace1.Class1]::GetString($true) -} catch { - Assert-Equals ($_.Exception.ToString().Contains("at Namespace1.Class1.GetString(Boolean error)`r`n")) -expected $true +} +catch { + Assert-Equal ($_.Exception.ToString().Contains("at Namespace1.Class1.GetString(Boolean error)`r`n")) -expected $true } $code_debug = @' @@ -62,17 +66,18 @@ namespace Namespace2 } '@ $res = Add-CSharpType -References $code_debug -IncludeDebugInfo -Assert-Equals -actual $res -expected $null +Assert-Equal -actual $res -expected $null $actual = [Namespace2.Class2]::GetString($false) -Assert-Equals $actual -expected "Hello World" +Assert-Equal $actual -expected "Hello World" try { [Namespace2.Class2]::GetString($true) -} catch { +} +catch { $tmp_path = [System.IO.Path]::GetFullPath($env:TMP).ToLower() - Assert-Equals ($_.Exception.ToString().ToLower().Contains("at namespace2.class2.getstring(boolean error) in $tmp_path")) -expected $true - Assert-Equals ($_.Exception.ToString().Contains(".cs:line 10")) -expected $true + Assert-Equal ($_.Exception.ToString().ToLower().Contains("at namespace2.class2.getstring(boolean error) in $tmp_path")) -expected $true + Assert-Equal ($_.Exception.ToString().Contains(".cs:line 10")) -expected $true } $code_tmp = @' @@ -93,19 +98,21 @@ namespace Namespace3 '@ $tmp_path = $env:USERPROFILE $res = Add-CSharpType -References $code_tmp -IncludeDebugInfo -TempPath $tmp_path -PassThru -Assert-Equals -actual $res.GetType().Name -expected "RuntimeAssembly" -Assert-Equals -actual $res.Location -expected "" -Assert-Equals -actual $res.GetTypes().Length -expected 1 -Assert-Equals -actual $res.GetTypes()[0].Name -expected "Class3" +Assert-Equal -actual $res.GetType().Name -expected "RuntimeAssembly" +Assert-Equal -actual $res.Location -expected "" +Assert-Equal -actual $res.GetTypes().Length -expected 1 +Assert-Equal -actual $res.GetTypes()[0].Name -expected "Class3" $actual = [Namespace3.Class3]::GetString($false) -Assert-Equals $actual -expected "Hello World" +Assert-Equal $actual -expected "Hello World" try { [Namespace3.Class3]::GetString($true) -} catch { - Assert-Equals ($_.Exception.ToString().ToLower().Contains("at namespace3.class3.getstring(boolean error) in $($tmp_path.ToLower())")) -expected $true - Assert-Equals ($_.Exception.ToString().Contains(".cs:line 10")) -expected $true +} +catch { + $actual = $_.Exception.ToString().ToLower().Contains("at namespace3.class3.getstring(boolean error) in $($tmp_path.ToLower())") + Assert-Equal $actual -expected $true + Assert-Equal ($_.Exception.ToString().Contains(".cs:line 10")) -expected $true } $warning_code = @' @@ -130,15 +137,17 @@ namespace Namespace4 $failed = $false try { Add-CSharpType -References $warning_code -} catch { +} +catch { $failed = $true - Assert-Equals -actual ($_.Exception.Message.Contains("error CS0219: Warning as Error: The variable 'a' is assigned but its value is never used")) -expected $true + $actual = $_.Exception.Message.Contains("error CS0219: Warning as Error: The variable 'a' is assigned but its value is never used") + Assert-Equal -actual $actual -expected $true } -Assert-Equals -actual $failed -expected $true +Assert-Equal -actual $failed -expected $true Add-CSharpType -References $warning_code -IgnoreWarnings $actual = [Namespace4.Class4]::GetString($true) -Assert-Equals -actual $actual -expected "Hello World" +Assert-Equal -actual $actual -expected "Hello World" $reference_1 = @' using System; @@ -181,7 +190,7 @@ namespace Namespace6 Add-CSharpType -References $reference_1, $reference_2 $actual = [Namespace6.Class6]::GetString() -Assert-Equals -actual $actual -expected "Hello World" +Assert-Equal -actual $actual -expected "Hello World" $ignored_warning = @' using System; @@ -202,7 +211,7 @@ namespace Namespace7 '@ Add-CSharpType -References $ignored_warning $actual = [Namespace7.Class7]::GetString() -Assert-Equals -actual $actual -expected "abc" +Assert-Equal -actual $actual -expected "abc" $defined_symbol = @' using System; @@ -225,7 +234,7 @@ namespace Namespace8 '@ Add-CSharpType -References $defined_symbol -CompileSymbols "SYMBOL1" $actual = [Namespace8.Class8]::GetString() -Assert-Equals -actual $actual -expected "symbol" +Assert-Equal -actual $actual -expected "symbol" $type_accelerator = @' using System; @@ -245,7 +254,7 @@ namespace Namespace9 '@ Add-CSharpType -Reference $type_accelerator $actual = [AnsibleType]::GetString() -Assert-Equals -actual $actual -expected "a" +Assert-Equal -actual $actual -expected "a" $missing_type_class = @' using System; @@ -266,11 +275,12 @@ namespace Namespace10 $failed = $false try { Add-CSharpType -Reference $missing_type_class -} catch { +} +catch { $failed = $true - Assert-Equals -actual $_.Exception.Message -expected "Failed to find compiled class 'MissingClass' for custom TypeAccelerator." + Assert-Equal -actual $_.Exception.Message -expected "Failed to find compiled class 'MissingClass' for custom TypeAccelerator." } -Assert-Equals -actual $failed -expected $true +Assert-Equal -actual $failed -expected $true $arch_class = @' using System; @@ -293,7 +303,7 @@ namespace Namespace11 } '@ Add-CSharpType -Reference $arch_class -Assert-Equals -actual ([Namespace11.Class11]::GetIntPtrSize()) -expected ([System.IntPtr]::Size) +Assert-Equal -actual ([Namespace11.Class11]::GetIntPtrSize()) -expected ([System.IntPtr]::Size) $lib_set = @' using System; @@ -316,7 +326,7 @@ try { finally { Remove-Item -LiteralPath env:\LIB } -Assert-Equals -actual ([Namespace12.Class12]::GetString()) -expected "b" +Assert-Equal -actual ([Namespace12.Class12]::GetString()) -expected "b" $result.res = "success" Exit-Json -obj $result diff --git a/test/integration/targets/module_utils_Ansible.ModuleUtils.Backup/library/backup_file_test.ps1 b/test/integration/targets/module_utils_Ansible.ModuleUtils.Backup/library/backup_file_test.ps1 index 15527560a1..39beab7853 100644 --- a/test/integration/targets/module_utils_Ansible.ModuleUtils.Backup/library/backup_file_test.ps1 +++ b/test/integration/targets/module_utils_Ansible.ModuleUtils.Backup/library/backup_file_test.ps1 @@ -8,37 +8,40 @@ $module = [Ansible.Basic.AnsibleModule]::Create($args, @{}) -Function Assert-Equals { +Function Assert-Equal { param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected + [Parameter(Mandatory = $true, ValueFromPipeline = $true)][AllowNull()]$Actual, + [Parameter(Mandatory = $true, Position = 0)][AllowNull()]$Expected ) - $matched = $false - if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { - $Actual.Count | Assert-Equals -Expected $Expected.Count - for ($i = 0; $i -lt $Actual.Count; $i++) { - $actual_value = $Actual[$i] - $expected_value = $Expected[$i] - Assert-Equals -Actual $actual_value -Expected $expected_value + process { + $matched = $false + if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { + $Actual.Count | Assert-Equal -Expected $Expected.Count + for ($i = 0; $i -lt $Actual.Count; $i++) { + $actual_value = $Actual[$i] + $expected_value = $Expected[$i] + Assert-Equal -Actual $actual_value -Expected $expected_value + } + $matched = $true } - $matched = $true - } else { - $matched = $Actual -ceq $Expected - } - - if (-not $matched) { - if ($Actual -is [PSObject]) { - $Actual = $Actual.ToString() + else { + $matched = $Actual -ceq $Expected } - $call_stack = (Get-PSCallStack)[1] - $module.Result.test = $test - $module.Result.actual = $Actual - $module.Result.expected = $Expected - $module.Result.line = $call_stack.ScriptLineNumber - $module.Result.method = $call_stack.Position.Text - $module.FailJson("AssertionError: actual != expected") + if (-not $matched) { + if ($Actual -is [PSObject]) { + $Actual = $Actual.ToString() + } + + $call_stack = (Get-PSCallStack)[1] + $module.Result.test = $test + $module.Result.actual = $Actual + $module.Result.expected = $Expected + $module.Result.line = $call_stack.ScriptLineNumber + $module.Result.method = $call_stack.Position.Text + $module.FailJson("AssertionError: actual != expected") + } } } @@ -47,7 +50,7 @@ $tmp_dir = $module.Tmpdir $tests = @{ "Test backup file with missing file" = { $actual = Backup-File -path (Join-Path -Path $tmp_dir -ChildPath "missing") - $actual | Assert-Equals -Expected $null + $actual | Assert-Equal -Expected $null } "Test backup file in check mode" = { @@ -55,12 +58,12 @@ $tests = @{ Set-Content -LiteralPath $orig_file -Value "abc" $actual = Backup-File -path $orig_file -WhatIf - (Test-Path -LiteralPath $actual) | Assert-Equals -Expected $false + (Test-Path -LiteralPath $actual) | Assert-Equal -Expected $false $parent_dir = Split-Path -LiteralPath $actual $backup_file = Split-Path -Path $actual -Leaf - $parent_dir | Assert-Equals -Expected $tmp_dir - ($backup_file -match "^file-check\.txt\.$pid\.\d{8}-\d{6}\.bak$") | Assert-Equals -Expected $true + $parent_dir | Assert-Equal -Expected $tmp_dir + ($backup_file -match "^file-check\.txt\.$pid\.\d{8}-\d{6}\.bak$") | Assert-Equal -Expected $true } "Test backup file" = { @@ -69,13 +72,13 @@ $tests = @{ Set-Content -LiteralPath $orig_file -Value $content $actual = Backup-File -path $orig_file - (Test-Path -LiteralPath $actual) | Assert-Equals -Expected $true + (Test-Path -LiteralPath $actual) | Assert-Equal -Expected $true $parent_dir = Split-Path -LiteralPath $actual $backup_file = Split-Path -Path $actual -Leaf - $parent_dir | Assert-Equals -Expected $tmp_dir - ($backup_file -match "^file\.txt\.$pid\.\d{8}-\d{6}\.bak$") | Assert-Equals -Expected $true - (Get-Content -LiteralPath $actual -Raw) | Assert-Equals -Expected "$content`r`n" + $parent_dir | Assert-Equal -Expected $tmp_dir + ($backup_file -match "^file\.txt\.$pid\.\d{8}-\d{6}\.bak$") | Assert-Equal -Expected $true + (Get-Content -LiteralPath $actual -Raw) | Assert-Equal -Expected "$content`r`n" } } diff --git a/test/integration/targets/module_utils_Ansible.ModuleUtils.CamelConversion/library/camel_conversion_test.ps1 b/test/integration/targets/module_utils_Ansible.ModuleUtils.CamelConversion/library/camel_conversion_test.ps1 index d3dc9d7b72..bcb9558e33 100644 --- a/test/integration/targets/module_utils_Ansible.ModuleUtils.CamelConversion/library/camel_conversion_test.ps1 +++ b/test/integration/targets/module_utils_Ansible.ModuleUtils.CamelConversion/library/camel_conversion_test.ps1 @@ -5,7 +5,7 @@ $ErrorActionPreference = 'Stop' -Function Assert-Equals($actual, $expected) { +Function Assert-Equal($actual, $expected) { if ($actual -cne $expected) { Fail-Json @{} "actual != expected`nActual: $actual`nExpected: $expected" } @@ -41,33 +41,40 @@ foreach ($entry in $output_dict.GetEnumerator()) { $value = $entry.Value if ($value -is [Hashtable]) { - Assert-Equals -actual $key -expected "inner_hash_table" + Assert-Equal -actual $key -expected "inner_hash_table" foreach ($inner_hash in $value.GetEnumerator()) { - Assert-Equals -actual $inner_hash.Name -expected $inner_hash.Value + Assert-Equal -actual $inner_hash.Name -expected $inner_hash.Value } - } elseif ($value -is [Array] -or $value -is [System.Collections.ArrayList]) { + } + elseif ($value -is [Array] -or $value -is [System.Collections.ArrayList]) { if ($key -eq "list_dict") { foreach ($inner_list in $value) { if ($inner_list -is [Hashtable]) { foreach ($inner_list_hash in $inner_list.GetEnumerator()) { - Assert-Equals -actual $inner_list_hash.Name -expected $inner_list_hash.Value + Assert-Equal -actual $inner_list_hash.Name -expected $inner_list_hash.Value } - } elseif ($inner_list -is [String]) { + } + elseif ($inner_list -is [String]) { # this is not a string key so we need to keep it the same - Assert-Equals -actual $inner_list -expected "stringTwo" - } else { - Assert-Equals -actual $inner_list -expected 0 + Assert-Equal -actual $inner_list -expected "stringTwo" + } + else { + Assert-Equal -actual $inner_list -expected 0 } } - } elseif ($key -eq "empty_list") { - Assert-Equals -actual $value.Count -expected 0 - } elseif ($key -eq "single_list") { - Assert-Equals -actual $value.Count -expected 1 - } else { + } + elseif ($key -eq "empty_list") { + Assert-Equal -actual $value.Count -expected 0 + } + elseif ($key -eq "single_list") { + Assert-Equal -actual $value.Count -expected 1 + } + else { Fail-Json -obj $result -message "invalid key found for list $key" } - } else { - Assert-Equals -actual $key -expected $value + } + else { + Assert-Equal -actual $key -expected $value } } diff --git a/test/integration/targets/module_utils_Ansible.ModuleUtils.CommandUtil/library/command_util_test.ps1 b/test/integration/targets/module_utils_Ansible.ModuleUtils.CommandUtil/library/command_util_test.ps1 index 6e644fe242..ebffae7ff0 100644 --- a/test/integration/targets/module_utils_Ansible.ModuleUtils.CommandUtil/library/command_util_test.ps1 +++ b/test/integration/targets/module_utils_Ansible.ModuleUtils.CommandUtil/library/command_util_test.ps1 @@ -16,7 +16,7 @@ $exe_directory = Split-Path -Path $exe -Parent $exe_filename = Split-Path -Path $exe -Leaf $test_name = $null -Function Assert-Equals($actual, $expected) { +Function Assert-Equal($actual, $expected) { if ($actual -cne $expected) { Fail-Json -obj $result -message "Test $test_name failed`nActual: '$actual' != Expected: '$expected'" } @@ -24,10 +24,10 @@ Function Assert-Equals($actual, $expected) { $test_name = "full exe path" $actual = Run-Command -command "`"$exe`" arg1 arg2 `"arg 3`"" -Assert-Equals -actual $actual.rc -expected 0 -Assert-Equals -actual $actual.stdout -expected "arg1`r`narg2`r`narg 3`r`n" -Assert-Equals -actual $actual.stderr -expected "" -Assert-Equals -actual $actual.executable -expected $exe +Assert-Equal -actual $actual.rc -expected 0 +Assert-Equal -actual $actual.stdout -expected "arg1`r`narg2`r`narg 3`r`n" +Assert-Equal -actual $actual.stderr -expected "" +Assert-Equal -actual $actual.executable -expected $exe $test_name = "exe in special char dir" $tmp_dir = Join-Path -Path $env:TEMP -ChildPath "ansible .ÅÑŚÌβŁÈ [$!@^&test(;)]" @@ -36,66 +36,70 @@ try { $exe_special = Join-Path $tmp_dir -ChildPath "PrintArgv.exe" Copy-Item -LiteralPath $exe -Destination $exe_special $actual = Run-Command -command "`"$exe_special`" arg1 arg2 `"arg 3`"" -} finally { +} +finally { Remove-Item -LiteralPath $tmp_dir -Force -Recurse } -Assert-Equals -actual $actual.rc -expected 0 -Assert-Equals -actual $actual.stdout -expected "arg1`r`narg2`r`narg 3`r`n" -Assert-Equals -actual $actual.stderr -expected "" -Assert-Equals -actual $actual.executable -expected $exe_special +Assert-Equal -actual $actual.rc -expected 0 +Assert-Equal -actual $actual.stdout -expected "arg1`r`narg2`r`narg 3`r`n" +Assert-Equal -actual $actual.stderr -expected "" +Assert-Equal -actual $actual.executable -expected $exe_special $test_name = "invalid exe path" try { $actual = Run-Command -command "C:\fakepath\$exe_filename arg1" Fail-Json -obj $result -message "Test $test_name failed`nCommand should have thrown an exception" -} catch { - Assert-Equals -actual $_.Exception.Message -expected "Exception calling `"SearchPath`" with `"1`" argument(s): `"Could not find file 'C:\fakepath\$exe_filename'.`"" +} +catch { + $expected = "Exception calling `"SearchPath`" with `"1`" argument(s): `"Could not find file 'C:\fakepath\$exe_filename'.`"" + Assert-Equal -actual $_.Exception.Message -expected $expected } $test_name = "exe in current folder" $actual = Run-Command -command "$exe_filename arg1" -working_directory $exe_directory -Assert-Equals -actual $actual.rc -expected 0 -Assert-Equals -actual $actual.stdout -expected "arg1`r`n" -Assert-Equals -actual $actual.stderr -expected "" -Assert-Equals -actual $actual.executable -expected $exe +Assert-Equal -actual $actual.rc -expected 0 +Assert-Equal -actual $actual.stdout -expected "arg1`r`n" +Assert-Equal -actual $actual.stderr -expected "" +Assert-Equal -actual $actual.executable -expected $exe $test_name = "no working directory set" $actual = Run-Command -command "cmd.exe /c cd" -Assert-Equals -actual $actual.rc -expected 0 -Assert-Equals -actual $actual.stdout -expected "$($pwd.Path)`r`n" -Assert-Equals -actual $actual.stderr -expected "" -Assert-Equals -actual $actual.executable.ToUpper() -expected "$env:SystemRoot\System32\cmd.exe".ToUpper() +Assert-Equal -actual $actual.rc -expected 0 +Assert-Equal -actual $actual.stdout -expected "$($pwd.Path)`r`n" +Assert-Equal -actual $actual.stderr -expected "" +Assert-Equal -actual $actual.executable.ToUpper() -expected "$env:SystemRoot\System32\cmd.exe".ToUpper() $test_name = "working directory override" $actual = Run-Command -command "cmd.exe /c cd" -working_directory $env:SystemRoot -Assert-Equals -actual $actual.rc -expected 0 -Assert-Equals -actual $actual.stdout -expected "$env:SystemRoot`r`n" -Assert-Equals -actual $actual.stderr -expected "" -Assert-Equals -actual $actual.executable.ToUpper() -expected "$env:SystemRoot\System32\cmd.exe".ToUpper() +Assert-Equal -actual $actual.rc -expected 0 +Assert-Equal -actual $actual.stdout -expected "$env:SystemRoot`r`n" +Assert-Equal -actual $actual.stderr -expected "" +Assert-Equal -actual $actual.executable.ToUpper() -expected "$env:SystemRoot\System32\cmd.exe".ToUpper() $test_name = "working directory invalid path" try { $actual = Run-Command -command "doesn't matter" -working_directory "invalid path here" Fail-Json -obj $result -message "Test $test_name failed`nCommand should have thrown an exception" -} catch { - Assert-Equals -actual $_.Exception.Message -expected "invalid working directory path 'invalid path here'" +} +catch { + Assert-Equal -actual $_.Exception.Message -expected "invalid working directory path 'invalid path here'" } $test_name = "invalid arguments" $actual = Run-Command -command "ipconfig.exe /asdf" -Assert-Equals -actual $actual.rc -expected 1 +Assert-Equal -actual $actual.rc -expected 1 $test_name = "test stdout and stderr streams" $actual = Run-Command -command "cmd.exe /c echo stdout && echo stderr 1>&2" -Assert-Equals -actual $actual.rc -expected 0 -Assert-Equals -actual $actual.stdout -expected "stdout `r`n" -Assert-Equals -actual $actual.stderr -expected "stderr `r`n" +Assert-Equal -actual $actual.rc -expected 0 +Assert-Equal -actual $actual.stdout -expected "stdout `r`n" +Assert-Equal -actual $actual.stderr -expected "stderr `r`n" $test_name = "Test UTF8 output from stdout stream" $actual = Run-Command -command "powershell.exe -ExecutionPolicy ByPass -Command `"Write-Host '💩'`"" -Assert-Equals -actual $actual.rc -expected 0 -Assert-Equals -actual $actual.stdout -expected "💩`n" -Assert-Equals -actual $actual.stderr -expected "" +Assert-Equal -actual $actual.rc -expected 0 +Assert-Equal -actual $actual.stdout -expected "💩`n" +Assert-Equal -actual $actual.stderr -expected "" $test_name = "test default environment variable" Set-Item -LiteralPath env:TESTENV -Value "test" @@ -129,7 +133,7 @@ begin { "@ $encoded_wrapper = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($wrapper)) $actual = Run-Command -command "powershell.exe -ExecutionPolicy ByPass -EncodedCommand $encoded_wrapper" -stdin "Ansible" -Assert-Equals -actual $actual.stdout -expected "Ansible`n" +Assert-Equal -actual $actual.stdout -expected "Ansible`n" $result.data = "success" Exit-Json -obj $result diff --git a/test/integration/targets/module_utils_Ansible.ModuleUtils.FileUtil/library/file_util_test.ps1 b/test/integration/targets/module_utils_Ansible.ModuleUtils.FileUtil/library/file_util_test.ps1 index ae3e68ec4a..c38f4e61e9 100644 --- a/test/integration/targets/module_utils_Ansible.ModuleUtils.FileUtil/library/file_util_test.ps1 +++ b/test/integration/targets/module_utils_Ansible.ModuleUtils.FileUtil/library/file_util_test.ps1 @@ -9,10 +9,13 @@ $result = @{ changed = $false } -Function Assert-Equals($actual, $expected) { +Function Assert-Equal($actual, $expected) { if ($actual -cne $expected) { $call_stack = (Get-PSCallStack)[1] - $error_msg = "AssertionError:`r`nActual: `"$actual`" != Expected: `"$expected`"`r`nLine: $($call_stack.ScriptLineNumber), Method: $($call_stack.Position.Text)" + $error_msg = -join @( + "AssertionError:`r`nActual: `"$actual`" != Expected: `"$expected`"`r`nLine: " + "$($call_stack.ScriptLineNumber), Method: $($call_stack.Position.Text)" + ) Fail-Json -obj $result -message $error_msg } } @@ -22,7 +25,8 @@ Function Get-PagefilePath() { $cs = Get-CimInstance -ClassName Win32_ComputerSystem if ($cs.AutomaticManagedPagefile) { $pagefile = "$($env:SystemRoot.Substring(0, 1)):\pagefile.sys" - } else { + } + else { $pf = Get-CimInstance -ClassName Win32_PageFileSetting if ($null -ne $pf) { $pagefile = $pf[0].Name @@ -35,74 +39,76 @@ $pagefile = Get-PagefilePath if ($pagefile) { # Test-AnsiblePath Hidden system file $actual = Test-AnsiblePath -Path $pagefile - Assert-Equals -actual $actual -expected $true + Assert-Equal -actual $actual -expected $true # Get-AnsibleItem file $actual = Get-AnsibleItem -Path $pagefile - Assert-Equals -actual $actual.FullName -expected $pagefile - Assert-Equals -actual $actual.Attributes.HasFlag([System.IO.FileAttributes]::Directory) -expected $false - Assert-Equals -actual $actual.Exists -expected $true + Assert-Equal -actual $actual.FullName -expected $pagefile + Assert-Equal -actual $actual.Attributes.HasFlag([System.IO.FileAttributes]::Directory) -expected $false + Assert-Equal -actual $actual.Exists -expected $true } # Test-AnsiblePath File that doesn't exist $actual = Test-AnsiblePath -Path C:\fakefile -Assert-Equals -actual $actual -expected $false +Assert-Equal -actual $actual -expected $false # Test-AnsiblePath Directory that doesn't exist $actual = Test-AnsiblePath -Path C:\fakedirectory -Assert-Equals -actual $actual -expected $false +Assert-Equal -actual $actual -expected $false # Test-AnsiblePath file in non-existant directory $actual = Test-AnsiblePath -Path C:\fakedirectory\fakefile.txt -Assert-Equals -actual $actual -expected $false +Assert-Equal -actual $actual -expected $false # Test-AnsiblePath Normal directory $actual = Test-AnsiblePath -Path C:\Windows -Assert-Equals -actual $actual -expected $true +Assert-Equal -actual $actual -expected $true # Test-AnsiblePath Normal file $actual = Test-AnsiblePath -Path C:\Windows\System32\kernel32.dll -Assert-Equals -actual $actual -expected $true +Assert-Equal -actual $actual -expected $true # Test-AnsiblePath fails with wildcard $failed = $false try { Test-AnsiblePath -Path C:\Windows\*.exe -} catch { +} +catch { $failed = $true - Assert-Equals -actual $_.Exception.Message -expected "Exception calling `"GetAttributes`" with `"1`" argument(s): `"Illegal characters in path.`"" + Assert-Equal -actual $_.Exception.Message -expected "Exception calling `"GetAttributes`" with `"1`" argument(s): `"Illegal characters in path.`"" } -Assert-Equals -actual $failed -expected $true +Assert-Equal -actual $failed -expected $true # Test-AnsiblePath on non file PS Provider object $actual = Test-AnsiblePath -Path Cert:\LocalMachine\My -Assert-Equals -actual $actual -expected $true +Assert-Equal -actual $actual -expected $true # Test-AnsiblePath on environment variable $actual = Test-AnsiblePath -Path env:SystemDrive -Assert-Equals -actual $actual -expected $true +Assert-Equal -actual $actual -expected $true # Test-AnsiblePath on environment variable that does not exist $actual = Test-AnsiblePath -Path env:FakeEnvValue -Assert-Equals -actual $actual -expected $false +Assert-Equal -actual $actual -expected $false # Get-AnsibleItem doesn't exist with -ErrorAction SilentlyContinue param $actual = Get-AnsibleItem -Path C:\fakefile -ErrorAction SilentlyContinue -Assert-Equals -actual $actual -expected $null +Assert-Equal -actual $actual -expected $null # Get-AnsibleItem directory $actual = Get-AnsibleItem -Path C:\Windows -Assert-Equals -actual $actual.FullName -expected C:\Windows -Assert-Equals -actual $actual.Attributes.HasFlag([System.IO.FileAttributes]::Directory) -expected $true -Assert-Equals -actual $actual.Exists -expected $true +Assert-Equal -actual $actual.FullName -expected C:\Windows +Assert-Equal -actual $actual.Attributes.HasFlag([System.IO.FileAttributes]::Directory) -expected $true +Assert-Equal -actual $actual.Exists -expected $true # ensure Get-AnsibleItem doesn't fail in a try/catch and -ErrorAction SilentlyContinue - stop's a trap from trapping it try { $actual = Get-AnsibleItem -Path C:\fakepath -ErrorAction SilentlyContinue -} catch { +} +catch { Fail-Json -obj $result -message "this should not fire" } -Assert-Equals -actual $actual -expected $null +Assert-Equal -actual $actual -expected $null $result.data = "success" Exit-Json -obj $result diff --git a/test/integration/targets/module_utils_Ansible.ModuleUtils.Legacy/library/testpath.ps1 b/test/integration/targets/module_utils_Ansible.ModuleUtils.Legacy/library/testpath.ps1 index 55cad70fb9..7a6ba0bef3 100644 --- a/test/integration/targets/module_utils_Ansible.ModuleUtils.Legacy/library/testpath.ps1 +++ b/test/integration/targets/module_utils_Ansible.ModuleUtils.Legacy/library/testpath.ps1 @@ -6,4 +6,4 @@ $params = Parse-Args $args $path = Get-AnsibleParam -Obj $params -Name path -Type path -Exit-Json @{ path=$path } +Exit-Json @{ path = $path } diff --git a/test/integration/targets/module_utils_Ansible.ModuleUtils.LinkUtil/library/symbolic_link_test.ps1 b/test/integration/targets/module_utils_Ansible.ModuleUtils.LinkUtil/library/symbolic_link_test.ps1 index 1decfe4fd8..de0bb8bbd2 100644 --- a/test/integration/targets/module_utils_Ansible.ModuleUtils.LinkUtil/library/symbolic_link_test.ps1 +++ b/test/integration/targets/module_utils_Ansible.ModuleUtils.LinkUtil/library/symbolic_link_test.ps1 @@ -25,7 +25,7 @@ New-Item -Path $folder_target -ItemType Directory | Out-Null New-Item -Path $file_target -ItemType File | Out-Null Set-Content -LiteralPath $file_target -Value "a" -Function Assert-Equals($actual, $expected) { +Function Assert-Equal($actual, $expected) { if ($actual -ne $expected) { Fail-Json @{} "actual != expected`nActual: $actual`nExpected: $expected" } @@ -48,105 +48,109 @@ Assert-True -expression ($null -eq $no_link_result) -message "did not return nul try { New-Link -link_path "$path\folder-hard" -link_target $folder_target -link_type "hard" Assert-True -expression $false -message "creation of hard link should have failed if target was a directory" -} catch { - Assert-Equals -actual $_.Exception.Message -expected "cannot set the target for a hard link to a directory" +} +catch { + Assert-Equal -actual $_.Exception.Message -expected "cannot set the target for a hard link to a directory" } # fail to create a junction point pointed to a file try { New-Link -link_path "$path\junction-fail" -link_target $file_target -link_type "junction" Assert-True -expression $false -message "creation of junction point should have failed if target was a file" -} catch { - Assert-Equals -actual $_.Exception.Message -expected "cannot set the target for a junction point to a file" +} +catch { + Assert-Equal -actual $_.Exception.Message -expected "cannot set the target for a junction point to a file" } # fail to create a symbolic link with non-existent target try { New-Link -link_path "$path\symlink-fail" -link_target "$path\fake-folder" -link_type "link" Assert-True -expression $false -message "creation of symbolic link should have failed if target did not exist" -} catch { - Assert-Equals -actual $_.Exception.Message -expected "link_target '$path\fake-folder' does not exist, cannot create link" +} +catch { + Assert-Equal -actual $_.Exception.Message -expected "link_target '$path\fake-folder' does not exist, cannot create link" } # create recursive symlink Run-Command -command "cmd.exe /c mklink /D symlink-rel folder" -working_directory $path | Out-Null $rel_link_result = Get-Link -link_path "$path\symlink-rel" -Assert-Equals -actual $rel_link_result.Type -expected "SymbolicLink" -Assert-Equals -actual $rel_link_result.SubstituteName -expected "folder" -Assert-Equals -actual $rel_link_result.PrintName -expected "folder" -Assert-Equals -actual $rel_link_result.TargetPath -expected "folder" -Assert-Equals -actual $rel_link_result.AbsolutePath -expected $folder_target -Assert-Equals -actual $rel_link_result.HardTargets -expected $null +Assert-Equal -actual $rel_link_result.Type -expected "SymbolicLink" +Assert-Equal -actual $rel_link_result.SubstituteName -expected "folder" +Assert-Equal -actual $rel_link_result.PrintName -expected "folder" +Assert-Equal -actual $rel_link_result.TargetPath -expected "folder" +Assert-Equal -actual $rel_link_result.AbsolutePath -expected $folder_target +Assert-Equal -actual $rel_link_result.HardTargets -expected $null # create a symbolic file test New-Link -link_path $symlink_file_path -link_target $file_target -link_type "link" $file_link_result = Get-Link -link_path $symlink_file_path -Assert-Equals -actual $file_link_result.Type -expected "SymbolicLink" -Assert-Equals -actual $file_link_result.SubstituteName -expected "\??\$file_target" -Assert-Equals -actual $file_link_result.PrintName -expected $file_target -Assert-Equals -actual $file_link_result.TargetPath -expected $file_target -Assert-Equals -actual $file_link_result.AbsolutePath -expected $file_target -Assert-Equals -actual $file_link_result.HardTargets -expected $null +Assert-Equal -actual $file_link_result.Type -expected "SymbolicLink" +Assert-Equal -actual $file_link_result.SubstituteName -expected "\??\$file_target" +Assert-Equal -actual $file_link_result.PrintName -expected $file_target +Assert-Equal -actual $file_link_result.TargetPath -expected $file_target +Assert-Equal -actual $file_link_result.AbsolutePath -expected $file_target +Assert-Equal -actual $file_link_result.HardTargets -expected $null # create a symbolic link folder test New-Link -link_path $symlink_folder_path -link_target $folder_target -link_type "link" $folder_link_result = Get-Link -link_path $symlink_folder_path -Assert-Equals -actual $folder_link_result.Type -expected "SymbolicLink" -Assert-Equals -actual $folder_link_result.SubstituteName -expected "\??\$folder_target" -Assert-Equals -actual $folder_link_result.PrintName -expected $folder_target -Assert-Equals -actual $folder_link_result.TargetPath -expected $folder_target -Assert-Equals -actual $folder_link_result.AbsolutePath -expected $folder_target -Assert-Equals -actual $folder_link_result.HardTargets -expected $null +Assert-Equal -actual $folder_link_result.Type -expected "SymbolicLink" +Assert-Equal -actual $folder_link_result.SubstituteName -expected "\??\$folder_target" +Assert-Equal -actual $folder_link_result.PrintName -expected $folder_target +Assert-Equal -actual $folder_link_result.TargetPath -expected $folder_target +Assert-Equal -actual $folder_link_result.AbsolutePath -expected $folder_target +Assert-Equal -actual $folder_link_result.HardTargets -expected $null # create a junction point test New-Link -link_path $junction_point_path -link_target $folder_target -link_type "junction" $junction_point_result = Get-Link -link_path $junction_point_path -Assert-Equals -actual $junction_point_result.Type -expected "JunctionPoint" -Assert-Equals -actual $junction_point_result.SubstituteName -expected "\??\$folder_target" -Assert-Equals -actual $junction_point_result.PrintName -expected $folder_target -Assert-Equals -actual $junction_point_result.TargetPath -expected $folder_target -Assert-Equals -actual $junction_point_result.AbsolutePath -expected $folder_target -Assert-Equals -actual $junction_point_result.HardTargets -expected $null +Assert-Equal -actual $junction_point_result.Type -expected "JunctionPoint" +Assert-Equal -actual $junction_point_result.SubstituteName -expected "\??\$folder_target" +Assert-Equal -actual $junction_point_result.PrintName -expected $folder_target +Assert-Equal -actual $junction_point_result.TargetPath -expected $folder_target +Assert-Equal -actual $junction_point_result.AbsolutePath -expected $folder_target +Assert-Equal -actual $junction_point_result.HardTargets -expected $null # create a hard link test New-Link -link_path $hardlink_path -link_target $file_target -link_type "hard" $hardlink_result = Get-Link -link_path $hardlink_path -Assert-Equals -actual $hardlink_result.Type -expected "HardLink" -Assert-Equals -actual $hardlink_result.SubstituteName -expected $null -Assert-Equals -actual $hardlink_result.PrintName -expected $null -Assert-Equals -actual $hardlink_result.TargetPath -expected $null -Assert-Equals -actual $hardlink_result.AbsolutePath -expected $null +Assert-Equal -actual $hardlink_result.Type -expected "HardLink" +Assert-Equal -actual $hardlink_result.SubstituteName -expected $null +Assert-Equal -actual $hardlink_result.PrintName -expected $null +Assert-Equal -actual $hardlink_result.TargetPath -expected $null +Assert-Equal -actual $hardlink_result.AbsolutePath -expected $null if ($hardlink_result.HardTargets[0] -ne $hardlink_path -and $hardlink_result.HardTargets[1] -ne $hardlink_path) { Assert-True -expression $false -message "file $hardlink_path is not a target of the hard link" } if ($hardlink_result.HardTargets[0] -ne $file_target -and $hardlink_result.HardTargets[1] -ne $file_target) { Assert-True -expression $false -message "file $file_target is not a target of the hard link" } -Assert-equals -actual (Get-Content -LiteralPath $hardlink_path -Raw) -expected (Get-Content -LiteralPath $file_target -Raw) +Assert-Equal -actual (Get-Content -LiteralPath $hardlink_path -Raw) -expected (Get-Content -LiteralPath $file_target -Raw) # create a new hard link and verify targets go to 3 New-Link -link_path $hardlink_path_2 -link_target $file_target -link_type "hard" $hardlink_result_2 = Get-Link -link_path $hardlink_path -Assert-True -expression ($hardlink_result_2.HardTargets.Count -eq 3) -message "did not return 3 targets for the hard link, actual $($hardlink_result_2.Targets.Count)" +$expected = "did not return 3 targets for the hard link, actual $($hardlink_result_2.Targets.Count)" +Assert-True -expression ($hardlink_result_2.HardTargets.Count -eq 3) -message $expected # check if broken symbolic link still works Remove-Item -LiteralPath $folder_target -Force | Out-Null $broken_link_result = Get-Link -link_path $symlink_folder_path -Assert-Equals -actual $broken_link_result.Type -expected "SymbolicLink" -Assert-Equals -actual $broken_link_result.SubstituteName -expected "\??\$folder_target" -Assert-Equals -actual $broken_link_result.PrintName -expected $folder_target -Assert-Equals -actual $broken_link_result.TargetPath -expected $folder_target -Assert-Equals -actual $broken_link_result.AbsolutePath -expected $folder_target -Assert-Equals -actual $broken_link_result.HardTargets -expected $null +Assert-Equal -actual $broken_link_result.Type -expected "SymbolicLink" +Assert-Equal -actual $broken_link_result.SubstituteName -expected "\??\$folder_target" +Assert-Equal -actual $broken_link_result.PrintName -expected $folder_target +Assert-Equal -actual $broken_link_result.TargetPath -expected $folder_target +Assert-Equal -actual $broken_link_result.AbsolutePath -expected $folder_target +Assert-Equal -actual $broken_link_result.HardTargets -expected $null # check if broken junction point still works $broken_junction_result = Get-Link -link_path $junction_point_path -Assert-Equals -actual $broken_junction_result.Type -expected "JunctionPoint" -Assert-Equals -actual $broken_junction_result.SubstituteName -expected "\??\$folder_target" -Assert-Equals -actual $broken_junction_result.PrintName -expected $folder_target -Assert-Equals -actual $broken_junction_result.TargetPath -expected $folder_target -Assert-Equals -actual $broken_junction_result.AbsolutePath -expected $folder_target -Assert-Equals -actual $broken_junction_result.HardTargets -expected $null +Assert-Equal -actual $broken_junction_result.Type -expected "JunctionPoint" +Assert-Equal -actual $broken_junction_result.SubstituteName -expected "\??\$folder_target" +Assert-Equal -actual $broken_junction_result.PrintName -expected $folder_target +Assert-Equal -actual $broken_junction_result.TargetPath -expected $folder_target +Assert-Equal -actual $broken_junction_result.AbsolutePath -expected $folder_target +Assert-Equal -actual $broken_junction_result.HardTargets -expected $null # delete file symbolic link Remove-Link -link_path $symlink_file_path diff --git a/test/integration/targets/module_utils_Ansible.ModuleUtils.PrivilegeUtil/library/privilege_util_test.ps1 b/test/integration/targets/module_utils_Ansible.ModuleUtils.PrivilegeUtil/library/privilege_util_test.ps1 index e1ca25da81..414b80a9f8 100644 --- a/test/integration/targets/module_utils_Ansible.ModuleUtils.PrivilegeUtil/library/privilege_util_test.ps1 +++ b/test/integration/targets/module_utils_Ansible.ModuleUtils.PrivilegeUtil/library/privilege_util_test.ps1 @@ -5,7 +5,7 @@ $module = [Ansible.Basic.AnsibleModule]::Create($args, @{}) -Function Assert-Equals($actual, $expected) { +Function Assert-Equal($actual, $expected) { if ($actual -cne $expected) { $call_stack = (Get-PSCallStack)[1] $module.Result.actual = $actual @@ -70,20 +70,21 @@ foreach ($privilege in $total_privileges) { $expected = $actual_privileges.$privilege } $actual = Get-AnsiblePrivilege -Name $privilege - Assert-Equals -actual $actual -expected $expected + Assert-Equal -actual $actual -expected $expected } # test c# GetAllPrivilegeInfo $actual = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) -Assert-Equals -actual $actual.GetType().Name -expected 'Dictionary`2' -Assert-Equals -actual $actual.Count -expected $actual_privileges.Count +Assert-Equal -actual $actual.GetType().Name -expected 'Dictionary`2' +Assert-Equal -actual $actual.Count -expected $actual_privileges.Count foreach ($privilege in $total_privileges) { if ($actual_privileges.ContainsKey($privilege)) { $actual_value = $actual.$privilege if ($actual_privileges.$privilege) { - Assert-Equals -actual $actual_value.HasFlag([Ansible.Privilege.PrivilegeAttributes]::Enabled) -expected $true - } else { - Assert-Equals -actual $actual_value.HasFlag([Ansible.Privilege.PrivilegeAttributes]::Enabled) -expected $false + Assert-Equal -actual $actual_value.HasFlag([Ansible.Privilege.PrivilegeAttributes]::Enabled) -expected $true + } + else { + Assert-Equal -actual $actual_value.HasFlag([Ansible.Privilege.PrivilegeAttributes]::Enabled) -expected $false } } } @@ -93,19 +94,19 @@ Set-AnsiblePrivilege -Name SeUndockPrivilege -Value $false # ensure we start wi Set-AnsiblePrivilege -Name SeUndockPrivilege -Value $true -WhatIf $actual = Get-AnsiblePrivilege -Name SeUndockPrivilege -Assert-Equals -actual $actual -expected $false +Assert-Equal -actual $actual -expected $false Set-AnsiblePrivilege -Name SeUndockPrivilege -Value $true $actual = Get-AnsiblePrivilege -Name SeUndockPrivilege -Assert-Equals -actual $actual -expected $true +Assert-Equal -actual $actual -expected $true Set-AnsiblePrivilege -Name SeUndockPrivilege -Value $false -WhatIf $actual = Get-AnsiblePrivilege -Name SeUndockPrivilege -Assert-Equals -actual $actual -expected $true +Assert-Equal -actual $actual -expected $true Set-AnsiblePrivilege -Name SeUndockPrivilege -Value $false $actual = Get-AnsiblePrivilege -Name SeUndockPrivilege -Assert-Equals -actual $actual -expected $false +Assert-Equal -actual $actual -expected $false $module.Result.data = "success" $module.ExitJson() diff --git a/test/integration/targets/module_utils_Ansible.ModuleUtils.SID/library/sid_utils_test.ps1 b/test/integration/targets/module_utils_Ansible.ModuleUtils.SID/library/sid_utils_test.ps1 index eb376c81d5..85bfbe112f 100644 --- a/test/integration/targets/module_utils_Ansible.ModuleUtils.SID/library/sid_utils_test.ps1 +++ b/test/integration/targets/module_utils_Ansible.ModuleUtils.SID/library/sid_utils_test.ps1 @@ -6,7 +6,7 @@ $params = Parse-Args $args $sid_account = Get-AnsibleParam -obj $params -name "sid_account" -type "str" -failifempty $true -Function Assert-Equals($actual, $expected) { +Function Assert-Equal($actual, $expected) { if ($actual -ne $expected) { Fail-Json @{} "actual != expected`nActual: $actual`nExpected: $expected" } @@ -39,10 +39,18 @@ $tests = @( @{ sid = "S-1-1-0"; full_name = "Everyone"; names = @("Everyone") }, @{ sid = "S-1-5-18"; full_name = "NT AUTHORITY\SYSTEM"; names = @("NT AUTHORITY\SYSTEM", "SYSTEM") }, @{ sid = "S-1-5-20"; full_name = "NT AUTHORITY\NETWORK SERVICE"; names = @("NT AUTHORITY\NETWORK SERVICE", "NETWORK SERVICE") }, - @{ sid = "$($default_admin.SID)"; full_name = "$($default_admin.FullName)"; names = @("$env:COMPUTERNAME\$($default_admin.Name)", "$($default_admin.Name)", ".\$($default_admin.Name)") }, + @{ + sid = "$($default_admin.SID)" + full_name = "$($default_admin.FullName)" + names = @("$env:COMPUTERNAME\$($default_admin.Name)", "$($default_admin.Name)", ".\$($default_admin.Name)") + }, # Local Groups - @{ sid = "$($default_admin_group.SID)"; full_name = "BUILTIN\$($default_admin_group.Name)"; names = @("BUILTIN\$($default_admin_group.Name)", "$($default_admin_group.Name)", ".\$($default_admin_group.Name)") } + @{ + sid = "$($default_admin_group.SID)" + full_name = "BUILTIN\$($default_admin_group.Name)" + names = @("BUILTIN\$($default_admin_group.Name)", "$($default_admin_group.Name)", ".\$($default_admin_group.Name)") + } ) # Add domain tests if the domain name has been set @@ -70,12 +78,12 @@ foreach ($test in $tests) { $actual_account_name = Convert-FromSID -sid $test.sid # renamed admins may have an empty FullName; skip comparison in that case if ($test.full_name) { - Assert-Equals -actual $actual_account_name -expected $test.full_name + Assert-Equal -actual $actual_account_name -expected $test.full_name } foreach ($test_name in $test.names) { $actual_sid = Convert-ToSID -account_name $test_name - Assert-Equals -actual $actual_sid -expected $test.sid + Assert-Equal -actual $actual_sid -expected $test.sid } } @@ -83,11 +91,11 @@ foreach ($test in $tests) { # in the normal test suite # Calling Convert-ToSID with a string like a SID should return that SID back $actual = Convert-ToSID -account_name $sid_account -Assert-Equals -actual $actual -expected $sid_account +Assert-Equal -actual $actual -expected $sid_account # Calling COnvert-ToSID with a string prefixed with .\ should return the SID # for a user that is called that SID and not the SID passed in $actual = Convert-ToSID -account_name ".\$sid_account" -Assert-Equals -actual ($actual -ne $sid_account) -expected $true +Assert-Equal -actual ($actual -ne $sid_account) -expected $true Exit-Json @{ data = "success" } diff --git a/test/integration/targets/module_utils_Ansible.ModuleUtils.WebRequest/library/web_request_test.ps1 b/test/integration/targets/module_utils_Ansible.ModuleUtils.WebRequest/library/web_request_test.ps1 index a483698ce3..c168b92cb1 100644 --- a/test/integration/targets/module_utils_Ansible.ModuleUtils.WebRequest/library/web_request_test.ps1 +++ b/test/integration/targets/module_utils_Ansible.ModuleUtils.WebRequest/library/web_request_test.ps1 @@ -13,45 +13,48 @@ $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec) $httpbin_host = $module.Params.httpbin_host -Function Assert-Equals { +Function Assert-Equal { param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected + [Parameter(Mandatory = $true, ValueFromPipeline = $true)][AllowNull()]$Actual, + [Parameter(Mandatory = $true, Position = 0)][AllowNull()]$Expected ) - $matched = $false - if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array] -or $Actual -is [System.Collections.IList]) { - $Actual.Count | Assert-Equals -Expected $Expected.Count - for ($i = 0; $i -lt $Actual.Count; $i++) { - $actualValue = $Actual[$i] - $expectedValue = $Expected[$i] - Assert-Equals -Actual $actualValue -Expected $expectedValue - } - $matched = $true - } else { - $matched = $Actual -ceq $Expected - } - - if (-not $matched) { - if ($Actual -is [PSObject]) { - $Actual = $Actual.ToString() + process { + $matched = $false + if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array] -or $Actual -is [System.Collections.IList]) { + $Actual.Count | Assert-Equal -Expected $Expected.Count + for ($i = 0; $i -lt $Actual.Count; $i++) { + $actualValue = $Actual[$i] + $expectedValue = $Expected[$i] + Assert-Equal -Actual $actualValue -Expected $expectedValue + } + $matched = $true } + else { + $matched = $Actual -ceq $Expected + } + + if (-not $matched) { + if ($Actual -is [PSObject]) { + $Actual = $Actual.ToString() + } - $call_stack = (Get-PSCallStack)[1] - $module.Result.test = $test - $module.Result.actual = $Actual - $module.Result.expected = $Expected - $module.Result.line = $call_stack.ScriptLineNumber - $module.Result.method = $call_stack.Position.Text + $call_stack = (Get-PSCallStack)[1] + $module.Result.test = $test + $module.Result.actual = $Actual + $module.Result.expected = $Expected + $module.Result.line = $call_stack.ScriptLineNumber + $module.Result.method = $call_stack.Position.Text - $module.FailJson("AssertionError: actual != expected") + $module.FailJson("AssertionError: actual != expected") + } } } Function Convert-StreamToString { [CmdletBinding()] param ( - [Parameter(Mandatory=$true)] + [Parameter(Mandatory = $true)] [System.IO.Stream] $Stream ) @@ -60,7 +63,8 @@ Function Convert-StreamToString { try { $Stream.CopyTo($ms) [System.Text.Encoding]::UTF8.GetString($ms.ToArray()) - } finally { + } + finally { $ms.Dispose() } } @@ -69,50 +73,50 @@ $tests = [Ordered]@{ 'GET request over http' = { $r = Get-AnsibleWebRequest -Uri "http://$httpbin_host/get" - $r.Method | Assert-Equals -Expected 'GET' - $r.Timeout | Assert-Equals -Expected 30000 - $r.UseDefaultCredentials | Assert-Equals -Expected $false - $r.Credentials | Assert-Equals -Expected $null - $r.ClientCertificates.Count | Assert-Equals -Expected 0 - $r.Proxy.Credentials | Assert-Equals -Expected $null - $r.UserAgent | Assert-Equals -Expected 'ansible-httpget' + $r.Method | Assert-Equal -Expected 'GET' + $r.Timeout | Assert-Equal -Expected 30000 + $r.UseDefaultCredentials | Assert-Equal -Expected $false + $r.Credentials | Assert-Equal -Expected $null + $r.ClientCertificates.Count | Assert-Equal -Expected 0 + $r.Proxy.Credentials | Assert-Equal -Expected $null + $r.UserAgent | Assert-Equal -Expected 'ansible-httpget' $actual = Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.StatusCode | Assert-Equals -Expected 200 + $Response.StatusCode | Assert-Equal -Expected 200 Convert-StreamToString -Stream $Stream } | ConvertFrom-Json - $actual.headers.'User-Agent' | Assert-Equals -Expected 'ansible-httpget' - $actual.headers.'Host' | Assert-Equals -Expected $httpbin_host + $actual.headers.'User-Agent' | Assert-Equal -Expected 'ansible-httpget' + $actual.headers.'Host' | Assert-Equal -Expected $httpbin_host - $module.Result.msg | Assert-Equals -Expected 'OK' - $module.Result.status_code | Assert-Equals -Expected 200 - $module.Result.ContainsKey('elapsed') | Assert-Equals -Expected $true + $module.Result.msg | Assert-Equal -Expected 'OK' + $module.Result.status_code | Assert-Equal -Expected 200 + $module.Result.ContainsKey('elapsed') | Assert-Equal -Expected $true } 'GET request over https' = { # url is an alias for the -Uri parameter. $r = Get-AnsibleWebRequest -url "https://$httpbin_host/get" - $r.Method | Assert-Equals -Expected 'GET' - $r.Timeout | Assert-Equals -Expected 30000 - $r.UseDefaultCredentials | Assert-Equals -Expected $false - $r.Credentials | Assert-Equals -Expected $null - $r.ClientCertificates.Count | Assert-Equals -Expected 0 - $r.Proxy.Credentials | Assert-Equals -Expected $null - $r.UserAgent | Assert-Equals -Expected 'ansible-httpget' + $r.Method | Assert-Equal -Expected 'GET' + $r.Timeout | Assert-Equal -Expected 30000 + $r.UseDefaultCredentials | Assert-Equal -Expected $false + $r.Credentials | Assert-Equal -Expected $null + $r.ClientCertificates.Count | Assert-Equal -Expected 0 + $r.Proxy.Credentials | Assert-Equal -Expected $null + $r.UserAgent | Assert-Equal -Expected 'ansible-httpget' $actual = Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.StatusCode | Assert-Equals -Expected 200 + $Response.StatusCode | Assert-Equal -Expected 200 Convert-StreamToString -Stream $Stream } | ConvertFrom-Json - $actual.headers.'User-Agent' | Assert-Equals -Expected 'ansible-httpget' - $actual.headers.'Host' | Assert-Equals -Expected $httpbin_host + $actual.headers.'User-Agent' | Assert-Equal -Expected 'ansible-httpget' + $actual.headers.'Host' | Assert-Equal -Expected $httpbin_host } 'POST request' = { @@ -125,14 +129,14 @@ $tests = [Ordered]@{ } $r = Get-AnsibleWebRequest @getParams - $r.Method | Assert-Equals -Expected 'POST' - $r.Timeout | Assert-Equals -Expected 30000 - $r.UseDefaultCredentials | Assert-Equals -Expected $false - $r.Credentials | Assert-Equals -Expected $null - $r.ClientCertificates.Count | Assert-Equals -Expected 0 - $r.Proxy.Credentials | Assert-Equals -Expected $null - $r.ContentType | Assert-Equals -Expected 'application/json' - $r.UserAgent | Assert-Equals -Expected 'ansible-httpget' + $r.Method | Assert-Equal -Expected 'POST' + $r.Timeout | Assert-Equal -Expected 30000 + $r.UseDefaultCredentials | Assert-Equal -Expected $false + $r.Credentials | Assert-Equal -Expected $null + $r.ClientCertificates.Count | Assert-Equal -Expected 0 + $r.Proxy.Credentials | Assert-Equal -Expected $null + $r.ContentType | Assert-Equal -Expected 'application/json' + $r.UserAgent | Assert-Equal -Expected 'ansible-httpget' $body = New-Object -TypeName System.IO.MemoryStream -ArgumentList @(, ([System.Text.Encoding]::UTF8.GetBytes('{"foo":"bar"}')) @@ -140,13 +144,13 @@ $tests = [Ordered]@{ $actual = Invoke-WithWebRequest -Module $module -Request $r -Body $body -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.StatusCode | Assert-Equals -Expected 200 + $Response.StatusCode | Assert-Equal -Expected 200 Convert-StreamToString -Stream $Stream } | ConvertFrom-Json - $actual.headers.'User-Agent' | Assert-Equals -Expected 'ansible-httpget' - $actual.headers.'Host' | Assert-Equals -Expected $httpbin_host - $actual.data | Assert-Equals -Expected '{"foo":"bar"}' + $actual.headers.'User-Agent' | Assert-Equal -Expected 'ansible-httpget' + $actual.headers.'Host' | Assert-Equal -Expected $httpbin_host + $actual.data | Assert-Equal -Expected '{"foo":"bar"}' } 'Safe redirection of GET' = { @@ -155,8 +159,8 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ResponseUri | Assert-Equals -Expected "http://$httpbin_host/get" - $Response.StatusCode | Assert-Equals -Expected 200 + $Response.ResponseUri | Assert-Equal -Expected "http://$httpbin_host/get" + $Response.StatusCode | Assert-Equal -Expected 200 } } @@ -166,8 +170,8 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ResponseUri | Assert-Equals -Expected "http://$httpbin_host/get" - $Response.StatusCode | Assert-Equals -Expected 200 + $Response.ResponseUri | Assert-Equal -Expected "http://$httpbin_host/get" + $Response.StatusCode | Assert-Equal -Expected 200 } } @@ -181,8 +185,8 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ResponseUri | Assert-Equals -Expected $r.RequestUri - $Response.StatusCode | Assert-Equals -Expected 302 + $Response.ResponseUri | Assert-Equal -Expected $r.RequestUri + $Response.StatusCode | Assert-Equal -Expected 302 } } @@ -196,8 +200,8 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ResponseUri | Assert-Equals -Expected $r.RequestUri - $Response.StatusCode | Assert-Equals -Expected 302 + $Response.ResponseUri | Assert-Equal -Expected $r.RequestUri + $Response.StatusCode | Assert-Equal -Expected 302 } } @@ -212,8 +216,8 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ResponseUri | Assert-Equals -Expected $r.RequestUri - $Response.StatusCode | Assert-Equals -Expected 302 + $Response.ResponseUri | Assert-Equal -Expected $r.RequestUri + $Response.StatusCode | Assert-Equal -Expected 302 } } @@ -228,8 +232,8 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ResponseUri | Assert-Equals -Expected $r.RequestUri - $Response.StatusCode | Assert-Equals -Expected 302 + $Response.ResponseUri | Assert-Equal -Expected $r.RequestUri + $Response.StatusCode | Assert-Equal -Expected 302 } } @@ -243,8 +247,8 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ResponseUri | Assert-Equals -Expected "http://$httpbin_host/get" - $Response.StatusCode | Assert-Equals -Expected 200 + $Response.ResponseUri | Assert-Equal -Expected "http://$httpbin_host/get" + $Response.StatusCode | Assert-Equal -Expected 200 } } @@ -259,8 +263,8 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ResponseUri | Assert-Equals -Expected "http://$httpbin_host/get" - $Response.StatusCode | Assert-Equals -Expected 200 + $Response.ResponseUri | Assert-Equal -Expected "http://$httpbin_host/get" + $Response.StatusCode | Assert-Equal -Expected 200 } } @@ -275,8 +279,8 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ResponseUri | Assert-Equals -Expected "https://$httpbin_host/put" - $Response.StatusCode | Assert-Equals -Expected 200 + $Response.ResponseUri | Assert-Equal -Expected "https://$httpbin_host/put" + $Response.StatusCode | Assert-Equal -Expected 200 } } @@ -290,8 +294,8 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -IgnoreBadResponse -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ResponseUri | Assert-Equals -Expected "https://$httpbin_host/relative-redirect/1" - $Response.StatusCode | Assert-Equals -Expected 302 + $Response.ResponseUri | Assert-Equal -Expected "https://$httpbin_host/relative-redirect/1" + $Response.StatusCode | Assert-Equal -Expected 302 } } @@ -305,12 +309,13 @@ $tests = [Ordered]@{ $failed = $false try { $null = Invoke-WithWebRequest -Module $module -Request $r -Script {} - } catch { - $_.Exception.GetType().Name | Assert-Equals -Expected 'WebException' - $_.Exception.Message | Assert-Equals -Expected 'Too many automatic redirections were attempted.' + } + catch { + $_.Exception.GetType().Name | Assert-Equal -Expected 'WebException' + $_.Exception.Message | Assert-Equal -Expected 'Too many automatic redirections were attempted.' $failed = $true } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } 'Basic auth as Credential' = { @@ -324,7 +329,7 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -IgnoreBadResponse -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.StatusCode | Assert-Equals -Expected 200 + $Response.StatusCode | Assert-Equal -Expected 200 } } @@ -340,7 +345,7 @@ $tests = [Ordered]@{ Invoke-WithWebRequest -Module $module -Request $r -IgnoreBadResponse -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.StatusCode | Assert-Equals -Expected 200 + $Response.StatusCode | Assert-Equal -Expected 200 } } @@ -359,13 +364,13 @@ $tests = [Ordered]@{ $actual = Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.StatusCode | Assert-Equals -Expected 200 + $Response.StatusCode | Assert-Equal -Expected 200 Convert-StreamToString -Stream $Stream } | ConvertFrom-Json - $actual.headers.'Testheader' | Assert-Equals -Expected 'test-header' - $actual.headers.'testingheader' | Assert-Equals -Expected 'testing_header' - $actual.Headers.'User-Agent' | Assert-Equals -Expected 'test-agent' + $actual.headers.'Testheader' | Assert-Equal -Expected 'test-header' + $actual.headers.'testingheader' | Assert-Equal -Expected 'testing_header' + $actual.Headers.'User-Agent' | Assert-Equal -Expected 'test-agent' } 'Request with timeout' = { @@ -378,12 +383,13 @@ $tests = [Ordered]@{ $failed = $false try { $null = Invoke-WithWebRequest -Module $module -Request $r -Script {} - } catch { + } + catch { $failed = $true - $_.Exception.GetType().Name | Assert-Equals -Expected WebException - $_.Exception.Message | Assert-Equals -Expected 'The operation has timed out' + $_.Exception.GetType().Name | Assert-Equal -Expected WebException + $_.Exception.Message | Assert-Equal -Expected 'The operation has timed out' } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } 'Request with file URI' = { @@ -395,12 +401,12 @@ $tests = [Ordered]@{ $actual = Invoke-WithWebRequest -Module $module -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ContentLength | Assert-Equals -Expected 6 + $Response.ContentLength | Assert-Equal -Expected 6 Convert-StreamToString -Stream $Stream } - $actual | Assert-Equals -Expected "test`r`n" - $module.Result.msg | Assert-Equals -Expected "OK" - $module.Result.status_code | Assert-Equals -Expected 200 + $actual | Assert-Equal -Expected "test`r`n" + $module.Result.msg | Assert-Equal -Expected "OK" + $module.Result.status_code | Assert-Equal -Expected 200 } 'Web request based on module options' = { @@ -419,9 +425,9 @@ $tests = [Ordered]@{ $spec = @{ options = @{ url = @{ type = 'str'; required = $true } - test = @{ type = 'str'; choices = 'abc', 'def'} + test = @{ type = 'str'; choices = 'abc', 'def' } } - mutually_exclusive = @(,@('url', 'test')) + mutually_exclusive = @(, @('url', 'test')) } $testModule = [Ansible.Basic.AnsibleModule]::Create(@(), $spec, @(Get-AnsibleWebRequestSpec)) @@ -430,10 +436,10 @@ $tests = [Ordered]@{ $actual = Invoke-WithWebRequest -Module $testModule -Request $r -Script { Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream) - $Response.ResponseUri | Assert-Equals -Expected "https://$httpbin_host/get" + $Response.ResponseUri | Assert-Equal -Expected "https://$httpbin_host/get" Convert-StreamToString -Stream $Stream } | ConvertFrom-Json - $actual.headers.'User-Agent' | Assert-Equals -Expected 'actual-agent' + $actual.headers.'User-Agent' | Assert-Equal -Expected 'actual-agent' } 'Web request with default proxy' = { @@ -442,7 +448,7 @@ $tests = [Ordered]@{ } $r = Get-AnsibleWebRequest @params - $null -ne $r.Proxy | Assert-Equals -Expected $true + $null -ne $r.Proxy | Assert-Equal -Expected $true } 'Web request with no proxy' = { @@ -452,7 +458,7 @@ $tests = [Ordered]@{ } $r = Get-AnsibleWebRequest @params - $null -eq $r.Proxy | Assert-Equals -Expected $true + $null -eq $r.Proxy | Assert-Equal -Expected $true } } diff --git a/test/integration/targets/module_utils_Ansible.Privilege/library/ansible_privilege_tests.ps1 b/test/integration/targets/module_utils_Ansible.Privilege/library/ansible_privilege_tests.ps1 index 7c76036a82..58ee9c113a 100644 --- a/test/integration/targets/module_utils_Ansible.Privilege/library/ansible_privilege_tests.ps1 +++ b/test/integration/targets/module_utils_Ansible.Privilege/library/ansible_privilege_tests.ps1 @@ -5,143 +5,82 @@ $module = [Ansible.Basic.AnsibleModule]::Create($args, @{}) -Function Assert-Equals { +Function Assert-Equal { param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected + [Parameter(Mandatory = $true, ValueFromPipeline = $true)][AllowNull()]$Actual, + [Parameter(Mandatory = $true, Position = 0)][AllowNull()]$Expected ) - $matched = $false - if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { - $Actual.Count | Assert-Equals -Expected $Expected.Count - for ($i = 0; $i -lt $Actual.Count; $i++) { - $actual_value = $Actual[$i] - $expected_value = $Expected[$i] - Assert-Equals -Actual $actual_value -Expected $expected_value + process { + $matched = $false + if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { + $Actual.Count | Assert-Equal -Expected $Expected.Count + for ($i = 0; $i -lt $Actual.Count; $i++) { + $actual_value = $Actual[$i] + $expected_value = $Expected[$i] + Assert-Equal -Actual $actual_value -Expected $expected_value + } + $matched = $true } - $matched = $true - } else { - $matched = $Actual -ceq $Expected - } - - if (-not $matched) { - if ($Actual -is [PSObject]) { - $Actual = $Actual.ToString() + else { + $matched = $Actual -ceq $Expected } - $call_stack = (Get-PSCallStack)[1] - $module.Result.test = $test - $module.Result.actual = $Actual - $module.Result.expected = $Expected - $module.Result.line = $call_stack.ScriptLineNumber - $module.Result.method = $call_stack.Position.Text - $module.FailJson("AssertionError: actual != expected") - } -} - -Function Assert-DictionaryEquals { - param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected - ) - $actual_keys = $Actual.Keys - $expected_keys = $Expected.Keys - - $actual_keys.Count | Assert-Equals -Expected $expected_keys.Count - foreach ($actual_entry in $Actual.GetEnumerator()) { - $actual_key = $actual_entry.Key - ($actual_key -cin $expected_keys) | Assert-Equals -Expected $true - $actual_value = $actual_entry.Value - $expected_value = $Expected.$actual_key - - if ($actual_value -is [System.Collections.IDictionary]) { - $actual_value | Assert-DictionaryEquals -Expected $expected_value - } elseif ($actual_value -is [System.Collections.ArrayList]) { - for ($i = 0; $i -lt $actual_value.Count; $i++) { - $actual_entry = $actual_value[$i] - $expected_entry = $expected_value[$i] - if ($actual_entry -is [System.Collections.IDictionary]) { - $actual_entry | Assert-DictionaryEquals -Expected $expected_entry - } else { - Assert-Equals -Actual $actual_entry -Expected $expected_entry - } + if (-not $matched) { + if ($Actual -is [PSObject]) { + $Actual = $Actual.ToString() } - } else { - Assert-Equals -Actual $actual_value -Expected $expected_value + + $call_stack = (Get-PSCallStack)[1] + $module.Result.test = $test + $module.Result.actual = $Actual + $module.Result.expected = $Expected + $module.Result.line = $call_stack.ScriptLineNumber + $module.Result.method = $call_stack.Position.Text + $module.FailJson("AssertionError: actual != expected") } } - foreach ($expected_key in $expected_keys) { - ($expected_key -cin $actual_keys) | Assert-Equals -Expected $true - } } -Function Assert-Equals { +Function Assert-DictionaryEqual { param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected + [Parameter(Mandatory = $true, ValueFromPipeline = $true)][AllowNull()]$Actual, + [Parameter(Mandatory = $true, Position = 0)][AllowNull()]$Expected ) - $matched = $false - if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { - $Actual.Count | Assert-Equals -Expected $Expected.Count - for ($i = 0; $i -lt $Actual.Count; $i++) { - $actual_value = $Actual[$i] - $expected_value = $Expected[$i] - Assert-Equals -Actual $actual_value -Expected $expected_value - } - $matched = $true - } else { - $matched = $Actual -ceq $Expected - } + process { + $actual_keys = $Actual.Keys + $expected_keys = $Expected.Keys - if (-not $matched) { - if ($Actual -is [PSObject]) { - $Actual = $Actual.ToString() - } - - $call_stack = (Get-PSCallStack)[1] - $module.Result.test = $test - $module.Result.actual = $Actual - $module.Result.expected = $Expected - $module.Result.line = $call_stack.ScriptLineNumber - $module.Result.method = $call_stack.Position.Text - $module.FailJson("AssertionError: actual != expected") - } -} + $actual_keys.Count | Assert-Equal -Expected $expected_keys.Count + foreach ($actual_entry in $Actual.GetEnumerator()) { + $actual_key = $actual_entry.Key + ($actual_key -cin $expected_keys) | Assert-Equal -Expected $true + $actual_value = $actual_entry.Value + $expected_value = $Expected.$actual_key -Function Assert-DictionaryEquals { - param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected - ) - $actual_keys = $Actual.Keys - $expected_keys = $Expected.Keys - - $actual_keys.Count | Assert-Equals -Expected $expected_keys.Count - foreach ($actual_entry in $Actual.GetEnumerator()) { - $actual_key = $actual_entry.Key - ($actual_key -cin $expected_keys) | Assert-Equals -Expected $true - $actual_value = $actual_entry.Value - $expected_value = $Expected.$actual_key - - if ($actual_value -is [System.Collections.IDictionary]) { - $actual_value | Assert-DictionaryEquals -Expected $expected_value - } elseif ($actual_value -is [System.Collections.ArrayList]) { - for ($i = 0; $i -lt $actual_value.Count; $i++) { - $actual_entry = $actual_value[$i] - $expected_entry = $expected_value[$i] - if ($actual_entry -is [System.Collections.IDictionary]) { - $actual_entry | Assert-DictionaryEquals -Expected $expected_entry - } else { - Assert-Equals -Actual $actual_entry -Expected $expected_entry + if ($actual_value -is [System.Collections.IDictionary]) { + $actual_value | Assert-DictionaryEqual -Expected $expected_value + } + elseif ($actual_value -is [System.Collections.ArrayList]) { + for ($i = 0; $i -lt $actual_value.Count; $i++) { + $actual_entry = $actual_value[$i] + $expected_entry = $expected_value[$i] + if ($actual_entry -is [System.Collections.IDictionary]) { + $actual_entry | Assert-DictionaryEqual -Expected $expected_entry + } + else { + Assert-Equal -Actual $actual_entry -Expected $expected_entry + } } } - } else { - Assert-Equals -Actual $actual_value -Expected $expected_value + else { + Assert-Equal -Actual $actual_value -Expected $expected_value + } + } + foreach ($expected_key in $expected_keys) { + ($expected_key -cin $actual_keys) | Assert-Equal -Expected $true } - } - foreach ($expected_key in $expected_keys) { - ($expected_key -cin $actual_keys) | Assert-Equals -Expected $true } } @@ -150,12 +89,12 @@ $process = [Ansible.Privilege.PrivilegeUtil]::GetCurrentProcess() $tests = @{ "Check valid privilege name" = { $actual = [Ansible.Privilege.PrivilegeUtil]::CheckPrivilegeName("SeTcbPrivilege") - $actual | Assert-Equals -Expected $true + $actual | Assert-Equal -Expected $true } "Check invalid privilege name" = { $actual = [Ansible.Privilege.PrivilegeUtil]::CheckPrivilegeName("SeFake") - $actual | Assert-Equals -Expected $false + $actual | Assert-Equal -Expected $false } "Disable a privilege" = { @@ -163,14 +102,14 @@ $tests = @{ [Ansible.Privilege.PrivilegeUtil]::EnablePrivilege($process, "SeTimeZonePrivilege") > $null $actual = [Ansible.Privilege.PrivilegeUtil]::DisablePrivilege($process, "SeTimeZonePrivilege") - $actual.GetType().Name | Assert-Equals -Expected 'Dictionary`2' - $actual.Count | Assert-Equals -Expected 1 - $actual.SeTimeZonePrivilege | Assert-Equals -Expected $true + $actual.GetType().Name | Assert-Equal -Expected 'Dictionary`2' + $actual.Count | Assert-Equal -Expected 1 + $actual.SeTimeZonePrivilege | Assert-Equal -Expected $true # Disable again $actual = [Ansible.Privilege.PrivilegeUtil]::DisablePrivilege($process, "SeTimeZonePrivilege") - $actual.GetType().Name | Assert-Equals -Expected 'Dictionary`2' - $actual.Count | Assert-Equals -Expected 0 + $actual.GetType().Name | Assert-Equal -Expected 'Dictionary`2' + $actual.Count | Assert-Equal -Expected 0 } "Enable a privilege" = { @@ -178,139 +117,154 @@ $tests = @{ [Ansible.Privilege.PrivilegeUtil]::DisablePrivilege($process, "SeTimeZonePrivilege") > $null $actual = [Ansible.Privilege.PrivilegeUtil]::EnablePrivilege($process, "SeTimeZonePrivilege") - $actual.GetType().Name | Assert-Equals -Expected 'Dictionary`2' - $actual.Count | Assert-Equals -Expected 1 - $actual.SeTimeZonePrivilege | Assert-Equals -Expected $false + $actual.GetType().Name | Assert-Equal -Expected 'Dictionary`2' + $actual.Count | Assert-Equal -Expected 1 + $actual.SeTimeZonePrivilege | Assert-Equal -Expected $false # Disable again $actual = [Ansible.Privilege.PrivilegeUtil]::EnablePrivilege($process, "SeTimeZonePrivilege") - $actual.GetType().Name | Assert-Equals -Expected 'Dictionary`2' - $actual.Count | Assert-Equals -Expected 0 + $actual.GetType().Name | Assert-Equal -Expected 'Dictionary`2' + $actual.Count | Assert-Equal -Expected 0 } "Disable and revert privileges" = { $current_state = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) $previous_state = [Ansible.Privilege.PrivilegeUtil]::DisableAllPrivileges($process) - $previous_state.GetType().Name | Assert-Equals -Expected 'Dictionary`2' + $previous_state.GetType().Name | Assert-Equal -Expected 'Dictionary`2' foreach ($previous_state_entry in $previous_state.GetEnumerator()) { - $previous_state_entry.Value | Assert-Equals -Expected $true + $previous_state_entry.Value | Assert-Equal -Expected $true } # Disable again $previous_state2 = [Ansible.Privilege.PrivilegeUtil]::DisableAllPrivileges($process) - $previous_state2.Count | Assert-Equals -Expected 0 + $previous_state2.Count | Assert-Equal -Expected 0 $actual = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) foreach ($actual_entry in $actual.GetEnumerator()) { - $actual_entry.Value -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 + $actual_entry.Value -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 } [Ansible.Privilege.PrivilegeUtil]::SetTokenPrivileges($process, $previous_state) > $null $actual = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) - $actual | Assert-DictionaryEquals -Expected $current_state + $actual | Assert-DictionaryEqual -Expected $current_state } "Remove a privilege" = { [Ansible.Privilege.PrivilegeUtil]::RemovePrivilege($process, "SeUndockPrivilege") > $null $actual = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) - $actual.ContainsKey("SeUndockPrivilege") | Assert-Equals -Expected $false + $actual.ContainsKey("SeUndockPrivilege") | Assert-Equal -Expected $false } "Test Enabler" = { # Disable privilege at the start $new_state = @{ - SeTimeZonePrivilege = $false - SeShutdownPrivilege = $false - SeIncreaseWorkingSetPrivilege = $false + SeTimeZonePrivilege = $false + SeShutdownPrivilege = $false + SeIncreaseWorkingSetPrivilege = $false } [Ansible.Privilege.PrivilegeUtil]::SetTokenPrivileges($process, $new_state) > $null $check_state = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) - $check_state.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 - $check_state.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 - $check_state.SeIncreaseWorkingSetPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 + $check_state.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 + $check_state.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 + $check_state.SeIncreaseWorkingSetPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 # Check that strict = false won't validate privileges not held but activates the ones we want $enabler = New-Object -TypeName Ansible.Privilege.PrivilegeEnabler -ArgumentList $false, "SeTimeZonePrivilege", "SeShutdownPrivilege", "SeTcbPrivilege" $actual = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) - $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) - $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) - $actual.SeIncreaseWorkingSetPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 - $actual.ContainsKey("SeTcbPrivilege") | Assert-Equals -Expected $false + $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | + Assert-Equal -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) + $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | + Assert-Equal -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) + $actual.SeIncreaseWorkingSetPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 + $actual.ContainsKey("SeTcbPrivilege") | Assert-Equal -Expected $false # Now verify a no-op enabler will not rever back to disabled $enabler2 = New-Object -TypeName Ansible.Privilege.PrivilegeEnabler -ArgumentList $false, "SeTimeZonePrivilege", "SeShutdownPrivilege", "SeTcbPrivilege" $enabler2.Dispose() $actual = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) - $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) - $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) + $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | + Assert-Equal -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) + $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | + Assert-Equal -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) # Verify that when disposing the object the privileges are reverted $enabler.Dispose() $actual = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) - $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 - $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 + $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 + $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 } "Test Enabler strict" = { # Disable privilege at the start $new_state = @{ - SeTimeZonePrivilege = $false - SeShutdownPrivilege = $false - SeIncreaseWorkingSetPrivilege = $false + SeTimeZonePrivilege = $false + SeShutdownPrivilege = $false + SeIncreaseWorkingSetPrivilege = $false } [Ansible.Privilege.PrivilegeUtil]::SetTokenPrivileges($process, $new_state) > $null $check_state = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) - $check_state.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 - $check_state.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 - $check_state.SeIncreaseWorkingSetPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 + $check_state.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 + $check_state.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 + $check_state.SeIncreaseWorkingSetPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 # Check that strict = false won't validate privileges not held but activates the ones we want $enabler = New-Object -TypeName Ansible.Privilege.PrivilegeEnabler -ArgumentList $true, "SeTimeZonePrivilege", "SeShutdownPrivilege" $actual = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) - $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) - $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) - $actual.SeIncreaseWorkingSetPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 + $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | + Assert-Equal -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) + $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | + Assert-Equal -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) + $actual.SeIncreaseWorkingSetPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 # Now verify a no-op enabler will not rever back to disabled $enabler2 = New-Object -TypeName Ansible.Privilege.PrivilegeEnabler -ArgumentList $true, "SeTimeZonePrivilege", "SeShutdownPrivilege" $enabler2.Dispose() $actual = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) - $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) - $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) + $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | + Assert-Equal -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) + $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | + Assert-Equal -Expected ([Ansible.Privilege.PrivilegeAttributes]::Enabled) # Verify that when disposing the object the privileges are reverted $enabler.Dispose() $actual = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) - $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 - $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 + $actual.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 + $actual.SeShutdownPrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 } "Test Enabler invalid privilege" = { $failed = $false try { New-Object -TypeName Ansible.Privilege.PrivilegeEnabler -ArgumentList $false, "SeTimeZonePrivilege", "SeFake" - } catch { + } + catch { $failed = $true - $_.Exception.InnerException.Message | Assert-Equals -Expected "Failed to enable privilege(s) SeTimeZonePrivilege, SeFake (A specified privilege does not exist, Win32ErrorCode 1313)" + $expected = "Failed to enable privilege(s) SeTimeZonePrivilege, SeFake (A specified privilege does not exist, Win32ErrorCode 1313)" + $_.Exception.InnerException.Message | Assert-Equal -Expected $expected } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "Test Enabler strict failure" = { # Start disabled [Ansible.Privilege.PrivilegeUtil]::DisablePrivilege($process, "SeTimeZonePrivilege") > $null $check_state = [Ansible.Privilege.PrivilegeUtil]::GetAllPrivilegeInfo($process) - $check_state.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equals -Expected 0 + $check_state.SeTimeZonePrivilege -band [Ansible.Privilege.PrivilegeAttributes]::Enabled | Assert-Equal -Expected 0 $failed = $false try { New-Object -TypeName Ansible.Privilege.PrivilegeEnabler -ArgumentList $true, "SeTimeZonePrivilege", "SeTcbPrivilege" - } catch { + } + catch { $failed = $true - $_.Exception.InnerException.Message | Assert-Equals -Expected "Failed to enable privilege(s) SeTimeZonePrivilege, SeTcbPrivilege (Not all privileges or groups referenced are assigned to the caller, Win32ErrorCode 1300)" + $expected = -join @( + "Failed to enable privilege(s) SeTimeZonePrivilege, SeTcbPrivilege " + "(Not all privileges or groups referenced are assigned to the caller, Win32ErrorCode 1300)" + ) + $_.Exception.InnerException.Message | Assert-Equal -Expected $expected } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } } diff --git a/test/integration/targets/module_utils_Ansible.Process/library/ansible_process_tests.ps1 b/test/integration/targets/module_utils_Ansible.Process/library/ansible_process_tests.ps1 index d906dfc524..bca7eb1e83 100644 --- a/test/integration/targets/module_utils_Ansible.Process/library/ansible_process_tests.ps1 +++ b/test/integration/targets/module_utils_Ansible.Process/library/ansible_process_tests.ps1 @@ -5,37 +5,40 @@ $module = [Ansible.Basic.AnsibleModule]::Create($args, @{}) -Function Assert-Equals { +Function Assert-Equal { param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected + [Parameter(Mandatory = $true, ValueFromPipeline = $true)][AllowNull()]$Actual, + [Parameter(Mandatory = $true, Position = 0)][AllowNull()]$Expected ) - $matched = $false - if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { - $Actual.Count | Assert-Equals -Expected $Expected.Count - for ($i = 0; $i -lt $Actual.Count; $i++) { - $actual_value = $Actual[$i] - $expected_value = $Expected[$i] - Assert-Equals -Actual $actual_value -Expected $expected_value + process { + $matched = $false + if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array]) { + $Actual.Count | Assert-Equal -Expected $Expected.Count + for ($i = 0; $i -lt $Actual.Count; $i++) { + $actual_value = $Actual[$i] + $expected_value = $Expected[$i] + Assert-Equal -Actual $actual_value -Expected $expected_value + } + $matched = $true } - $matched = $true - } else { - $matched = $Actual -ceq $Expected - } - - if (-not $matched) { - if ($Actual -is [PSObject]) { - $Actual = $Actual.ToString() + else { + $matched = $Actual -ceq $Expected } - $call_stack = (Get-PSCallStack)[1] - $module.Result.test = $test - $module.Result.actual = $Actual - $module.Result.expected = $Expected - $module.Result.line = $call_stack.ScriptLineNumber - $module.Result.method = $call_stack.Position.Text - $module.FailJson("AssertionError: actual != expected") + if (-not $matched) { + if ($Actual -is [PSObject]) { + $Actual = $Actual.ToString() + } + + $call_stack = (Get-PSCallStack)[1] + $module.Result.test = $test + $module.Result.actual = $Actual + $module.Result.expected = $Expected + $module.Result.line = $call_stack.ScriptLineNumber + $module.Result.method = $call_stack.Position.Text + $module.FailJson("AssertionError: actual != expected") + } } } @@ -43,116 +46,118 @@ $tests = @{ "ParseCommandLine empty string" = { $expected = @((Get-Process -Id $pid).Path) $actual = [Ansible.Process.ProcessUtil]::ParseCommandLine("") - Assert-Equals -Actual $actual -Expected $expected + Assert-Equal -Actual $actual -Expected $expected } "ParseCommandLine single argument" = { $expected = @("powershell.exe") $actual = [Ansible.Process.ProcessUtil]::ParseCommandLine("powershell.exe") - Assert-Equals -Actual $actual -Expected $expected + Assert-Equal -Actual $actual -Expected $expected } "ParseCommandLine multiple arguments" = { $expected = @("powershell.exe", "-File", "C:\temp\script.ps1") $actual = [Ansible.Process.ProcessUtil]::ParseCommandLine("powershell.exe -File C:\temp\script.ps1") - Assert-Equals -Actual $actual -Expected $expected + Assert-Equal -Actual $actual -Expected $expected } "ParseCommandLine comples arguments" = { $expected = @('abc', 'd', 'ef gh', 'i\j', 'k"l', 'm\n op', 'ADDLOCAL=qr, s', 'tuv\', 'w''x', 'yz') $actual = [Ansible.Process.ProcessUtil]::ParseCommandLine('abc d "ef gh" i\j k\"l m\\"n op" ADDLOCAL="qr, s" tuv\ w''x yz') - Assert-Equals -Actual $actual -Expected $expected + Assert-Equal -Actual $actual -Expected $expected } "SearchPath normal" = { $expected = "$($env:SystemRoot)\System32\WindowsPowerShell\v1.0\powershell.exe" $actual = [Ansible.Process.ProcessUtil]::SearchPath("powershell.exe") - $actual | Assert-Equals -Expected $expected + $actual | Assert-Equal -Expected $expected } "SearchPath missing" = { $failed = $false try { [Ansible.Process.ProcessUtil]::SearchPath("fake.exe") - } catch { + } + catch { $failed = $true - $_.Exception.InnerException.GetType().FullName | Assert-Equals -Expected "System.IO.FileNotFoundException" + $_.Exception.InnerException.GetType().FullName | Assert-Equal -Expected "System.IO.FileNotFoundException" $expected = 'Exception calling "SearchPath" with "1" argument(s): "Could not find file ''fake.exe''."' - $_.Exception.Message | Assert-Equals -Expected $expected + $_.Exception.Message | Assert-Equal -Expected $expected } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "CreateProcess basic" = { $actual = [Ansible.Process.ProcessUtil]::CreateProcess("whoami.exe") - $actual.GetType().FullName | Assert-Equals -Expected "Ansible.Process.Result" - $actual.StandardOut | Assert-Equals -Expected "$(&whoami.exe)`r`n" - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.GetType().FullName | Assert-Equal -Expected "Ansible.Process.Result" + $actual.StandardOut | Assert-Equal -Expected "$(&whoami.exe)`r`n" + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess stderr" = { $actual = [Ansible.Process.ProcessUtil]::CreateProcess("powershell.exe [System.Console]::Error.WriteLine('hi')") - $actual.StandardOut | Assert-Equals -Expected "" - $actual.StandardError | Assert-Equals -Expected "hi`r`n" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected "" + $actual.StandardError | Assert-Equal -Expected "hi`r`n" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess exit code" = { $actual = [Ansible.Process.ProcessUtil]::CreateProcess("powershell.exe exit 10") - $actual.StandardOut | Assert-Equals -Expected "" - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 10 + $actual.StandardOut | Assert-Equal -Expected "" + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 10 } "CreateProcess bad executable" = { $failed = $false try { [Ansible.Process.ProcessUtil]::CreateProcess("fake.exe") - } catch { + } + catch { $failed = $true - $_.Exception.InnerException.GetType().FullName | Assert-Equals -Expected "Ansible.Process.Win32Exception" + $_.Exception.InnerException.GetType().FullName | Assert-Equal -Expected "Ansible.Process.Win32Exception" $expected = 'Exception calling "CreateProcess" with "1" argument(s): "CreateProcessW() failed ' $expected += '(The system cannot find the file specified, Win32ErrorCode 2)"' - $_.Exception.Message | Assert-Equals -Expected $expected + $_.Exception.Message | Assert-Equal -Expected $expected } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "CreateProcess with unicode" = { $actual = [Ansible.Process.ProcessUtil]::CreateProcess("cmd.exe /c echo 💩 café") - $actual.StandardOut | Assert-Equals -Expected "💩 café`r`n" - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected "💩 café`r`n" + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $actual = [Ansible.Process.ProcessUtil]::CreateProcess($null, "cmd.exe /c echo 💩 café", $null, $null) - $actual.StandardOut | Assert-Equals -Expected "💩 café`r`n" - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected "💩 café`r`n" + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess without working dir" = { $expected = $pwd.Path + "`r`n" $actual = [Ansible.Process.ProcessUtil]::CreateProcess($null, 'powershell.exe $pwd.Path', $null, $null) - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess with working dir" = { $expected = "C:\Windows`r`n" $actual = [Ansible.Process.ProcessUtil]::CreateProcess($null, 'powershell.exe $pwd.Path', "C:\Windows", $null) - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess without environment" = { $expected = "$($env:USERNAME)`r`n" $actual = [Ansible.Process.ProcessUtil]::CreateProcess($null, 'powershell.exe $env:TEST; $env:USERNAME', $null, $null) - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess with environment" = { @@ -161,69 +166,70 @@ $tests = @{ TEST2 = "Testing 2" } $actual = [Ansible.Process.ProcessUtil]::CreateProcess($null, 'cmd.exe /c set', $null, $env_vars) - ("TEST=tesTing" -cin $actual.StandardOut.Split("`r`n")) | Assert-Equals -Expected $true - ("TEST2=Testing 2" -cin $actual.StandardOut.Split("`r`n")) | Assert-Equals -Expected $true - ("USERNAME=$($env:USERNAME)" -cnotin $actual.StandardOut.Split("`r`n")) | Assert-Equals -Expected $true - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + ("TEST=tesTing" -cin $actual.StandardOut.Split("`r`n")) | Assert-Equal -Expected $true + ("TEST2=Testing 2" -cin $actual.StandardOut.Split("`r`n")) | Assert-Equal -Expected $true + ("USERNAME=$($env:USERNAME)" -cnotin $actual.StandardOut.Split("`r`n")) | Assert-Equal -Expected $true + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess with string stdin" = { $expected = "input value`r`n`r`n" $actual = [Ansible.Process.ProcessUtil]::CreateProcess($null, 'powershell.exe [System.Console]::In.ReadToEnd()', $null, $null, "input value") - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess with string stdin and newline" = { $expected = "input value`r`n`r`n" $actual = [Ansible.Process.ProcessUtil]::CreateProcess($null, 'powershell.exe [System.Console]::In.ReadToEnd()', $null, $null, "input value`r`n") - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess with byte stdin" = { $expected = "input value`r`n" $actual = [Ansible.Process.ProcessUtil]::CreateProcess($null, 'powershell.exe [System.Console]::In.ReadToEnd()', $null, $null, [System.Text.Encoding]::UTF8.GetBytes("input value")) - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess with byte stdin and newline" = { $expected = "input value`r`n`r`n" $actual = [Ansible.Process.ProcessUtil]::CreateProcess($null, 'powershell.exe [System.Console]::In.ReadToEnd()', $null, $null, [System.Text.Encoding]::UTF8.GetBytes("input value`r`n")) - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess with lpApplicationName" = { $expected = "abc`r`n" $full_path = "$($env:SystemRoot)\System32\WindowsPowerShell\v1.0\powershell.exe" $actual = [Ansible.Process.ProcessUtil]::CreateProcess($full_path, "Write-Output 'abc'", $null, $null) - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 $actual = [Ansible.Process.ProcessUtil]::CreateProcess($full_path, "powershell.exe Write-Output 'abc'", $null, $null) - $actual.StandardOut | Assert-Equals -Expected $expected - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected $expected + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } "CreateProcess with unicode and us-ascii encoding" = { - $poop = [System.Char]::ConvertFromUtf32(0xE05A) # Coverage breaks due to script parsing encoding issues with unicode chars, just use the code point instead + # Coverage breaks due to script parsing encoding issues with unicode chars, just use the code point instead + $poop = [System.Char]::ConvertFromUtf32(0xE05A) $actual = [Ansible.Process.ProcessUtil]::CreateProcess($null, "cmd.exe /c echo $poop café", $null, $null, '', 'us-ascii') - $actual.StandardOut | Assert-Equals -Expected "??? caf??`r`n" - $actual.StandardError | Assert-Equals -Expected "" - $actual.ExitCode | Assert-Equals -Expected 0 + $actual.StandardOut | Assert-Equal -Expected "??? caf??`r`n" + $actual.StandardError | Assert-Equal -Expected "" + $actual.ExitCode | Assert-Equal -Expected 0 } } diff --git a/test/integration/targets/module_utils_Ansible.Service/library/ansible_service_tests.ps1 b/test/integration/targets/module_utils_Ansible.Service/library/ansible_service_tests.ps1 index 6c8f729b2d..dab42d4c22 100644 --- a/test/integration/targets/module_utils_Ansible.Service/library/ansible_service_tests.ps1 +++ b/test/integration/targets/module_utils_Ansible.Service/library/ansible_service_tests.ps1 @@ -9,49 +9,52 @@ $module = [Ansible.Basic.AnsibleModule]::Create($args, @{}) $path = "$env:SystemRoot\System32\svchost.exe" -Function Assert-Equals { +Function Assert-Equal { param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)][AllowNull()]$Actual, - [Parameter(Mandatory=$true, Position=0)][AllowNull()]$Expected + [Parameter(Mandatory = $true, ValueFromPipeline = $true)][AllowNull()]$Actual, + [Parameter(Mandatory = $true, Position = 0)][AllowNull()]$Expected ) - $matched = $false - if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array] -or $Actual -is [System.Collections.IList]) { - $Actual.Count | Assert-Equals -Expected $Expected.Count - for ($i = 0; $i -lt $Actual.Count; $i++) { - $actualValue = $Actual[$i] - $expectedValue = $Expected[$i] - Assert-Equals -Actual $actualValue -Expected $expectedValue + process { + $matched = $false + if ($Actual -is [System.Collections.ArrayList] -or $Actual -is [Array] -or $Actual -is [System.Collections.IList]) { + $Actual.Count | Assert-Equal -Expected $Expected.Count + for ($i = 0; $i -lt $Actual.Count; $i++) { + $actualValue = $Actual[$i] + $expectedValue = $Expected[$i] + Assert-Equal -Actual $actualValue -Expected $expectedValue + } + $matched = $true } - $matched = $true - } else { - $matched = $Actual -ceq $Expected - } - - if (-not $matched) { - if ($Actual -is [PSObject]) { - $Actual = $Actual.ToString() + else { + $matched = $Actual -ceq $Expected } - $call_stack = (Get-PSCallStack)[1] - $module.Result.test = $test - $module.Result.actual = $Actual - $module.Result.expected = $Expected - $module.Result.line = $call_stack.ScriptLineNumber - $module.Result.method = $call_stack.Position.Text + if (-not $matched) { + if ($Actual -is [PSObject]) { + $Actual = $Actual.ToString() + } + + $call_stack = (Get-PSCallStack)[1] + $module.Result.test = $test + $module.Result.actual = $Actual + $module.Result.expected = $Expected + $module.Result.line = $call_stack.ScriptLineNumber + $module.Result.method = $call_stack.Position.Text - $module.FailJson("AssertionError: actual != expected") + $module.FailJson("AssertionError: actual != expected") + } } } Function Invoke-Sc { [CmdletBinding()] param ( - [Parameter(Mandatory=$true)] + [Parameter(Mandatory = $true)] [String] $Action, - [Parameter(Mandatory=$true)] + [Parameter(Mandatory = $true)] [String] $Name, @@ -66,7 +69,8 @@ Function Invoke-Sc { $commandArgs.Add("$($arg.Key)=") $commandArgs.Add($arg.Value) } - } else { + } + else { foreach ($arg in $Arguments) { $commandArgs.Add($arg) } @@ -118,7 +122,8 @@ Function Invoke-Sc { } $v = $lineSplit[1].Trim() - } else { + } + else { $k = $currentKey $v = $line } @@ -126,18 +131,21 @@ Function Invoke-Sc { if ($qtriggerSection.Count -gt 0) { if ($k -eq 'DATA') { $qtriggerSection.Data.Add($v) - } else { + } + else { $qtriggerSection.Type = $k $qtriggerSection.SubType = $v $qtriggerSection.Data = [System.Collections.Generic.List[String]]@() } - } else { + } + else { if ($info.ContainsKey($k)) { if ($info[$k] -isnot [System.Collections.Generic.List[String]]) { $info[$k] = [System.Collections.Generic.List[String]]@($info[$k]) } $info[$k].Add($v) - } else { + } + else { $currentKey = $k $info[$k] = $v } @@ -155,42 +163,43 @@ $tests = [Ordered]@{ "Props on service created by New-Service" = { $actual = New-Object -TypeName Ansible.Service.Service -ArgumentList $serviceName - $actual.ServiceName | Assert-Equals -Expected $serviceName - $actual.ServiceType | Assert-Equals -Expected ([Ansible.Service.ServiceType]::Win32OwnProcess) - $actual.StartType | Assert-Equals -Expected ([Ansible.Service.ServiceStartType]::DemandStart) - $actual.ErrorControl | Assert-Equals -Expected ([Ansible.Service.ErrorControl]::Normal) - $actual.Path | Assert-Equals -Expected ('"{0}"' -f $path) - $actual.LoadOrderGroup | Assert-Equals -Expected "" - $actual.DependentOn.Count | Assert-Equals -Expected 0 - $actual.Account | Assert-Equals -Expected ( + $actual.ServiceName | Assert-Equal -Expected $serviceName + $actual.ServiceType | Assert-Equal -Expected ([Ansible.Service.ServiceType]::Win32OwnProcess) + $actual.StartType | Assert-Equal -Expected ([Ansible.Service.ServiceStartType]::DemandStart) + $actual.ErrorControl | Assert-Equal -Expected ([Ansible.Service.ErrorControl]::Normal) + $actual.Path | Assert-Equal -Expected ('"{0}"' -f $path) + $actual.LoadOrderGroup | Assert-Equal -Expected "" + $actual.DependentOn.Count | Assert-Equal -Expected 0 + $actual.Account | Assert-Equal -Expected ( [System.Security.Principal.SecurityIdentifier]'S-1-5-18').Translate([System.Security.Principal.NTAccount] ) - $actual.DisplayName | Assert-Equals -Expected $serviceName - $actual.Description | Assert-Equals -Expected $null - $actual.FailureActions.ResetPeriod | Assert-Equals -Expected 0 - $actual.FailureActions.RebootMsg | Assert-Equals -Expected $null - $actual.FailureActions.Command | Assert-Equals -Expected $null - $actual.FailureActions.Actions.Count | Assert-Equals -Expected 0 - $actual.FailureActionsOnNonCrashFailures | Assert-Equals -Expected $false - $actual.ServiceSidInfo | Assert-Equals -Expected ([Ansible.Service.ServiceSidInfo]::None) - $actual.RequiredPrivileges.Count | Assert-Equals -Expected 0 + $actual.DisplayName | Assert-Equal -Expected $serviceName + $actual.Description | Assert-Equal -Expected $null + $actual.FailureActions.ResetPeriod | Assert-Equal -Expected 0 + $actual.FailureActions.RebootMsg | Assert-Equal -Expected $null + $actual.FailureActions.Command | Assert-Equal -Expected $null + $actual.FailureActions.Actions.Count | Assert-Equal -Expected 0 + $actual.FailureActionsOnNonCrashFailures | Assert-Equal -Expected $false + $actual.ServiceSidInfo | Assert-Equal -Expected ([Ansible.Service.ServiceSidInfo]::None) + $actual.RequiredPrivileges.Count | Assert-Equal -Expected 0 # Cannot test default values as it differs per OS version - $null -ne $actual.PreShutdownTimeout | Assert-Equals -Expected $true - $actual.Triggers.Count | Assert-Equals -Expected 0 - $actual.PreferredNode | Assert-Equals -Expected $null + $null -ne $actual.PreShutdownTimeout | Assert-Equal -Expected $true + $actual.Triggers.Count | Assert-Equal -Expected 0 + $actual.PreferredNode | Assert-Equal -Expected $null if ([Environment]::OSVersion.Version -ge [Version]'6.3') { - $actual.LaunchProtection | Assert-Equals -Expected ([Ansible.Service.LaunchProtection]::None) - } else { - $actual.LaunchProtection | Assert-Equals -Expected $null + $actual.LaunchProtection | Assert-Equal -Expected ([Ansible.Service.LaunchProtection]::None) + } + else { + $actual.LaunchProtection | Assert-Equal -Expected $null } - $actual.State | Assert-Equals -Expected ([Ansible.Service.ServiceStatus]::Stopped) - $actual.Win32ExitCode | Assert-Equals -Expected 1077 # ERROR_SERVICE_NEVER_STARTED - $actual.ServiceExitCode | Assert-Equals -Expected 0 - $actual.Checkpoint | Assert-Equals -Expected 0 - $actual.WaitHint | Assert-Equals -Expected 0 - $actual.ProcessId | Assert-Equals -Expected 0 - $actual.ServiceFlags | Assert-Equals -Expected ([Ansible.Service.ServiceFlags]::None) - $actual.DependedBy.Count | Assert-Equals 0 + $actual.State | Assert-Equal -Expected ([Ansible.Service.ServiceStatus]::Stopped) + $actual.Win32ExitCode | Assert-Equal -Expected 1077 # ERROR_SERVICE_NEVER_STARTED + $actual.ServiceExitCode | Assert-Equal -Expected 0 + $actual.Checkpoint | Assert-Equal -Expected 0 + $actual.WaitHint | Assert-Equal -Expected 0 + $actual.ProcessId | Assert-Equal -Expected 0 + $actual.ServiceFlags | Assert-Equal -Expected ([Ansible.Service.ServiceFlags]::None) + $actual.DependedBy.Count | Assert-Equal 0 } "Service creation through util" = { @@ -199,44 +208,46 @@ $tests = [Ordered]@{ try { $cmdletService = Get-Service -Name $testName -ErrorAction SilentlyContinue - $null -ne $cmdletService | Assert-Equals -Expected $true - - $actual.ServiceName | Assert-Equals -Expected $testName - $actual.ServiceType | Assert-Equals -Expected ([Ansible.Service.ServiceType]::Win32OwnProcess) - $actual.StartType | Assert-Equals -Expected ([Ansible.Service.ServiceStartType]::DemandStart) - $actual.ErrorControl | Assert-Equals -Expected ([Ansible.Service.ErrorControl]::Normal) - $actual.Path | Assert-Equals -Expected ('"{0}"' -f $path) - $actual.LoadOrderGroup | Assert-Equals -Expected "" - $actual.DependentOn.Count | Assert-Equals -Expected 0 - $actual.Account | Assert-Equals -Expected ( + $null -ne $cmdletService | Assert-Equal -Expected $true + + $actual.ServiceName | Assert-Equal -Expected $testName + $actual.ServiceType | Assert-Equal -Expected ([Ansible.Service.ServiceType]::Win32OwnProcess) + $actual.StartType | Assert-Equal -Expected ([Ansible.Service.ServiceStartType]::DemandStart) + $actual.ErrorControl | Assert-Equal -Expected ([Ansible.Service.ErrorControl]::Normal) + $actual.Path | Assert-Equal -Expected ('"{0}"' -f $path) + $actual.LoadOrderGroup | Assert-Equal -Expected "" + $actual.DependentOn.Count | Assert-Equal -Expected 0 + $actual.Account | Assert-Equal -Expected ( [System.Security.Principal.SecurityIdentifier]'S-1-5-18').Translate([System.Security.Principal.NTAccount] ) - $actual.DisplayName | Assert-Equals -Expected $testName - $actual.Description | Assert-Equals -Expected $null - $actual.FailureActions.ResetPeriod | Assert-Equals -Expected 0 - $actual.FailureActions.RebootMsg | Assert-Equals -Expected $null - $actual.FailureActions.Command | Assert-Equals -Expected $null - $actual.FailureActions.Actions.Count | Assert-Equals -Expected 0 - $actual.FailureActionsOnNonCrashFailures | Assert-Equals -Expected $false - $actual.ServiceSidInfo | Assert-Equals -Expected ([Ansible.Service.ServiceSidInfo]::None) - $actual.RequiredPrivileges.Count | Assert-Equals -Expected 0 - $null -ne $actual.PreShutdownTimeout | Assert-Equals -Expected $true - $actual.Triggers.Count | Assert-Equals -Expected 0 - $actual.PreferredNode | Assert-Equals -Expected $null + $actual.DisplayName | Assert-Equal -Expected $testName + $actual.Description | Assert-Equal -Expected $null + $actual.FailureActions.ResetPeriod | Assert-Equal -Expected 0 + $actual.FailureActions.RebootMsg | Assert-Equal -Expected $null + $actual.FailureActions.Command | Assert-Equal -Expected $null + $actual.FailureActions.Actions.Count | Assert-Equal -Expected 0 + $actual.FailureActionsOnNonCrashFailures | Assert-Equal -Expected $false + $actual.ServiceSidInfo | Assert-Equal -Expected ([Ansible.Service.ServiceSidInfo]::None) + $actual.RequiredPrivileges.Count | Assert-Equal -Expected 0 + $null -ne $actual.PreShutdownTimeout | Assert-Equal -Expected $true + $actual.Triggers.Count | Assert-Equal -Expected 0 + $actual.PreferredNode | Assert-Equal -Expected $null if ([Environment]::OSVersion.Version -ge [Version]'6.3') { - $actual.LaunchProtection | Assert-Equals -Expected ([Ansible.Service.LaunchProtection]::None) - } else { - $actual.LaunchProtection | Assert-Equals -Expected $null + $actual.LaunchProtection | Assert-Equal -Expected ([Ansible.Service.LaunchProtection]::None) + } + else { + $actual.LaunchProtection | Assert-Equal -Expected $null } - $actual.State | Assert-Equals -Expected ([Ansible.Service.ServiceStatus]::Stopped) - $actual.Win32ExitCode | Assert-Equals -Expected 1077 # ERROR_SERVICE_NEVER_STARTED - $actual.ServiceExitCode | Assert-Equals -Expected 0 - $actual.Checkpoint | Assert-Equals -Expected 0 - $actual.WaitHint | Assert-Equals -Expected 0 - $actual.ProcessId | Assert-Equals -Expected 0 - $actual.ServiceFlags | Assert-Equals -Expected ([Ansible.Service.ServiceFlags]::None) - $actual.DependedBy.Count | Assert-Equals 0 - } finally { + $actual.State | Assert-Equal -Expected ([Ansible.Service.ServiceStatus]::Stopped) + $actual.Win32ExitCode | Assert-Equal -Expected 1077 # ERROR_SERVICE_NEVER_STARTED + $actual.ServiceExitCode | Assert-Equal -Expected 0 + $actual.Checkpoint | Assert-Equal -Expected 0 + $actual.WaitHint | Assert-Equal -Expected 0 + $actual.ProcessId | Assert-Equal -Expected 0 + $actual.ServiceFlags | Assert-Equal -Expected ([Ansible.Service.ServiceFlags]::None) + $actual.DependedBy.Count | Assert-Equal 0 + } + finally { $actual.Delete() } } @@ -245,13 +256,14 @@ $tests = [Ordered]@{ $failed = $false try { $null = New-Object -TypeName Ansible.Service.Service -ArgumentList 'fake_service' - } catch [Ansible.Service.ServiceManagerException] { + } + catch [Ansible.Service.ServiceManagerException] { # 1060 == ERROR_SERVICE_DOES_NOT_EXIST - $_.Exception.Message -like '*Win32ErrorCode 1060 - 0x00000424*' | Assert-Equals -Expected $true + $_.Exception.Message -like '*Win32ErrorCode 1060 - 0x00000424*' | Assert-Equal -Expected $true $failed = $true } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } "Open with specific access rights" = { @@ -260,19 +272,20 @@ $tests = [Ordered]@{ ) # QueryStatus can get the status - $service.State | Assert-Equals -Expected ([Ansible.Service.ServiceStatus]::Stopped) + $service.State | Assert-Equal -Expected ([Ansible.Service.ServiceStatus]::Stopped) # Should fail to get the config because we did not request that right $failed = $false try { $service.Path = 'fail' - } catch [Ansible.Service.ServiceManagerException] { + } + catch [Ansible.Service.ServiceManagerException] { # 5 == ERROR_ACCESS_DENIED - $_.Exception.Message -like '*Win32ErrorCode 5 - 0x00000005*' | Assert-Equals -Expected $true + $_.Exception.Message -like '*Win32ErrorCode 5 - 0x00000005*' | Assert-Equal -Expected $true $failed = $true } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true } @@ -281,12 +294,12 @@ $tests = [Ordered]@{ $service.ServiceType = [Ansible.Service.ServiceType]::Win32ShareProcess $actual = Invoke-Sc -Action qc -Name $serviceName - $service.ServiceType | Assert-Equals -Expected ([Ansible.Service.ServiceType]::Win32ShareProcess) - $actual.TYPE | Assert-Equals -Expected "20 WIN32_SHARE_PROCESS" + $service.ServiceType | Assert-Equal -Expected ([Ansible.Service.ServiceType]::Win32ShareProcess) + $actual.TYPE | Assert-Equal -Expected "20 WIN32_SHARE_PROCESS" - $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{type="own"} + $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{type = "own" } $service.Refresh() - $service.ServiceType | Assert-Equals -Expected ([Ansible.Service.ServiceType]::Win32OwnProcess) + $service.ServiceType | Assert-Equal -Expected ([Ansible.Service.ServiceType]::Win32OwnProcess) } "Create desktop interactive service" = { @@ -294,29 +307,30 @@ $tests = [Ordered]@{ $service.ServiceType = [Ansible.Service.ServiceType]'Win32OwnProcess, InteractiveProcess' $actual = Invoke-Sc -Action qc -Name $serviceName - $actual.TYPE | Assert-Equals -Expected "110 WIN32_OWN_PROCESS (interactive)" - $service.ServiceType | Assert-Equals -Expected ([Ansible.Service.ServiceType]'Win32OwnProcess, InteractiveProcess') + $actual.TYPE | Assert-Equal -Expected "110 WIN32_OWN_PROCESS (interactive)" + $service.ServiceType | Assert-Equal -Expected ([Ansible.Service.ServiceType]'Win32OwnProcess, InteractiveProcess') # Change back from interactive process $service.ServiceType = [Ansible.Service.ServiceType]::Win32OwnProcess $actual = Invoke-Sc -Action qc -Name $serviceName - $actual.TYPE | Assert-Equals -Expected "10 WIN32_OWN_PROCESS" - $service.ServiceType | Assert-Equals -Expected ([Ansible.Service.ServiceType]::Win32OwnProcess) + $actual.TYPE | Assert-Equal -Expected "10 WIN32_OWN_PROCESS" + $service.ServiceType | Assert-Equal -Expected ([Ansible.Service.ServiceType]::Win32OwnProcess) $service.Account = [System.Security.Principal.SecurityIdentifier]'S-1-5-20' $failed = $false try { $service.ServiceType = [Ansible.Service.ServiceType]'Win32OwnProcess, InteractiveProcess' - } catch [Ansible.Service.ServiceManagerException] { + } + catch [Ansible.Service.ServiceManagerException] { $failed = $true - $_.Exception.NativeErrorCode | Assert-Equals -Expected 87 # ERROR_INVALID_PARAMETER + $_.Exception.NativeErrorCode | Assert-Equal -Expected 87 # ERROR_INVALID_PARAMETER } - $failed | Assert-Equals -Expected $true + $failed | Assert-Equal -Expected $true $actual = Invoke-Sc -Action qc -Name $serviceName - $actual.TYPE | Assert-Equals -Expected "10 WIN32_OWN_PROCESS" + $actual.TYPE | Assert-Equal -Expected "10 WIN32_OWN_PROCESS" } "Modify StartType" = { @@ -324,12 +338,12 @@ $tests = [Ordered]@{ $service.StartType = [Ansible.Service.ServiceStartType]::Disabled $actual = Invoke-Sc -Action qc -Name $serviceName - $service.StartType | Assert-Equals -Expected ([Ansible.Service.ServiceStartType]::Disabled) - $actual.START_TYPE | Assert-Equals -Expected "4 DISABLED" + $service.StartType | Assert-Equal -Expected ([Ansible.Service.ServiceStartType]::Disabled) + $actual.START_TYPE | Assert-Equal -Expected "4 DISABLED" - $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{start="demand"} + $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{start = "demand" } $service.Refresh() - $service.StartType | Assert-Equals -Expected ([Ansible.Service.ServiceStartType]::DemandStart) + $service.StartType | Assert-Equal -Expected ([Ansible.Service.ServiceStartType]::DemandStart) } "Modify StartType auto delayed" = { @@ -342,29 +356,29 @@ $tests = [Ordered]@{ $service.StartType = [Ansible.Service.ServiceStartType]::AutoStartDelayed $actual = Invoke-Sc -Action qc -Name $serviceName - $service.StartType | Assert-Equals -Expected ([Ansible.Service.ServiceStartType]::AutoStartDelayed) - $actual.START_TYPE | Assert-Equals -Expected "2 AUTO_START (DELAYED)" + $service.StartType | Assert-Equal -Expected ([Ansible.Service.ServiceStartType]::AutoStartDelayed) + $actual.START_TYPE | Assert-Equal -Expected "2 AUTO_START (DELAYED)" # Auto Start Delayed -> Auto Start $service.StartType = [Ansible.Service.ServiceStartType]::AutoStart $actual = Invoke-Sc -Action qc -Name $serviceName - $service.StartType | Assert-Equals -Expected ([Ansible.Service.ServiceStartType]::AutoStart) - $actual.START_TYPE | Assert-Equals -Expected "2 AUTO_START" + $service.StartType | Assert-Equal -Expected ([Ansible.Service.ServiceStartType]::AutoStart) + $actual.START_TYPE | Assert-Equal -Expected "2 AUTO_START" # Auto Start -> Auto Start Delayed $service.StartType = [Ansible.Service.ServiceStartType]::AutoStartDelayed $actual = Invoke-Sc -Action qc -Name $serviceName - $service.StartType | Assert-Equals -Expected ([Ansible.Service.ServiceStartType]::AutoStartDelayed) - $actual.START_TYPE | Assert-Equals -Expected "2 AUTO_START (DELAYED)" + $service.StartType | Assert-Equal -Expected ([Ansible.Service.ServiceStartType]::AutoStartDelayed) + $actual.START_TYPE | Assert-Equal -Expected "2 AUTO_START (DELAYED)" # Auto Start Delayed -> Manual $service.StartType = [Ansible.Service.ServiceStartType]::DemandStart $actual = Invoke-Sc -Action qc -Name $serviceName - $service.StartType | Assert-Equals -Expected ([Ansible.Service.ServiceStartType]::DemandStart) - $actual.START_TYPE | Assert-Equals -Expected "3 DEMAND_START" + $service.StartType | Assert-Equal -Expected ([Ansible.Service.ServiceStartType]::DemandStart) + $actual.START_TYPE | Assert-Equal -Expected "3 DEMAND_START" } "Modify ErrorControl" = { @@ -372,12 +386,12 @@ $tests = [Ordered]@{ $service.ErrorControl = [Ansible.Service.ErrorControl]::Severe $actual = Invoke-Sc -Action qc -Name $serviceName - $service.ErrorControl | Assert-Equals -Expected ([Ansible.Service.ErrorControl]::Severe) - $actual.ERROR_CONTROL | Assert-Equals -Expected "2 SEVERE" + $service.ErrorControl | Assert-Equal -Expected ([Ansible.Service.ErrorControl]::Severe) + $actual.ERROR_CONTROL | Assert-Equal -Expected "2 SEVERE" - $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{error="ignore"} + $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{error = "ignore" } $service.Refresh() - $service.ErrorControl | Assert-Equals -Expected ([Ansible.Service.ErrorControl]::Ignore) + $service.ErrorControl | Assert-Equal -Expected ([Ansible.Service.ErrorControl]::Ignore) } "Modify Path" = { @@ -385,12 +399,12 @@ $tests = [Ordered]@{ $service.Path = "Fake path" $actual = Invoke-Sc -Action qc -Name $serviceName - $service.Path | Assert-Equals -Expected "Fake path" - $actual.BINARY_PATH_NAME | Assert-Equals -Expected "Fake path" + $service.Path | Assert-Equal -Expected "Fake path" + $actual.BINARY_PATH_NAME | Assert-Equal -Expected "Fake path" - $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{binpath="other fake path"} + $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{binpath = "other fake path" } $service.Refresh() - $service.Path | Assert-Equals -Expected "other fake path" + $service.Path | Assert-Equal -Expected "other fake path" } "Modify LoadOrderGroup" = { @@ -398,12 +412,12 @@ $tests = [Ordered]@{ $service.LoadOrderGroup = "my group" $actual = Invoke-Sc -Action qc -Name $serviceName - $service.LoadOrderGroup | Assert-Equals -Expected "my group" - $actual.LOAD_ORDER_GROUP | Assert-Equals -Expected "my group" + $service.LoadOrderGroup | Assert-Equal -Expected "my group" + $actual.LOAD_ORDER_GROUP | Assert-Equal -Expected "my group" - $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{group=""} + $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{group = "" } $service.Refresh() - $service.LoadOrderGroup | Assert-Equals -Expected "" + $service.LoadOrderGroup | Assert-Equal -Expected "" } "Modify DependentOn" = { @@ -411,17 +425,17 @@ $tests = [Ordered]@{ $service.DependentOn = @("HTTP", "WinRM") $actual = Invoke-Sc -Action qc -Name $serviceName - @(,$service.DependentOn) | Assert-Equals -Expected @("HTTP", "WinRM") - @(,$actual.DEPENDENCIES) | Assert-Equals -Expected @("HTTP", "WinRM") + @(, $service.DependentOn) | Assert-Equal -Expected @("HTTP", "WinRM") + @(, $actual.DEPENDENCIES) | Assert-Equal -Expected @("HTTP", "WinRM") - $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{depend=""} + $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{depend = "" } $service.Refresh() - $service.DependentOn.Count | Assert-Equals -Expected 0 + $service.DependentOn.Count | Assert-Equal -Expected 0 } "Modify Account - service account" = { $systemSid = [System.Security.Principal.SecurityIdentifier]'S-1-5-18' - $systemName =$systemSid.Translate([System.Security.Principal.NTAccount]) + $systemName = $systemSid.Translate([System.Security.Principal.NTAccount]) $localSid = [System.Security.Principal.SecurityIdentifier]'S-1-5-19' $localName = $localSid.Translate([System.Security.Principal.NTAccount]) $networkSid = [System.Security.Principal.SecurityIdentifier]'S-1-5-20' @@ -431,17 +445,17 @@ $tests = [Ordered]@{ $service.Account = $networkSid $actual = Invoke-Sc -Action qc -Name $serviceName - $service.Account | Assert-Equals -Expected $networkName - $actual.SERVICE_START_NAME | Assert-Equals -Expected $networkName.Value + $service.Account | Assert-Equal -Expected $networkName + $actual.SERVICE_START_NAME | Assert-Equal -Expected $networkName.Value - $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{obj=$localName.Value} + $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{obj = $localName.Value } $service.Refresh() - $service.Account | Assert-Equals -Expected $localName + $service.Account | Assert-Equal -Expected $localName $service.Account = $systemSid $actual = Invoke-Sc -Action qc -Name $serviceName - $service.Account | Assert-Equals -Expected $systemName - $actual.SERVICE_START_NAME | Assert-Equals -Expected "LocalSystem" + $service.Account | Assert-Equal -Expected $systemName + $actual.SERVICE_START_NAME | Assert-Equal -Expected "LocalSystem" } "Modify Account - user" = { @@ -459,19 +473,20 @@ $tests = [Ordered]@{ $actualSid = ([System.Security.Principal.NTAccount]"$env:COMPUTERNAME\$username").Translate( [System.Security.Principal.SecurityIdentifier] ) - } else { + } + else { $actualSid = $service.Account.Translate([System.Security.Principal.SecurityIdentifier]) } - $actualSid.Value | Assert-Equals -Expected $currentSid.Value - $actual.SERVICE_START_NAME | Assert-Equals -Expected $service.Account.Value + $actualSid.Value | Assert-Equal -Expected $currentSid.Value + $actual.SERVICE_START_NAME | Assert-Equal -Expected $service.Account.Value # Go back to SYSTEM from account $systemSid = [System.Security.Principal.SecurityIdentifier]'S-1-5-18' $service.Account = $systemSid $actual = Invoke-Sc -Action qc -Name $serviceName - $service.Account | Assert-Equals -Expected $systemSid.Translate([System.Security.Principal.NTAccount]) - $actual.SERVICE_START_NAME | Assert-Equals -Expected "LocalSystem" + $service.Account | Assert-Equal -Expected $systemSid.Translate([System.Security.Principal.NTAccount]) + $actual.SERVICE_START_NAME | Assert-Equal -Expected "LocalSystem" } "Modify Account - virtual account" = { @@ -481,8 +496,8 @@ $tests = [Ordered]@{ $service.Account = $account $actual = Invoke-Sc -Action qc -Name $serviceName - $service.Account | Assert-Equals -Expected $account - $actual.SERVICE_START_NAME | Assert-Equals -Expected $account.Value + $service.Account | Assert-Equal -Expected $account + $actual.SERVICE_START_NAME | Assert-Equal -Expected $account.Value } "Modify Account - gMSA" = { @@ -497,8 +512,8 @@ $tests = [Ordered]@{ $service.Account = $gmsaName $actual = Invoke-Sc -Action qc -Name $serviceName - $service.Account | Assert-Equals -Expected $gmsaName - $actual.SERVICE_START_NAME | Assert-Equals -Expected $gmsaName + $service.Account | Assert-Equal -Expected $gmsaName + $actual.SERVICE_START_NAME | Assert-Equal -Expected $gmsaName # Go from gMSA to account and back to verify the Password doesn't matter. $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().User @@ -510,8 +525,8 @@ $tests = [Ordered]@{ $service.Account = $gmsaSid $actual = Invoke-Sc -Action qc -Name $serviceName - $service.Account | Assert-Equals -Expected $gmsaNetlogon - $actual.SERVICE_START_NAME | Assert-Equals -Expected $gmsaNetlogon.Value + $service.Account | Assert-Equal -Expected $gmsaNetlogon + $actual.SERVICE_START_NAME | Assert-Equal -Expected $gmsaNetlogon.Value } "Modify DisplayName" = { @@ -519,12 +534,12 @@ $tests = [Ordered]@{ $service.DisplayName = "Custom Service Name" $actual = Invoke-Sc -Action qc -Name $serviceName - $service.DisplayName | Assert-Equals -Expected "Custom Service Name" - $actual.DISPLAY_NAME | Assert-Equals -Expected "Custom Service Name" + $service.DisplayName | Assert-Equal -Expected "Custom Service Name" + $actual.DISPLAY_NAME | Assert-Equal -Expected "Custom Service Name" - $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{displayname="New Service Name"} + $null = Invoke-Sc -Action config -Name $serviceName -Arguments @{displayname = "New Service Name" } $service.Refresh() - $service.DisplayName | Assert-Equals -Expected "New Service Name" + $service.DisplayName | Assert-Equal -Expected "New Service Name" } "Modify Description" = { @@ -532,17 +547,17 @@ $tests = [Ordered]@{ $service.Description = "My custom service description" $actual = Invoke-Sc -Action qdescription -Name $serviceName - $service.Description | Assert-Equals -Expected "My custom service description" - $actual.DESCRIPTION | Assert-Equals -Expected "My custom service description" + $service.Description | Assert-Equal -Expected "My custom service description" + $actual.DESCRIPTION | Assert-Equal -Expected "My custom service description" - $null = Invoke-Sc -Action description -Name $serviceName -Arguments @(,"new description") - $service.Description | Assert-Equals -Expected "new description" + $null = Invoke-Sc -Action description -Name $serviceName -Arguments @(, "new description") + $service.Description | Assert-Equal -Expected "new description" $service.Description = $null $actual = Invoke-Sc -Action qdescription -Name $serviceName - $service.Description | Assert-Equals -Expected $null - $actual.DESCRIPTION | Assert-Equals -Expected "" + $service.Description | Assert-Equal -Expected $null + $actual.DESCRIPTION | Assert-Equal -Expected "" } "Modify FailureActions" = { @@ -551,93 +566,93 @@ $tests = [Ordered]@{ RebootMsg = 'Reboot msg' Command = 'Command line' Actions = @( - [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::RunCommand; Delay = 1000}, - [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::RunCommand; Delay = 2000}, - [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::Restart; Delay = 1000}, - [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::Reboot; Delay = 1000} + [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::RunCommand; Delay = 1000 }, + [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::RunCommand; Delay = 2000 }, + [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::Restart; Delay = 1000 }, + [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::Reboot; Delay = 1000 } ) } $service = New-Object -TypeName Ansible.Service.Service -ArgumentList $serviceName $service.FailureActions = $newAction $actual = Invoke-Sc -Action qfailure -Name $serviceName - $actual.'RESET_PERIOD (in seconds)' | Assert-Equals -Expected 86400 - $actual.REBOOT_MESSAGE | Assert-Equals -Expected 'Reboot msg' - $actual.COMMAND_LINE | Assert-Equals -Expected 'Command line' - $actual.FAILURE_ACTIONS.Count | Assert-Equals -Expected 4 - $actual.FAILURE_ACTIONS[0] | Assert-Equals -Expected "RUN PROCESS -- Delay = 1000 milliseconds." - $actual.FAILURE_ACTIONS[1] | Assert-Equals -Expected "RUN PROCESS -- Delay = 2000 milliseconds." - $actual.FAILURE_ACTIONS[2] | Assert-Equals -Expected "RESTART -- Delay = 1000 milliseconds." - $actual.FAILURE_ACTIONS[3] | Assert-Equals -Expected "REBOOT -- Delay = 1000 milliseconds." - $service.FailureActions.Actions.Count | Assert-Equals -Expected 4 + $actual.'RESET_PERIOD (in seconds)' | Assert-Equal -Expected 86400 + $actual.REBOOT_MESSAGE | Assert-Equal -Expected 'Reboot msg' + $actual.COMMAND_LINE | Assert-Equal -Expected 'Command line' + $actual.FAILURE_ACTIONS.Count | Assert-Equal -Expected 4 + $actual.FAILURE_ACTIONS[0] | Assert-Equal -Expected "RUN PROCESS -- Delay = 1000 milliseconds." + $actual.FAILURE_ACTIONS[1] | Assert-Equal -Expected "RUN PROCESS -- Delay = 2000 milliseconds." + $actual.FAILURE_ACTIONS[2] | Assert-Equal -Expected "RESTART -- Delay = 1000 milliseconds." + $actual.FAILURE_ACTIONS[3] | Assert-Equal -Expected "REBOOT -- Delay = 1000 milliseconds." + $service.FailureActions.Actions.Count | Assert-Equal -Expected 4 # Test that we can change individual settings and it doesn't change all - $service.FailureActions = [Ansible.Service.FailureActions]@{ResetPeriod = 172800} + $service.FailureActions = [Ansible.Service.FailureActions]@{ResetPeriod = 172800 } $actual = Invoke-Sc -Action qfailure -Name $serviceName - $actual.'RESET_PERIOD (in seconds)' | Assert-Equals -Expected 172800 - $actual.REBOOT_MESSAGE | Assert-Equals -Expected 'Reboot msg' - $actual.COMMAND_LINE | Assert-Equals -Expected 'Command line' - $actual.FAILURE_ACTIONS.Count | Assert-Equals -Expected 4 - $service.FailureActions.Actions.Count | Assert-Equals -Expected 4 + $actual.'RESET_PERIOD (in seconds)' | Assert-Equal -Expected 172800 + $actual.REBOOT_MESSAGE | Assert-Equal -Expected 'Reboot msg' + $actual.COMMAND_LINE | Assert-Equal -Expected 'Command line' + $actual.FAILURE_ACTIONS.Count | Assert-Equal -Expected 4 + $service.FailureActions.Actions.Count | Assert-Equal -Expected 4 - $service.FailureActions = [Ansible.Service.FailureActions]@{RebootMsg = "New reboot msg"} + $service.FailureActions = [Ansible.Service.FailureActions]@{RebootMsg = "New reboot msg" } $actual = Invoke-Sc -Action qfailure -Name $serviceName - $actual.'RESET_PERIOD (in seconds)' | Assert-Equals -Expected 172800 - $actual.REBOOT_MESSAGE | Assert-Equals -Expected 'New reboot msg' - $actual.COMMAND_LINE | Assert-Equals -Expected 'Command line' - $actual.FAILURE_ACTIONS.Count | Assert-Equals -Expected 4 - $service.FailureActions.Actions.Count | Assert-Equals -Expected 4 + $actual.'RESET_PERIOD (in seconds)' | Assert-Equal -Expected 172800 + $actual.REBOOT_MESSAGE | Assert-Equal -Expected 'New reboot msg' + $actual.COMMAND_LINE | Assert-Equal -Expected 'Command line' + $actual.FAILURE_ACTIONS.Count | Assert-Equal -Expected 4 + $service.FailureActions.Actions.Count | Assert-Equal -Expected 4 - $service.FailureActions = [Ansible.Service.FailureActions]@{Command = "New command line"} + $service.FailureActions = [Ansible.Service.FailureActions]@{Command = "New command line" } $actual = Invoke-Sc -Action qfailure -Name $serviceName - $actual.'RESET_PERIOD (in seconds)' | Assert-Equals -Expected 172800 - $actual.REBOOT_MESSAGE | Assert-Equals -Expected 'New reboot msg' - $actual.COMMAND_LINE | Assert-Equals -Expected 'New command line' - $actual.FAILURE_ACTIONS.Count | Assert-Equals -Expected 4 - $service.FailureActions.Actions.Count | Assert-Equals -Expected 4 + $actual.'RESET_PERIOD (in seconds)' | Assert-Equal -Expected 172800 + $actual.REBOOT_MESSAGE | Assert-Equal -Expected 'New reboot msg' + $actual.COMMAND_LINE | Assert-Equal -Expected 'New command line' + $actual.FAILURE_ACTIONS.Count | Assert-Equal -Expected 4 + $service.FailureActions.Actions.Count | Assert-Equal -Expected 4 # Test setting both ResetPeriod and Actions together $service.FailureActions = [Ansible.Service.FailureActions]@{ ResetPeriod = 86400 Actions = @( - [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::RunCommand; Delay = 5000}, - [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::None; Delay = 0} + [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::RunCommand; Delay = 5000 }, + [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::None; Delay = 0 } ) } $actual = Invoke-Sc -Action qfailure -Name $serviceName - $actual.'RESET_PERIOD (in seconds)' | Assert-Equals -Expected 86400 - $actual.REBOOT_MESSAGE | Assert-Equals -Expected 'New reboot msg' - $actual.COMMAND_LINE | Assert-Equals -Expected 'New command line' + $actual.'RESET_PERIOD (in seconds)' | Assert-Equal -Expected 86400 + $actual.REBOOT_MESSAGE | Assert-Equal -Expected 'New reboot msg' + $actual.COMMAND_LINE | Assert-Equal -Expected 'New command line' # sc.exe does not show the None action it just ends the list, so we verify from get_FailureActions - $actual.FAILURE_ACTIONS | Assert-Equals -Expected "RUN PROCESS -- Delay = 5000 milliseconds." - $service.FailureActions.Actions.Count | Assert-Equals -Expected 2 - $service.FailureActions.Actions[1].Type | Assert-Equals -Expected ([Ansible.Service.FailureAction]::None) + $actual.FAILURE_ACTIONS | Assert-Equal -Expected "RUN PROCESS -- Delay = 5000 milliseconds." + $service.FailureActions.Actions.Count | Assert-Equal -Expected 2 + $service.FailureActions.Actions[1].Type | Assert-Equal -Expected ([Ansible.Service.FailureAction]::None) # Test setting just Actions without ResetPeriod $service.FailureActions = [Ansible.Service.FailureActions]@{ - Actions = [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::RunCommand; Delay = 10000} + Actions = [Ansible.Service.Action]@{Type = [Ansible.Service.FailureAction]::RunCommand; Delay = 10000 } } $actual = Invoke-Sc -Action qfailure -Name $serviceName - $actual.'RESET_PERIOD (in seconds)' | Assert-Equals -Expected 86400 - $actual.REBOOT_MESSAGE | Assert-Equals -Expected 'New reboot msg' - $actual.COMMAND_LINE | Assert-Equals -Expected 'New command line' - $actual.FAILURE_ACTIONS | Assert-Equals -Expected "RUN PROCESS -- Delay = 10000 milliseconds." - $service.FailureActions.Actions.Count | Assert-Equals -Expected 1 + $actual.'RESET_PERIOD (in seconds)' | Assert-Equal -Expected 86400 + $actual.REBOOT_MESSAGE | Assert-Equal -Expected 'New reboot msg' + $actual.COMMAND_LINE | Assert-Equal -Expected 'New command line' + $actual.FAILURE_ACTIONS | Assert-Equal -Expected "RUN PROCESS -- Delay = 10000 milliseconds." + $service.FailureActions.Actions.Count | Assert-Equal -Expected 1 # Test removing all actions $service.FailureActions = [Ansible.Service.FailureActions]@{ Actions = @() } $actual = Invoke-Sc -Action qfailure -Name $serviceName - $actual.'RESET_PERIOD (in seconds)' | Assert-Equals -Expected 0 # ChangeServiceConfig2W resets this back to 0. - $actual.REBOOT_MESSAGE | Assert-Equals -Expected 'New reboot msg' - $actual.COMMAND_LINE | Assert-Equals -Expected 'New command line' - $actual.PSObject.Properties.Name.Contains('FAILURE_ACTIONS') | Assert-Equals -Expected $false - $service.FailureActions.Actions.Count | Assert-Equals -Expected 0 + $actual.'RESET_PERIOD (in seconds)' | Assert-Equal -Expected 0 # ChangeServiceConfig2W resets this back to 0. + $actual.REBOOT_MESSAGE | Assert-Equal -Expected 'New reboot msg' + $actual.COMMAND_LINE | Assert-Equal -Expected 'New command line' + $actual.PSObject.Properties.Name.Contains('FAILURE_ACTIONS') | Assert-Equal -Expected $false + $service.FailureActions.Actions.Count | Assert-Equal -Expected 0 # Test that we are reading the right values $null = Invoke-Sc -Action failure -Name $serviceName -Arguments @{ @@ -648,14 +663,14 @@ $tests = [Ordered]@{ } $actual = $service.FailureActions - $actual.ResetPeriod | Assert-Equals -Expected 172800 - $actual.RebootMsg | Assert-Equals -Expected "sc reboot msg" - $actual.Command | Assert-Equals -Expected "sc command line" - $actual.Actions.Count | Assert-Equals -Expected 2 - $actual.Actions[0].Type | Assert-Equals -Expected ([Ansible.Service.FailureAction]::RunCommand) - $actual.Actions[0].Delay | Assert-Equals -Expected 5000 - $actual.Actions[1].Type | Assert-Equals -Expected ([Ansible.Service.FailureAction]::Reboot) - $actual.Actions[1].Delay | Assert-Equals -Expected 800 + $actual.ResetPeriod | Assert-Equal -Expected 172800 + $actual.RebootMsg | Assert-Equal -Expected "sc reboot msg" + $actual.Command | Assert-Equal -Expected "sc command line" + $actual.Actions.Count | Assert-Equal -Expected 2 + $actual.Actions[0].Type | Assert-Equal -Expected ([Ansible.Service.FailureAction]::RunCommand) + $actual.Actions[0].Delay | Assert-Equal -Expected 5000 + $actual.Actions[1].Type | Assert-Equal -Expected ([Ansible.Service.FailureAction]::Reboot) + $actual.Actions[1].Delay | Assert-Equal -Expected 800 } "Modify FailureActionsOnNonCrashFailures" = { @@ -663,11 +678,11 @@ $tests = [Ordered]@{ $service.FailureActionsOnNonCrashFailures = $true $actual = Invoke-Sc -Action qfailureflag -Name $serviceName - $service.FailureActionsOnNonCrashFailures | Assert-Equals -Expected $true - $actual.FAILURE_ACTIONS_ON_NONCRASH_FAILURES | Assert-Equals -Expected "TRUE" + $service.FailureActionsOnNonCrashFailures | Assert-Equal -Expected $true + $actual.FAILURE_ACTIONS_ON_NONCRASH_FAILURES | Assert-Equal -Expected "TRUE" - $null = Invoke-Sc -Action failureflag -Name $serviceName -Arguments @(,0) - $service.FailureActionsOnNonCrashFailures | Assert-Equals -Expected $false + $null = Invoke-Sc -Action failureflag -Name $serviceName -Arguments @(, 0) + $service.FailureActionsOnNonCrashFailures | Assert-Equal -Expected $false } "Modify ServiceSidInfo" = { @@ -675,17 +690,17 @@ $tests = [Ordered]@{ $service.ServiceSidInfo = [Ansible.Service.ServiceSidInfo]::None $actual = Invoke-Sc -Action qsidtype -Name $serviceName - $service.ServiceSidInfo | Assert-Equals -Expected ([Ansible.Service.ServiceSidInfo]::None) - $actual.SERVICE_SID_TYPE | Assert-Equals -Expected 'NONE' + $service.ServiceSidInfo | Assert-Equal -Expected ([Ansible.Service.ServiceSidInfo]::None) + $actual.SERVICE_SID_TYPE | Assert-Equal -Expected 'NONE' - $null = Invoke-Sc -Action sidtype -Name $serviceName -Arguments @(,'unrestricted') - $service.ServiceSidInfo | Assert-Equals -Expected ([Ansible.Service.ServiceSidInfo]::Unrestricted) + $null = Invoke-Sc -Action sidtype -Name $serviceName -Arguments @(, 'unrestricted') + $service.ServiceSidInfo | Assert-Equal -Expected ([Ansible.Service.ServiceSidInfo]::Unrestricted) $service.ServiceSidInfo = [Ansible.Service.ServiceSidInfo]::Restricted $actual = Invoke-Sc -Action qsidtype -Name $serviceName - $service.ServiceSidInfo | Assert-Equals -Expected ([Ansible.Service.ServiceSidInfo]::Restricted) - $actual.SERVICE_SID_TYPE | Assert-Equals -Expected 'RESTRICTED' + $service.ServiceSidInfo | Assert-Equal -Expected ([Ansible.Service.ServiceSidInfo]::Restricted) + $actual.SERVICE_SID_TYPE | Assert-Equal -Expected 'RESTRICTED' } "Modify RequiredPrivileges" = { @@ -693,25 +708,25 @@ $tests = [Ordered]@{ $service.RequiredPrivileges = @("SeBackupPrivilege", "SeTcbPrivilege") $actual = Invoke-Sc -Action qprivs -Name $serviceName - ,$service.RequiredPrivileges | Assert-Equals -Expected @("SeBackupPrivilege", "SeTcbPrivilege") - ,$actual.PRIVILEGES | Assert-Equals -Expected @("SeBackupPrivilege", "SeTcbPrivilege") + , $service.RequiredPrivileges | Assert-Equal -Expected @("SeBackupPrivilege", "SeTcbPrivilege") + , $actual.PRIVILEGES | Assert-Equal -Expected @("SeBackupPrivilege", "SeTcbPrivilege") # Ensure setting to $null is the same as an empty array $service.RequiredPrivileges = $null $actual = Invoke-Sc -Action qprivs -Name $serviceName - ,$service.RequiredPrivileges | Assert-Equals -Expected @() - ,$actual.PRIVILEGES | Assert-Equals -Expected @() + , $service.RequiredPrivileges | Assert-Equal -Expected @() + , $actual.PRIVILEGES | Assert-Equal -Expected @() $service.RequiredPrivileges = @("SeBackupPrivilege", "SeTcbPrivilege") $service.RequiredPrivileges = @() $actual = Invoke-Sc -Action qprivs -Name $serviceName - ,$service.RequiredPrivileges | Assert-Equals -Expected @() - ,$actual.PRIVILEGES | Assert-Equals -Expected @() + , $service.RequiredPrivileges | Assert-Equal -Expected @() + , $actual.PRIVILEGES | Assert-Equal -Expected @() - $null = Invoke-Sc -Action privs -Name $serviceName -Arguments @(,"SeCreateTokenPrivilege/SeRestorePrivilege") - ,$service.RequiredPrivileges | Assert-Equals -Expected @("SeCreateTokenPrivilege", "SeRestorePrivilege") + $null = Invoke-Sc -Action privs -Name $serviceName -Arguments @(, "SeCreateTokenPrivilege/SeRestorePrivilege") + , $service.RequiredPrivileges | Assert-Equal -Expected @("SeCreateTokenPrivilege", "SeRestorePrivilege") } "Modify PreShutdownTimeout" = { @@ -722,7 +737,7 @@ $tests = [Ordered]@{ $actual = ( Get-ItemProperty -LiteralPath "HKLM:\SYSTEM\CurrentControlSet\Services\$serviceName" -Name PreshutdownTimeout ).PreshutdownTimeout - $actual | Assert-Equals -Expected 60000 + $actual | Assert-Equal -Expected 60000 } "Modify Triggers" = { @@ -794,49 +809,49 @@ $tests = [Ordered]@{ $actual = Invoke-Sc -Action qtriggerinfo -Name $serviceName - $actual.Triggers.Count | Assert-Equals -Expected 6 - $actual.Triggers[0].Type | Assert-Equals -Expected 'DOMAIN JOINED STATUS' - $actual.Triggers[0].Action | Assert-Equals -Expected 'STOP SERVICE' - $actual.Triggers[0].SubType | Assert-Equals -Expected "$([Ansible.Service.Trigger]::DOMAIN_JOIN_GUID) [DOMAIN JOINED]" - $actual.Triggers[0].Data.Count | Assert-Equals -Expected 0 - - $actual.Triggers[1].Type | Assert-Equals -Expected 'NETWORK EVENT' - $actual.Triggers[1].Action | Assert-Equals -Expected 'START SERVICE' - $actual.Triggers[1].SubType | Assert-Equals -Expected "$([Ansible.Service.Trigger]::NAMED_PIPE_EVENT_GUID) [NAMED PIPE EVENT]" - $actual.Triggers[1].Data.Count | Assert-Equals -Expected 1 - $actual.Triggers[1].Data[0] | Assert-Equals -Expected 'my named pipe' - - $actual.Triggers[2].Type | Assert-Equals -Expected 'NETWORK EVENT' - $actual.Triggers[2].Action | Assert-Equals -Expected 'START SERVICE' - $actual.Triggers[2].SubType | Assert-Equals -Expected "$([Ansible.Service.Trigger]::NAMED_PIPE_EVENT_GUID) [NAMED PIPE EVENT]" - $actual.Triggers[2].Data.Count | Assert-Equals -Expected 1 - $actual.Triggers[2].Data[0] | Assert-Equals -Expected 'my named pipe 2' - - $actual.Triggers[3].Type | Assert-Equals -Expected 'CUSTOM' - $actual.Triggers[3].Action | Assert-Equals -Expected 'START SERVICE' - $actual.Triggers[3].SubType | Assert-Equals -Expected '9bf04e57-05dc-4914-9ed9-84bf992db88c [ETW PROVIDER UUID]' - $actual.Triggers[3].Data.Count | Assert-Equals -Expected 2 - $actual.Triggers[3].Data[0] | Assert-Equals -Expected '01 02 03 04' - $actual.Triggers[3].Data[1] | Assert-Equals -Expected '05 06 07 08 09' - - $actual.Triggers[4].Type | Assert-Equals -Expected 'CUSTOM' - $actual.Triggers[4].Action | Assert-Equals -Expected 'START SERVICE' - $actual.Triggers[4].SubType | Assert-Equals -Expected '9fbcfc7e-7581-4d46-913b-53bb15c80c51 [ETW PROVIDER UUID]' - $actual.Triggers[4].Data.Count | Assert-Equals -Expected 2 - $actual.Triggers[4].Data[0] | Assert-Equals -Expected "entry 1" - $actual.Triggers[4].Data[1] | Assert-Equals -Expected "entry 2" - - $actual.Triggers[5].Type | Assert-Equals -Expected 'FIREWALL PORT EVENT' - $actual.Triggers[5].Action | Assert-Equals -Expected 'STOP SERVICE' - $actual.Triggers[5].SubType | Assert-Equals -Expected "$([Ansible.Service.Trigger]::FIREWALL_PORT_CLOSE_GUID) [PORT CLOSE]" - $actual.Triggers[5].Data.Count | Assert-Equals -Expected 1 - $actual.Triggers[5].Data[0] | Assert-Equals -Expected '1234;tcp;imagepath;servicename' + $actual.Triggers.Count | Assert-Equal -Expected 6 + $actual.Triggers[0].Type | Assert-Equal -Expected 'DOMAIN JOINED STATUS' + $actual.Triggers[0].Action | Assert-Equal -Expected 'STOP SERVICE' + $actual.Triggers[0].SubType | Assert-Equal -Expected "$([Ansible.Service.Trigger]::DOMAIN_JOIN_GUID) [DOMAIN JOINED]" + $actual.Triggers[0].Data.Count | Assert-Equal -Expected 0 + + $actual.Triggers[1].Type | Assert-Equal -Expected 'NETWORK EVENT' + $actual.Triggers[1].Action | Assert-Equal -Expected 'START SERVICE' + $actual.Triggers[1].SubType | Assert-Equal -Expected "$([Ansible.Service.Trigger]::NAMED_PIPE_EVENT_GUID) [NAMED PIPE EVENT]" + $actual.Triggers[1].Data.Count | Assert-Equal -Expected 1 + $actual.Triggers[1].Data[0] | Assert-Equal -Expected 'my named pipe' + + $actual.Triggers[2].Type | Assert-Equal -Expected 'NETWORK EVENT' + $actual.Triggers[2].Action | Assert-Equal -Expected 'START SERVICE' + $actual.Triggers[2].SubType | Assert-Equal -Expected "$([Ansible.Service.Trigger]::NAMED_PIPE_EVENT_GUID) [NAMED PIPE EVENT]" + $actual.Triggers[2].Data.Count | Assert-Equal -Expected 1 + $actual.Triggers[2].Data[0] | Assert-Equal -Expected 'my named pipe 2' + + $actual.Triggers[3].Type | Assert-Equal -Expected 'CUSTOM' + $actual.Triggers[3].Action | Assert-Equal -Expected 'START SERVICE' + $actual.Triggers[3].SubType | Assert-Equal -Expected '9bf04e57-05dc-4914-9ed9-84bf992db88c [ETW PROVIDER UUID]' + $actual.Triggers[3].Data.Count | Assert-Equal -Expected 2 + $actual.Triggers[3].Data[0] | Assert-Equal -Expected '01 02 03 04' + $actual.Triggers[3].Data[1] | Assert-Equal -Expected '05 06 07 08 09' + + $actual.Triggers[4].Type | Assert-Equal -Expected 'CUSTOM' + $actual.Triggers[4].Action | Assert-Equal -Expected 'START SERVICE' + $actual.Triggers[4].SubType | Assert-Equal -Expected '9fbcfc7e-7581-4d46-913b-53bb15c80c51 [ETW PROVIDER UUID]' + $actual.Triggers[4].Data.Count | Assert-Equal -Expected 2 + $actual.Triggers[4].Data[0] | Assert-Equal -Expected "entry 1" + $actual.Triggers[4].Data[1] | Assert-Equal -Expected "entry 2" + + $actual.Triggers[5].Type | Assert-Equal -Expected 'FIREWALL PORT EVENT' + $actual.Triggers[5].Action | Assert-Equal -Expected 'STOP SERVICE' + $actual.Triggers[5].SubType | Assert-Equal -Expected "$([Ansible.Service.Trigger]::FIREWALL_PORT_CLOSE_GUID) [PORT CLOSE]" + $actual.Triggers[5].Data.Count | Assert-Equal -Expected 1 + $actual.Triggers[5].Data[0] | Assert-Equal -Expected '1234;tcp;imagepath;servicename' # Remove trigger with $null $service.Triggers = $null $actual = Invoke-Sc -Action qtriggerinfo -Name $serviceName - $actual.Triggers.Count | Assert-Equals -Expected 0 + $actual.Triggers.Count | Assert-Equal -Expected 0 # Add a single trigger $service.Triggers = [Ansible.Service.Trigger]@{ @@ -846,17 +861,17 @@ $tests = [Ordered]@{ } $actual = Invoke-Sc -Action qtriggerinfo -Name $serviceName - $actual.Triggers.Count | Assert-Equals -Expected 1 - $actual.Triggers[0].Type | Assert-Equals -Expected 'GROUP POLICY' - $actual.Triggers[0].Action | Assert-Equals -Expected 'START SERVICE' - $actual.Triggers[0].SubType | Assert-Equals -Expected "$([Ansible.Service.Trigger]::MACHINE_POLICY_PRESENT_GUID) [MACHINE POLICY PRESENT]" - $actual.Triggers[0].Data.Count | Assert-Equals -Expected 0 + $actual.Triggers.Count | Assert-Equal -Expected 1 + $actual.Triggers[0].Type | Assert-Equal -Expected 'GROUP POLICY' + $actual.Triggers[0].Action | Assert-Equal -Expected 'START SERVICE' + $actual.Triggers[0].SubType | Assert-Equal -Expected "$([Ansible.Service.Trigger]::MACHINE_POLICY_PRESENT_GUID) [MACHINE POLICY PRESENT]" + $actual.Triggers[0].Data.Count | Assert-Equal -Expected 0 # Remove trigger with empty list $service.Triggers = @() $actual = Invoke-Sc -Action qtriggerinfo -Name $serviceName - $actual.Triggers.Count | Assert-Equals -Expected 0 + $actual.Triggers.Count | Assert-Equal -Expected 0 # Add triggers through sc and check we get the values correctly $null = Invoke-Sc -Action triggerinfo -Name $serviceName -Arguments @( @@ -869,51 +884,51 @@ $tests = [Ordered]@{ ) $actual = $service.Triggers - $actual.Count | Assert-Equals -Expected 6 + $actual.Count | Assert-Equal -Expected 6 - $actual[0].Type | Assert-Equals -Expected ([Ansible.Service.TriggerType]::NetworkEndpoint) - $actual[0].Action | Assert-Equals -Expected ([Ansible.Service.TriggerAction]::ServiceStart) + $actual[0].Type | Assert-Equal -Expected ([Ansible.Service.TriggerType]::NetworkEndpoint) + $actual[0].Action | Assert-Equal -Expected ([Ansible.Service.TriggerAction]::ServiceStart) $actual[0].SubType = [Guid][Ansible.Service.Trigger]::NAMED_PIPE_EVENT_GUID - $actual[0].DataItems.Count | Assert-Equals -Expected 1 - $actual[0].DataItems[0].Type | Assert-Equals -Expected ([Ansible.Service.TriggerDataType]::String) - $actual[0].DataItems[0].Data | Assert-Equals -Expected 'abc' + $actual[0].DataItems.Count | Assert-Equal -Expected 1 + $actual[0].DataItems[0].Type | Assert-Equal -Expected ([Ansible.Service.TriggerDataType]::String) + $actual[0].DataItems[0].Data | Assert-Equal -Expected 'abc' - $actual[1].Type | Assert-Equals -Expected ([Ansible.Service.TriggerType]::NetworkEndpoint) - $actual[1].Action | Assert-Equals -Expected ([Ansible.Service.TriggerAction]::ServiceStart) + $actual[1].Type | Assert-Equal -Expected ([Ansible.Service.TriggerType]::NetworkEndpoint) + $actual[1].Action | Assert-Equal -Expected ([Ansible.Service.TriggerAction]::ServiceStart) $actual[1].SubType = [Guid][Ansible.Service.Trigger]::NAMED_PIPE_EVENT_GUID - $actual[1].DataItems.Count | Assert-Equals -Expected 1 - $actual[1].DataItems[0].Type | Assert-Equals -Expected ([Ansible.Service.TriggerDataType]::String) - $actual[1].DataItems[0].Data | Assert-Equals -Expected 'def' + $actual[1].DataItems.Count | Assert-Equal -Expected 1 + $actual[1].DataItems[0].Type | Assert-Equal -Expected ([Ansible.Service.TriggerDataType]::String) + $actual[1].DataItems[0].Data | Assert-Equal -Expected 'def' - $actual[2].Type | Assert-Equals -Expected ([Ansible.Service.TriggerType]::Custom) - $actual[2].Action | Assert-Equals -Expected ([Ansible.Service.TriggerAction]::ServiceStart) + $actual[2].Type | Assert-Equal -Expected ([Ansible.Service.TriggerType]::Custom) + $actual[2].Action | Assert-Equal -Expected ([Ansible.Service.TriggerAction]::ServiceStart) $actual[2].SubType = [Guid]'d4497e12-ac36-4823-af61-92db0dbd4a76' - $actual[2].DataItems.Count | Assert-Equals -Expected 2 - $actual[2].DataItems[0].Type | Assert-Equals -Expected ([Ansible.Service.TriggerDataType]::Binary) - ,$actual[2].DataItems[0].Data | Assert-Equals -Expected ([byte[]]@(17, 34, 51, 68)) - $actual[2].DataItems[1].Type | Assert-Equals -Expected ([Ansible.Service.TriggerDataType]::Binary) - ,$actual[2].DataItems[1].Data | Assert-Equals -Expected ([byte[]]@(170, 187, 204, 221)) - - $actual[3].Type | Assert-Equals -Expected ([Ansible.Service.TriggerType]::Custom) - $actual[3].Action | Assert-Equals -Expected ([Ansible.Service.TriggerAction]::ServiceStart) + $actual[2].DataItems.Count | Assert-Equal -Expected 2 + $actual[2].DataItems[0].Type | Assert-Equal -Expected ([Ansible.Service.TriggerDataType]::Binary) + , $actual[2].DataItems[0].Data | Assert-Equal -Expected ([byte[]]@(17, 34, 51, 68)) + $actual[2].DataItems[1].Type | Assert-Equal -Expected ([Ansible.Service.TriggerDataType]::Binary) + , $actual[2].DataItems[1].Data | Assert-Equal -Expected ([byte[]]@(170, 187, 204, 221)) + + $actual[3].Type | Assert-Equal -Expected ([Ansible.Service.TriggerType]::Custom) + $actual[3].Action | Assert-Equal -Expected ([Ansible.Service.TriggerAction]::ServiceStart) $actual[3].SubType = [Guid]'435a1742-22c5-4234-9db3-e32dafde695c' - $actual[3].DataItems.Count | Assert-Equals -Expected 2 - $actual[3].DataItems[0].Type | Assert-Equals -Expected ([Ansible.Service.TriggerDataType]::String) - $actual[3].DataItems[0].Data | Assert-Equals -Expected '11223344' - $actual[3].DataItems[1].Type | Assert-Equals -Expected ([Ansible.Service.TriggerDataType]::String) - $actual[3].DataItems[1].Data | Assert-Equals -Expected 'aabbccdd' - - $actual[4].Type | Assert-Equals -Expected ([Ansible.Service.TriggerType]::FirewallPortEvent) - $actual[4].Action | Assert-Equals -Expected ([Ansible.Service.TriggerAction]::ServiceStop) + $actual[3].DataItems.Count | Assert-Equal -Expected 2 + $actual[3].DataItems[0].Type | Assert-Equal -Expected ([Ansible.Service.TriggerDataType]::String) + $actual[3].DataItems[0].Data | Assert-Equal -Expected '11223344' + $actual[3].DataItems[1].Type | Assert-Equal -Expected ([Ansible.Service.TriggerDataType]::String) + $actual[3].DataItems[1].Data | Assert-Equal -Expected 'aabbccdd' + + $actual[4].Type | Assert-Equal -Expected ([Ansible.Service.TriggerType]::FirewallPortEvent) + $actual[4].Action | Assert-Equal -Expected ([Ansible.Service.TriggerAction]::ServiceStop) $actual[4].SubType = [Guid][Ansible.Service.Trigger]::FIREWALL_PORT_CLOSE_GUID - $actual[4].DataItems.Count | Assert-Equals -Expected 1 - $actual[4].DataItems[0].Type | Assert-Equals -Expected ([Ansible.Service.TriggerDataType]::String) - ,$actual[4].DataItems[0].Data | Assert-Equals -Expected @('1234', 'tcp', 'imagepath', 'servicename') + $actual[4].DataItems.Count | Assert-Equal -Expected 1 + $actual[4].DataItems[0].Type | Assert-Equal -Expected ([Ansible.Service.TriggerDataType]::String) + , $actual[4].DataItems[0].Data | Assert-Equal -Expected @('1234', 'tcp', 'imagepath', 'servicename') - $actual[5].Type | Assert-Equals -Expected ([Ansible.Service.TriggerType]::IpAddressAvailability) - $actual[5].Action | Assert-Equals -Expected ([Ansible.Service.TriggerAction]::ServiceStop) + $actual[5].Type | Assert-Equal -Expected ([Ansible.Service.TriggerType]::IpAddressAvailability) + $actual[5].Action | Assert-Equal -Expected ([Ansible.Service.TriggerAction]::ServiceStop) $actual[5].SubType = [Guid][Ansible.Service.Trigger]::NETWORK_MANAGER_LAST_IP_ADDRESS_REMOVAL_GUID - $actual[5].DataItems.Count | Assert-Equals -Expected 0 + $actual[5].DataItems.Count | Assert-Equal -Expected 0 } # Cannot test PreferredNode as we can't guarantee CI is set up with NUMA support. @@ -928,7 +943,8 @@ foreach ($testImpl in $tests.GetEnumerator()) { try { $test = $testImpl.Key &$testImpl.Value - } finally { + } + finally { $null = Invoke-Sc -Action delete -Name $serviceName } } diff --git a/test/integration/targets/win_async_wrapper/library/async_test.ps1 b/test/integration/targets/win_async_wrapper/library/async_test.ps1 index fa41b3e824..3b4c1c85f3 100644 --- a/test/integration/targets/win_async_wrapper/library/async_test.ps1 +++ b/test/integration/targets/win_async_wrapper/library/async_test.ps1 @@ -7,9 +7,9 @@ $parsed_args = Parse-Args $args $sleep_delay_sec = Get-AnsibleParam -obj $parsed_args -name "sleep_delay_sec" -type "int" -default 0 -$fail_mode = Get-AnsibleParam -obj $parsed_args -name "fail_mode" -type "str" -default "success" -validateset "success","graceful","exception" +$fail_mode = Get-AnsibleParam -obj $parsed_args -name "fail_mode" -type "str" -default "success" -validateset "success", "graceful", "exception" -If($fail_mode -isnot [array]) { +If ($fail_mode -isnot [array]) { $fail_mode = @($fail_mode) } @@ -19,30 +19,29 @@ $result = @{ module_tempdir = $PSScriptRoot } -If($sleep_delay_sec -gt 0) { +If ($sleep_delay_sec -gt 0) { Sleep -Seconds $sleep_delay_sec $result["slept_sec"] = $sleep_delay_sec } -If($fail_mode -contains "leading_junk") { +If ($fail_mode -contains "leading_junk") { Write-Output "leading junk before module output" } -If($fail_mode -contains "graceful") { +If ($fail_mode -contains "graceful") { Fail-Json $result "failed gracefully" } Try { - If($fail_mode -contains "exception") { + If ($fail_mode -contains "exception") { Throw "failing via exception" } Exit-Json $result } -Finally -{ - If($fail_mode -contains "trailing_junk") { +Finally { + If ($fail_mode -contains "trailing_junk") { Write-Output "trailing junk after module output" } } diff --git a/test/integration/targets/win_exec_wrapper/library/test_common_functions.ps1 b/test/integration/targets/win_exec_wrapper/library/test_common_functions.ps1 index 9a5918f943..dde1ebc41c 100644 --- a/test/integration/targets/win_exec_wrapper/library/test_common_functions.ps1 +++ b/test/integration/targets/win_exec_wrapper/library/test_common_functions.ps1 @@ -4,10 +4,13 @@ $ErrorActionPreference = "Stop" -Function Assert-Equals($actual, $expected) { +Function Assert-Equal($actual, $expected) { if ($actual -cne $expected) { $call_stack = (Get-PSCallStack)[1] - $error_msg = "AssertionError:`r`nActual: `"$actual`" != Expected: `"$expected`"`r`nLine: $($call_stack.ScriptLineNumber), Method: $($call_stack.Position.Text)" + $error_msg = -join @( + "AssertionError:`r`nActual: `"$actual`" != Expected: `"$expected`"`r`nLine: " + "$($call_stack.ScriptLineNumber), Method: $($call_stack.Position.Text)" + ) Fail-Json -obj $result -message $error_msg } } @@ -17,23 +20,23 @@ $result = @{ } #ConvertFrom-AnsibleJso -$input_json = '{"string":"string","float":3.1415926,"dict":{"string":"string","int":1},"list":["entry 1","entry 2"],"null":null,"int":1}' +$input_json = '{"string":"string","float":3.1415926,"dict":{"string":"string","int":1},"list":["entry 1","entry 2"],"null":null,"int":1}' $actual = ConvertFrom-AnsibleJson -InputObject $input_json -Assert-Equals -actual $actual.GetType() -expected ([Hashtable]) -Assert-Equals -actual $actual.string.GetType() -expected ([String]) -Assert-Equals -actual $actual.string -expected "string" -Assert-Equals -actual $actual.int.GetType() -expected ([Int32]) -Assert-Equals -actual $actual.int -expected 1 -Assert-Equals -actual $actual.null -expected $null -Assert-Equals -actual $actual.float.GetType() -expected ([Decimal]) -Assert-Equals -actual $actual.float -expected 3.1415926 -Assert-Equals -actual $actual.list.GetType() -expected ([Object[]]) -Assert-Equals -actual $actual.list.Count -expected 2 -Assert-Equals -actual $actual.list[0] -expected "entry 1" -Assert-Equals -actual $actual.list[1] -expected "entry 2" -Assert-Equals -actual $actual.GetType() -expected ([Hashtable]) -Assert-Equals -actual $actual.dict.string -expected "string" -Assert-Equals -actual $actual.dict.int -expected 1 +Assert-Equal -actual $actual.GetType() -expected ([Hashtable]) +Assert-Equal -actual $actual.string.GetType() -expected ([String]) +Assert-Equal -actual $actual.string -expected "string" +Assert-Equal -actual $actual.int.GetType() -expected ([Int32]) +Assert-Equal -actual $actual.int -expected 1 +Assert-Equal -actual $actual.null -expected $null +Assert-Equal -actual $actual.float.GetType() -expected ([Decimal]) +Assert-Equal -actual $actual.float -expected 3.1415926 +Assert-Equal -actual $actual.list.GetType() -expected ([Object[]]) +Assert-Equal -actual $actual.list.Count -expected 2 +Assert-Equal -actual $actual.list[0] -expected "entry 1" +Assert-Equal -actual $actual.list[1] -expected "entry 2" +Assert-Equal -actual $actual.GetType() -expected ([Hashtable]) +Assert-Equal -actual $actual.dict.string -expected "string" +Assert-Equal -actual $actual.dict.int -expected 1 $result.msg = "good" Exit-Json -obj $result diff --git a/test/integration/targets/win_exec_wrapper/library/test_fail.ps1 b/test/integration/targets/win_exec_wrapper/library/test_fail.ps1 index 06c63f72c4..72b89c69f4 100644 --- a/test/integration/targets/win_exec_wrapper/library/test_fail.ps1 +++ b/test/integration/targets/win_exec_wrapper/library/test_fail.ps1 @@ -31,24 +31,32 @@ Function Test-ThrowException { if ($data -eq "normal") { Exit-Json -obj $result -} elseif ($data -eq "fail") { +} +elseif ($data -eq "fail") { Fail-Json -obj $result -message "fail message" -} elseif ($data -eq "throw") { +} +elseif ($data -eq "throw") { throw [ArgumentException]"module is thrown" -} elseif ($data -eq "error") { +} +elseif ($data -eq "error") { Write-Error -Message $data -} elseif ($data -eq "cmdlet_error") { +} +elseif ($data -eq "cmdlet_error") { Get-Item -Path "fake:\path" -} elseif ($data -eq "dotnet_exception") { +} +elseif ($data -eq "dotnet_exception") { [System.IO.Path]::GetFullPath($null) -} elseif ($data -eq "function_throw") { +} +elseif ($data -eq "function_throw") { Test-ThrowException -} elseif ($data -eq "proc_exit_fine") { +} +elseif ($data -eq "proc_exit_fine") { # verifies that if no error was actually fired and we have an output, we # don't use the RC to validate if the module failed &cmd.exe /c exit 2 Exit-Json -obj $result -} elseif ($data -eq "proc_exit_fail") { +} +elseif ($data -eq "proc_exit_fail") { &cmd.exe /c exit 2 Fail-Json -obj $result -message "proc_exit_fail" } diff --git a/test/integration/targets/win_module_utils/library/legacy_only_new_way.ps1 b/test/integration/targets/win_module_utils/library/legacy_only_new_way.ps1 index 8ea3e06197..045ca75fdd 100644 --- a/test/integration/targets/win_module_utils/library/legacy_only_new_way.ps1 +++ b/test/integration/targets/win_module_utils/library/legacy_only_new_way.ps1 @@ -2,4 +2,4 @@ #Requires -Module Ansible.ModuleUtils.Legacy -Exit-Json @{ data="success" } +Exit-Json @{ data = "success" } diff --git a/test/integration/targets/win_module_utils/library/legacy_only_new_way_win_line_ending.ps1 b/test/integration/targets/win_module_utils/library/legacy_only_new_way_win_line_ending.ps1 index d9c2e00825..837a5162fc 100644 --- a/test/integration/targets/win_module_utils/library/legacy_only_new_way_win_line_ending.ps1 +++ b/test/integration/targets/win_module_utils/library/legacy_only_new_way_win_line_ending.ps1 @@ -2,5 +2,5 @@ #Requires -Module Ansible.ModuleUtils.Legacy
-Exit-Json @{ data="success" }
+Exit-Json @{ data = "success" }
diff --git a/test/integration/targets/win_module_utils/library/legacy_only_old_way.ps1 b/test/integration/targets/win_module_utils/library/legacy_only_old_way.ps1 index 652e128179..3c6b083252 100644 --- a/test/integration/targets/win_module_utils/library/legacy_only_old_way.ps1 +++ b/test/integration/targets/win_module_utils/library/legacy_only_old_way.ps1 @@ -2,4 +2,4 @@ # POWERSHELL_COMMON -Exit-Json @{ data="success" } +Exit-Json @{ data = "success" } diff --git a/test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1 b/test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1 index d5d328a5d8..afe7548dbc 100644 --- a/test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1 +++ b/test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1 @@ -1,4 +1,4 @@ #!powershell
# POWERSHELL_COMMON
-Exit-Json @{ data="success" }
+Exit-Json @{ data = "success" }
diff --git a/test/integration/targets/win_module_utils/library/uses_bogus_utils.ps1 b/test/integration/targets/win_module_utils/library/uses_bogus_utils.ps1 index 0a1c21a3a3..3886aec6f7 100644 --- a/test/integration/targets/win_module_utils/library/uses_bogus_utils.ps1 +++ b/test/integration/targets/win_module_utils/library/uses_bogus_utils.ps1 @@ -3,4 +3,4 @@ # this should fail #Requires -Module Ansible.ModuleUtils.BogusModule -Exit-Json @{ data="success" } +Exit-Json @{ data = "success" } diff --git a/test/integration/targets/win_module_utils/library/uses_local_utils.ps1 b/test/integration/targets/win_module_utils/library/uses_local_utils.ps1 index 3dfc940c17..48c2757118 100644 --- a/test/integration/targets/win_module_utils/library/uses_local_utils.ps1 +++ b/test/integration/targets/win_module_utils/library/uses_local_utils.ps1 @@ -6,4 +6,4 @@ $o = CustomFunction -Exit-Json @{data=$o} +Exit-Json @{data = $o } diff --git a/test/integration/targets/win_script/files/test_script_bool.ps1 b/test/integration/targets/win_script/files/test_script_bool.ps1 index 970dedceb8..d5116f36e7 100644 --- a/test/integration/targets/win_script/files/test_script_bool.ps1 +++ b/test/integration/targets/win_script/files/test_script_bool.ps1 @@ -1,5 +1,5 @@ Param( -[bool]$boolvariable + [bool]$boolvariable ) Write-Output $boolvariable.GetType().FullName diff --git a/test/integration/targets/win_script/files/test_script_creates_file.ps1 b/test/integration/targets/win_script/files/test_script_creates_file.ps1 index 47f85a2d49..3a7c3a9f58 100644 --- a/test/integration/targets/win_script/files/test_script_creates_file.ps1 +++ b/test/integration/targets/win_script/files/test_script_creates_file.ps1 @@ -1,3 +1,3 @@ # Test script to create a file. -echo $null > $args[0] +Write-Output $null > $args[0] diff --git a/test/integration/targets/win_script/files/test_script_with_args.ps1 b/test/integration/targets/win_script/files/test_script_with_args.ps1 index 520aafa395..01bb37f5d7 100644 --- a/test/integration/targets/win_script/files/test_script_with_args.ps1 +++ b/test/integration/targets/win_script/files/test_script_with_args.ps1 @@ -1,7 +1,6 @@ # Test script to make sure the Ansible script module works when arguments are # passed to the script. -foreach ($i in $args) -{ +foreach ($i in $args) { Write-Host $i; } diff --git a/test/integration/targets/win_script/files/test_script_with_errors.ps1 b/test/integration/targets/win_script/files/test_script_with_errors.ps1 index 2d60dc1f19..56f9773548 100644 --- a/test/integration/targets/win_script/files/test_script_with_errors.ps1 +++ b/test/integration/targets/win_script/files/test_script_with_errors.ps1 @@ -1,7 +1,6 @@ # Test script to make sure we handle non-zero exit codes. -trap -{ +trap { Write-Error -ErrorRecord $_ exit 1; } |