Skip to content

Commit

Permalink
refr: Refactor Mock-EnvironmentVariable
Browse files Browse the repository at this point in the history
  • Loading branch information
BusHero committed Jul 25, 2022
1 parent 702f6aa commit 19abcf7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
17 changes: 10 additions & 7 deletions src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,31 @@ function Mock-EnvironmentVariable {
[ScriptBlock]
$Fixture
)
if (Test-Path -Path "env:${Variable}") {
$OriginalValue = (Get-ChildItem -Path "env:${Variable}").Value
$EnvironmentVariable = "env:${Variable}"
if (Test-Path -Path $EnvironmentVariable) {
$OriginalValue = (Get-ChildItem -Path $EnvironmentVariable).Value
if ($value) {
Set-Item -Path "env:${Variable}" -Value $Value
Set-Item -Path $EnvironmentVariable -Value $Value
}
}
else {
New-Item -Path "env:${Variable}" -Value $Value
New-Item -Path $EnvironmentVariable -Value $Value
}
try {
Invoke-Command -ScriptBlock $Fixture
}

catch {
throw $_
}

finally {
if ($OriginalValue) {
Set-Item -Path "env:${Variable}" -Value $OriginalValue
Set-Item -Path $EnvironmentVariable -Value $OriginalValue
}
elseif (Test-Path -Path "env:${Variable}") {
elseif (Test-Path -Path $EnvironmentVariable) {
Remove-Item `
-Path "env:${Variable}" `
-Path $EnvironmentVariable `
-Recurse `
-Force `
-ErrorAction Stop
Expand Down
15 changes: 9 additions & 6 deletions tests/PesterExtensions/Public/Mock-EnvironmentVariable.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,25 @@ Describe 'Mock an environment variable' {
}
Describe 'Environment variable is set up' {
BeforeAll {
$script:environmentVariable = "test$(New-Guid)"
$script:InitialValue = 'Some value here and there'
$environmentVariableName = "test$(New-Guid)"
$environmentVariable = "env:${environmentVariableName}"
$InitialValue = 'Some value here and there'
}

It 'Environment variable is set up' {
$environmentVariable = "test$(New-Guid)"
$InitialValue = 'Some value here and there'
Test-Path -Path $environmentVariable | Should -BeFalse
Mock-EnvironmentVariable -Variable $environmentVariable -Value $InitialValue {
(Get-ChildItem -Path "env:${environmentVariable}").Value | Should -Be $InitialValue
(Get-ChildItem -Path $environmentVariable).Value | Should -Be $InitialValue
}
Test-Path -Path $environmentVariable | Should -BeFalse
}

AfterAll {

Remove-Item `
-Path $environmentVariable `
-Recurse `
-Force `
-ErrorAction Ignore
}
}

Expand Down

0 comments on commit 19abcf7

Please sign in to comment.