Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion Functions/Mock.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2103,7 +2103,15 @@ if ($PSVersionTable.PSVersion.Major -ge 3) {
It 'returns default mock' {
Get-Content -Path "c:\temp.txt" | Should -Be "default-get-content"
}
}

Context "Alias rewriting works when alias and parameter name differ in length" {

Mock New-Item { return "nic" } -ParameterFilter { $Type -ne $null -and $Type.StartsWith("nic") }

It 'calls the mock' {
New-Item -Path 'Hello' -Type "nic" | Should -Be "nic"
}
}

if ($PSVersionTable.PSVersion -ge 5.1) {
Expand All @@ -2121,7 +2129,7 @@ if ($PSVersionTable.PSVersion.Major -ge 3) {
}

Context 'Assert-MockCalled' {
It "Uses parameter aliases in Parameter-Filter" {
It "Uses parameter aliases in ParameterFilter" {
function f { Get-Content -Path 'temp.txt' -Tail 10 }
Mock Get-Content { }

Expand Down Expand Up @@ -2207,3 +2215,8 @@ Describe "Mock definition output" {
$output | Should -Be $null
}
}

Describe 'Mocking using ParameterFilter with scriptblock' {
$filter = [scriptblock]::Create( ('$Path -eq ''C:\Windows''') )
Mock -CommandName 'Test-Path' -ParameterFilter $filter
}
12 changes: 6 additions & 6 deletions Functions/Mock.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1615,26 +1615,26 @@ function New-BlockWithoutParameterAliases {
try {
if ($PSVersionTable.PSVersion.Major -ge 3) {
$params = $Metadata.Parameters.Values
$ast = $Block.Ast
$ast = $Block.Ast.EndBlock
$blockText = $ast.Extent.Text
$variables = $Ast.FindAll( { param($ast) $ast -is [System.Management.Automation.Language.VariableExpressionAst]}, $true)
$variables = [array]($Ast.FindAll( { param($ast) $ast -is [System.Management.Automation.Language.VariableExpressionAst]}, $true))
[array]::Reverse($variables)

foreach ($var in $variables) {
$varName = $var.VariablePath.UserPath
$length = $varName.Length

foreach ($param in $params) {
if ($param.Aliases -contains $varName) {
$startIndex = $var.Extent.StartOffset - $block.Ast.Extent.StartOffset + 1
$startIndex = $var.Extent.StartOffset - $ast.Extent.StartOffset + 1 # move one position after the dollar sign

$blockText = $blockText.Remove($startIndex, $length).Insert($startIndex, $param.Name)

break # It is safe to stop checking for further params here, since aliases cannot be shared by parameters
}
}
}

# Remove top-level brackets {}
$blockText = $blockText.Remove($blockText.Length - 1, 1).Remove(0, 1)

$Block = [scriptblock]::Create($blockText)
}

Expand Down