powershell - 如何在 Pester 5 中为嵌套函数定义“It”测试?
问题描述
给定一个带有函数和嵌套函数的 PowerShell 脚本 (.ps1)。函数“内部”不应移动到外部范围,因此不应导出。如何为“内部”功能定义“It”测试(希望不修改代码)?
使用:PS核心7.1.4:
Function Outer {
Function Inner {
# ...
}
# ...
}
使用:纠缠 5.3.0:
Describe "A" {
It "A" { Outer } | Should -be $null # OK
It "B" { Inner } | Should -be $null # ERROR
}
解决方案
如果你真的必须这样做,有一种方法,但它涉及通过抽象语法树进行搜索。这可能有点复杂,但它可以完成工作。
所以你有这样定义的功能:
Function Outer {
Function Inner {
# ...
}
# ...
}
你可以找到如下scriptblock
的函数:Inner
$outerCommandInfo = Get-Command -Name 'Outer'
$innerDefinition = $outerCommandInfo.ScriptBlock.Ast.FindAll( { param($ast) $ast -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true) | ? Name -eq 'Inner'
$innerScriptBlock = $innerDefinition.Body.GetScriptBlock()
现在,在$innerScriptBlock
变量中你有Inner
函数的定义。您可以使用调用运算符调用它,或者简单地调用它$innerScriptBlock.Invoke()
传递参数和测试它会有点棘手。
Describe "A" {
BeforeAll {
# the code above
}
It "A" { Outer } | Should -be $null # OK
It "B" { & $innerScriptBlock } | Should -be $null # OK?
}
推荐阅读
- javascript - Svelte 3 getContext:不在 IE11 中获取存储
- core-data - 在@FetchRequest 中输入一个动态值,以从 SwiftUI 中的核心数据中获取单个实体
- accessibility - 测试注入网页的小部件的可访问性:是否有工具可以做到这一点?
- c++ - 当一个结构在 C++ 中也被引用时,它是否有可能返回其成员之一?
- html - 如何移动按钮文本?
- android - 在android中动态添加n个进度条
- javascript - 在 highcharts 中一次拖动多个点
- html - 如何使用多样式图像制作 html 表格
- hybris - Hybris 使用 CmsItemConverter 转换所有属性
- reactjs - react redux-saga 在哪里处理一些逻辑