diff --git a/dsc_lib/src/functions/envvar.rs b/dsc_lib/src/functions/envvar.rs index b0278da5..372360c8 100644 --- a/dsc_lib/src/functions/envvar.rs +++ b/dsc_lib/src/functions/envvar.rs @@ -25,7 +25,30 @@ impl Function for Envvar { } fn invoke(&self, args: &[Value], _context: &Context) -> Result { - let val = env::var(args[0].as_str().unwrap_or_default()).unwrap_or_default(); - Ok(Value::String(val)) + if let Ok(val) = env::var(args[0].as_str().unwrap_or_default()) { + return Ok(Value::String(val)); + } + + Err(DscError::Function("envvar".to_string(), "Environment variable not found".to_string())) + } +} + +#[cfg(test)] +mod tests { + use crate::configure::context::Context; + use crate::parser::Statement; + + #[test] + fn valid() { + let mut parser = Statement::new().unwrap(); + let result = parser.parse_and_execute("[envvar('PATH')]", &Context::new()).unwrap(); + assert_eq!(result, std::env::var("PATH").unwrap()); + } + + #[test] + fn invalid() { + let mut parser = Statement::new().unwrap(); + let result = parser.parse_and_execute("[envvar('INVALID')]", &Context::new()); + assert!(result.is_err()); } } diff --git a/powershell-adapter/Tests/powershellgroup.config.tests.ps1 b/powershell-adapter/Tests/powershellgroup.config.tests.ps1 index 1ff020b2..ccc261bb 100644 --- a/powershell-adapter/Tests/powershellgroup.config.tests.ps1 +++ b/powershell-adapter/Tests/powershellgroup.config.tests.ps1 @@ -120,7 +120,7 @@ Describe 'PowerShell adapter resource tests' { $res.results[0].result.actualState.Prop1 | Should -Be $TestDrive } - It 'DSCConfigRoot macro is empty when config is piped from stdin' -Skip:(!$IsWindows){ + It 'DSC_CONFIG_ROOT env var does not exist when config is piped from stdin' -Skip:(!$IsWindows){ $yaml = @" `$schema: https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2023/10/config/document.json @@ -134,10 +134,7 @@ Describe 'PowerShell adapter resource tests' { properties: Name: "[envvar('DSC_CONFIG_ROOT')]" "@ - $out = $yaml | dsc config get - $LASTEXITCODE | Should -Be 0 - $res = $out | ConvertFrom-Json - $res.results[0].result.actualState.Name | Should -Be "" - $res.results[0].result.actualState.Prop1 | Should -Be "" + $null = $yaml | dsc config get + $LASTEXITCODE | Should -Be 2 } }