Skip to content

Commit

Permalink
test(flags): ensure temp files are cleaned up (#1727)
Browse files Browse the repository at this point in the history
  • Loading branch information
piksel authored Aug 12, 2023
1 parent 32204a7 commit 139f672
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 42 deletions.
34 changes: 18 additions & 16 deletions internal/flags/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"os"
"strings"
"time"
Expand Down Expand Up @@ -469,12 +468,14 @@ func GetSecretsFromFiles(rootCmd *cobra.Command) {
"notification-url",
}
for _, secret := range secrets {
getSecretFromFile(flags, secret)
if err := getSecretFromFile(flags, secret); err != nil {
log.Fatalf("failed to get secret from flag %v: %s", secret, err)
}
}
}

// getSecretFromFile will check if the flag contains a reference to a file; if it does, replaces the value of the flag with the contents of the file.
func getSecretFromFile(flags *pflag.FlagSet, secret string) {
func getSecretFromFile(flags *pflag.FlagSet, secret string) error {
flag := flags.Lookup(secret)
if sliceValue, ok := flag.Value.(pflag.SliceValue); ok {
oldValues := sliceValue.GetSlice()
Expand All @@ -483,7 +484,7 @@ func getSecretFromFile(flags *pflag.FlagSet, secret string) {
if value != "" && isFile(value) {
file, err := os.Open(value)
if err != nil {
log.Fatal(err)
return err
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
Expand All @@ -493,25 +494,26 @@ func getSecretFromFile(flags *pflag.FlagSet, secret string) {
}
values = append(values, line)
}
if err := file.Close(); err != nil {
return err
}
} else {
values = append(values, value)
}
}
sliceValue.Replace(values)
return
return sliceValue.Replace(values)
}

value := flag.Value.String()
if value != "" && isFile(value) {
file, err := ioutil.ReadFile(value)
content, err := os.ReadFile(value)
if err != nil {
log.Fatal(err)
}
err = flags.Set(secret, strings.TrimSpace(string(file)))
if err != nil {
log.Error(err)
return err
}
return flags.Set(secret, strings.TrimSpace(string(content)))
}

return nil
}

func isFile(s string) bool {
Expand Down Expand Up @@ -564,15 +566,15 @@ func ProcessFlagAliases(flags *pflag.FlagSet) {
// update schedule flag to match interval if it's set, or to the default if none of them are
if intervalChanged || !scheduleChanged {
interval, _ := flags.GetInt(`interval`)
flags.Set(`schedule`, fmt.Sprintf(`@every %ds`, interval))
_ = flags.Set(`schedule`, fmt.Sprintf(`@every %ds`, interval))
}

if flagIsEnabled(flags, `debug`) {
flags.Set(`log-level`, `debug`)
_ = flags.Set(`log-level`, `debug`)
}

if flagIsEnabled(flags, `trace`) {
flags.Set(`log-level`, `trace`)
_ = flags.Set(`log-level`, `trace`)
}

}
Expand All @@ -593,7 +595,7 @@ func appendFlagValue(flags *pflag.FlagSet, name string, values ...string) error

if flagValues, ok := flag.Value.(pflag.SliceValue); ok {
for _, value := range values {
flagValues.Append(value)
_ = flagValues.Append(value)
}
} else {
return fmt.Errorf(`the value for flag %q is not a slice value`, name)
Expand Down
39 changes: 13 additions & 26 deletions internal/flags/flags_test.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
package flags

import (
"io/ioutil"
"os"
"testing"

"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"os"
"testing"
)

func TestEnvConfig_Defaults(t *testing.T) {
// Unset testing environments own variables, since those are not what is under test
os.Unsetenv("DOCKER_TLS_VERIFY")
os.Unsetenv("DOCKER_HOST")
_ = os.Unsetenv("DOCKER_TLS_VERIFY")
_ = os.Unsetenv("DOCKER_HOST")

cmd := new(cobra.Command)
SetDefaults()
Expand Down Expand Up @@ -48,10 +46,7 @@ func TestEnvConfig_Custom(t *testing.T) {

func TestGetSecretsFromFilesWithString(t *testing.T) {
value := "supersecretstring"

err := os.Setenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD", value)
require.NoError(t, err)
defer os.Unsetenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD")
t.Setenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD", value)

testGetSecretsFromFiles(t, "notification-email-server-password", value)
}
Expand All @@ -60,18 +55,15 @@ func TestGetSecretsFromFilesWithFile(t *testing.T) {
value := "megasecretstring"

// Create the temporary file which will contain a secret.
file, err := ioutil.TempFile(os.TempDir(), "watchtower-")
file, err := os.CreateTemp(t.TempDir(), "watchtower-")
require.NoError(t, err)
defer os.Remove(file.Name()) // Make sure to remove the temporary file later.

// Write the secret to the temporary file.
secret := []byte(value)
_, err = file.Write(secret)
_, err = file.Write([]byte(value))
require.NoError(t, err)
require.NoError(t, file.Close())

err = os.Setenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD", file.Name())
require.NoError(t, err)
defer os.Unsetenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD")
t.Setenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD", file.Name())

testGetSecretsFromFiles(t, "notification-email-server-password", value)
}
Expand All @@ -80,16 +72,15 @@ func TestGetSliceSecretsFromFiles(t *testing.T) {
values := []string{"entry2", "", "entry3"}

// Create the temporary file which will contain a secret.
file, err := ioutil.TempFile(os.TempDir(), "watchtower-")
file, err := os.CreateTemp(t.TempDir(), "watchtower-")
require.NoError(t, err)
defer os.Remove(file.Name()) // Make sure to remove the temporary file later.

// Write the secret to the temporary file.
for _, value := range values {
_, err = file.WriteString("\n" + value)
require.NoError(t, err)
}
file.Close()
require.NoError(t, file.Close())

testGetSecretsFromFiles(t, "notification-url", `[entry1,entry2,entry3]`,
`--notification-url`, "entry1",
Expand Down Expand Up @@ -166,9 +157,7 @@ func TestProcessFlagAliases(t *testing.T) {

func TestProcessFlagAliasesLogLevelFromEnvironment(t *testing.T) {
cmd := new(cobra.Command)
err := os.Setenv("WATCHTOWER_DEBUG", `true`)
require.NoError(t, err)
defer os.Unsetenv("WATCHTOWER_DEBUG")
t.Setenv("WATCHTOWER_DEBUG", `true`)

SetDefaults()
RegisterDockerFlags(cmd)
Expand Down Expand Up @@ -202,9 +191,7 @@ func TestProcessFlagAliasesSchedAndInterval(t *testing.T) {
func TestProcessFlagAliasesScheduleFromEnvironment(t *testing.T) {
cmd := new(cobra.Command)

err := os.Setenv("WATCHTOWER_SCHEDULE", `@hourly`)
require.NoError(t, err)
defer os.Unsetenv("WATCHTOWER_SCHEDULE")
t.Setenv("WATCHTOWER_SCHEDULE", `@hourly`)

SetDefaults()
RegisterDockerFlags(cmd)
Expand Down

0 comments on commit 139f672

Please sign in to comment.