Skip to content

Commit c5c9f9e

Browse files
author
petru
committed
feat: Update Mock-EnvironmentVariable function
Add the posibility to specify targets to mock and refactor the implementation to a more enjoyable state.
1 parent ffc0af6 commit c5c9f9e

File tree

2 files changed

+267
-149
lines changed

2 files changed

+267
-149
lines changed

src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1

Lines changed: 52 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,68 @@
1+
function Restore {
2+
param (
3+
[string]
4+
$Variable,
5+
6+
[EnvironmentVariableTarget[]]
7+
$Targets,
8+
9+
[hashtable]
10+
$Backup
11+
)
12+
foreach ($target in $targets) {
13+
[Environment]::SetEnvironmentVariable($Variable, $Backup[$target], $target)
14+
}
15+
}
16+
17+
function Set-Values {
18+
param (
19+
[string]
20+
$Variable,
21+
22+
[EnvironmentVariableTarget[]]
23+
$Targets,
24+
25+
[string]
26+
$value
27+
)
28+
$Backup = @{}
29+
30+
foreach ($target in $Targets) {
31+
$OriginalValue = [Environment]::GetEnvironmentVariable($Variable, $target)
32+
$Backup.Add($target, $OriginalValue)
33+
if ($Value) {
34+
[Environment]::SetEnvironmentVariable($Variable, $Value, $target)
35+
}
36+
}
37+
38+
return $Backup
39+
}
40+
41+
142
function Mock-EnvironmentVariable {
243
param (
3-
[parameter(Mandatory = $true, Position = 0)]
44+
[parameter(Mandatory = $true)]
445
[string]
546
$Variable,
647

48+
[Parameter(Mandatory = $true)]
49+
[ScriptBlock]
50+
$Fixture,
51+
752
[Parameter(Mandatory = $false)]
853
[string]
954
$Value,
1055

1156
[Parameter(Mandatory = $false)]
12-
[System.EnvironmentVariableTarget]
13-
$Targets = [EnvironmentVariableTarget]::Process,
14-
15-
[Parameter(Mandatory = $true, Position = 1)]
16-
[ScriptBlock]
17-
$Fixture
18-
57+
[EnvironmentVariableTarget[]]
58+
$Targets = @([EnvironmentVariableTarget]::Process)
1959
)
20-
$EnvironmentVariable = "env:${Variable}"
21-
22-
if (Test-Path -Path $EnvironmentVariable) {
23-
$OriginalValue = (Get-ChildItem -Path $EnvironmentVariable).Value
24-
if ($value) {
25-
Set-Item -Path $EnvironmentVariable -Value $Value
26-
}
27-
}
28-
else {
29-
New-Item -Path $EnvironmentVariable -Value $Value | Out-Null
30-
}
31-
try {
32-
Invoke-Command -ScriptBlock $Fixture
33-
}
3460

35-
catch {
36-
throw $_
37-
}
61+
$Backup = Set-Values -Variable $Variable -Targets $Targets -value $Value
3862

39-
finally {
40-
if ($OriginalValue) {
41-
Set-Item -Path $EnvironmentVariable -Value $OriginalValue
42-
}
43-
elseif (Test-Path -Path $EnvironmentVariable) {
44-
Remove-Item `
45-
-Path $EnvironmentVariable `
46-
-Recurse `
47-
-Force `
48-
-ErrorAction Stop
49-
}
50-
}
63+
try { Invoke-Command -ScriptBlock $Fixture }
64+
catch { throw $_ }
65+
finally { Restore -Variable $Variable -Targets $Targets -Backup $Backup }
5166

5267
<#
5368
.PARAMETER Variable

0 commit comments

Comments
 (0)