Simplify tests by testing.TempDir instead of os.MkdirTemp

Signed-off-by: Oleksandr Redko <Oleksandr_Redko@epam.com>
This commit is contained in:
Oleksandr Redko 2024-01-05 22:35:07 +02:00
parent b683ff68e1
commit a1db72dfa0
23 changed files with 135 additions and 328 deletions

View File

@ -16,8 +16,7 @@ import (
func TestCorruptedLayers(t *testing.T) { func TestCorruptedLayers(t *testing.T) {
// Regression tests for https://bugzilla.redhat.com/show_bug.cgi?id=1966872. // Regression tests for https://bugzilla.redhat.com/show_bug.cgi?id=1966872.
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
pullOptions.Writer = os.Stdout pullOptions.Writer = os.Stdout

View File

@ -17,8 +17,7 @@ func TestFilterReference(t *testing.T) {
busyboxLatest := "quay.io/libpod/busybox:latest" busyboxLatest := "quay.io/libpod/busybox:latest"
alpineLatest := "quay.io/libpod/alpine:latest" alpineLatest := "quay.io/libpod/alpine:latest"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
@ -93,8 +92,7 @@ func TestFilterDigest(t *testing.T) {
busyboxLatest := "quay.io/libpod/busybox:latest" busyboxLatest := "quay.io/libpod/busybox:latest"
alpineLatest := "quay.io/libpod/alpine:latest" alpineLatest := "quay.io/libpod/alpine:latest"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
@ -136,8 +134,7 @@ func TestFilterID(t *testing.T) {
busyboxLatest := "quay.io/libpod/busybox:latest" busyboxLatest := "quay.io/libpod/busybox:latest"
alpineLatest := "quay.io/libpod/alpine:latest" alpineLatest := "quay.io/libpod/alpine:latest"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
@ -175,8 +172,7 @@ func TestFilterManifest(t *testing.T) {
busyboxLatest := "quay.io/libpod/busybox:latest" busyboxLatest := "quay.io/libpod/busybox:latest"
alpineLatest := "quay.io/libpod/alpine:latest" alpineLatest := "quay.io/libpod/alpine:latest"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
@ -229,8 +225,7 @@ func TestFilterAfterSinceBeforeUntil(t *testing.T) {
busyboxLatest := "quay.io/libpod/busybox:latest" busyboxLatest := "quay.io/libpod/busybox:latest"
alpineLatest := "quay.io/libpod/alpine:latest" alpineLatest := "quay.io/libpod/alpine:latest"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
@ -282,8 +277,7 @@ func TestFilterIdLabel(t *testing.T) {
busyboxLatest := "quay.io/libpod/busybox:latest" busyboxLatest := "quay.io/libpod/busybox:latest"
alpineLatest := "quay.io/libpod/alpine:latest" alpineLatest := "quay.io/libpod/alpine:latest"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}

View File

@ -11,8 +11,7 @@ import (
) )
func TestHistory(t *testing.T) { func TestHistory(t *testing.T) {
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
name := "quay.io/libpod/alpine:3.10.2" name := "quay.io/libpod/alpine:3.10.2"

View File

@ -22,8 +22,7 @@ func TestImageFunctions(t *testing.T) {
busyboxLatest := busybox + ":latest" busyboxLatest := busybox + ":latest"
busyboxDigest := busybox + "@" busyboxDigest := busybox + "@"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
// Looking up image by invalid sha. // Looking up image by invalid sha.
@ -190,8 +189,7 @@ func TestLookupImage(t *testing.T) {
alpineNoTag := "quay.io/libpod/alpine" alpineNoTag := "quay.io/libpod/alpine"
alpineLatest := alpineNoTag + ":latest" alpineLatest := alpineNoTag + ":latest"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
@ -245,8 +243,7 @@ func TestLookupImage(t *testing.T) {
} }
func TestInspectHealthcheck(t *testing.T) { func TestInspectHealthcheck(t *testing.T) {
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
imageName := "quay.io/libpod/healthcheck:config-only" imageName := "quay.io/libpod/healthcheck:config-only"
@ -265,8 +262,7 @@ func TestInspectHealthcheck(t *testing.T) {
} }
func TestTag(t *testing.T) { func TestTag(t *testing.T) {
runtime, image, cleanup := getImageAndRuntime(t) runtime, image := getImageAndRuntime(t)
defer cleanup()
digest := "sha256:adab3844f497ab9171f070d4cae4114b5aec565ac772e2f2579405b78be67c96" digest := "sha256:adab3844f497ab9171f070d4cae4114b5aec565ac772e2f2579405b78be67c96"
@ -303,8 +299,7 @@ func TestTag(t *testing.T) {
} }
func TestTagAndUntagParallel(t *testing.T) { func TestTagAndUntagParallel(t *testing.T) {
runtime, image, cleanup := getImageAndRuntime(t) runtime, image := getImageAndRuntime(t)
defer cleanup()
tagCount := 10 tagCount := 10
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
@ -354,8 +349,7 @@ func TestTagAndUntagParallel(t *testing.T) {
} }
func TestUntag(t *testing.T) { func TestUntag(t *testing.T) {
runtime, image, cleanup := getImageAndRuntime(t) runtime, image := getImageAndRuntime(t)
defer cleanup()
digest := "sha256:adab3844f497ab9171f070d4cae4114b5aec565ac772e2f2579405b78be67c96" digest := "sha256:adab3844f497ab9171f070d4cae4114b5aec565ac772e2f2579405b78be67c96"
@ -394,12 +388,12 @@ func TestUntag(t *testing.T) {
require.ErrorIs(t, err, errUntagDigest, "check for specific digest error") require.ErrorIs(t, err, errUntagDigest, "check for specific digest error")
} }
func getImageAndRuntime(t *testing.T) (*Runtime, *Image, func()) { func getImageAndRuntime(t *testing.T) (*Runtime, *Image) {
// Note: this will resolve pull from the GCR registry (see // Note: this will resolve pull from the GCR registry (see
// testdata/registries.conf). // testdata/registries.conf).
busyboxLatest := "docker.io/library/busybox:latest" busyboxLatest := "docker.io/library/busybox:latest"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
@ -410,5 +404,5 @@ func getImageAndRuntime(t *testing.T) (*Runtime, *Image, func()) {
image := pulledImages[0] image := pulledImages[0]
return runtime, image, cleanup return runtime, image
} }

View File

@ -11,8 +11,7 @@ import (
) )
func TestImport(t *testing.T) { func TestImport(t *testing.T) {
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
importOptions := &ImportOptions{} importOptions := &ImportOptions{}

View File

@ -22,8 +22,7 @@ func TestLoad(t *testing.T) {
os.Unsetenv("TMPDIR") os.Unsetenv("TMPDIR")
}() }()
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
loadOptions := &LoadOptions{} loadOptions := &LoadOptions{}
loadOptions.Writer = os.Stdout loadOptions.Writer = os.Stdout

View File

@ -13,8 +13,7 @@ import (
) )
func TestCreateManifestList(t *testing.T) { func TestCreateManifestList(t *testing.T) {
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
list, err := runtime.CreateManifestList("mylist") list, err := runtime.CreateManifestList("mylist")
@ -44,8 +43,7 @@ func TestCreateManifestList(t *testing.T) {
// Inspect must contain both formats i.e OCIv1 and docker // Inspect must contain both formats i.e OCIv1 and docker
func TestInspectManifestListWithAnnotations(t *testing.T) { func TestInspectManifestListWithAnnotations(t *testing.T) {
listName := "testinspect" listName := "testinspect"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
list, err := runtime.CreateManifestList(listName) list, err := runtime.CreateManifestList(listName)
@ -84,8 +82,7 @@ func TestInspectManifestListWithAnnotations(t *testing.T) {
func TestCreateAndTagManifestList(t *testing.T) { func TestCreateAndTagManifestList(t *testing.T) {
tagName := "testlisttagged" tagName := "testlisttagged"
listName := "testlist" listName := "testlist"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
list, err := runtime.CreateManifestList(listName) list, err := runtime.CreateManifestList(listName)
@ -121,8 +118,7 @@ func TestCreateAndTagManifestList(t *testing.T) {
func TestCreateAndRemoveManifestList(t *testing.T) { func TestCreateAndRemoveManifestList(t *testing.T) {
tagName := "manifestlisttagged" tagName := "manifestlisttagged"
listName := "manifestlist" listName := "manifestlist"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
list, err := runtime.CreateManifestList(listName) list, err := runtime.CreateManifestList(listName)

View File

@ -4,7 +4,6 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
@ -50,10 +49,7 @@ func TestSaveLoad(t *testing.T) {
t.Skip("Test can only run as root") t.Skip("Test can only run as root")
} }
dir, err := os.MkdirTemp("", "manifests") dir := t.TempDir()
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(dir)
storeOptions := storage.StoreOptions{ storeOptions := storage.StoreOptions{
GraphRoot: filepath.Join(dir, "root"), GraphRoot: filepath.Join(dir, "root"),
RunRoot: filepath.Join(dir, "runroot"), RunRoot: filepath.Join(dir, "runroot"),
@ -168,10 +164,7 @@ func TestReference(t *testing.T) {
} }
ctx := context.Background() ctx := context.Background()
dir, err := os.MkdirTemp("", "manifests") dir := t.TempDir()
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(dir)
storeOptions := storage.StoreOptions{ storeOptions := storage.StoreOptions{
GraphRoot: filepath.Join(dir, "root"), GraphRoot: filepath.Join(dir, "root"),
RunRoot: filepath.Join(dir, "runroot"), RunRoot: filepath.Join(dir, "runroot"),
@ -268,10 +261,7 @@ func TestPushManifest(t *testing.T) {
} }
ctx := context.Background() ctx := context.Background()
dir, err := os.MkdirTemp("", "manifests") dir := t.TempDir()
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(dir)
storeOptions := storage.StoreOptions{ storeOptions := storage.StoreOptions{
GraphRoot: filepath.Join(dir, "root"), GraphRoot: filepath.Join(dir, "root"),
RunRoot: filepath.Join(dir, "runroot"), RunRoot: filepath.Join(dir, "runroot"),
@ -288,11 +278,7 @@ func TestPushManifest(t *testing.T) {
} }
}() }()
dest, err := os.MkdirTemp("", "manifests") destRef, err := alltransports.ParseImageName(fmt.Sprintf("dir:%s", t.TempDir()))
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(dest)
destRef, err := alltransports.ParseImageName(fmt.Sprintf("dir:%s", dest))
assert.Nilf(t, err, "ParseImageName()") assert.Nilf(t, err, "ParseImageName()")
ref, err := alltransports.ParseImageName(otherListImage) ref, err := alltransports.ParseImageName(otherListImage)

View File

@ -15,8 +15,7 @@ import (
) )
func TestPull(t *testing.T) { func TestPull(t *testing.T) {
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
pullOptions.Writer = os.Stdout pullOptions.Writer = os.Stdout
@ -81,8 +80,8 @@ func TestPull(t *testing.T) {
} }
func TestPullPlatforms(t *testing.T) { func TestPullPlatforms(t *testing.T) {
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
pullOptions.Writer = os.Stdout pullOptions.Writer = os.Stdout
@ -141,8 +140,7 @@ func TestPullPlatforms(t *testing.T) {
} }
func TestPullPlatformsWithEmptyRegistriesConf(t *testing.T) { func TestPullPlatformsWithEmptyRegistriesConf(t *testing.T) {
runtime, cleanup := testNewRuntime(t, testNewRuntimeOptions{registriesConfPath: "/dev/null"}) runtime := testNewRuntime(t, testNewRuntimeOptions{registriesConfPath: "/dev/null"})
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
pullOptions.Writer = os.Stdout pullOptions.Writer = os.Stdout
@ -171,8 +169,7 @@ func TestPullPlatformsWithEmptyRegistriesConf(t *testing.T) {
} }
func TestPullPolicy(t *testing.T) { func TestPullPolicy(t *testing.T) {
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
@ -191,8 +188,7 @@ func TestPullPolicy(t *testing.T) {
func TestShortNameAndIDconflict(t *testing.T) { func TestShortNameAndIDconflict(t *testing.T) {
// Regression test for https://github.com/containers/podman/issues/12761 // Regression test for https://github.com/containers/podman/issues/12761
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
pullOptions.Writer = os.Stdout pullOptions.Writer = os.Stdout
@ -228,8 +224,7 @@ func TestPullOCINoReference(t *testing.T) {
// specified reference is preserved in the image name. // specified reference is preserved in the image name.
busybox := "docker.io/library/busybox:latest" busybox := "docker.io/library/busybox:latest"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}
pullOptions.Writer = os.Stdout pullOptions.Writer = os.Stdout

View File

@ -16,8 +16,7 @@ import (
) )
func TestPush(t *testing.T) { func TestPush(t *testing.T) {
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
// Prefetch alpine. // Prefetch alpine.
@ -29,9 +28,7 @@ func TestPush(t *testing.T) {
pushOptions := &PushOptions{} pushOptions := &PushOptions{}
pushOptions.Writer = os.Stdout pushOptions.Writer = os.Stdout
workdir, err := os.MkdirTemp("", "libimagepush") workdir := t.TempDir()
require.NoError(t, err)
defer os.RemoveAll(workdir)
for _, test := range []struct { for _, test := range []struct {
source string source string
@ -77,8 +74,7 @@ func TestPush(t *testing.T) {
} }
func TestPushOtherPlatform(t *testing.T) { func TestPushOtherPlatform(t *testing.T) {
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
// Prefetch alpine. // Prefetch alpine.
@ -104,8 +100,7 @@ func TestPushOtherPlatform(t *testing.T) {
} }
func TestPushWithForceCompression(t *testing.T) { func TestPushWithForceCompression(t *testing.T) {
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
// Prefetch alpine. // Prefetch alpine.

View File

@ -16,8 +16,7 @@ func TestRemoveImages(t *testing.T) {
// testdata/registries.conf). // testdata/registries.conf).
busyboxLatest := "docker.io/library/busybox:latest" busyboxLatest := "docker.io/library/busybox:latest"
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
pullOptions := &PullOptions{} pullOptions := &PullOptions{}

View File

@ -24,12 +24,9 @@ type testNewRuntimeOptions struct {
registriesConfPath string registriesConfPath string
} }
// Create a new Runtime that can be used for testing. The second return value // Create a new Runtime that can be used for testing.
// is a clean-up function that should be called by users to make sure all func testNewRuntime(t *testing.T, options ...testNewRuntimeOptions) *Runtime {
// temporary test data gets removed. workdir := t.TempDir()
func testNewRuntime(t *testing.T, options ...testNewRuntimeOptions) (runtime *Runtime, cleanup func()) {
workdir, err := os.MkdirTemp("", "testStorageRuntime")
require.NoError(t, err)
storeOptions := &storage.StoreOptions{ storeOptions := &storage.StoreOptions{
RunRoot: workdir, RunRoot: workdir,
GraphRoot: workdir, GraphRoot: workdir,
@ -46,20 +43,17 @@ func testNewRuntime(t *testing.T, options ...testNewRuntimeOptions) (runtime *Ru
systemContext.SystemRegistriesConfPath = options[0].registriesConfPath systemContext.SystemRegistriesConfPath = options[0].registriesConfPath
} }
runtime, err = RuntimeFromStoreOptions(&RuntimeOptions{SystemContext: systemContext}, storeOptions) runtime, err := RuntimeFromStoreOptions(&RuntimeOptions{SystemContext: systemContext}, storeOptions)
require.NoError(t, err) require.NoError(t, err)
tmpd, err := tmpdir() tmpd, err := tmpdir()
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, runtime.systemContext.BigFilesTemporaryDir, tmpd) require.Equal(t, runtime.systemContext.BigFilesTemporaryDir, tmpd)
cleanup = func() { t.Cleanup(func() { _ = runtime.Shutdown(true) })
_ = runtime.Shutdown(true)
_ = os.RemoveAll(workdir)
}
sys := runtime.SystemContext() sys := runtime.SystemContext()
require.NotNil(t, sys) require.NotNil(t, sys)
return runtime, cleanup return runtime
} }
func TestTmpdir(t *testing.T) { func TestTmpdir(t *testing.T) {

View File

@ -13,8 +13,7 @@ import (
) )
func TestSave(t *testing.T) { func TestSave(t *testing.T) {
runtime, cleanup := testNewRuntime(t) runtime := testNewRuntime(t)
defer cleanup()
ctx := context.Background() ctx := context.Background()
// Prefetch alpine, busybox. // Prefetch alpine, busybox.
@ -73,9 +72,7 @@ func TestSave(t *testing.T) {
_, err = runtime.Load(ctx, imageCache.Name(), loadOptions) _, err = runtime.Load(ctx, imageCache.Name(), loadOptions)
require.NoError(t, err) require.NoError(t, err)
tmp, err := os.MkdirTemp("", "libimagesavetest") tmp := t.TempDir()
require.NoError(t, err)
defer os.RemoveAll(tmp)
if !test.isDir { if !test.isDir {
tmp += "/archive.tar" tmp += "/archive.tar"
} }

View File

@ -14,13 +14,6 @@ func TestDangerousHostPath(t *testing.T) {
t.Skip("Current paths are supported only by Linux") t.Skip("Current paths are supported only by Linux")
} }
// Create a temp dir that is not dangerous
td, err := os.MkdirTemp("/tmp", "validDir")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(td)
tests := []struct { tests := []struct {
Path string Path string
Expected bool Expected bool
@ -34,7 +27,7 @@ func TestDangerousHostPath(t *testing.T) {
"", "",
}, },
{ {
td, t.TempDir(), // Create a temp dir that is not dangerous
false, false,
false, false,
"", "",
@ -65,11 +58,7 @@ func TestChangeHostPathOwnership(t *testing.T) {
} }
// Create a temp dir that is not dangerous // Create a temp dir that is not dangerous
td, err := os.MkdirTemp("/tmp", "validDir") td := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(td)
// Get host path info // Get host path info
f, err := os.Lstat(td) f, err := os.Lstat(td)

View File

@ -2,7 +2,6 @@ package configmaps
import ( import (
"bytes" "bytes"
"os"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -10,28 +9,17 @@ import (
var drivertype = "file" var drivertype = "file"
var opts map[string]string func setup(t *testing.T) (manager *ConfigMapManager, opts map[string]string) {
testpath := t.TempDir()
func setup() (*ConfigMapManager, string, error) {
testpath, err := os.MkdirTemp("", "cmdata")
if err != nil {
return nil, "", err
}
manager, err := NewManager(testpath) manager, err := NewManager(testpath)
opts = map[string]string{"path": testpath} require.NoError(t, err)
return manager, testpath, err return manager, map[string]string{"path": testpath}
}
func cleanup(testpath string) {
os.RemoveAll(testpath)
} }
func TestAddSecretAndLookupData(t *testing.T) { func TestAddSecretAndLookupData(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
_, err = manager.Store("myconfigmap", []byte("mydata"), drivertype, opts) _, err := manager.Store("myconfigmap", []byte("mydata"), drivertype, opts)
require.NoError(t, err) require.NoError(t, err)
_, err = manager.lookupConfigMap("myconfigmap") _, err = manager.lookupConfigMap("myconfigmap")
@ -45,12 +33,10 @@ func TestAddSecretAndLookupData(t *testing.T) {
} }
func TestAddConfigMapName(t *testing.T) { func TestAddConfigMapName(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
// test one char configmap name // test one char configmap name
_, err = manager.Store("a", []byte("mydata"), drivertype, opts) _, err := manager.Store("a", []byte("mydata"), drivertype, opts)
require.NoError(t, err) require.NoError(t, err)
_, err = manager.lookupConfigMap("a") _, err = manager.lookupConfigMap("a")
@ -82,9 +68,7 @@ func TestAddConfigMapName(t *testing.T) {
} }
func TestAddMultipleConfigMaps(t *testing.T) { func TestAddMultipleConfigMaps(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
id, err := manager.Store("myconfigmap", []byte("mydata"), drivertype, opts) id, err := manager.Store("myconfigmap", []byte("mydata"), drivertype, opts)
require.NoError(t, err) require.NoError(t, err)
@ -116,11 +100,9 @@ func TestAddMultipleConfigMaps(t *testing.T) {
} }
func TestAddConfigMapDupName(t *testing.T) { func TestAddConfigMapDupName(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
_, err = manager.Store("myconfigmap", []byte("mydata"), drivertype, opts) _, err := manager.Store("myconfigmap", []byte("mydata"), drivertype, opts)
require.NoError(t, err) require.NoError(t, err)
_, err = manager.Store("myconfigmap", []byte("mydata"), drivertype, opts) _, err = manager.Store("myconfigmap", []byte("mydata"), drivertype, opts)
@ -128,9 +110,7 @@ func TestAddConfigMapDupName(t *testing.T) {
} }
func TestAddConfigMapPrefix(t *testing.T) { func TestAddConfigMapPrefix(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
// If the randomly generated configmap id is something like "abcdeiuoergnadufigh" // If the randomly generated configmap id is something like "abcdeiuoergnadufigh"
// we should still allow someone to store a configmap with the name "abcd" or "a" // we should still allow someone to store a configmap with the name "abcd" or "a"
@ -142,11 +122,9 @@ func TestAddConfigMapPrefix(t *testing.T) {
} }
func TestRemoveConfigMap(t *testing.T) { func TestRemoveConfigMap(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
_, err = manager.Store("myconfigmap", []byte("mydata"), drivertype, opts) _, err := manager.Store("myconfigmap", []byte("mydata"), drivertype, opts)
require.NoError(t, err) require.NoError(t, err)
_, err = manager.lookupConfigMap("myconfigmap") _, err = manager.lookupConfigMap("myconfigmap")
@ -163,18 +141,14 @@ func TestRemoveConfigMap(t *testing.T) {
} }
func TestRemoveConfigMapNoExist(t *testing.T) { func TestRemoveConfigMapNoExist(t *testing.T) {
manager, testpath, err := setup() manager, _ := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
_, err = manager.Delete("myconfigmap") _, err := manager.Delete("myconfigmap")
require.Error(t, err) require.Error(t, err)
} }
func TestLookupAllConfigMaps(t *testing.T) { func TestLookupAllConfigMaps(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
id, err := manager.Store("myconfigmap", []byte("mydata"), drivertype, opts) id, err := manager.Store("myconfigmap", []byte("mydata"), drivertype, opts)
require.NoError(t, err) require.NoError(t, err)
@ -186,9 +160,7 @@ func TestLookupAllConfigMaps(t *testing.T) {
} }
func TestInspectConfigMapId(t *testing.T) { func TestInspectConfigMapId(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
id, err := manager.Store("myconfigmap", []byte("mydata"), drivertype, opts) id, err := manager.Store("myconfigmap", []byte("mydata"), drivertype, opts)
require.NoError(t, err) require.NoError(t, err)
@ -209,20 +181,16 @@ func TestInspectConfigMapId(t *testing.T) {
} }
func TestInspectConfigMapBogus(t *testing.T) { func TestInspectConfigMapBogus(t *testing.T) {
manager, testpath, err := setup() manager, _ := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
_, err = manager.Lookup("bogus") _, err := manager.Lookup("bogus")
require.Error(t, err) require.Error(t, err)
} }
func TestConfigMapList(t *testing.T) { func TestConfigMapList(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
_, err = manager.Store("myconfigmap", []byte("mydata"), drivertype, opts) _, err := manager.Store("myconfigmap", []byte("mydata"), drivertype, opts)
require.NoError(t, err) require.NoError(t, err)
_, err = manager.Store("myconfigmap2", []byte("mydata2"), drivertype, opts) _, err = manager.Store("myconfigmap2", []byte("mydata2"), drivertype, opts)
require.NoError(t, err) require.NoError(t, err)

View File

@ -1,24 +1,14 @@
package filedriver package filedriver
import ( import (
"os"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func setup() (*Driver, error) {
tmppath, err := os.MkdirTemp("", "configmapsdata")
if err != nil {
return nil, err
}
return NewDriver(tmppath)
}
func TestStoreAndLookupConfigMapData(t *testing.T) { func TestStoreAndLookupConfigMapData(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.configMapsDataFilePath)
err = tstdriver.Store("unique_id", []byte("somedata")) err = tstdriver.Store("unique_id", []byte("somedata"))
require.NoError(t, err) require.NoError(t, err)
@ -29,9 +19,8 @@ func TestStoreAndLookupConfigMapData(t *testing.T) {
} }
func TestStoreDupID(t *testing.T) { func TestStoreDupID(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.configMapsDataFilePath)
err = tstdriver.Store("unique_id", []byte("somedata")) err = tstdriver.Store("unique_id", []byte("somedata"))
require.NoError(t, err) require.NoError(t, err)
@ -41,18 +30,16 @@ func TestStoreDupID(t *testing.T) {
} }
func TestLookupBogus(t *testing.T) { func TestLookupBogus(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.configMapsDataFilePath)
_, err = tstdriver.Lookup("bogus") _, err = tstdriver.Lookup("bogus")
require.Error(t, err) require.Error(t, err)
} }
func TestDeleteConfigMapData(t *testing.T) { func TestDeleteConfigMapData(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.configMapsDataFilePath)
err = tstdriver.Store("unique_id", []byte("somedata")) err = tstdriver.Store("unique_id", []byte("somedata"))
require.NoError(t, err) require.NoError(t, err)
@ -64,18 +51,16 @@ func TestDeleteConfigMapData(t *testing.T) {
} }
func TestDeleteConfigMapDataNotExist(t *testing.T) { func TestDeleteConfigMapDataNotExist(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.configMapsDataFilePath)
err = tstdriver.Delete("bogus") err = tstdriver.Delete("bogus")
require.Error(t, err) require.Error(t, err)
} }
func TestList(t *testing.T) { func TestList(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.configMapsDataFilePath)
err = tstdriver.Store("unique_id", []byte("somedata")) err = tstdriver.Store("unique_id", []byte("somedata"))
require.NoError(t, err) require.NoError(t, err)

View File

@ -147,10 +147,7 @@ func TestRunCwd(t *testing.T) {
Path: path, Path: path,
Args: []string{"sh", "-c", "pwd"}, Args: []string{"sh", "-c", "pwd"},
} }
cwd, err := os.MkdirTemp("", "userdata") cwd := t.TempDir()
if err != nil {
t.Fatal(err)
}
var stderr, stdout bytes.Buffer var stderr, stdout bytes.Buffer
hookErr, err := RunWithOptions(ctx, RunOptions{Hook: hook, Dir: cwd, State: []byte("{}"), Stdout: &stdout, Stderr: &stderr, PostKillTimeout: DefaultPostKillTimeout}) hookErr, err := RunWithOptions(ctx, RunOptions{Hook: hook, Dir: cwd, State: []byte("{}"), Stdout: &stdout, Stderr: &stderr, PostKillTimeout: DefaultPostKillTimeout})
if err != nil { if err != nil {

View File

@ -1,24 +1,14 @@
package filedriver package filedriver
import ( import (
"os"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func setup() (*Driver, error) {
tmppath, err := os.MkdirTemp("", "secretsdata")
if err != nil {
return nil, err
}
return NewDriver(tmppath)
}
func TestStoreAndLookupSecretData(t *testing.T) { func TestStoreAndLookupSecretData(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.secretsDataFilePath)
err = tstdriver.Store("unique_id", []byte("somedata")) err = tstdriver.Store("unique_id", []byte("somedata"))
require.NoError(t, err) require.NoError(t, err)
@ -29,9 +19,8 @@ func TestStoreAndLookupSecretData(t *testing.T) {
} }
func TestStoreDupID(t *testing.T) { func TestStoreDupID(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.secretsDataFilePath)
err = tstdriver.Store("unique_id", []byte("somedata")) err = tstdriver.Store("unique_id", []byte("somedata"))
require.NoError(t, err) require.NoError(t, err)
@ -41,18 +30,16 @@ func TestStoreDupID(t *testing.T) {
} }
func TestLookupBogus(t *testing.T) { func TestLookupBogus(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.secretsDataFilePath)
_, err = tstdriver.Lookup("bogus") _, err = tstdriver.Lookup("bogus")
require.Error(t, err) require.Error(t, err)
} }
func TestDeleteSecretData(t *testing.T) { func TestDeleteSecretData(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.secretsDataFilePath)
err = tstdriver.Store("unique_id", []byte("somedata")) err = tstdriver.Store("unique_id", []byte("somedata"))
require.NoError(t, err) require.NoError(t, err)
@ -64,18 +51,16 @@ func TestDeleteSecretData(t *testing.T) {
} }
func TestDeleteSecretDataNotExist(t *testing.T) { func TestDeleteSecretDataNotExist(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.secretsDataFilePath)
err = tstdriver.Delete("bogus") err = tstdriver.Delete("bogus")
require.Error(t, err) require.Error(t, err)
} }
func TestList(t *testing.T) { func TestList(t *testing.T) {
tstdriver, err := setup() tstdriver, err := NewDriver(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tstdriver.secretsDataFilePath)
err = tstdriver.Store("unique_id", []byte("somedata")) err = tstdriver.Store("unique_id", []byte("somedata"))
require.NoError(t, err) require.NoError(t, err)

View File

@ -3,7 +3,6 @@ package passdriver
import ( import (
"context" "context"
"fmt" "fmt"
"os"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -11,13 +10,11 @@ import (
const gpgTestID = "testing@passdriver" const gpgTestID = "testing@passdriver"
func setupDriver(t *testing.T) (driver *Driver, cleanup func()) { func setupDriver(t *testing.T) *Driver {
base, err := os.MkdirTemp(os.TempDir(), "pass-test") base := t.TempDir()
require.NoError(t, err) gpghomedir := t.TempDir()
gpghomedir, err := os.MkdirTemp(os.TempDir(), "gpg-dir")
require.NoError(t, err)
driver, err = NewDriver(map[string]string{ driver, err := NewDriver(map[string]string{
"root": base, "root": base,
"key": gpgTestID, "key": gpgTestID,
"gpghomedir": gpghomedir, "gpghomedir": gpghomedir,
@ -27,10 +24,7 @@ func setupDriver(t *testing.T) (driver *Driver, cleanup func()) {
err = driver.gpg(context.TODO(), nil, nil, "--batch", "--passphrase", "--quick-generate-key", "testing@passdriver") err = driver.gpg(context.TODO(), nil, nil, "--batch", "--passphrase", "--quick-generate-key", "testing@passdriver")
require.NoError(t, err) require.NoError(t, err)
return driver, func() { return driver
os.RemoveAll(base)
os.RemoveAll(gpghomedir)
}
} }
func TestStoreAndLookup(t *testing.T) { func TestStoreAndLookup(t *testing.T) {
@ -67,8 +61,7 @@ func TestStoreAndLookup(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
tc := tc tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
driver, cleanup := setupDriver(t) driver := setupDriver(t)
defer cleanup()
err := driver.Store(tc.key, tc.value) err := driver.Store(tc.key, tc.value)
if tc.expStoreErr != nil { if tc.expStoreErr != nil {
require.Error(t, err) require.Error(t, err)
@ -89,8 +82,7 @@ func TestStoreAndLookup(t *testing.T) {
} }
func TestLookup(t *testing.T) { func TestLookup(t *testing.T) {
driver, cleanup := setupDriver(t) driver := setupDriver(t)
defer cleanup()
// prepare a valid lookup target // prepare a valid lookup target
err := driver.Store("valid", []byte("abc")) err := driver.Store("valid", []byte("abc"))
@ -133,8 +125,7 @@ func TestLookup(t *testing.T) {
} }
func TestList(t *testing.T) { func TestList(t *testing.T) {
driver, cleanup := setupDriver(t) driver := setupDriver(t)
defer cleanup()
require.NoError(t, driver.Store("a", []byte("abc"))) require.NoError(t, driver.Store("a", []byte("abc")))
require.NoError(t, driver.Store("b", []byte("abc"))) require.NoError(t, driver.Store("b", []byte("abc")))
require.NoError(t, driver.Store("c", []byte("abc"))) require.NoError(t, driver.Store("c", []byte("abc")))
@ -145,8 +136,7 @@ func TestList(t *testing.T) {
} }
func TestDelete(t *testing.T) { func TestDelete(t *testing.T) {
driver, cleanup := setupDriver(t) driver := setupDriver(t)
defer cleanup()
require.NoError(t, driver.Store("a", []byte("abc"))) require.NoError(t, driver.Store("a", []byte("abc")))
cases := []struct { cases := []struct {

View File

@ -2,7 +2,6 @@ package secrets
import ( import (
"bytes" "bytes"
"os"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -10,26 +9,15 @@ import (
var drivertype = "file" var drivertype = "file"
var opts map[string]string func setup(t *testing.T) (manager *SecretsManager, opts map[string]string) {
testpath := t.TempDir()
func setup() (*SecretsManager, string, error) {
testpath, err := os.MkdirTemp("", "secretsdata")
if err != nil {
return nil, "", err
}
manager, err := NewManager(testpath) manager, err := NewManager(testpath)
opts = map[string]string{"path": testpath} require.NoError(t, err)
return manager, testpath, err return manager, map[string]string{"path": testpath}
}
func cleanup(testpath string) {
os.RemoveAll(testpath)
} }
func TestAddSecretAndLookupData(t *testing.T) { func TestAddSecretAndLookupData(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
metaData := make(map[string]string) metaData := make(map[string]string)
metaData["immutable"] = "true" metaData["immutable"] = "true"
@ -92,9 +80,7 @@ func TestAddSecretAndLookupData(t *testing.T) {
} }
func TestAddSecretName(t *testing.T) { func TestAddSecretName(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
storeOpts := StoreOptions{ storeOpts := StoreOptions{
DriverOpts: opts, DriverOpts: opts,
@ -104,7 +90,7 @@ func TestAddSecretName(t *testing.T) {
for _, value := range []string{"a", "user@mail.com", longstring[:253]} { for _, value := range []string{"a", "user@mail.com", longstring[:253]} {
// test one char secret name // test one char secret name
_, err = manager.Store(value, []byte("mydata"), drivertype, storeOpts) _, err := manager.Store(value, []byte("mydata"), drivertype, storeOpts)
require.NoError(t, err) require.NoError(t, err)
_, err = manager.lookupSecret(value) _, err = manager.lookupSecret(value)
@ -112,15 +98,13 @@ func TestAddSecretName(t *testing.T) {
} }
for _, value := range []string{"", "chocolate,vanilla", "file/path", "foo=bar", "bad\000Null", longstring[:254]} { for _, value := range []string{"", "chocolate,vanilla", "file/path", "foo=bar", "bad\000Null", longstring[:254]} {
_, err = manager.Store(value, []byte("mydata"), drivertype, storeOpts) _, err := manager.Store(value, []byte("mydata"), drivertype, storeOpts)
require.Error(t, err) require.Error(t, err)
} }
} }
func TestAddMultipleSecrets(t *testing.T) { func TestAddMultipleSecrets(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
storeOpts := StoreOptions{ storeOpts := StoreOptions{
DriverOpts: opts, DriverOpts: opts,
@ -156,15 +140,13 @@ func TestAddMultipleSecrets(t *testing.T) {
} }
func TestAddSecretDupName(t *testing.T) { func TestAddSecretDupName(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
storeOpts := StoreOptions{ storeOpts := StoreOptions{
DriverOpts: opts, DriverOpts: opts,
} }
_, err = manager.Store("mysecret", []byte("mydata"), drivertype, storeOpts) _, err := manager.Store("mysecret", []byte("mydata"), drivertype, storeOpts)
require.NoError(t, err) require.NoError(t, err)
_, err = manager.Store("mysecret", []byte("mydata"), drivertype, storeOpts) _, err = manager.Store("mysecret", []byte("mydata"), drivertype, storeOpts)
@ -172,9 +154,7 @@ func TestAddSecretDupName(t *testing.T) {
} }
func TestAddSecretPrefix(t *testing.T) { func TestAddSecretPrefix(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
storeOpts := StoreOptions{ storeOpts := StoreOptions{
DriverOpts: opts, DriverOpts: opts,
@ -190,15 +170,13 @@ func TestAddSecretPrefix(t *testing.T) {
} }
func TestRemoveSecret(t *testing.T) { func TestRemoveSecret(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
storeOpts := StoreOptions{ storeOpts := StoreOptions{
DriverOpts: opts, DriverOpts: opts,
} }
_, err = manager.Store("mysecret", []byte("mydata"), drivertype, storeOpts) _, err := manager.Store("mysecret", []byte("mydata"), drivertype, storeOpts)
require.NoError(t, err) require.NoError(t, err)
_, err = manager.lookupSecret("mysecret") _, err = manager.lookupSecret("mysecret")
@ -215,18 +193,14 @@ func TestRemoveSecret(t *testing.T) {
} }
func TestRemoveSecretNoExist(t *testing.T) { func TestRemoveSecretNoExist(t *testing.T) {
manager, testpath, err := setup() manager, _ := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
_, err = manager.Delete("mysecret") _, err := manager.Delete("mysecret")
require.Error(t, err) require.Error(t, err)
} }
func TestLookupAllSecrets(t *testing.T) { func TestLookupAllSecrets(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
storeOpts := StoreOptions{ storeOpts := StoreOptions{
DriverOpts: opts, DriverOpts: opts,
@ -242,9 +216,7 @@ func TestLookupAllSecrets(t *testing.T) {
} }
func TestInspectSecretId(t *testing.T) { func TestInspectSecretId(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
storeOpts := StoreOptions{ storeOpts := StoreOptions{
DriverOpts: opts, DriverOpts: opts,
@ -269,24 +241,20 @@ func TestInspectSecretId(t *testing.T) {
} }
func TestInspectSecretBogus(t *testing.T) { func TestInspectSecretBogus(t *testing.T) {
manager, testpath, err := setup() manager, _ := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
_, err = manager.Lookup("bogus") _, err := manager.Lookup("bogus")
require.Error(t, err) require.Error(t, err)
} }
func TestSecretList(t *testing.T) { func TestSecretList(t *testing.T) {
manager, testpath, err := setup() manager, opts := setup(t)
require.NoError(t, err)
defer cleanup(testpath)
storeOpts := StoreOptions{ storeOpts := StoreOptions{
DriverOpts: opts, DriverOpts: opts,
} }
_, err = manager.Store("mysecret", []byte("mydata"), drivertype, storeOpts) _, err := manager.Store("mysecret", []byte("mydata"), drivertype, storeOpts)
require.NoError(t, err) require.NoError(t, err)
_, err = manager.Store("mysecret2", []byte("mydata2"), drivertype, storeOpts) _, err = manager.Store("mysecret2", []byte("mydata2"), drivertype, storeOpts)
require.NoError(t, err) require.NoError(t, err)

View File

@ -2,23 +2,21 @@ package shelldriver
import ( import (
"fmt" "fmt"
"os"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func setupDriver(t *testing.T) (driver *Driver, cleanup func()) { func setupDriver(t *testing.T) *Driver {
base, err := os.MkdirTemp(os.TempDir(), "external-driver-test") base := t.TempDir()
require.NoError(t, err) driver, err := NewDriver(map[string]string{
driver, err = NewDriver(map[string]string{
"delete": fmt.Sprintf("rm %s/${SECRET_ID}", base), "delete": fmt.Sprintf("rm %s/${SECRET_ID}", base),
"list": fmt.Sprintf("ls %s", base), "list": fmt.Sprintf("ls %s", base),
"lookup": fmt.Sprintf("cat %s/${SECRET_ID} ", base), "lookup": fmt.Sprintf("cat %s/${SECRET_ID} ", base),
"store": fmt.Sprintf("cat - > %s/${SECRET_ID}", base), "store": fmt.Sprintf("cat - > %s/${SECRET_ID}", base),
}) })
require.NoError(t, err) require.NoError(t, err)
return driver, func() { os.RemoveAll(base) } return driver
} }
func TestStoreAndLookup(t *testing.T) { func TestStoreAndLookup(t *testing.T) {
@ -55,8 +53,7 @@ func TestStoreAndLookup(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
tc := tc tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
driver, cleanup := setupDriver(t) driver := setupDriver(t)
defer cleanup()
err := driver.Store(tc.key, tc.value) err := driver.Store(tc.key, tc.value)
if tc.expStoreErr != nil { if tc.expStoreErr != nil {
require.Error(t, err) require.Error(t, err)
@ -77,8 +74,7 @@ func TestStoreAndLookup(t *testing.T) {
} }
func TestLookup(t *testing.T) { func TestLookup(t *testing.T) {
driver, cleanup := setupDriver(t) driver := setupDriver(t)
defer cleanup()
// prepare a valid lookup target // prepare a valid lookup target
err := driver.Store("valid", []byte("abc")) err := driver.Store("valid", []byte("abc"))
@ -121,8 +117,7 @@ func TestLookup(t *testing.T) {
} }
func TestList(t *testing.T) { func TestList(t *testing.T) {
driver, cleanup := setupDriver(t) driver := setupDriver(t)
defer cleanup()
require.NoError(t, driver.Store("a", []byte("abc"))) require.NoError(t, driver.Store("a", []byte("abc")))
require.NoError(t, driver.Store("b", []byte("abc"))) require.NoError(t, driver.Store("b", []byte("abc")))
require.NoError(t, driver.Store("c", []byte("abc"))) require.NoError(t, driver.Store("c", []byte("abc")))
@ -133,8 +128,7 @@ func TestList(t *testing.T) {
} }
func TestDelete(t *testing.T) { func TestDelete(t *testing.T) {
driver, cleanup := setupDriver(t) driver := setupDriver(t)
defer cleanup()
require.NoError(t, driver.Store("a", []byte("abc"))) require.NoError(t, driver.Store("a", []byte("abc")))
cases := []struct { cases := []struct {

View File

@ -8,7 +8,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"os"
"runtime" "runtime"
"testing" "testing"
"time" "time"
@ -103,11 +102,10 @@ func makeManifest(layer, config []byte) v1.Manifest {
} }
} }
func makeImage(t *testing.T, arch, osStr string) (ref types.ImageReference, dir string, layer, config, manifest []byte) { func makeImage(t *testing.T, arch, osStr string) (ref types.ImageReference, layer, config, manifest []byte) {
ctx := context.TODO() ctx := context.TODO()
dir, err := os.MkdirTemp("", "supplemented") dir := t.TempDir()
assert.Nilf(t, err, "error creating temporary directory")
layerBytes := makeLayer(t) layerBytes := makeLayer(t)
cb := makeConfig(arch, osStr, layer) cb := makeConfig(arch, osStr, layer)
@ -141,7 +139,7 @@ func makeImage(t *testing.T, arch, osStr string) (ref types.ImageReference, dir
err = dest.Commit(ctx, nil) err = dest.Commit(ctx, nil)
assert.Nilf(t, err, "error committing image to 'dir:%s'", dir) assert.Nilf(t, err, "error committing image to 'dir:%s'", dir)
return ref, dir, layerBytes, configBytes, manifestBytes return ref, layerBytes, configBytes, manifestBytes
} }
func TestSupplemented(t *testing.T) { func TestSupplemented(t *testing.T) {
@ -157,29 +155,18 @@ func TestSupplemented(t *testing.T) {
policyContext, err := signature.NewPolicyContext(defaultPolicy) policyContext, err := signature.NewPolicyContext(defaultPolicy)
assert.Nilf(t, err, "error obtaining policy context") assert.Nilf(t, err, "error obtaining policy context")
ref1, dir1, layer1, config1, manifest1 := makeImage(t, runtime.GOARCH, runtime.GOOS) ref1, layer1, config1, manifest1 := makeImage(t, runtime.GOARCH, runtime.GOOS)
defer os.RemoveAll(dir1)
digest1, err := manifest.Digest(manifest1) digest1, err := manifest.Digest(manifest1)
assert.Nilf(t, err, "error digesting manifest") assert.Nilf(t, err, "error digesting manifest")
ref2, dir2, layer2, config2, manifest2 := makeImage(t, arch2, runtime.GOOS) ref2, layer2, config2, manifest2 := makeImage(t, arch2, runtime.GOOS)
defer os.RemoveAll(dir2)
digest2, err := manifest.Digest(manifest2) digest2, err := manifest.Digest(manifest2)
assert.Nilf(t, err, "error digesting manifest") assert.Nilf(t, err, "error digesting manifest")
ref3, dir3, layer3, config3, manifest3 := makeImage(t, arch3, runtime.GOOS) ref3, layer3, config3, manifest3 := makeImage(t, arch3, runtime.GOOS)
defer os.RemoveAll(dir3)
digest3, err := manifest.Digest(manifest3) digest3, err := manifest.Digest(manifest3)
assert.Nilf(t, err, "error digesting manifest") assert.Nilf(t, err, "error digesting manifest")
multidir, err := os.MkdirTemp("", "supplemented")
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(multidir)
destDir, err := os.MkdirTemp("", "supplemented")
assert.Nilf(t, err, "error creating temporary directory")
defer os.RemoveAll(destDir)
index := v1.Index{ index := v1.Index{
Versioned: specs.Versioned{ Versioned: specs.Versioned{
SchemaVersion: 2, SchemaVersion: 2,
@ -220,9 +207,11 @@ func TestSupplemented(t *testing.T) {
indexDigest, err := manifest.Digest(indexBytes) indexDigest, err := manifest.Digest(indexBytes)
assert.Nilf(t, err, "error digesting image index") assert.Nilf(t, err, "error digesting image index")
destDir := t.TempDir()
destRef, err := alltransports.ParseImageName(fmt.Sprintf("dir:%s", destDir)) destRef, err := alltransports.ParseImageName(fmt.Sprintf("dir:%s", destDir))
assert.Nilf(t, err, "error parsing reference 'dir:%s'", destDir) assert.Nilf(t, err, "error parsing reference 'dir:%s'", destDir)
multidir := t.TempDir()
multiRef, err := alltransports.ParseImageName(fmt.Sprintf("dir:%s", multidir)) multiRef, err := alltransports.ParseImageName(fmt.Sprintf("dir:%s", multidir))
assert.Nilf(t, err, "error parsing reference 'dir:%s'", multidir) assert.Nilf(t, err, "error parsing reference 'dir:%s'", multidir)
destImg, err := multiRef.NewImageDestination(ctx, sys) destImg, err := multiRef.NewImageDestination(ctx, sys)

View File

@ -12,12 +12,10 @@ import (
) )
func TestReadProcBool(t *testing.T) { func TestReadProcBool(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "test-sysinfo-proc") tmpDir := t.TempDir()
require.NoError(t, err)
defer os.RemoveAll(tmpDir)
procFile := filepath.Join(tmpDir, "read-proc-bool") procFile := filepath.Join(tmpDir, "read-proc-bool")
err = os.WriteFile(procFile, []byte("1"), 0o644) err := os.WriteFile(procFile, []byte("1"), 0o644)
require.NoError(t, err) require.NoError(t, err)
if !readProcBool(procFile) { if !readProcBool(procFile) {
@ -37,15 +35,13 @@ func TestReadProcBool(t *testing.T) {
} }
func TestCgroupEnabled(t *testing.T) { func TestCgroupEnabled(t *testing.T) {
cgroupDir, err := os.MkdirTemp("", "cgroup-test") cgroupDir := t.TempDir()
require.NoError(t, err)
defer os.RemoveAll(cgroupDir)
if cgroupEnabled(cgroupDir, "test") { if cgroupEnabled(cgroupDir, "test") {
t.Fatal("cgroupEnabled should be false") t.Fatal("cgroupEnabled should be false")
} }
err = os.WriteFile(path.Join(cgroupDir, "test"), []byte{}, 0o644) err := os.WriteFile(path.Join(cgroupDir, "test"), []byte{}, 0o644)
require.NoError(t, err) require.NoError(t, err)
if !cgroupEnabled(cgroupDir, "test") { if !cgroupEnabled(cgroupDir, "test") {