From 19abcf77e72b0fc120b8347c877de99a2f93ec7e Mon Sep 17 00:00:00 2001 From: bus1hero Date: Mon, 25 Jul 2022 21:51:04 +0300 Subject: [PATCH] refr: Refactor Mock-EnvironmentVariable --- .../Public/Mock-EnvironmentVariable.ps1 | 17 ++++++++++------- .../Public/Mock-EnvironmentVariable.Tests.ps1 | 15 +++++++++------ 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1 b/src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1 index 8846a49..e1afbf7 100644 --- a/src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1 +++ b/src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1 @@ -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 diff --git a/tests/PesterExtensions/Public/Mock-EnvironmentVariable.Tests.ps1 b/tests/PesterExtensions/Public/Mock-EnvironmentVariable.Tests.ps1 index 5a4b1fd..9c57ced 100644 --- a/tests/PesterExtensions/Public/Mock-EnvironmentVariable.Tests.ps1 +++ b/tests/PesterExtensions/Public/Mock-EnvironmentVariable.Tests.ps1 @@ -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 } }