用佩斯特5.3.3进行测试

发布于 2025-02-11 03:17:46 字数 946 浏览 1 评论 0原文

我已经写了一个函数来编写在CSV文件中函数中发生的错误,此功能在我的函数的捕获块中调用。我想在佩斯特(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 {
        Write-Logs -LogFilePath:$CSVLogPath -Message:$Error[0].Exception.Message `
        -Source:"FunctionName()" -MessageType:"Error"
        return
    }

I have written a function to write the errors that occur in my functions in a csv file, this function is called in the catch block of my functions. I would like to write a Test in Pester to check that my function works correctly, but to be honest I don't know where to start, I have tried some things but they don't work for me, I have also been reading in the documentation but I am still not clear, I would appreciate any help/comments.

Here is the function for which I want to write a Test in 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
}

and so I´m calling the function in the catch block:

    catch {
        Write-Logs -LogFilePath:$CSVLogPath -Message:$Error[0].Exception.Message `
        -Source:"FunctionName()" -MessageType:"Error"
        return
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晚雾 2025-02-18 03:17:46

继续我的评论,这是一些代码。

首先通过实际使用-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 docs
  • 一旦获得了一些基本测试,您可能需要通过使用数据驱动的测试来改进测试代码。这样可以避免重复,因为您只需要单个测试,该测试可以从不同的数据集中馈送。参见 pester docs ,尤其是“为测试提供外部数据的部分)。

Continuing from my comments, here is some code.

First make the function testable, by actually using the -LogFilePath parameter. This way you can write the log to a temporay file during testing. Due to the default value you can still use it without -LogFilePath when calling it from normal code.

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
}

Test code:

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: is a temporary drive created by Pester for each script block. It is very convenient for writing temporary files because Pester cleans it automatically when the script block ends. See Pester docs.
  • Once you got some basic tests working, you might want to improve your test code by using data-driven tests. This avoids duplication as you only need a single test, that can be fed from different data sets. See Pester docs, especially section "Providing external data to tests".
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文