Skip to content

Commit 1ed2167

Browse files
nohwndCopilot
andauthored
Fix #2628: Add -LiteralPath switch to Should -Exist (#2691)
Keep default wildcard behavior (Test-Path) and add optional -LiteralPath switch that uses Test-Path -LiteralPath for paths with special characters. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 2f5333a commit 1ed2167

2 files changed

Lines changed: 24 additions & 8 deletions

File tree

src/functions/assertions/Exist.ps1

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
function Should-ExistAssertion($ActualValue, [switch] $Negate, [string] $Because) {
1+
function Should-ExistAssertion($ActualValue, [switch] $Negate, [string] $Because, [switch] $LiteralPath) {
22
<#
33
.SYNOPSIS
44
Does not perform any comparison, but checks if the object calling Exist is present in a PS Provider.
@@ -12,7 +12,12 @@
1212
`Should -Exist` calls Test-Path. Test-Path expects a file,
1313
returns $false because the file was removed, and fails the test.
1414
#>
15-
[bool] $succeeded = & $SafeCommands['Test-Path'] $ActualValue
15+
if ($LiteralPath) {
16+
[bool] $succeeded = & $SafeCommands['Test-Path'] -LiteralPath $ActualValue
17+
}
18+
else {
19+
[bool] $succeeded = & $SafeCommands['Test-Path'] $ActualValue
20+
}
1621

1722
if ($Negate) {
1823
$succeeded = -not $succeeded

tst/functions/assertions/Exist.Tests.ps1

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ InPesterModuleScope {
1616
"TestDrive:\``[test``].txt" | Should -Exist
1717
}
1818

19+
It 'matches wildcard patterns by default' {
20+
New-Item -Path "TestDrive:\wildcard1.txt" -ItemType File | Out-Null
21+
"TestDrive:\wild*.txt" | Should -Exist
22+
}
23+
1924
It 'returns correct result for function drive' {
2025
function f1 {
2126
}
@@ -29,18 +34,24 @@ InPesterModuleScope {
2934
'env:test' | Should -Exist
3035
}
3136

32-
It 'returns correct result for env drive' {
33-
$env:test = 'somevalue'
34-
35-
'env:test' | Should -Exist
36-
}
37-
3837
It 'returns correct assertion message' {
3938
$err = { 'c:\nonexistingpath' | Should -Exist -Because 'reason' } | Verify-AssertionFailed
4039
$err.Exception.Message | Verify-Equal "Expected path 'c:\nonexistingpath' to exist, because reason, but it did not exist."
4140
}
4241
}
4342

43+
Describe "Should -Exist -LiteralPath" {
44+
It 'works for path with literal [ ] characters' {
45+
New-Item -Path "TestDrive:\[literal].txt" -ItemType File | Out-Null
46+
"TestDrive:\[literal].txt" | Should -Exist -LiteralPath
47+
}
48+
49+
It 'does not match wildcard patterns' {
50+
New-Item -Path "TestDrive:\nowild.txt" -ItemType File | Out-Null
51+
"TestDrive:\no*.txt" | Should -Not -Exist -LiteralPath
52+
}
53+
}
54+
4455
Describe "Should -Not -Exist" {
4556
It 'returns correct assertion message' {
4657
$currentPath = $pwd.Path

0 commit comments

Comments
 (0)