test(flags): ensure temp files are cleaned up (#1727)

pull/1732/head
nils måsén 1 year ago committed by GitHub
parent 32204a7c2d
commit 139f67270b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -4,7 +4,6 @@ import (
"bufio" "bufio"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"strings" "strings"
"time" "time"
@ -469,12 +468,14 @@ func GetSecretsFromFiles(rootCmd *cobra.Command) {
"notification-url", "notification-url",
} }
for _, secret := range secrets { 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. // 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) flag := flags.Lookup(secret)
if sliceValue, ok := flag.Value.(pflag.SliceValue); ok { if sliceValue, ok := flag.Value.(pflag.SliceValue); ok {
oldValues := sliceValue.GetSlice() oldValues := sliceValue.GetSlice()
@ -483,7 +484,7 @@ func getSecretFromFile(flags *pflag.FlagSet, secret string) {
if value != "" && isFile(value) { if value != "" && isFile(value) {
file, err := os.Open(value) file, err := os.Open(value)
if err != nil { if err != nil {
log.Fatal(err) return err
} }
scanner := bufio.NewScanner(file) scanner := bufio.NewScanner(file)
for scanner.Scan() { for scanner.Scan() {
@ -493,25 +494,26 @@ func getSecretFromFile(flags *pflag.FlagSet, secret string) {
} }
values = append(values, line) values = append(values, line)
} }
if err := file.Close(); err != nil {
return err
}
} else { } else {
values = append(values, value) values = append(values, value)
} }
} }
sliceValue.Replace(values) return sliceValue.Replace(values)
return
} }
value := flag.Value.String() value := flag.Value.String()
if value != "" && isFile(value) { if value != "" && isFile(value) {
file, err := ioutil.ReadFile(value) content, err := os.ReadFile(value)
if err != nil { if err != nil {
log.Fatal(err) return err
}
err = flags.Set(secret, strings.TrimSpace(string(file)))
if err != nil {
log.Error(err)
} }
return flags.Set(secret, strings.TrimSpace(string(content)))
} }
return nil
} }
func isFile(s string) bool { func isFile(s string) bool {
@ -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 // update schedule flag to match interval if it's set, or to the default if none of them are
if intervalChanged || !scheduleChanged { if intervalChanged || !scheduleChanged {
interval, _ := flags.GetInt(`interval`) interval, _ := flags.GetInt(`interval`)
flags.Set(`schedule`, fmt.Sprintf(`@every %ds`, interval)) _ = flags.Set(`schedule`, fmt.Sprintf(`@every %ds`, interval))
} }
if flagIsEnabled(flags, `debug`) { if flagIsEnabled(flags, `debug`) {
flags.Set(`log-level`, `debug`) _ = flags.Set(`log-level`, `debug`)
} }
if flagIsEnabled(flags, `trace`) { if flagIsEnabled(flags, `trace`) {
flags.Set(`log-level`, `trace`) _ = flags.Set(`log-level`, `trace`)
} }
} }
@ -593,7 +595,7 @@ func appendFlagValue(flags *pflag.FlagSet, name string, values ...string) error
if flagValues, ok := flag.Value.(pflag.SliceValue); ok { if flagValues, ok := flag.Value.(pflag.SliceValue); ok {
for _, value := range values { for _, value := range values {
flagValues.Append(value) _ = flagValues.Append(value)
} }
} else { } else {
return fmt.Errorf(`the value for flag %q is not a slice value`, name) return fmt.Errorf(`the value for flag %q is not a slice value`, name)

@ -1,20 +1,18 @@
package flags package flags
import ( import (
"io/ioutil"
"os"
"testing"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"os"
"testing"
) )
func TestEnvConfig_Defaults(t *testing.T) { func TestEnvConfig_Defaults(t *testing.T) {
// Unset testing environments own variables, since those are not what is under test // Unset testing environments own variables, since those are not what is under test
os.Unsetenv("DOCKER_TLS_VERIFY") _ = os.Unsetenv("DOCKER_TLS_VERIFY")
os.Unsetenv("DOCKER_HOST") _ = os.Unsetenv("DOCKER_HOST")
cmd := new(cobra.Command) cmd := new(cobra.Command)
SetDefaults() SetDefaults()
@ -48,10 +46,7 @@ func TestEnvConfig_Custom(t *testing.T) {
func TestGetSecretsFromFilesWithString(t *testing.T) { func TestGetSecretsFromFilesWithString(t *testing.T) {
value := "supersecretstring" value := "supersecretstring"
t.Setenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD", value)
err := os.Setenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD", value)
require.NoError(t, err)
defer os.Unsetenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD")
testGetSecretsFromFiles(t, "notification-email-server-password", value) testGetSecretsFromFiles(t, "notification-email-server-password", value)
} }
@ -60,18 +55,15 @@ func TestGetSecretsFromFilesWithFile(t *testing.T) {
value := "megasecretstring" value := "megasecretstring"
// Create the temporary file which will contain a secret. // 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) require.NoError(t, err)
defer os.Remove(file.Name()) // Make sure to remove the temporary file later.
// Write the secret to the temporary file. // Write the secret to the temporary file.
secret := []byte(value) _, err = file.Write([]byte(value))
_, err = file.Write(secret)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, file.Close())
err = os.Setenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD", file.Name()) t.Setenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD", file.Name())
require.NoError(t, err)
defer os.Unsetenv("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PASSWORD")
testGetSecretsFromFiles(t, "notification-email-server-password", value) testGetSecretsFromFiles(t, "notification-email-server-password", value)
} }
@ -80,16 +72,15 @@ func TestGetSliceSecretsFromFiles(t *testing.T) {
values := []string{"entry2", "", "entry3"} values := []string{"entry2", "", "entry3"}
// Create the temporary file which will contain a secret. // 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) require.NoError(t, err)
defer os.Remove(file.Name()) // Make sure to remove the temporary file later.
// Write the secret to the temporary file. // Write the secret to the temporary file.
for _, value := range values { for _, value := range values {
_, err = file.WriteString("\n" + value) _, err = file.WriteString("\n" + value)
require.NoError(t, err) require.NoError(t, err)
} }
file.Close() require.NoError(t, file.Close())
testGetSecretsFromFiles(t, "notification-url", `[entry1,entry2,entry3]`, testGetSecretsFromFiles(t, "notification-url", `[entry1,entry2,entry3]`,
`--notification-url`, "entry1", `--notification-url`, "entry1",
@ -166,9 +157,7 @@ func TestProcessFlagAliases(t *testing.T) {
func TestProcessFlagAliasesLogLevelFromEnvironment(t *testing.T) { func TestProcessFlagAliasesLogLevelFromEnvironment(t *testing.T) {
cmd := new(cobra.Command) cmd := new(cobra.Command)
err := os.Setenv("WATCHTOWER_DEBUG", `true`) t.Setenv("WATCHTOWER_DEBUG", `true`)
require.NoError(t, err)
defer os.Unsetenv("WATCHTOWER_DEBUG")
SetDefaults() SetDefaults()
RegisterDockerFlags(cmd) RegisterDockerFlags(cmd)
@ -202,9 +191,7 @@ func TestProcessFlagAliasesSchedAndInterval(t *testing.T) {
func TestProcessFlagAliasesScheduleFromEnvironment(t *testing.T) { func TestProcessFlagAliasesScheduleFromEnvironment(t *testing.T) {
cmd := new(cobra.Command) cmd := new(cobra.Command)
err := os.Setenv("WATCHTOWER_SCHEDULE", `@hourly`) t.Setenv("WATCHTOWER_SCHEDULE", `@hourly`)
require.NoError(t, err)
defer os.Unsetenv("WATCHTOWER_SCHEDULE")
SetDefaults() SetDefaults()
RegisterDockerFlags(cmd) RegisterDockerFlags(cmd)

Loading…
Cancel
Save