【发布时间】:2018-05-17 15:47:54
【问题描述】:
我有一个专门处理异常并忽略它的实用程序函数,但是当使用 Pester 测试它时,测试失败,显示已经捕获和处理的异常。我是否遗漏了什么,或者这是 Pester 中的错误?
这段代码重现了这个问题:
function Test-FSPath {
[cmdletbinding()]
param([string]$FileSystemPath)
if([string]::IsNullOrWhiteSpace($FileSystemPath)) { return $false }
$result = $false
try {
if(Test-Path $FileSystemPath) {
Write-Debug "Verifying that $FileSystemPath is a file system path"
$item = Get-Item $FileSystemPath -ErrorAction Ignore
$result = ($item -ne $null) -and $($item.PSProvider.Name -eq 'FileSystem')
}
} catch {
# Path pattern that Test-Path / Get-Item can't handle
Write-Debug "Ignoring exception $($_.Exception.Message)"
}
return ($result -or ([System.IO.Directory]::Exists($FileSystemPath)) -or ([System.IO.File]::Exists($FileSystemPath)))
}
Describe 'Test' {
Context Test-FSPath {
It 'returns true for a path not supported by PowerShell Test-Path' {
$absPath = "$env:TEMP\temp-file[weird-chars.txt"
[System.IO.File]::WriteAllText($absPath, 'Hello world')
$result = Test-FSPath $absPath -Debug
$result | Should -Be $true
Write-Host "`$result = $result"
Remove-Item $absPath
}
}
}
预期结果:测试通过
实际结果:测试失败:
[-] returns true for a path not supported by PowerShell Test-Path 2.62s
WildcardPatternException: The specified wildcard character pattern is not valid: temp-file[weird-chars.txt
ParameterBindingException: Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: temp-file[weird-chars.txt
【问题讨论】:
-
Test-Path不应该抛出任何错误,除非你告诉它。您不会抛出任何被捕获的异常,并且您会特别忽略可以执行的操作。在Test-Path上添加-ErrorAction Stop -
如果您更改文件名(即,删除“[”)完美!
-
@VictorSilva 这错过了测试的重点。方括号是有效的 Windows 文件路径,Test-Path 无法处理。 Test-FSPath 函数旨在解决此问题
标签: powershell pester