Skip to content

Fix envvar() function to error if env var doesn't exist #358

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions dsc_lib/src/functions/envvar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,30 @@ impl Function for Envvar {
}

fn invoke(&self, args: &[Value], _context: &Context) -> Result<Value, DscError> {
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());
}
}
9 changes: 3 additions & 6 deletions powershell-adapter/Tests/powershellgroup.config.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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://github.com/raw/PowerShell/DSC/main/schemas/2023/10/config/document.json
Expand All @@ -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
}
}