PowerShell Pester - Code Coverage

本文介绍如何使用Pester进行PowerShell脚本的单元测试,并通过具体案例演示如何测量代码覆盖率及确保所有功能均被测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天继续学习Pester,invoke-pester有一个很nb的选项叫codeCoverage,可以指定需要测试的脚本,function甚至某一个片段的范围,然后他会告诉你这个范围内的功能是否都测试过了。


来个实例看看,豆子直接在上一篇的脚本里面添加了一个switchtest的function,然后测试了其中一个if的功能


Test.ps1

function add {
param(
[int]$a,
[int]$b
)
$sum=$a+$b
$sum
}
function switchtest{
param(
[switch]$switch
)
if($switch){
return "Switch is On"
}
else{
return "Switch is Off"
}
}


Test.tests.ps1

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"
Describe "Test" {
Context "Should be test"{
    It "Add 1 and 2 is equal to 3" {
        add 1 2 | Should Be 3
    }
      It "Add -1 and 2 is not equal to 0" {
        add -1 2 | Should not Be 0
    }
    It "Test Switch option"{
        switchtest -switch | Should be "Switch is on"
    }
}
Context "Should BeExactly test"{
    It "HostName" {
        hostname | Should beexactly "yli-ise"
    }
}
Context "Should BeGreaterThan test"{
    It "PsVersion is above 3" {
        $PSVersionTable.PSVersion.Major | Should beGreaterThan 3
    }
}
Context "Should beOfType test"{
    It "Get-ADUser type"{
        Get-aduser yli | Should beoftype Microsoft.ActiveDirectory.Management.ADUser
    }
}
Context "Should Exist test"{
    It "C:\temp exist"{
        "c:\temp" | should exist
    }
     
}
Context "Should match test"{
    It "Find Email"{
        "jksjsjsjssdjs abc.xyz@yahoo.com hsosofs" | should match "[a-z0-9!#\$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#\$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
    }
     
}
Context "Should Throw test" {
    It "Get a non-exist Process"{ 
    
        {Get-Process -Name "!@#$%&" -ErrorAction Stop} | Should Throw
    }
}
Context "Should BeNullorEmpty test"{
    It "Get something from test folder"{
    
        get-childitem C:\temp | should not benullorempty
    }
}
}


执行看看,最后他告诉我在我指定的脚本里面,只完成了80%的测试,因为if语句的还有一个分支我没有测试


wKioL1djhKKAg25VAADEhJ8ZYGY621.png


改变一下脚本的范围,只测试16-18行的内容,那么最后报告表示选择范围的功能已经100%测试过了

wKioL1djhX2D2nmWAAC5exxYP4o607.png

