diff --git a/internal/tmpdir/tmpdir.go b/internal/tmpdir/tmpdir.go index 9cfde4e72c4..b33b0fee2c7 100644 --- a/internal/tmpdir/tmpdir.go +++ b/internal/tmpdir/tmpdir.go @@ -17,10 +17,8 @@ func GetTempDir() string { } logrus.Warnf("ignoring TMPDIR from environment, evaluating it: %v", err) } - containerConfig, err := config.Default() - if err != nil { - tmpdir, err := containerConfig.ImageCopyTmpDir() - if err != nil { + if containerConfig, err := config.Default(); err == nil { + if tmpdir, err := containerConfig.ImageCopyTmpDir(); err == nil { return tmpdir } } diff --git a/internal/tmpdir/tmpdir_test.go b/internal/tmpdir/tmpdir_test.go new file mode 100644 index 00000000000..3da9048afdf --- /dev/null +++ b/internal/tmpdir/tmpdir_test.go @@ -0,0 +1,49 @@ +package tmpdir + +import ( + "os" + "testing" + + "github.com/containers/common/pkg/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGetTempDir(t *testing.T) { + // test default + err := os.Unsetenv("TMPDIR") + require.NoError(t, err) + err = os.Setenv("CONTAINERS_CONF", "/dev/null") + require.NoError(t, err) + tmpdir := GetTempDir() + assert.Equal(t, "/var/tmp", tmpdir) + + // test TMPDIR Environment + err = os.Setenv("TMPDIR", "/tmp/bogus") + require.NoError(t, err) + tmpdir = GetTempDir() + assert.Equal(t, tmpdir, "/tmp/bogus") + err = os.Unsetenv("TMPDIR") + require.NoError(t, err) + + f, err := os.CreateTemp("", "containers.conf-") + require.NoError(t, err) + // close and remove the temporary file at the end of the program + defer f.Close() + defer os.Remove(f.Name()) + data := []byte("[engine]\nimage_copy_tmp_dir=\"/mnt\"\n") + _, err = f.Write(data) + require.NoError(t, err) + + err = os.Setenv("CONTAINERS_CONF", f.Name()) + require.NoError(t, err) + // force config reset of default containers.conf + options := config.Options{ + SetDefault: true, + } + _, err = config.New(&options) + require.NoError(t, err) + tmpdir = GetTempDir() + assert.Equal(t, "/mnt", tmpdir) + +}