如何使用Pester v4将两项网站拦截测试合并为单一成功验证
合并Pester v4中两项拦截测试为单一成功判定
问题背景
使用Pester v4测试特定网站是否被成功拦截时,现有代码对每个黑名单站点执行两个独立测试:验证连接状态码非200、验证连接超时。但实际场景中只要满足任一条件(超时或非200状态码)就应判定站点被拦截,当前逻辑导致同一站点出现一失败一成功的矛盾结果。
原测试代码
$PrivacyBlackList = @('nexusrules.live.com', 'auc-visio-telemetry.officeapps.live.com') Describe '- Check MS Telemetry Compliance' { Context '- Get Windows and Office Telemetry' { foreach ($BlackSite in $PrivacyBlackList) { It "Should not succesfully connect to $BlackSite" { $ConnectTest = Invoke-WebRequest -Uri $BlackSite -UseBasicParsing -TimeoutSec 3 $ConnectTest.StatusCode | Should -Not -Be '200' } It "Should timeout connecting to $BlackSite" { {$ConnectTest = Invoke-WebRequest -Uri $BlackSite -UseBasicParsing -TimeoutSec 3} | Should -Throw 'The operation has timed out.' } }# end foreach } }
当前测试结果
Describing - Check MS Telemetry Compliance Context - Get Windows and Office Telemetry [-] Should not succesfully connect to nexusrules.live.com 3.23s WebException: The operation has timed out. [+] Should timeout connecting to nexusrules.live.com 3.23s [-] Should not succesfully connect to auc-visio-telemetry.officeapps.live.com 2s Expected '200' to be different from the actual value, but got the same value. 9: $ConnectTest.StatusCode | Should -Not -Be '200' [-] Should timeout connecting to auc-visio-telemetry.officeapps.live.com 1.19s Expected an exception, with message 'The operation has timed out.' to be thrown, but no exception was thrown. 14: Should -Throw 'The operation has timed out.'
解决方案
利用try/catch块统一处理连接结果,在单个It块中通过逻辑或判断两种拦截条件,满足其一即判定测试成功:
$PrivacyBlackList = @('nexusrules.live.com', 'auc-visio-telemetry.officeapps.live.com') Describe '- Check MS Telemetry Compliance' { Context '- Get Windows and Office Telemetry' { foreach ($BlackSite in $PrivacyBlackList) { It "Should be blocked (timeout or non-200 status): $BlackSite" { $connectionSuccess = $false $timedOut = $false try { $ConnectTest = Invoke-WebRequest -Uri $BlackSite -UseBasicParsing -TimeoutSec 3 $connectionSuccess = $true } catch [System.Net.WebException] { if ($_.Exception.Message -match 'The operation has timed out\.') { $timedOut = $true } # 其他Web异常(如403/404)也视为拦截成功 } # 满足超时,或连接成功但状态码非200,即判定拦截生效 ($timedOut -or ($connectionSuccess -and $ConnectTest.StatusCode -ne 200)) | Should -Be $true } }# end foreach } }
逻辑说明
- 通过
try/catch捕获Invoke-WebRequest的所有执行情况 - 单独标记超时异常,其他Web异常默认视为拦截成功
- 用PowerShell原生逻辑或(
-or)组合两种拦截条件,最终通过Should -Be $true统一判定测试结果
内容的提问来源于stack exchange,提问作者Dennis
相关产品推荐
相关产品推荐

