【发布时间】:2015-06-16 22:37:10
【问题描述】:
此 PowerShell 函数可识别 不 包含特定字符串的文件:
function GetFilesLackingItem([string]$pattern)
{
Get-ChildItem | ? { !( Select-String -pattern $pattern -path $_ ) }
}
我试图通过模拟 Get-ChildItem 和 Select-String 来编写 Pester 单元测试,但遇到了问题。这是两次以相同方式失败的尝试。第一个测试使用 Mock 的 parameterFilter 进行区分,而第二个测试在 mockCommand 本身中添加了执行此操作的逻辑。
Describe "Tests" {
$fileList = "nameA", "nameB", "nameC", "nameD", "nameE" | % {
[pscustomobject]@{ FullName = $_; }
}
$filter = '(B|D|E)$'
Mock Get-ChildItem { return $fileList }
It "reports files that did not return a match" {
Mock Select-String { "matches found" } -param { $Path -match $filter }
Mock Select-String
$result = Get-ChildItem | ? { !(Select-String -pattern "any" -path $_) }
$result[0].FullName | Should Be "nameA"
$result[1].FullName | Should Be "nameC"
$result.Count | Should Be 2
}
It "reports files that did not return a match" {
Mock Select-String {
if ($Path -match $filter) { "matches found" } else { "" }
}
$result = Get-ChildItem | ? { !(Select-String -pattern "any" -path $_ ) }
$result[0].FullName | Should Be "nameA"
$result[1].FullName | Should Be "nameC"
$result.Count | Should Be 2
}
}
如果我修改测试,使 Select-String -path 参数是 $_.FullName 而不是 $_,那么两个测试都会通过。但在现实生活中(即,如果我在没有模拟的情况下运行这条线)它只需要$_ 就可以正常工作。 (它也可以与$_.FullName 一起正常工作。)因此,真正的 Select-String 似乎能够从 FileInfo 对象数组中为 Path 参数映射 FullName(尽管我找不到这样做的参数别名)。
我的问题:是否可以保留原始代码,即在被测行上将 Path 参数保留为 $_,然后修改 Select-String 模拟以提取 FullName 属性?例如,在任一模拟中尝试 $Path.FullName 都不起作用。
【问题讨论】:
-
Select-String是否实际上将PSPath属性映射到LiteralPath参数(别名PSPath,按属性名称从管道获取),而不是FullName?你可以试试PSPath到LiteralPath而不是FullName? -
@Roman:不太清楚你的建议是什么。我尝试了 $fileList 而不是 FullName 中的不同属性组合,还尝试了 -LiteralPath 与 -Path to Select-String,但没有找到有效的组合。
-
我并不是在建议具体的东西。我只是认为“Select-String 似乎能够从 FileInfo 数组映射 FullName”不太正确,因为映射的是 LiteralPath 或 PSPath,而不是 FullName。
标签: unit-testing powershell pester