2

例外を具体的に処理して無視するユーティリティ関数がありますが、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
4

1 に答える 1

1

あなたが見ている例外はあなたの関数から来ているのではなく、あなたの使用から来てRemove-Item、間違ったパスを削除しようとしてエラーをスローしています(これも存在しません)。とにかくアイテムが作成されるとは思わないので、単に削除する必要があります。

または、代わりに(コメントで述べたように) TestDrive: を使用します。これにより、クリーンアップについて心配する必要がなくなります(使用する必要があるパスがサポートされているようです$Testdrive)。

    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
        $result | Should -Be $true 
    } 

余談ですが、私は通常、 の外部で実行タイプの処理を行いIt、内部で結果をテストするだけです。コードに対してこれを開始すると、エラーがContextブロックで発生するようになったため、テストに合格したことがわかりました。これが私が言いたいことです(この例でも、変数を介してTestDrive:$testdriveを使用しています):

Describe 'Test' {
    Context Test-FSPath { 
        $absPath = "$testdrive\temp-file[weird-chars.txt"
        [System.IO.File]::WriteAllText($absPath, 'Hello world')
        $result = Test-FSPath $absPath

        It 'returns true for a path not supported by PowerShell Test-Path' {
            $result | Should -Be $true 
        } 
    }
}
于 2018-05-17T17:03:04.480 に答える