我撰寫了一個函式來將函式中發生的錯誤寫入 csv 檔案,該函式在函式的 catch 塊中呼叫。我想在 Pester 中撰寫一個測驗來檢查我的功能是否正常作業,但老實說我不知道??從哪里開始,我嘗試了一些東西但它們對我不起作用,我也一直在閱讀檔案,但我仍然不清楚,我將不勝感激任何幫助/意見。
這是我想在 Pester 中撰寫測驗的函式:
function Write-Logs {
param (
[ValidateSet("Error")]$MessageType,
[string][Parameter(Mandatory=$true)]$Message,
$LogFilePath,
$Source
)
$CSVLogPath = Join-Path -Path $PSScriptRoot -ChildPath ".\errorslog.csv"
$CSVLogObject = [PSCustomObject] @{
Date = Get-Date
Message = $Message
MessageType = $MessageType
Source = $Source
}
$CSVLogObject | Export-Csv -Path $CSVLogPath -NoTypeInformation -Encoding UTF8 -Append
}
所以我在 catch 塊中呼叫函式:
catch {
Write-Logs -LogFilePath:$CSVLogPath -Message:$Error[0].Exception.Message `
-Source:"FunctionName()" -MessageType:"Error"
return
}
uj5u.com熱心網友回復:
繼續我的評論,這里有一些代碼。
-LogFilePath首先通過實際使用引數使函式可測驗。這樣,您可以在測驗期間將日志寫入臨時檔案。由于默認值,您仍然可以在沒有-LogFilePath從普通代碼呼叫它的情況下使用它。
function Write-Logs {
param (
[ValidateSet("Error")]$MessageType,
[string][Parameter(Mandatory=$true)]$Message,
$LogFilePath = (Join-Path -Path $PSScriptRoot -ChildPath ".\errorslog.csv"),
$Source
)
$CSVLogObject = [PSCustomObject] @{
Date = Get-Date
Message = $Message
MessageType = $MessageType
Source = $Source
}
$CSVLogObject | Export-Csv -Path $LogFilePath -NoTypeInformation -Encoding UTF8 -Append
}
測驗代碼:
BeforeAll {
. $PSCommandPath.Replace('.Tests.ps1','.ps1')
}
Describe "Write-Logs" {
BeforeEach{
# Mock Get-Date so it returns a constant value suitable for testing
$expectedDate = [DateTime]::new( 2022, 06, 28, 12, 36, 21 )
Mock Get-Date { return $expectedDate }
}
It "writes the expected CSV" {
# You might read this from a file using Import-Csv
$expectedCsv = [PSCustomObject]@{
Date = $expectedDate
Message = 'test message'
MessageType = 'Error'
Source = 'test source'
}
# Write log to temp file (Pester cleans it automatically, when It block ends)
$testLogPath = "TestDrive:\test.log"
Write-Logs -LogFilePath $testLogPath -MessageType $expectedCsv.MessageType -Message $expectedCsv.Message -Source $expectedCsv.Source
$actualCsv = Import-Csv $testLogPath
# Test if $expectedCsv equals $actualCsv
Compare-Object $expectedCsv $actualCsv -Property Date, Message, MessageType, Source | Should -BeNullOrEmpty
}
}
TestDrive:是 Pester 為每個腳本塊創建的臨時驅動器。撰寫臨時檔案非常方便,因為 Pester 會在腳本塊結束時自動清理它。請參閱糾纏檔案。- 一旦您完成了一些基本測驗,您可能希望通過使用資料驅動測驗來改進您的測驗代碼。這避免了重復,因為您只需要一個可以從不同資料集提供的測驗。請參閱Pester 檔案,尤其是“為測驗提供外部資料”部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/496652.html
