From d26f83c460c129448dd692e0b9aa8f0938b2140e Mon Sep 17 00:00:00 2001 From: yxxhero Date: Thu, 21 Apr 2022 19:29:32 +0800 Subject: [PATCH] add unittest for Exec and add feature that inherit the environment variables from the parent process for Exec Signed-off-by: yxxhero --- pkg/tmpl/context_funcs.go | 2 ++ pkg/tmpl/context_funcs_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/pkg/tmpl/context_funcs.go b/pkg/tmpl/context_funcs.go index 574be4d4..afd4f1c3 100644 --- a/pkg/tmpl/context_funcs.go +++ b/pkg/tmpl/context_funcs.go @@ -66,6 +66,8 @@ func (c *Context) Exec(command string, args []interface{}, inputs ...string) (st cmd := exec.Command(command, strArgs...) cmd.Dir = c.basePath + // inherit the environment variables from the parent process + cmd.Env = os.Environ() g := errgroup.Group{} diff --git a/pkg/tmpl/context_funcs_test.go b/pkg/tmpl/context_funcs_test.go index 7878863f..41d05a35 100644 --- a/pkg/tmpl/context_funcs_test.go +++ b/pkg/tmpl/context_funcs_test.go @@ -252,3 +252,28 @@ func TestRequiredEnv(t *testing.T) { require.Equalf(t, expected, envVal, "Expected %s to be returned when environment variable %s is set to a non-empty string", expected, envKey) } + +// TestExec tests that Exec returns the expected output. +func TestExec(t *testing.T) { + ctx := &Context{basePath: "."} + + // test that the command is executed + expected := "foo\n" + output, err := ctx.Exec("echo", []interface{}{"foo"}, "") + require.Nilf(t, err, "Expected no error to be returned when executing command") + require.Equalf(t, expected, output, "Expected %s to be returned when executing command", expected) + + // test inherited environment + expected = "bar\n" + os.Setenv("HELMFILE_TEST", "bar") + defer os.Unsetenv("HELMFILE_TEST") + output, err = ctx.Exec("bash", []interface{}{"-c", "echo $HELMFILE_TEST"}, "") + require.Nilf(t, err, "Expected no error to be returned when executing command") + require.Equalf(t, expected, output, "Expected %s to be returned when executing command", expected) + + // test that the command is executed with no-zero exit code + + _, err = ctx.Exec("bash", []interface{}{"-c", "exit 1"}, "") + require.Error(t, err, "Expected error to be returned when executing command with non-zero exit code") + +}