Skip to content

Commit 410a995

Browse files
committed
feat: Update Mock-EnvironmentVariable
Add a test to ensure that no environment variable is created
1 parent 6924975 commit 410a995

File tree

2 files changed

+49
-3
lines changed

2 files changed

+49
-3
lines changed

src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ function Mock-EnvironmentVariable {
1414
)
1515
if (Test-Path -Path "env:${Variable}") {
1616
$OriginalValue = (Get-ChildItem -Path "env:${Variable}").Value
17-
Set-Item -Path "env:${Variable}" -Value $Value
17+
if ($value) {
18+
Set-Item -Path "env:${Variable}" -Value $Value
19+
}
1820
}
1921
else {
2022
New-Item -Path "env:${Variable}" -Value $Value
@@ -29,8 +31,12 @@ function Mock-EnvironmentVariable {
2931
if ($OriginalValue) {
3032
Set-Item -Path "env:${Variable}" -Value $OriginalValue
3133
}
32-
else {
33-
Remove-Item -Path "env:${Variable}"
34+
elseif (Test-Path -Path "env:${Variable}") {
35+
Remove-Item `
36+
-Path "env:${Variable}" `
37+
-Recurse `
38+
-Force `
39+
-ErrorAction Stop
3440
}
3541
}
3642

tests/PesterExtensions/Public/Mock-EnvironmentVariable.Tests.ps1

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,47 @@ Describe 'Mock an environment variable' {
7474
-Recurse `
7575
-ErrorAction Ignore
7676
}
77+
}
78+
79+
Describe 'Use the original value if value is not set up' {
80+
BeforeAll {
81+
$script:environmentVariableName = "test$(New-Guid)"
82+
$script:environmentVariable = "env:${environmentVariableName}"
83+
$script:InitialValue = 'Some value here and there'
84+
New-Item -Path $environmentVariable -Value $InitialValue
85+
}
86+
It 'Test' {
87+
Mock-EnvironmentVariable -Variable $environmentVariableName {
88+
(Get-ChildItem -Path $environmentVariable).Value | Should -Be $InitialValue
89+
}
90+
}
91+
AfterAll {
92+
Remove-Item `
93+
-Path $environmentVariable `
94+
-Force `
95+
-Recurse `
96+
-ErrorAction Ignore
97+
}
98+
}
7799

100+
Describe 'Do not create the variable if no value is specified' {
101+
BeforeAll {
102+
$script:environmentVariableName = "test$(New-Guid)"
103+
$script:environmentVariable = "env:${environmentVariableName}"
104+
$script:InitialValue = 'Some value here and there'
105+
}
106+
It 'Test' {
107+
Mock-EnvironmentVariable -Variable $environmentVariableName {
108+
Test-Path -Path $environmentVariable | Should -BeFalse
109+
}
110+
}
111+
AfterAll {
112+
Remove-Item `
113+
-Path $environmentVariable `
114+
-Force `
115+
-Recurse `
116+
-ErrorAction Ignore
117+
}
78118
}
79119

80120
Describe 'Initial value should be reasigned' {

0 commit comments

Comments
 (0)