PS C:\Users\Administrator> Install-Module -Name Pester -Force -SkipPublisherCheck >> 需需要要使使用用 NuGet 提提供供程程序序来来继继续续操操作作 PowerShellGet 需需要要使使用用 NuGet 提提供供程程序序““2.8.5.201””或或更更高高版版本本来来与与基基于于 NuGet 的的存存储储库库交交互互。。必必须须在在““C:\Program Files\PackageManagement\ProviderAssemblies””或或““C:\Users\Administrator\AppData\Local\PackageManagement\ProviderAssemblies”” 中提供 NuGet 提供程序。也可以通过运行 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force' 安装 NuGet 提供程序。是否要让 PowerShellGet 立即安装并导入 NuGet 提供程序? [Y] 是(Y) [N] 否(N) [S] 暂停(S) [?] 帮助 (默认值为“Y”): y PS C:\Users\Administrator> PS C:\Users\Administrator> PS C:\Users\Administrator> # 执行所有测试 >> Invoke-Pester -Path "E:\CurlTools\Modules\Tests\CurlTools.Tests.ps1" >> >> # 输出示例 >> Describing 模块加载测试 >> [+] 应成功导入模块 102ms >> [+] 应导出Get-CurlPath函数 41ms >> [+] 应正确检测curl.exe路径 35ms >> >> Describing 核心功能测试 >> [+] Get-CurlPath返回有效的可执行文件路径 52ms >> [+] Get-CurlVersion返回版本信息 78ms >> [+] Invoke-SecureDownload成功下载文件 1.2s >> [+] 优雅处理无效URL 45ms >> >> Describing 安全策略测试 >> [+] 应拒绝未授权域名 32ms >> [+] 应允许github.com下载 890ms >> 所在位置 行:6 字符: 4 + [+] 应成功导入模块 102ms + ~ "[" 后面缺少类型名称。 所在位置 行:7 字符: 4 + [+] 应导出Get-CurlPath函数 41ms + ~ "[" 后面缺少类型名称。 所在位置 行:8 字符: 4 + [+] 应正确检测curl.exe路径 35ms + ~ "[" 后面缺少类型名称。 所在位置 行:11 字符: 4 + [+] Get-CurlPath返回有效的可执行文件路径 52ms + ~ "[" 后面缺少类型名称。 所在位置 行:12 字符: 4 + [+] Get-CurlVersion返回版本信息 78ms + ~ "[" 后面缺少类型名称。 所在位置 行:13 字符: 4 + [+] Invoke-SecureDownload成功下载文件 1.2s + ~ "[" 后面缺少类型名称。 所在位置 行:14 字符: 4 + [+] 优雅处理无效URL 45ms + ~ "[" 后面缺少类型名称。 所在位置 行:17 字符: 4 + [+] 应拒绝未授权域名 32ms + ~ "[" 后面缺少类型名称。 所在位置 行:18 字符: 4 + [+] 应允许github.com下载 890ms + ~ "[" 后面缺少类型名称。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingTypename PS C:\Users\Administrator> name: CurlTools CI >> >> on: [push, pull_request] >> >> jobs: >> test: >> runs-on: windows-latest >> steps: >> - uses: actions/checkout@v2 >> - name: Setup PowerShell >> uses: actions/setup-powershell@v1 >> with: >> pwsh: true >> - name: Run Pester tests >> run: | >> Install-Module Pester -Force -AllowClobber >> Invoke-Pester -Path .\Modules\Tests\ -OutputFile TestResults.xml -OutputFormat NUnitXml >> - name: Publish test results >> uses: actions/upload-artifact@v2 >> with: >> name: TestResults >> path: TestResults.xml >> 所在位置 行:9 字符: 6 + - uses: actions/checkout@v2 + ~ 一元运算符“-”后面缺少表达式。 所在位置 行:9 字符: 7 + - uses: actions/checkout@v2 + ~~~~~ 表达式或语句中包含意外的标记“uses:”。 所在位置 行:10 字符: 6 + - name: Setup PowerShell + ~ 一元运算符“-”后面缺少表达式。 所在位置 行:10 字符: 7 + - name: Setup PowerShell + ~~~~~ 表达式或语句中包含意外的标记“name:”。 所在位置 行:14 字符: 6 + - name: Run Pester tests + ~ 一元运算符“-”后面缺少表达式。 所在位置 行:14 字符: 7 + - name: Run Pester tests + ~~~~~ 表达式或语句中包含意外的标记“name:”。 所在位置 行:18 字符: 6 + - name: Publish test results + ~ 一元运算符“-”后面缺少表达式。 所在位置 行:18 字符: 7 + - name: Publish test results + ~~~~~ 表达式或语句中包含意外的标记“name:”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingExpressionAfterOperator PS C:\Users\Administrator> It "应处理大文件下载" { >> # 测试>1GB文件下载 >> } >> >> It "应验证文件哈希" { >> # 测试哈希校验功能 >> } >> >> It "应限制下载速度" { >> # 测试限速功能 >> } >> 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1026 字符: 35 + ... ath = @(<# Get full name #> $history = $state.Stack.ToArray(); [Array ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 使用“1”个参数调用“Reverse”时发生异常:“值不能为 null。 参数名: array” 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1026 字符: 70 + ... $history = $state.Stack.ToArray(); [Array]::Reverse($history); $histo ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentNullException 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1051 字符: 5 + $state.CurrentBlock.Tests.Add($Test) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1052 字符: 5 + $state.CurrentBlock.Order.Add($Test) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1026 字符: 35 + ... ath = @(<# Get full name #> $history = $state.Stack.ToArray(); [Array ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 使用“1”个参数调用“Reverse”时发生异常:“值不能为 null。 参数名: array” 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1026 字符: 70 + ... $history = $state.Stack.ToArray(); [Array]::Reverse($history); $histo ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentNullException 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1051 字符: 5 + $state.CurrentBlock.Tests.Add($Test) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1052 字符: 5 + $state.CurrentBlock.Order.Add($Test) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1026 字符: 35 + ... ath = @(<# Get full name #> $history = $state.Stack.ToArray(); [Array ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 使用“1”个参数调用“Reverse”时发生异常:“值不能为 null。 参数名: array” 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1026 字符: 70 + ... $history = $state.Stack.ToArray(); [Array]::Reverse($history); $histo ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentNullException 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1051 字符: 5 + $state.CurrentBlock.Tests.Add($Test) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1052 字符: 5 + $state.CurrentBlock.Order.Add($Test) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull PS C:\Users\Administrator> It "应处理网络中断" { >> # 使用Fiddler或Charles模拟网络中断 >> } >> 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1026 字符: 35 + ... ath = @(<# Get full name #> $history = $state.Stack.ToArray(); [Array ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 使用“1”个参数调用“Reverse”时发生异常:“值不能为 null。 参数名: array” 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1026 字符: 70 + ... $history = $state.Stack.ToArray(); [Array]::Reverse($history); $histo ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentNullException 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1051 字符: 5 + $state.CurrentBlock.Tests.Add($Test) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 不能对 Null 值表达式调用方法。 所在位置 C:\Program Files\WindowsPowerShell\Modules\Pester\5.7.1\Pester.psm1:1052 字符: 5 + $state.CurrentBlock.Order.Add($Test) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull PS C:\Users\Administrator>
08-15
内容概要:该研究通过在黑龙江省某示范村进行24小时实地测试,比较了燃煤炉具与自动/手动进料生物质炉具的污染物排放特征。结果显示,生物质炉具相比燃煤炉具显著降低了PM2.5、CO和SO2的排放(自动进料分别降低41.2%、54.3%、40.0%;手动进料降低35.3%、22.1%、20.0%),但NOx排放未降低甚至有所增加。研究还发现,经济性和便利性是影响生物质炉具推广的重要因素。该研究不仅提供了实际排放数据支持,还通过Python代码详细复现了排放特征比较、减排效果计算和结果可视化,进一步探讨了燃料性质、动态排放特征、碳平衡计算以及政策建议。 适合人群:从事环境科学研究的学者、政府环保部门工作人员、能源政策制定者、关注农村能源转型的社会人士。 使用场景及目标:①评估生物质炉具在农村地区的推广潜力;②为政策制定者提供科学依据,优化补贴政策;③帮助研究人员深入了解生物质炉具的排放特征和技术改进方向;④为企业研发更高效的生物质炉具提供参考。 其他说明:该研究通过大量数据分析和模拟,揭示了生物质炉具在实际应用中的优点和挑战,特别是NOx排放增加的问题。研究还提出了多项具体的技术改进方向和政策建议,如优化进料方式、提高热效率、建设本地颗粒厂等,为生物质炉具的广泛推广提供了可行路径。此外,研究还开发了一个智能政策建议生成系统,可以根据不同地区的特征定制化生成政策建议,为农村能源转型提供了有力支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值