From 9dfa7c3ae621c4c98b7027a1283db80de4e7677b Mon Sep 17 00:00:00 2001 From: Andrei Aaron Date: Fri, 5 Dec 2025 09:54:38 +0200 Subject: [PATCH] refactor(test): new apis for creating temporary files (#3605) Replace MakeTempFile usage with MakeTempFilePath and MakeTempFileWithContent helpers that automatically handle file lifecycle. This prevents resource leaks by ensuring temporary files are properly closed. Shoudld also make the tests easier to read. Signed-off-by: Andrei Aaron --- pkg/api/authn_test.go | 12 +- pkg/api/config/redis/redis_test.go | 5 +- pkg/api/controller_test.go | 240 +-- pkg/api/htpasswd_test.go | 42 +- pkg/api/routes_test.go | 5 +- pkg/cli/client/client_test.go | 33 +- pkg/cli/client/config_cmd_test.go | 87 +- pkg/cli/client/cve_cmd_internal_test.go | 82 +- pkg/cli/client/cve_cmd_test.go | 123 +- pkg/cli/client/elevated_test.go | 4 +- pkg/cli/client/image_cmd_internal_test.go | 111 +- pkg/cli/client/image_cmd_test.go | 45 +- pkg/cli/client/repo_test.go | 4 +- pkg/cli/client/search_cmd_internal_test.go | 7 +- pkg/cli/client/search_cmd_test.go | 93 +- .../client/search_functions_internal_test.go | 13 +- pkg/cli/client/server_info_cmd_test.go | 3 +- pkg/cli/server/config_reloader_test.go | 122 +- pkg/cli/server/extensions_test.go | 409 ++--- pkg/cli/server/root_test.go | 1580 ++++++----------- pkg/cli/server/stress_test.go | 30 +- pkg/cli/server/verify_retention_test.go | 111 +- pkg/debug/pprof/pprof_test.go | 5 +- .../extension_events_disabled_test.go | 8 +- .../extension_image_trust_disabled_test.go | 4 +- pkg/extensions/extension_image_trust_test.go | 43 +- pkg/extensions/extension_ui_test.go | 5 +- pkg/extensions/extensions_test.go | 142 +- .../get_extensions_disabled_test.go | 8 +- pkg/extensions/imagetrust/image_trust_test.go | 13 +- pkg/extensions/monitoring/monitoring_test.go | 15 +- pkg/extensions/scrub/scrub_test.go | 66 +- pkg/extensions/search/cve/cve_test.go | 27 +- pkg/extensions/search/cve/scan_test.go | 16 +- pkg/extensions/search/cve/update_test.go | 8 +- pkg/extensions/search/search_test.go | 10 +- pkg/extensions/search/userprefs_test.go | 19 +- pkg/extensions/sync/sync_disabled_test.go | 8 +- pkg/extensions/sync/sync_internal_test.go | 22 +- pkg/extensions/sync/sync_test.go | 156 +- pkg/log/log_test.go | 4 +- pkg/scheduler/scheduler_test.go | 82 +- pkg/storage/local/local_test.go | 25 +- pkg/test/common/fs.go | 38 +- pkg/test/common/fs_test.go | 42 +- pkg/test/image-utils/upload_test.go | 6 +- 46 files changed, 1321 insertions(+), 2612 deletions(-) diff --git a/pkg/api/authn_test.go b/pkg/api/authn_test.go index 2cb91da6..56407634 100644 --- a/pkg/api/authn_test.go +++ b/pkg/api/authn_test.go @@ -99,9 +99,7 @@ func TestAPIKeys(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) mockOIDCServer, err := authutils.MockOIDCRun() if err != nil { @@ -871,9 +869,7 @@ func TestAPIKeysOpenDBError(t *testing.T) { conf := config.New() username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) mockOIDCServer, err := authutils.MockOIDCRun() if err != nil { @@ -1154,9 +1150,7 @@ func TestCookieSecureFlag(t *testing.T) { username, _ := test.GenerateRandomString() password, _ := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) mockOIDCConfig := mockOIDCServer.Config() defaultVal := true diff --git a/pkg/api/config/redis/redis_test.go b/pkg/api/config/redis/redis_test.go index cf227ef2..090606a0 100644 --- a/pkg/api/config/redis/redis_test.go +++ b/pkg/api/config/redis/redis_test.go @@ -15,12 +15,13 @@ import ( rediscfg "zotregistry.dev/zot/v2/pkg/api/config/redis" "zotregistry.dev/zot/v2/pkg/cli/server" "zotregistry.dev/zot/v2/pkg/log" + test "zotregistry.dev/zot/v2/pkg/test/common" ) func TestRedisLogger(t *testing.T) { Convey("Print using Redis logger", t, func() { - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - So(err, ShouldBeNil) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() writers := io.MultiWriter(os.Stdout, logFile) logger := log.NewLoggerWithWriter("debug", writers) diff --git a/pkg/api/controller_test.go b/pkg/api/controller_test.go index bd6fe851..7c9e4212 100644 --- a/pkg/api/controller_test.go +++ b/pkg/api/controller_test.go @@ -493,13 +493,11 @@ func TestAutoPortSelection(t *testing.T) { conf := config.New() conf.HTTP.Port = "0" - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // clean up - ctlr := makeController(conf, t.TempDir()) cm := test.NewControllerManager(ctlr) @@ -508,12 +506,7 @@ func TestAutoPortSelection(t *testing.T) { defer cm.StopServer() - file, err := os.Open(logFile.Name()) - So(err, ShouldBeNil) - - defer file.Close() - - scanner := bufio.NewScanner(file) + scanner := bufio.NewScanner(logFile) var contents bytes.Buffer @@ -736,8 +729,7 @@ func TestHtpasswdSingleCred(t *testing.T) { conf := config.New() conf.HTTP.Port = port - htpasswdPath := test.MakeHtpasswdFileFromString(testString) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, testString) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ Path: htpasswdPath, @@ -790,9 +782,7 @@ func TestAllowMethodsHeader(t *testing.T) { simpleUser := "simpleUser" simpleUserPassword := "simpleUserPass" - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(simpleUser, simpleUserPassword)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(simpleUser, simpleUserPassword)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -883,8 +873,7 @@ func TestHtpasswdTwoCreds(t *testing.T) { conf := config.New() conf.HTTP.Port = port - htpasswdPath := test.MakeHtpasswdFileFromString(testString) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, testString) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -935,9 +924,7 @@ func TestHtpasswdFiveCreds(t *testing.T) { baseURL := test.GetBaseURL(port) conf := config.New() conf.HTTP.Port = port - htpasswdPath := test.MakeHtpasswdFileFromString(credString.String()) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, credString.String()) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ Path: htpasswdPath, @@ -1081,9 +1068,7 @@ func TestBasicAuth(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -1370,9 +1355,7 @@ func TestScaleOutRequestProxy(t *testing.T) { username, _ := test.GenerateRandomString() password, _ := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) resty.SetTLSClientConfig(&tls.Config{RootCAs: caCertPool, MinVersion: tls.VersionTLS12}) @@ -1655,13 +1638,11 @@ func TestPrintTracebackOnPanic(t *testing.T) { conf := config.New() conf.HTTP.Port = port - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // clean up - ctlr := makeController(conf, t.TempDir()) cm := test.NewControllerManager(ctlr) @@ -1942,9 +1923,7 @@ func TestMultipleInstance(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -1986,9 +1965,7 @@ func TestMultipleInstance(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -2036,9 +2013,7 @@ func TestMultipleInstance(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -2090,9 +2065,7 @@ func TestTLSWithBasicAuth(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) port := test.GetFreePort() baseURL := test.GetBaseURL(port) @@ -2161,9 +2134,7 @@ func TestTLSWithBasicAuthAllowReadAccess(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) port := test.GetFreePort() baseURL := test.GetBaseURL(port) @@ -2835,9 +2806,7 @@ func TestTLSMutualAndBasicAuth(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) port := test.GetFreePort() baseURL := test.GetBaseURL(port) @@ -2922,9 +2891,7 @@ func TestTLSMutualAndBasicAuthAllowReadAccess(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) port := test.GetFreePort() baseURL := test.GetBaseURL(port) @@ -4588,9 +4555,7 @@ func TestOpenIDMiddleware(t *testing.T) { // need a username different than ldap one, to test both logic htpasswdUsername, seedUser := test.GenerateRandomString() htpasswdPassword, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(htpasswdUsername, htpasswdPassword)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(htpasswdUsername, htpasswdPassword)) ldapServer := newTestLDAPServer() port = test.GetFreePort() @@ -5004,9 +4969,7 @@ func TestOpenIDMiddlewareWithRedisSessionDriver(t *testing.T) { // need a username different than ldap one, to test both logic htpasswdUsername, seedUser := test.GenerateRandomString() htpasswdPassword, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(htpasswdUsername, htpasswdPassword)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(htpasswdUsername, htpasswdPassword)) ldapServer := newTestLDAPServer() port = test.GetFreePort() @@ -5490,9 +5453,7 @@ func TestAuthnSessionErrors(t *testing.T) { htpasswdUsername, seedUser := test.GenerateRandomString() htpasswdPassword, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(htpasswdUsername, htpasswdPassword)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(htpasswdUsername, htpasswdPassword)) ldapServer := newTestLDAPServer() port = test.GetFreePort() @@ -5895,9 +5856,7 @@ func TestAuthnMetaDBErrors(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) mockOIDCServer, err := authutils.MockOIDCRun() if err != nil { @@ -6008,9 +5967,7 @@ func TestAuthorization(t *testing.T) { conf.HTTP.Port = port username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -6128,9 +6085,7 @@ func TestGetUsername(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf := config.New() conf.HTTP.Port = port @@ -6201,9 +6156,7 @@ func TestAuthorizationMountBlob(t *testing.T) { content := test.GetBcryptCredString(username1, password1) + test.GetBcryptCredString(username2, password2) - htpasswdPath := test.MakeHtpasswdFileFromString(content) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, content) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -6557,9 +6510,7 @@ func TestAuthorizationWithAnonymousPolicyBasicAuthAndSessionHeader(t *testing.T) badpassphrase := "bad" htpasswdUsername, seedUser := test.GenerateRandomString() htpasswdPassword, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(htpasswdUsername, htpasswdPassword)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(htpasswdUsername, htpasswdPassword)) img := CreateRandomImage() tagAnonymous := "1.0-anon" @@ -6769,9 +6720,7 @@ func TestAuthorizationWithMultiplePolicies(t *testing.T) { password2, seedPass2 := test.GenerateRandomString() content := test.GetBcryptCredString(username1, password1) + test.GetBcryptCredString(username2, password2) - htpasswdPath := test.MakeHtpasswdFileFromString(content) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, content) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -6926,9 +6875,7 @@ func TestInvalidCases(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -7005,8 +6952,7 @@ func TestHTTPReadOnly(t *testing.T) { }, } - htpasswdPath := test.MakeHtpasswdFileFromString(testString) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, testString) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ Path: htpasswdPath, @@ -7057,9 +7003,7 @@ func TestCrossRepoMount(t *testing.T) { conf.HTTP.Port = port username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -7272,9 +7216,7 @@ func TestCrossRepoMount(t *testing.T) { conf := config.New() conf.HTTP.Port = port - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -7416,11 +7358,7 @@ func TestParallelRequests(t *testing.T) { conf.HTTP.Port = port username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - t.Cleanup(func() { - os.Remove(htpasswdPath) - }) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -8979,9 +8917,7 @@ func TestPagedRepositoriesWithAuthorization(t *testing.T) { conf.HTTP.Port = port username, _ := test.GenerateRandomString() password, _ := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -11882,11 +11818,8 @@ func TestGCSignaturesAndUntaggedManifestsWithMetaDB(t *testing.T) { baseURL := test.GetBaseURL(port) conf := config.New() conf.HTTP.Port = port - - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - conf.Log.Audit = logFile.Name() + conf.Log.Output = test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Audit = test.MakeTempFilePath(t, "zot-audit.log") value := true searchConfig := &extconf.SearchConfig{ @@ -11898,10 +11831,8 @@ func TestGCSignaturesAndUntaggedManifestsWithMetaDB(t *testing.T) { Search: searchConfig, } - ctlr := makeController(conf, t.TempDir()) - dir := t.TempDir() - ctlr.Config.Storage.RootDirectory = dir + ctlr := makeController(conf, dir) ctlr.Config.Storage.GC = true ctlr.Config.Storage.GCDelay = 1 * time.Millisecond ctlr.Config.Storage.Retention = config.ImageRetention{ @@ -11930,7 +11861,7 @@ func TestGCSignaturesAndUntaggedManifestsWithMetaDB(t *testing.T) { img := CreateDefaultImage() - err = UploadImage(img, baseURL, repoName, tag) + err := UploadImage(img, baseURL, repoName, tag) So(err, ShouldBeNil) gc := gc.NewGarbageCollect(ctlr.StoreController.DefaultStore, ctlr.MetaDB, @@ -12143,10 +12074,8 @@ func TestGCSignaturesAndUntaggedManifestsWithMetaDB(t *testing.T) { conf := config.New() conf.HTTP.Port = port - ctlr := makeController(conf, t.TempDir()) - dir := t.TempDir() - ctlr.Config.Storage.RootDirectory = dir + ctlr := makeController(conf, dir) ctlr.Config.Storage.GC = true ctlr.Config.Storage.GCDelay = 1 * time.Second ctlr.Config.Storage.Retention = config.ImageRetention{ @@ -12244,12 +12173,8 @@ func TestPeriodicGC(t *testing.T) { conf.HTTP.Port = port conf.Storage.RemoteCache = false - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - conf.Log.Output = logFile.Name() - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath ctlr := api.NewController(conf) dir := t.TempDir() @@ -12259,7 +12184,7 @@ func TestPeriodicGC(t *testing.T) { ctlr.Config.Storage.GCInterval = 1 * time.Hour ctlr.Config.Storage.GCDelay = 1 * time.Second - err = WriteImageToFileSystem(CreateDefaultImage(), repoName, "0.0.1", + err := WriteImageToFileSystem(CreateDefaultImage(), repoName, "0.0.1", ociutils.GetDefaultStoreController(dir, ctlr.Log)) So(err, ShouldBeNil) @@ -12270,7 +12195,7 @@ func TestPeriodicGC(t *testing.T) { time.Sleep(5000 * time.Millisecond) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "\"GC\":true,\"Commit\":false,\"GCDelay\":1000000000,\"GCInterval\":3600000000000") @@ -12285,12 +12210,8 @@ func TestPeriodicGC(t *testing.T) { conf := config.New() conf.HTTP.Port = port - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - conf.Log.Output = logFile.Name() - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath dir := t.TempDir() ctlr := makeController(conf, dir) @@ -12314,7 +12235,7 @@ func TestPeriodicGC(t *testing.T) { defer cm.StopServer() - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) // periodic GC is enabled by default for default store with a default interval @@ -12334,12 +12255,8 @@ func TestPeriodicGC(t *testing.T) { conf.HTTP.Port = port conf.Storage.RemoteCache = false - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - conf.Log.Output = logFile.Name() - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath ctlr := api.NewController(conf) dir := t.TempDir() @@ -12350,7 +12267,7 @@ func TestPeriodicGC(t *testing.T) { ctlr.Config.Storage.GCInterval = 1 * time.Hour ctlr.Config.Storage.GCDelay = 1 * time.Second - err = WriteImageToFileSystem(CreateDefaultImage(), repoName, "0.0.1", + err := WriteImageToFileSystem(CreateDefaultImage(), repoName, "0.0.1", ociutils.GetDefaultStoreController(dir, ctlr.Log)) So(err, ShouldBeNil) @@ -12367,7 +12284,7 @@ func TestPeriodicGC(t *testing.T) { time.Sleep(5000 * time.Millisecond) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "\"GC\":true,\"Commit\":false,\"GCDelay\":1000000000,\"GCInterval\":3600000000000") @@ -12390,9 +12307,7 @@ func TestSearchRoutes(t *testing.T) { password1 := "test" testString1 := test.GetBcryptCredString(user1, password1) - htpasswdPath := test.MakeHtpasswdFileFromString(testString1) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, testString1) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -12533,9 +12448,7 @@ func TestSearchRoutes(t *testing.T) { group1 := "testgroup3" testString1 := test.GetBcryptCredString(user1, password1) - htpasswdPath := test.MakeHtpasswdFileFromString(testString1) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, testString1) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -12620,9 +12533,7 @@ func TestSearchRoutes(t *testing.T) { group1 := "testgroup1" group2 := "secondtestgroup" testString1 := test.GetBcryptCredString(user1, password1) - htpasswdPath := test.MakeHtpasswdFileFromString(testString1) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, testString1) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ Path: htpasswdPath, @@ -12690,9 +12601,7 @@ func TestSearchRoutes(t *testing.T) { password1 := "test3" group1 := "testgroup" testString1 := test.GetBcryptCredString(user1, password1) - htpasswdPath := test.MakeHtpasswdFileFromString(testString1) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, testString1) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ Path: htpasswdPath, @@ -12761,9 +12670,7 @@ func TestSearchRoutes(t *testing.T) { group1 := "testgroup1" testString1 := test.GetBcryptCredString(user1, password1) - htpasswdPath := test.MakeHtpasswdFileFromString(testString1) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, testString1) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -12832,9 +12739,7 @@ func TestSearchRoutes(t *testing.T) { password1 := "test5" group1 := "testgroup2" testString1 := test.GetBcryptCredString(user1, password1) - htpasswdPath := test.MakeHtpasswdFileFromString(testString1) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, testString1) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ Path: htpasswdPath, @@ -12891,8 +12796,8 @@ func TestSearchRoutes(t *testing.T) { user1, seedUser1 := test.GenerateRandomString() password1, seedPass1 := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(user1, password1)) - defer os.Remove(htpasswdPath) + tempDir := t.TempDir() + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(user1, password1)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -12955,6 +12860,7 @@ func TestDistSpecExtensions(t *testing.T) { baseURL := test.GetBaseURL(port) conf.HTTP.Port = port + conf.Log.Output = test.MakeTempFilePath(t, "zot-log.txt") defaultVal := true @@ -12969,13 +12875,6 @@ func TestDistSpecExtensions(t *testing.T) { conf.Extensions.Trust.Cosign = defaultVal conf.Extensions.Trust.Notation = defaultVal - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - conf.Log.Output = logFile.Name() - - defer os.Remove(logFile.Name()) // clean up - ctlr := makeController(conf, t.TempDir()) cm := test.NewControllerManager(ctlr) @@ -13019,13 +12918,7 @@ func TestDistSpecExtensions(t *testing.T) { conf.Extensions = &extconf.ExtensionConfig{} conf.Extensions.Search = &extconf.SearchConfig{} conf.Extensions.Search.Enable = &defaultVal - - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - conf.Log.Output = logFile.Name() - - defer os.Remove(logFile.Name()) // clean up + conf.Log.Output = test.MakeTempFilePath(t, "zot-log.txt") ctlr := makeController(conf, t.TempDir()) @@ -13067,12 +12960,7 @@ func TestDistSpecExtensions(t *testing.T) { conf.HTTP.Port = port - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - conf.Log.Output = logFile.Name() - - defer os.Remove(logFile.Name()) // clean up + conf.Log.Output = test.MakeTempFilePath(t, "zot-log.txt") ctlr := makeController(conf, t.TempDir()) @@ -13100,13 +12988,7 @@ func TestDistSpecExtensions(t *testing.T) { baseURL := test.GetBaseURL(port) conf.HTTP.Port = port - - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - conf.Log.Output = logFile.Name() - - defer os.Remove(logFile.Name()) // clean up + conf.Log.Output = test.MakeTempFilePath(t, "zot-log.txt") ctlr := makeController(conf, t.TempDir()) diff --git a/pkg/api/htpasswd_test.go b/pkg/api/htpasswd_test.go index d7260c6c..1b841ec3 100644 --- a/pkg/api/htpasswd_test.go +++ b/pkg/api/htpasswd_test.go @@ -20,9 +20,7 @@ func TestHTPasswdWatcherOriginal(t *testing.T) { username, _ := test.GenerateRandomString() password1, _ := test.GenerateRandomString() password2, _ := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password1)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password1)) htp := api.NewHTPasswd(logger) @@ -99,11 +97,8 @@ func TestHTPasswdWatcher(t *testing.T) { username2, _ := test.GenerateRandomString() password2, _ := test.GenerateRandomString() - htpasswdPath1 := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username1, password1)) - htpasswdPath2 := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username2, password2)) - - defer os.Remove(htpasswdPath1) - defer os.Remove(htpasswdPath2) + htpasswdPath1 := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username1, password1)) + htpasswdPath2 := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username2, password2)) htp := api.NewHTPasswd(logger) htw, err := api.NewHTPasswdWatcher(htp, "") @@ -196,11 +191,8 @@ func TestHTPasswdWatcher(t *testing.T) { username2, _ := test.GenerateRandomString() password2, _ := test.GenerateRandomString() - htpasswdPath1 := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username1, password1)) - htpasswdPath2 := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username2, password2)) - - defer os.Remove(htpasswdPath1) - defer os.Remove(htpasswdPath2) + htpasswdPath1 := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username1, password1)) + htpasswdPath2 := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username2, password2)) htp := api.NewHTPasswd(capturingLogger) htw, err := api.NewHTPasswdWatcher(htp, htpasswdPath1) @@ -238,8 +230,7 @@ func TestHTPasswdWatcher(t *testing.T) { So(present, ShouldBeTrue) // Test file rename (should not trigger reload) - htpasswdPath3 := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username1, password1)) - defer os.Remove(htpasswdPath3) + htpasswdPath3 := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username1, password1)) err = htw.ChangeFile(htpasswdPath3) So(err, ShouldBeNil) time.Sleep(10 * time.Millisecond) @@ -307,11 +298,8 @@ func TestHTPasswdWatcher(t *testing.T) { username2, _ := test.GenerateRandomString() password2, _ := test.GenerateRandomString() - htpasswdPath1 := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username1, password1)) - htpasswdPath2 := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username2, password2)) - - defer os.Remove(htpasswdPath1) - defer os.Remove(htpasswdPath2) + htpasswdPath1 := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username1, password1)) + htpasswdPath2 := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username2, password2)) htp := api.NewHTPasswd(capturingLogger) htw, err := api.NewHTPasswdWatcher(htp, "") @@ -413,9 +401,7 @@ func TestHTPasswdWatcher(t *testing.T) { // Test 2: File watching with fsnotify resources cleanup username, _ := test.GenerateRandomString() password, _ := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) htp2 := api.NewHTPasswd(capturingLogger) htw2, err := api.NewHTPasswdWatcher(htp2, htpasswdPath) @@ -477,8 +463,7 @@ func TestHTPasswdWatcher(t *testing.T) { htp := api.NewHTPasswd(capturingLogger) // Test file with only colons (malformed) - colonPath := test.MakeHtpasswdFileFromString(":::") - defer os.Remove(colonPath) + colonPath := test.MakeHtpasswdFileFromString(t, ":::") htw1, err := api.NewHTPasswdWatcher(htp, colonPath) So(err, ShouldBeNil) htw1.Run() @@ -496,9 +481,7 @@ func TestHTPasswdWatcher(t *testing.T) { // Test file with empty lines and comments content := "\n\n" + test.GetBcryptCredString(username, password) + "\n# comment\n" - commentedPath := test.MakeHtpasswdFileFromString(content) - - defer os.Remove(commentedPath) + commentedPath := test.MakeHtpasswdFileFromString(t, content) htw2, err := api.NewHTPasswdWatcher(htp, commentedPath) So(err, ShouldBeNil) htw2.Run() @@ -525,8 +508,7 @@ func TestHTPasswdWatcher(t *testing.T) { So(err, ShouldBeNil) // Load some initial data - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) // Load initial file (this will populate the store) err = htw.ChangeFile(htpasswdPath) diff --git a/pkg/api/routes_test.go b/pkg/api/routes_test.go index 415141ec..572c76a2 100644 --- a/pkg/api/routes_test.go +++ b/pkg/api/routes_test.go @@ -9,7 +9,6 @@ import ( "io" "net/http" "net/http/httptest" - "os" "testing" "github.com/google/uuid" @@ -45,9 +44,7 @@ func TestRoutes(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) mockOIDCServer, err := mockoidc.Run() if err != nil { diff --git a/pkg/cli/client/client_test.go b/pkg/cli/client/client_test.go index a45cc39d..5f7410c5 100644 --- a/pkg/cli/client/client_test.go +++ b/pkg/cli/client/client_test.go @@ -35,7 +35,7 @@ const ( ServerKey = "../../../test/data/server.key" CACert = "../../../test/data/ca.crt" sourceCertsDir = "../../../test/data" - certsDir1 = "/.config/containers/certs.d/127.0.0.1:8088/" + certsDir1 = ".config/containers/certs.d/127.0.0.1:8088" ) func TestTLSWithAuth(t *testing.T) { @@ -54,8 +54,7 @@ func TestTLSWithAuth(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -83,9 +82,9 @@ func TestTLSWithAuth(t *testing.T) { defer cm.StopServer() Convey("Test with htpassw auth", func() { - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","showspinner":false}]}`) + // Use the HOME that makeConfigFile set (temp directory) for certificates home := os.Getenv("HOME") destCertsDir := filepath.Join(home, certsDir1) err := test.CopyTestKeysAndCerts(destCertsDir) @@ -105,10 +104,15 @@ func TestTLSWithAuth(t *testing.T) { args = []string{"list", "--config", "imagetest"} - configPath = makeConfigFile( + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s%s%s","showspinner":false}]}`, BaseSecureURL1, constants.RoutePrefix, constants.ExtCatalogPrefix)) - defer os.Remove(configPath) + + // Ensure certificates are in the HOME directory that makeConfigFile set + home = os.Getenv("HOME") + destCertsDir = filepath.Join(home, certsDir1) + err = test.CopyTestKeysAndCerts(destCertsDir) + So(err, ShouldBeNil) imageCmd = client.NewImageCommand(client.NewSearchService()) imageBuff = bytes.NewBufferString("") @@ -122,10 +126,9 @@ func TestTLSWithAuth(t *testing.T) { user := fmt.Sprintf("%s:%s", username, password) args = []string{"-u", user, "--config", "imagetest"} - configPath = makeConfigFile( + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s%s%s","showspinner":false}]}`, BaseSecureURL1, constants.RoutePrefix, constants.ExtCatalogPrefix)) - defer os.Remove(configPath) imageCmd = client.NewImageCommand(client.NewSearchService()) imageBuff = bytes.NewBufferString("") @@ -170,10 +173,9 @@ func TestTLSWithoutAuth(t *testing.T) { defer cm.StopServer() Convey("Certs in user's home", func() { - configPath := makeConfigFile( + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s%s%s","showspinner":false}]}`, BaseSecureURL1, constants.RoutePrefix, constants.ExtCatalogPrefix)) - defer os.Remove(configPath) home := os.Getenv("HOME") destCertsDir := filepath.Join(home, certsDir1) @@ -223,10 +225,9 @@ func TestTLSBadCerts(t *testing.T) { defer cm.StopServer() Convey("Test with system certs", func() { - configPath := makeConfigFile( + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s%s%s","showspinner":false}]}`, BaseSecureURL3, constants.RoutePrefix, constants.ExtCatalogPrefix)) - defer os.Remove(configPath) args := []string{"list", "--config", "imagetest"} imageCmd := client.NewImageCommand(client.NewSearchService()) @@ -241,8 +242,10 @@ func TestTLSBadCerts(t *testing.T) { }) } -func makeConfigFile(content string) string { - os.Setenv("HOME", os.TempDir()) +func makeConfigFile(t *testing.T, content string) string { + t.Helper() + tempDir := t.TempDir() + os.Setenv("HOME", tempDir) home, err := os.UserHomeDir() if err != nil { diff --git a/pkg/cli/client/config_cmd_test.go b/pkg/cli/client/config_cmd_test.go index acc3e4f9..3d74a413 100644 --- a/pkg/cli/client/config_cmd_test.go +++ b/pkg/cli/client/config_cmd_test.go @@ -20,8 +20,7 @@ func TestConfigCmdBasics(t *testing.T) { Convey("Test config help", t, func() { args := []string{"--help"} - configPath := makeConfigFile("showspinner = false") - defer os.Remove(configPath) + _ = makeConfigFile(t, "showspinner = false") cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -36,8 +35,7 @@ func TestConfigCmdBasics(t *testing.T) { Convey("with the shorthand", func() { args[0] = "-h" - configPath := makeConfigFile("showspinner = false") - defer os.Remove(configPath) + _ = makeConfigFile(t, "showspinner = false") cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -54,8 +52,7 @@ func TestConfigCmdBasics(t *testing.T) { Convey("Test config no args", t, func() { args := []string{} - configPath := makeConfigFile("showspinner = false") - defer os.Remove(configPath) + _ = makeConfigFile(t, "showspinner = false") cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -73,8 +70,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test add config", t, func() { args := []string{"add", "configtest1", "https://test-url.com"} - file := makeConfigFile("") - defer os.Remove(file) + configPath := makeConfigFile(t, "") cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -83,7 +79,7 @@ func TestConfigCmdMain(t *testing.T) { cmd.SetArgs(args) _ = cmd.Execute() - actual, err := os.ReadFile(file) + actual, err := os.ReadFile(configPath) if err != nil { panic(err) } @@ -95,8 +91,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test error on home directory", t, func() { args := []string{"add", "configtest1", "https://test-url.com"} - file := makeConfigFile("") - defer os.Remove(file) + _ = makeConfigFile(t, "") err := os.Setenv("HOME", "nonExistentDirectory") if err != nil { @@ -125,8 +120,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test error on home directory at new add config", t, func() { args := []string{"add", "configtest1", "https://test-url.com"} - file := makeConfigFile("") - defer os.Remove(file) + _ = makeConfigFile(t, "") err := os.Setenv("HOME", "nonExistentDirectory") if err != nil { @@ -155,8 +149,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test add config with invalid format", t, func() { args := []string{"--list"} - configPath := makeConfigFile(`{"configs":{"_name":"configtest","url":"https://test-url.com","showspinner":false}}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":{"_name":"configtest","url":"https://test-url.com","showspinner":false}}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -170,8 +163,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test add config with invalid URL", t, func() { args := []string{"add", "configtest1", "test..com"} - file := makeConfigFile("") - defer os.Remove(file) + _ = makeConfigFile(t, "") cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -186,8 +178,8 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test remove config entry successfully", t, func() { args := []string{"remove", "configtest"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + configPath := makeConfigFile(t, + `{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -206,8 +198,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test remove missing config entry", t, func() { args := []string{"remove", "configtest"} - configPath := makeConfigFile(`{"configs":[]`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[]`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -222,8 +213,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test remove bad config file content", t, func() { args := []string{"remove", "configtest"} - configPath := makeConfigFile(`{"asdf":[]`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"asdf":[]`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -238,8 +228,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test remove bad config file entry", t, func() { args := []string{"remove", "configtest"} - configPath := makeConfigFile(`{"configs":[asdad]`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[asdad]`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -253,11 +242,11 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test remove config bad permissions", t, func() { args := []string{"remove", "configtest"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) + configPath := makeConfigFile(t, + `{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) defer func() { _ = os.Chmod(configPath, 0o600) - os.Remove(configPath) }() err := os.Chmod(configPath, 0o400) // Read-only, so we fail only on updating the file, not reading @@ -276,8 +265,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test fetch all config", t, func() { args := []string{"--list"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -292,8 +280,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("with the shorthand", func() { args := []string{"-l"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -310,8 +297,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("From empty file", func() { args := []string{"-l"} - configPath := makeConfigFile(``) - defer os.Remove(configPath) + _ = makeConfigFile(t, ``) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -329,8 +315,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test fetch a config", t, func() { args := []string{"configtest", "--list"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -347,8 +332,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("with the shorthand", func() { args := []string{"configtest", "-l"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -366,8 +350,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("From empty file", func() { args := []string{"configtest", "-l"} - configPath := makeConfigFile(``) - defer os.Remove(configPath) + _ = makeConfigFile(t, ``) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -385,8 +368,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test fetch a config val", t, func() { args := []string{"configtest", "url"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -401,8 +383,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("From empty file", func() { args := []string{"configtest", "url"} - configPath := makeConfigFile(``) - defer os.Remove(configPath) + _ = makeConfigFile(t, ``) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -420,8 +401,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test add a config val", t, func() { args := []string{"configtest", "showspinner", "false"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com"}]}`) - defer os.Remove(configPath) + configPath := makeConfigFile(t, `{"configs":[{"_name":"configtest","url":"https://test-url.com"}]}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -443,8 +423,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("To an empty file", func() { args := []string{"configtest", "showspinner", "false"} - configPath := makeConfigFile(``) - defer os.Remove(configPath) + _ = makeConfigFile(t, ``) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -462,8 +441,8 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test overwrite a config", t, func() { args := []string{"configtest", "url", "https://new-url.com"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + configPath := makeConfigFile(t, + `{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -487,8 +466,8 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test reset a config val", t, func() { args := []string{"configtest", "showspinner", "--reset"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + configPath := makeConfigFile(t, + `{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -511,8 +490,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test reset a url", t, func() { args := []string{"configtest", "url", "--reset"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") @@ -529,8 +507,7 @@ func TestConfigCmdMain(t *testing.T) { Convey("Test add a config with an existing saved name", t, func() { args := []string{"add", "configtest", "https://test-url.com/new"} - configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) cmd := client.NewConfigCommand() buff := bytes.NewBufferString("") diff --git a/pkg/cli/client/cve_cmd_internal_test.go b/pkg/cli/client/cve_cmd_internal_test.go index 5c0f0a80..6cd12fb2 100644 --- a/pkg/cli/client/cve_cmd_internal_test.go +++ b/pkg/cli/client/cve_cmd_internal_test.go @@ -7,7 +7,6 @@ import ( "context" "errors" "fmt" - "os" "regexp" "strconv" "strings" @@ -47,8 +46,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE help", t, func() { args := []string{"--help"} - configPath := makeConfigFile("") - defer os.Remove(configPath) + _ = makeConfigFile(t, "") cmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -64,8 +62,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE help - with the shorthand", t, func() { args := []string{"-h"} - configPath := makeConfigFile("") - defer os.Remove(configPath) + _ = makeConfigFile(t, "") cmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -81,8 +78,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE no url", t, func() { args := []string{"affected", "CVE-cveIdRandom", "--config", "cvetest"} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -97,8 +93,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE invalid url", t, func() { args := []string{"list", "dummyImageName:tag", "--url", "invalidUrl"} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cmd := NewCVECommand(new(searchService)) buff := bytes.NewBufferString("") @@ -114,8 +109,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE invalid url port", t, func() { args := []string{"list", "dummyImageName:tag", "--url", "http://localhost:99999"} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cmd := NewCVECommand(new(searchService)) buff := bytes.NewBufferString("") @@ -130,8 +124,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE unreachable", t, func() { args := []string{"list", "dummyImageName:tag", "--url", "http://localhost:9999"} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cmd := NewCVECommand(new(searchService)) buff := bytes.NewBufferString("") @@ -145,8 +138,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE url from config", t, func() { args := []string{"list", "dummyImageName:tag", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, baseURL)) cmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -177,8 +169,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test debug flag", t, func() { args := []string{"list", "dummyImageName:tag", "--debug", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, baseURL)) cmd := NewCVECommand(new(searchService)) buff := bytes.NewBufferString("") @@ -195,8 +186,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE by name and CVE ID - long option", t, func() { args := []string{"affected", "CVE-CVEID", "--repo", "dummyImageName", "--url", baseURL} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -215,8 +205,7 @@ func TestSearchCVECmd(t *testing.T) { args := []string{"affected", "CVE-CVEID", "--repo", "dummyImageName", "--url", baseURL} buff := bytes.NewBufferString("") - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(new(mockService)) cveCmd.SetOut(buff) @@ -233,8 +222,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE by image name - in text format", t, func() { args := []string{"list", "dummyImageName:tag", "--url", baseURL} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -265,8 +253,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE by image name - in text format - in verbose mode", t, func() { args := []string{"list", "dummyImageName:tag", "--url", baseURL, "--verbose"} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -304,8 +291,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE by image name - in json format", t, func() { args := []string{"list", "dummyImageName:tag", "--url", baseURL, "-f", "json"} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -326,8 +312,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE by image name - in yaml format", t, func() { args := []string{"list", "dummyImageName:tag", "--url", baseURL, "-f", "yaml"} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -346,8 +331,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test CVE by image name - invalid format", t, func() { args := []string{"list", "dummyImageName:tag", "--url", baseURL, "-f", "random"} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -366,8 +350,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test images by CVE ID - positive", t, func() { args := []string{"affected", "CVE-CVEID", "--repo", "anImage", "--url", baseURL} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -385,8 +368,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test images by CVE ID - positive with retries", t, func() { args := []string{"affected", "CVE-CVEID", "--repo", "anImage", "--url", baseURL} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) mockService := mockServiceForRetry{succeedOn: 2} // CVE info will be provided in 2nd attempt cveCmd := NewCVECommand(&mockService) @@ -408,8 +390,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test images by CVE ID - failed after retries", t, func() { args := []string{"affected", "CVE-CVEID", "--url", baseURL} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) mockService := mockServiceForRetry{succeedOn: -1} // CVE info will be unavailable on all retries cveCmd := NewCVECommand(&mockService) @@ -431,8 +412,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test images by CVE ID - invalid CVE ID", t, func() { args := []string{"affected", "CVE-invalidCVEID", "--config", "cvetest"} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -446,8 +426,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test images by CVE ID - invalid url", t, func() { args := []string{"affected", "CVE-CVEID", "--url", "invalidURL"} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(NewSearchService()) buff := bytes.NewBufferString("") @@ -463,8 +442,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test fixed tags by and image name CVE ID - positive", t, func() { args := []string{"fixed", "fixedImage", "CVE-CVEID", "--url", baseURL} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(new(mockService)) buff := bytes.NewBufferString("") @@ -482,8 +460,7 @@ func TestSearchCVECmd(t *testing.T) { Convey("Test fixed tags by and image name CVE ID - invalid image name", t, func() { args := []string{"affected", "CVE-CVEID", "--image", "invalidImageName", "--config", "cvetest"} - configPath := makeConfigFile(`{"configs":[{"_name":"cvetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"cvetest","showspinner":false}]}`) cveCmd := NewCVECommand(NewSearchService()) buff := bytes.NewBufferString("") @@ -516,8 +493,7 @@ func TestCVECommandGQL(t *testing.T) { defer cm.StopServer() Convey("commands without gql", t, func() { - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, baseURL)) Convey("cveid", func() { args := []string{"affected", "CVE-1942", "--config", "cvetest"} @@ -538,9 +514,8 @@ func TestCVECommandGQL(t *testing.T) { count := 0 args := []string{"affected", "CVE-12345", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) cmd := NewCVECommand(mockService{ getTagsForCVEGQLFn: func(ctx context.Context, config SearchConfig, username, password, @@ -587,9 +562,8 @@ func TestCVECommandGQL(t *testing.T) { count := 0 args := []string{"fixed", "repo", "CVE-2222", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) cmd := NewCVECommand(mockService{ getFixedTagsForCVEGQLFn: func(ctx context.Context, config SearchConfig, username, password, @@ -639,9 +613,8 @@ func TestCVECommandGQL(t *testing.T) { count := 0 args := []string{"list", "repo:vuln", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) cmd := NewCVECommand(mockService{ getCveByImageGQLFn: func(ctx context.Context, config SearchConfig, username, password, @@ -691,8 +664,7 @@ func TestCVECommandErrors(t *testing.T) { defer cm.StopServer() Convey("commands without gql", t, func() { - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, baseURL)) Convey("cveid", func() { args := []string{"affected", "CVE-1942"} diff --git a/pkg/cli/client/cve_cmd_test.go b/pkg/cli/client/cve_cmd_test.go index 5c31c6cf..6b1ee2da 100644 --- a/pkg/cli/client/cve_cmd_test.go +++ b/pkg/cli/client/cve_cmd_test.go @@ -70,13 +70,9 @@ func TestNegativeServerResponse(t *testing.T) { Search: searchConfig, } - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - if err != nil { - panic(err) - } - + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() logPath := logFile.Name() - defer os.Remove(logPath) writers := io.MultiWriter(os.Stdout, logFile) @@ -95,8 +91,7 @@ func TestNegativeServerResponse(t *testing.T) { Convey("Status Code Not Found", func() { args := []string{"list", "zot-cve-test:0.0.1", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -151,13 +146,9 @@ func TestNegativeServerResponse(t *testing.T) { Search: searchConfig, } - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - if err != nil { - panic(err) - } - + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() logPath := logFile.Name() - defer os.Remove(logPath) writers := io.MultiWriter(os.Stdout, logFile) @@ -188,8 +179,7 @@ func TestNegativeServerResponse(t *testing.T) { args := []string{"fixed", "zot-cve-test", "CVE-2019-9923", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -226,14 +216,8 @@ func TestCVEDiffList(t *testing.T) { Search: searchConfig, } - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - if err != nil { - panic(err) - } - - logPath := logFile.Name() - defer os.Remove(logPath) - + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() writers := io.MultiWriter(os.Stdout, logFile) ctlr := api.NewController(conf) @@ -365,7 +349,7 @@ func TestCVEDiffList(t *testing.T) { test.WaitTillServerReady(url) ctx := context.Background() - _, err = ociutils.InitializeTestMetaDB(ctx, ctlr.MetaDB, + _, _ = ociutils.InitializeTestMetaDB(ctx, ctlr.MetaDB, ociutils.Repo{ Name: "repo", Images: []ociutils.RepoImage{ @@ -387,15 +371,15 @@ func TestCVEDiffList(t *testing.T) { Convey("Test CVE by image name - GQL - positive", t, func() { args := []string{"diff", "repo:image", "repo:base-image", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") cveCmd.SetOut(buff) cveCmd.SetErr(buff) cveCmd.SetArgs(args) - err = cveCmd.Execute() + err := cveCmd.Execute() + So(err, ShouldBeNil) fmt.Println(buff.String()) @@ -408,8 +392,7 @@ func TestCVEDiffList(t *testing.T) { }) Convey("Errors", t, func() { - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) @@ -501,14 +484,8 @@ func TestServerCVEResponse(t *testing.T) { Search: searchConfig, } - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - if err != nil { - panic(err) - } - - logPath := logFile.Name() - defer os.Remove(logPath) - + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() writers := io.MultiWriter(os.Stdout, logFile) ctlr := api.NewController(conf) @@ -532,11 +509,12 @@ func TestServerCVEResponse(t *testing.T) { image := CreateDefaultImage() - err = UploadImage(image, url, "zot-cve-test", "0.0.1") + err := UploadImage(image, url, "zot-cve-test", "0.0.1") if err != nil { panic(err) } + logPath := logFile.Name() _, err = test.ReadLogFileAndSearchString(logPath, "cve-db update completed, next update scheduled after interval", 90*time.Second) if err != nil { @@ -546,15 +524,14 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test CVE by image name - GQL - positive", t, func() { args := []string{"list", "zot-cve-test:0.0.1", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") cveCmd.SetOut(buff) cveCmd.SetErr(buff) cveCmd.SetArgs(args) - err = cveCmd.Execute() + err := cveCmd.Execute() space := regexp.MustCompile(`\s+`) str := space.ReplaceAllString(buff.String(), " ") str = strings.TrimSpace(str) @@ -567,15 +544,14 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test CVE by image name - GQL - search CVE by title in results", t, func() { args := []string{"list", "zot-cve-test:0.0.1", "--cve-id", "CVE-C1", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") cveCmd.SetOut(buff) cveCmd.SetErr(buff) cveCmd.SetArgs(args) - err = cveCmd.Execute() + err := cveCmd.Execute() space := regexp.MustCompile(`\s+`) str := space.ReplaceAllString(buff.String(), " ") str = strings.TrimSpace(str) @@ -589,8 +565,7 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test CVE by image name - GQL - search CVE by id in results", t, func() { args := []string{"list", "zot-cve-test:0.0.1", "--cve-id", "CVE-2", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -614,15 +589,14 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test CVE by image name - GQL - search nonexistent CVE", t, func() { args := []string{"list", "zot-cve-test:0.0.1", "--cve-id", "CVE-100", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") cveCmd.SetOut(buff) cveCmd.SetErr(buff) cveCmd.SetArgs(args) - err = cveCmd.Execute() + err := cveCmd.Execute() space := regexp.MustCompile(`\s+`) str := space.ReplaceAllString(buff.String(), " ") str = strings.TrimSpace(str) @@ -634,45 +608,42 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test CVE by image name - GQL - invalid image", t, func() { args := []string{"list", "invalid:0.0.1", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") cveCmd.SetOut(buff) cveCmd.SetErr(buff) cveCmd.SetArgs(args) - err = cveCmd.Execute() + err := cveCmd.Execute() So(err, ShouldNotBeNil) }) Convey("Test CVE by image name - GQL - invalid image name and tag", t, func() { args := []string{"list", "invalid:", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") cveCmd.SetOut(buff) cveCmd.SetErr(buff) cveCmd.SetArgs(args) - err = cveCmd.Execute() + err := cveCmd.Execute() So(err, ShouldNotBeNil) }) Convey("Test CVE by image name - GQL - invalid cli output format", t, func() { args := []string{"list", "zot-cve-test:0.0.1", "-f", "random", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") cveCmd.SetOut(buff) cveCmd.SetErr(buff) cveCmd.SetArgs(args) - err = cveCmd.Execute() + err := cveCmd.Execute() So(err, ShouldNotBeNil) So(buff.String(), ShouldContainSubstring, "invalid cli output format") @@ -681,8 +652,7 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test images by CVE ID - GQL - positive", t, func() { args := []string{"affected", "CVE-2019-9923", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -703,8 +673,7 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test images by CVE ID - GQL - invalid CVE ID", t, func() { args := []string{"affected", "CVE-invalid", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -725,15 +694,14 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test images by CVE ID - GQL - invalid cli output format", t, func() { args := []string{"affected", "CVE-2019-9923", "-f", "random", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") cveCmd.SetOut(buff) cveCmd.SetErr(buff) cveCmd.SetArgs(args) - err = cveCmd.Execute() + err := cveCmd.Execute() So(err, ShouldNotBeNil) So(buff.String(), ShouldContainSubstring, "invalid cli output format") }) @@ -741,8 +709,7 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test fixed tags by image name and CVE ID - GQL - positive", t, func() { args := []string{"fixed", "zot-cve-test", "CVE-2019-9923", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -763,8 +730,7 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test fixed tags by image name and CVE ID - GQL - random cve", t, func() { args := []string{"fixed", "zot-cve-test", "random", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -783,8 +749,7 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test fixed tags by image name and CVE ID - GQL - random image", t, func() { args := []string{"fixed", "zot-cv-test", "CVE-2019-20807", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -805,8 +770,7 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test fixed tags by image name and CVE ID - GQL - invalid image", t, func() { args := []string{"fixed", "zot-cv-test:tag", "CVE-2019-20807", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -827,8 +791,7 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test CVE by name and CVE ID - GQL - positive", t, func() { args := []string{"affected", "CVE-2019-9923", "--repo", "zot-cve-test", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -849,8 +812,7 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test CVE by name and CVE ID - GQL - invalid name and CVE ID", t, func() { args := []string{"affected", "CVE-20807", "--repo", "test", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -870,15 +832,14 @@ func TestServerCVEResponse(t *testing.T) { Convey("Test CVE by name and CVE ID - GQL - invalid cli output format", t, func() { args := []string{"affected", "CVE-2019-9923", "--repo", "zot-cve-test", "-f", "random", "--config", "cvetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"cvetest","url":"%s","showspinner":false}]}`, url)) cveCmd := client.NewCVECommand(client.NewSearchService()) buff := bytes.NewBufferString("") cveCmd.SetOut(buff) cveCmd.SetErr(buff) cveCmd.SetArgs(args) - err = cveCmd.Execute() + err := cveCmd.Execute() So(err, ShouldNotBeNil) So(buff.String(), ShouldContainSubstring, "invalid cli output format") }) diff --git a/pkg/cli/client/elevated_test.go b/pkg/cli/client/elevated_test.go index fd2955f1..67f5e297 100644 --- a/pkg/cli/client/elevated_test.go +++ b/pkg/cli/client/elevated_test.go @@ -101,12 +101,10 @@ func TestElevatedPrivilegesTLSNewControllerPrivilegedCert(t *testing.T) { defer cm.StopServer() Convey("Certs in privileged path", func() { - configPath := makeConfigFile( + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s%s%s","showspinner":false}]}`, BaseSecureURL2, constants.RoutePrefix, constants.ExtCatalogPrefix)) - defer os.Remove(configPath) - args := []string{"list", "--config", "imagetest"} imageCmd := client.NewImageCommand(client.NewSearchService()) imageBuff := bytes.NewBufferString("") diff --git a/pkg/cli/client/image_cmd_internal_test.go b/pkg/cli/client/image_cmd_internal_test.go index f2ebcc3e..f2d7edfa 100644 --- a/pkg/cli/client/image_cmd_internal_test.go +++ b/pkg/cli/client/image_cmd_internal_test.go @@ -35,8 +35,7 @@ func TestSearchImageCmd(t *testing.T) { Convey("Test image help", t, func() { args := []string{"--help"} - configPath := makeConfigFile("") - defer os.Remove(configPath) + _ = makeConfigFile(t, "") cmd := NewImageCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -51,8 +50,7 @@ func TestSearchImageCmd(t *testing.T) { Convey("with the shorthand", func() { args[0] = "-h" - configPath := makeConfigFile("") - defer os.Remove(configPath) + _ = makeConfigFile(t, "") cmd := NewImageCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -69,8 +67,7 @@ func TestSearchImageCmd(t *testing.T) { Convey("Test image no url", t, func() { args := []string{"name", "dummyIdRandom", "--config", "imagetest"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","showspinner":false}]}`) cmd := NewImageCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -85,8 +82,7 @@ func TestSearchImageCmd(t *testing.T) { Convey("Test image invalid home directory", t, func() { args := []string{"name", "dummyImageName", "--config", "imagetest"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) err := os.Setenv("HOME", "nonExistentDirectory") if err != nil { @@ -115,8 +111,7 @@ func TestSearchImageCmd(t *testing.T) { Convey("Test image no params", t, func() { args := []string{"--url", "someUrl"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","showspinner":false}]}`) cmd := NewImageCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -130,8 +125,7 @@ func TestSearchImageCmd(t *testing.T) { Convey("Test image invalid url", t, func() { args := []string{"name", "dummyImageName", "--url", "invalidUrl"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","showspinner":false}]}`) cmd := NewImageCommand(new(searchService)) buff := bytes.NewBufferString("") @@ -147,8 +141,7 @@ func TestSearchImageCmd(t *testing.T) { Convey("Test image invalid url port", t, func() { args := []string{"name", "dummyImageName", "--url", "http://localhost:99999"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","showspinner":false}]}`) cmd := NewImageCommand(new(searchService)) buff := bytes.NewBufferString("") @@ -162,8 +155,7 @@ func TestSearchImageCmd(t *testing.T) { Convey("without flags", func() { args := []string{"list", "--url", "http://localhost:99999"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","showspinner":false}]}`) cmd := NewImageCommand(new(searchService)) buff := bytes.NewBufferString("") @@ -179,8 +171,7 @@ func TestSearchImageCmd(t *testing.T) { Convey("Test image unreachable", t, func() { args := []string{"name", "dummyImageName", "--url", "http://localhost:9999"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","showspinner":false}]}`) cmd := NewImageCommand(new(searchService)) buff := bytes.NewBufferString("") @@ -194,8 +185,7 @@ func TestSearchImageCmd(t *testing.T) { Convey("Test image url from config", t, func() { args := []string{"name", "dummyImageName", "--config", "imagetest"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) cmd := NewImageCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -213,8 +203,7 @@ func TestSearchImageCmd(t *testing.T) { Convey("Test image by name", t, func() { args := []string{"name", "dummyImageName", "--url", "http://127.0.0.1:8080"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","showspinner":false}]}`) imageCmd := NewImageCommand(new(mockService)) buff := &bytes.Buffer{} @@ -257,8 +246,7 @@ func TestListRepos(t *testing.T) { Convey("Test listing repositories with debug flag", t, func() { args := []string{"list", "--config", "config-test", "--debug"} - configPath := makeConfigFile(`{"configs":[{"_name":"config-test","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"config-test","url":"https://test-url.com","showspinner":false}]}`) cmd := NewRepoCommand(new(searchService)) @@ -277,8 +265,7 @@ func TestListRepos(t *testing.T) { Convey("Test error on home directory", t, func() { args := []string{"list", "--config", "config-test"} - configPath := makeConfigFile(`{"configs":[{"_name":"config-test","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"config-test","url":"https://test-url.com","showspinner":false}]}`) err := os.Setenv("HOME", "nonExistentDirectory") if err != nil { @@ -307,9 +294,8 @@ func TestListRepos(t *testing.T) { Convey("Test listing repositories error", t, func() { args := []string{"list", "--config", "config-test"} - configPath := makeConfigFile(`{"configs":[{"_name":"config-test", + _ = makeConfigFile(t, `{"configs":[{"_name":"config-test", "url":"https://invalid.invalid","showspinner":false}]}`) - defer os.Remove(configPath) cmd := NewRepoCommand(new(searchService)) buff := bytes.NewBufferString("") @@ -323,8 +309,7 @@ func TestListRepos(t *testing.T) { Convey("Test unable to get config value", t, func() { args := []string{"list", "--config", "config-test-nonexistent"} - configPath := makeConfigFile(`{"configs":[{"_name":"config-test","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"config-test","url":"https://test-url.com","showspinner":false}]}`) cmd := NewRepoCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -338,8 +323,7 @@ func TestListRepos(t *testing.T) { Convey("Test error - no url provided", t, func() { args := []string{"list", "--config", "config-test"} - configPath := makeConfigFile(`{"configs":[{"_name":"config-test","url":"","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"config-test","url":"","showspinner":false}]}`) cmd := NewRepoCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -353,9 +337,8 @@ func TestListRepos(t *testing.T) { Convey("Test error - spinner config invalid", t, func() { args := []string{"list", "--config", "config-test"} - configPath := makeConfigFile(`{"configs":[{"_name":"config-test", + _ = makeConfigFile(t, `{"configs":[{"_name":"config-test", "url":"https://test-url.com","showspinner":invalid}]}`) - defer os.Remove(configPath) cmd := NewRepoCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -369,9 +352,8 @@ func TestListRepos(t *testing.T) { Convey("Test error - verifyTLSConfig fails", t, func() { args := []string{"list", "--config", "config-test"} - configPath := makeConfigFile(`{"configs":[{"_name":"config-test", + _ = makeConfigFile(t, `{"configs":[{"_name":"config-test", "verify-tls":"invalid", "url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) cmd := NewRepoCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -387,8 +369,7 @@ func TestOutputFormat(t *testing.T) { Convey("Test text", t, func() { args := []string{"name", "dummyImageName", "--config", "imagetest", "-f", "text"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) cmd := NewImageCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -406,8 +387,7 @@ func TestOutputFormat(t *testing.T) { Convey("Test json", t, func() { args := []string{"name", "dummyImageName", "--config", "imagetest", "-f", "json"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) cmd := NewImageCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -437,8 +417,7 @@ func TestOutputFormat(t *testing.T) { Convey("Test yaml", t, func() { args := []string{"name", "dummyImageName", "--config", "imagetest", "-f", "yaml"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) cmd := NewImageCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -473,11 +452,10 @@ func TestOutputFormat(t *testing.T) { Convey("Test yml", func() { args := []string{"name", "dummyImageName", "--config", "imagetest", "-f", "yml"} - configPath := makeConfigFile( - `{"configs":[{"_name":"imagetest",` + + _ = makeConfigFile(t, + `{"configs":[{"_name":"imagetest",`+ `"url":"https://test-url.com","showspinner":false}]}`, ) - defer os.Remove(configPath) cmd := NewImageCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -513,8 +491,7 @@ func TestOutputFormat(t *testing.T) { Convey("Test invalid", t, func() { args := []string{"name", "dummyImageName", "--config", "imagetest", "-f", "random"} - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","url":"https://test-url.com","showspinner":false}]}`) cmd := NewImageCommand(new(mockService)) buff := bytes.NewBufferString("") @@ -565,9 +542,8 @@ func TestImagesCommandGQL(t *testing.T) { err = UploadImage(derivedImage, baseURL, "repo", "derived") So(err, ShouldBeNil) - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"base", "repo:derived", "--config", "imagetest"} cmd := NewImageCommand(NewSearchService()) @@ -654,9 +630,8 @@ func TestImagesCommandGQL(t *testing.T) { err := UploadImage(image, baseURL, "repo", "img") So(err, ShouldBeNil) - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"digest", image.DigestStr(), "--config", "imagetest"} cmd := NewImageCommand(NewSearchService()) @@ -711,9 +686,8 @@ func TestImagesCommandGQL(t *testing.T) { err := UploadImage(image, baseURL, "repo", "img") So(err, ShouldBeNil) - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"list", "--config", "imagetest"} cmd := NewImageCommand(NewSearchService()) @@ -763,9 +737,8 @@ func TestImagesCommandGQL(t *testing.T) { err = UploadImage(CreateRandomImage(), baseURL, "repo", "img2") So(err, ShouldBeNil) - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"name", "repo:img", "--config", "imagetest"} cmd := NewImageCommand(NewSearchService()) @@ -821,9 +794,8 @@ func TestImagesCommandGQL(t *testing.T) { err := UploadImage(vulnImage, baseURL, "repo", "vuln") So(err, ShouldBeNil) - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"cve", "repo:vuln", "--config", "imagetest"} cmd := NewImageCommand(mockService{}) buff := bytes.NewBufferString("") @@ -842,9 +814,8 @@ func TestImagesCommandGQL(t *testing.T) { Convey("CVE errors", func() { count := 0 - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"cve", "repo:vuln", "--config", "imagetest"} cmd := NewImageCommand(mockService{ @@ -875,6 +846,8 @@ func TestImagesCommandGQL(t *testing.T) { }) Convey("Config error", t, func() { + // Create config file with a different config name to test error when config doesn't exist + _ = makeConfigFile(t, `{"configs":[{"_name":"other-config","url":"https://test-url.com","showspinner":false}]}`) args := []string{"base", "repo:derived", "--config", "imagetest"} cmd := NewImageCommand(NewSearchService()) buff := bytes.NewBufferString("") @@ -964,9 +937,8 @@ func TestImageCommandREST(t *testing.T) { err = UploadImage(derivedImage, baseURL, "repo", "derived") So(err, ShouldBeNil) - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"base", "repo:derived", "--config", "imagetest"} cmd := NewImageCommand(NewSearchService()) buff := bytes.NewBufferString("") @@ -992,9 +964,8 @@ func TestImageCommandREST(t *testing.T) { err := UploadImage(image, baseURL, "repo", "img") So(err, ShouldBeNil) - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"digest", image.DigestStr(), "--config", "imagetest"} cmd := NewImageCommand(NewSearchService()) buff := bytes.NewBufferString("") @@ -1011,9 +982,8 @@ func TestImageCommandREST(t *testing.T) { err := UploadImage(image, baseURL, "repo", "img") So(err, ShouldBeNil) - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"list", "--config", "imagetest"} cmd := NewImageCommand(NewSearchService()) buff := bytes.NewBufferString("") @@ -1035,9 +1005,8 @@ func TestImageCommandREST(t *testing.T) { err = UploadImage(CreateRandomImage(), baseURL, "repo", "img2") So(err, ShouldBeNil) - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"name", "repo:img", "--config", "imagetest"} cmd := NewImageCommand(NewSearchService()) buff := bytes.NewBufferString("") @@ -1056,9 +1025,8 @@ func TestImageCommandREST(t *testing.T) { So(err, ShouldBeNil) args := []string{"cve", "repo:vuln", "--config", "imagetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) cmd := NewImageCommand(mockService{}) buff := bytes.NewBufferString("") @@ -1534,8 +1502,9 @@ func (service mockService) getImagesByDigest(ctx context.Context, config SearchC service.getImageByName(ctx, config, username, password, "anImage", rch, wtgrp) } -func makeConfigFile(content string) string { - os.Setenv("HOME", os.TempDir()) +func makeConfigFile(t *testing.T, content string) string { + tempDir := t.TempDir() + os.Setenv("HOME", tempDir) home, err := os.UserHomeDir() if err != nil { diff --git a/pkg/cli/client/image_cmd_test.go b/pkg/cli/client/image_cmd_test.go index ed69aeb5..802be27b 100644 --- a/pkg/cli/client/image_cmd_test.go +++ b/pkg/cli/client/image_cmd_test.go @@ -369,8 +369,7 @@ func TestOutputFormatGQL(t *testing.T) { t.Logf("%s", ctlr.Config.Storage.RootDirectory) args := []string{"name", "repo7", "--config", "imagetest", "-f", "json"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -417,8 +416,7 @@ func TestOutputFormatGQL(t *testing.T) { Convey("Test yaml", func() { args := []string{"name", "repo7", "--config", "imagetest", "-f", "yaml"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -468,8 +466,7 @@ func TestOutputFormatGQL(t *testing.T) { Convey("Test yml", func() { args := []string{"name", "repo7", "--config", "imagetest", "-f", "yml"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -519,8 +516,7 @@ func TestOutputFormatGQL(t *testing.T) { Convey("Test invalid", func() { args := []string{"name", "repo7", "--config", "imagetest", "-f", "random"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -560,8 +556,7 @@ func TestServerResponseGQL(t *testing.T) { t.Logf("%s", ctlr.Config.Storage.RootDirectory) args := []string{"list", "--config", "imagetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := &bytes.Buffer{} @@ -579,8 +574,7 @@ func TestServerResponseGQL(t *testing.T) { Convey("Test all images invalid output format", func() { args := []string{"list", "--config", "imagetest", "-f", "random"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -596,8 +590,7 @@ func TestServerResponseGQL(t *testing.T) { Convey("Test all images verbose", func() { args := []string{"list", "--config", "imagetest", "--verbose"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -623,8 +616,7 @@ func TestServerResponseGQL(t *testing.T) { Convey("Test all images with debug flag", func() { args := []string{"list", "--config", "imagetest", "--debug"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -648,8 +640,7 @@ func TestServerResponseGQL(t *testing.T) { Convey("Test image by name config url", func() { args := []string{"name", "repo7", "--config", "imagetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -671,8 +662,7 @@ func TestServerResponseGQL(t *testing.T) { Convey("invalid output format", func() { args := []string{"name", "repo7", "--config", "imagetest", "-f", "random"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -688,8 +678,7 @@ func TestServerResponseGQL(t *testing.T) { Convey("Test image by digest", func() { args := []string{"digest", "51e18f50", "--config", "imagetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -712,8 +701,7 @@ func TestServerResponseGQL(t *testing.T) { Convey("nonexistent digest", func() { args := []string{"digest", "d1g35t", "--config", "imagetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -728,8 +716,7 @@ func TestServerResponseGQL(t *testing.T) { Convey("invalid output format", func() { args := []string{"digest", "51e18f50", "--config", "imagetest", "-f", "random"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -745,8 +732,7 @@ func TestServerResponseGQL(t *testing.T) { Convey("Test image by name nonexistent name", func() { args := []string{"name", "repo777", "--config", "imagetest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"imagetest","url":"%s","showspinner":false}]}`, url)) cmd := client.NewImageCommand(client.NewSearchService()) buff := bytes.NewBufferString("") @@ -761,9 +747,8 @@ func TestServerResponseGQL(t *testing.T) { Convey("Test list repos error", func() { args := []string{"list", "--config", "config-test"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"config-test", + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"config-test", "url":"%s","showspinner":false}]}`, url)) - defer os.Remove(configPath) cmd := client.NewRepoCommand(client.NewSearchService()) buff := &bytes.Buffer{} diff --git a/pkg/cli/client/repo_test.go b/pkg/cli/client/repo_test.go index fa41d925..e27dbd5f 100644 --- a/pkg/cli/client/repo_test.go +++ b/pkg/cli/client/repo_test.go @@ -5,7 +5,6 @@ package client_test import ( "bytes" "fmt" - "os" "regexp" "strings" "testing" @@ -38,9 +37,8 @@ func TestReposCommand(t *testing.T) { err = UploadImage(CreateRandomImage(), baseURL, "repo2", "tag2") So(err, ShouldBeNil) - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"repostest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"repostest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"list", "--config", "repostest"} cmd := client.NewRepoCommand(client.NewSearchService()) diff --git a/pkg/cli/client/search_cmd_internal_test.go b/pkg/cli/client/search_cmd_internal_test.go index 06644881..102ef294 100644 --- a/pkg/cli/client/search_cmd_internal_test.go +++ b/pkg/cli/client/search_cmd_internal_test.go @@ -5,7 +5,6 @@ package client import ( "bytes" "fmt" - "os" "regexp" "strings" "testing" @@ -40,9 +39,8 @@ func TestSearchCommandGQL(t *testing.T) { defer cm.StopServer() Convey("commands without gql", t, func() { - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) Convey("query", func() { args := []string{"query", "repo/al", "--config", "searchtest"} @@ -120,9 +118,8 @@ func TestSearchCommandREST(t *testing.T) { defer cm.StopServer() Convey("commands without gql", t, func() { - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) Convey("query", func() { args := []string{"query", "repo/al", "--config", "searchtest"} diff --git a/pkg/cli/client/search_cmd_test.go b/pkg/cli/client/search_cmd_test.go index 640fef70..201d0cfa 100644 --- a/pkg/cli/client/search_cmd_test.go +++ b/pkg/cli/client/search_cmd_test.go @@ -5,7 +5,6 @@ package client_test import ( "bytes" "fmt" - "os" "regexp" "strings" "testing" @@ -83,9 +82,8 @@ func TestReferrerCLI(t *testing.T) { args := []string{"subject", repo + "@" + image.DigestStr(), "--config", "reftest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) cmd := client.NewSearchCommand(client.NewSearchService()) @@ -104,13 +102,10 @@ func TestReferrerCLI(t *testing.T) { fmt.Println(buff.String()) - os.Remove(configPath) - args = []string{"subject", repo + ":" + "tag", "--config", "reftest"} - configPath = makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) cmd = client.NewSearchCommand(client.NewSearchService()) @@ -182,7 +177,7 @@ func TestReferrerCLI(t *testing.T) { // get referrers by digest args := []string{"subject", repo + "@" + image.DigestStr(), "--config", "reftest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, baseURL)) cmd := client.NewSearchCommand(client.NewSearchService()) @@ -201,13 +196,10 @@ func TestReferrerCLI(t *testing.T) { So(str, ShouldContainSubstring, "custom.art.type.v2 611 B "+ref3.DigestStr()) fmt.Println(buff.String()) - os.Remove(configPath) - args = []string{"subject", repo + ":" + "tag", "--config", "reftest"} - configPath = makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) buff = &bytes.Buffer{} cmd.SetOut(buff) @@ -279,11 +271,9 @@ func TestFormatsReferrersCLI(t *testing.T) { Convey("JSON format", func() { args := []string{"subject", repo + "@" + image.DigestStr(), "--format", "json", "--config", "reftest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) - cmd := client.NewSearchCommand(client.NewSearchService()) buff := &bytes.Buffer{} @@ -297,11 +287,9 @@ func TestFormatsReferrersCLI(t *testing.T) { Convey("YAML format", func() { args := []string{"subject", repo + "@" + image.DigestStr(), "--format", "yaml", "--config", "reftest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) - cmd := client.NewSearchCommand(client.NewSearchService()) buff := &bytes.Buffer{} @@ -315,11 +303,9 @@ func TestFormatsReferrersCLI(t *testing.T) { Convey("Invalid format", func() { args := []string{"subject", repo + "@" + image.DigestStr(), "--format", "invalid_format", "--config", "reftest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"reftest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) - cmd := client.NewSearchCommand(client.NewSearchService()) buff := &bytes.Buffer{} @@ -339,9 +325,7 @@ func TestReferrersCLIErrors(t *testing.T) { Convey("no url provided", func() { args := []string{"query", "repo/alpine", "--format", "invalid", "--config", "reftest"} - configPath := makeConfigFile(`{"configs":[{"_name":"reftest","showspinner":false}]}`) - - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"reftest","showspinner":false}]}`) buff := &bytes.Buffer{} cmd.SetOut(buff) @@ -354,9 +338,7 @@ func TestReferrersCLIErrors(t *testing.T) { Convey("getConfigValue", func() { args := []string{"subject", "repo/alpine", "--config", "reftest"} - configPath := makeConfigFile(`bad-json`) - - defer os.Remove(configPath) + _ = makeConfigFile(t, `bad-json`) buff := &bytes.Buffer{} cmd.SetOut(buff) @@ -369,9 +351,7 @@ func TestReferrersCLIErrors(t *testing.T) { Convey("bad showspinnerConfig ", func() { args := []string{"query", "repo", "--config", "reftest"} - configPath := makeConfigFile(`{"configs":[{"_name":"reftest", "url":"http://127.0.0.1:8080", "showspinner":"bad"}]}`) - - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"reftest", "url":"http://127.0.0.1:8080", "showspinner":"bad"}]}`) buff := &bytes.Buffer{} cmd.SetOut(buff) @@ -384,11 +364,9 @@ func TestReferrersCLIErrors(t *testing.T) { Convey("bad verifyTLSConfig ", func() { args := []string{"query", "repo", "reftest"} - configPath := makeConfigFile( + _ = makeConfigFile(t, `{"configs":[{"_name":"reftest", "url":"http://127.0.0.1:8080", "showspinner":false, "verify-tls": "bad"}]}`) - defer os.Remove(configPath) - buff := &bytes.Buffer{} cmd.SetOut(buff) cmd.SetErr(buff) @@ -400,9 +378,7 @@ func TestReferrersCLIErrors(t *testing.T) { Convey("url from config is empty", func() { args := []string{"subject", "repo/alpine", "--config", "reftest"} - configPath := makeConfigFile(`{"configs":[{"_name":"reftest", "url":"", "showspinner":false}]}`) - - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"reftest", "url":"", "showspinner":false}]}`) buff := &bytes.Buffer{} cmd.SetOut(buff) @@ -415,9 +391,7 @@ func TestReferrersCLIErrors(t *testing.T) { Convey("bad params combination", func() { args := []string{"query", "repo", "reftest"} - configPath := makeConfigFile(`{"configs":[{"_name":"reftest", "url":"http://127.0.0.1:8080", "showspinner":false}]}`) - - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"reftest", "url":"http://127.0.0.1:8080", "showspinner":false}]}`) buff := &bytes.Buffer{} cmd.SetOut(buff) @@ -497,9 +471,8 @@ func TestSearchCLI(t *testing.T) { args := []string{"query", "test/alpin", "--verbose", "--config", "searchtest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) cmd := client.NewSearchCommand(client.NewSearchService()) @@ -518,17 +491,13 @@ func TestSearchCLI(t *testing.T) { fmt.Println("\n", buff.String()) - os.Remove(configPath) - cmd = client.NewSearchCommand(client.NewSearchService()) args = []string{"query", "repo/alpine:", "--config", "searchtest"} - configPath = makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) - buff = &bytes.Buffer{} cmd.SetOut(buff) cmd.SetErr(buff) @@ -601,11 +570,9 @@ func TestFormatsSearchCLI(t *testing.T) { Convey("JSON format", func() { args := []string{"query", "repo/alpine", "--format", "json", "--config", "searchtest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) - buff := &bytes.Buffer{} cmd.SetOut(buff) cmd.SetErr(buff) @@ -618,11 +585,9 @@ func TestFormatsSearchCLI(t *testing.T) { Convey("YAML format", func() { args := []string{"query", "repo/alpine", "--format", "yaml", "--config", "searchtest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) - buff := &bytes.Buffer{} cmd.SetOut(buff) cmd.SetErr(buff) @@ -635,11 +600,9 @@ func TestFormatsSearchCLI(t *testing.T) { Convey("Invalid format", func() { args := []string{"query", "repo/alpine", "--format", "invalid", "--config", "searchtest"} - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"searchtest","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) - buff := &bytes.Buffer{} cmd.SetOut(buff) cmd.SetErr(buff) @@ -657,9 +620,7 @@ func TestSearchCLIErrors(t *testing.T) { Convey("no url provided", func() { args := []string{"query", "repo/alpine", "--format", "invalid", "--config", "searchtest"} - configPath := makeConfigFile(`{"configs":[{"_name":"searchtest","showspinner":false}]}`) - - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"searchtest","showspinner":false}]}`) buff := &bytes.Buffer{} cmd.SetOut(buff) @@ -672,9 +633,7 @@ func TestSearchCLIErrors(t *testing.T) { Convey("getConfigValue", func() { args := []string{"query", "repo/alpine", "--format", "invalid", "--config", "searchtest"} - configPath := makeConfigFile(`bad-json`) - - defer os.Remove(configPath) + _ = makeConfigFile(t, `bad-json`) buff := &bytes.Buffer{} cmd.SetOut(buff) @@ -687,11 +646,9 @@ func TestSearchCLIErrors(t *testing.T) { Convey("bad showspinnerConfig ", func() { args := []string{"query", "repo/alpine", "--config", "searchtest"} - configPath := makeConfigFile( + _ = makeConfigFile(t, `{"configs":[{"_name":"searchtest", "url":"http://127.0.0.1:8080", "showspinner":"bad"}]}`) - defer os.Remove(configPath) - buff := &bytes.Buffer{} cmd.SetOut(buff) cmd.SetErr(buff) @@ -703,11 +660,9 @@ func TestSearchCLIErrors(t *testing.T) { Convey("bad verifyTLSConfig ", func() { args := []string{"query", "repo/alpine", "--config", "searchtest"} - configPath := makeConfigFile( + _ = makeConfigFile(t, `{"configs":[{"_name":"searchtest", "url":"http://127.0.0.1:8080", "showspinner":false, "verify-tls": "bad"}]}`) - defer os.Remove(configPath) - buff := &bytes.Buffer{} cmd.SetOut(buff) cmd.SetErr(buff) @@ -719,9 +674,7 @@ func TestSearchCLIErrors(t *testing.T) { Convey("url from config is empty", func() { args := []string{"query", "repo/alpine", "--format", "invalid", "--config", "searchtest"} - configPath := makeConfigFile(`{"configs":[{"_name":"searchtest", "url":"", "showspinner":false}]}`) - - defer os.Remove(configPath) + _ = makeConfigFile(t, `{"configs":[{"_name":"searchtest", "url":"", "showspinner":false}]}`) buff := &bytes.Buffer{} cmd.SetOut(buff) diff --git a/pkg/cli/client/search_functions_internal_test.go b/pkg/cli/client/search_functions_internal_test.go index f27c3242..a2560e84 100644 --- a/pkg/cli/client/search_functions_internal_test.go +++ b/pkg/cli/client/search_functions_internal_test.go @@ -8,7 +8,6 @@ import ( "bytes" "context" "io" - "os" "regexp" "strings" "sync" @@ -859,24 +858,22 @@ func TestUtils(t *testing.T) { So(verifyTLS, ShouldBeFalse) // bad showspinner - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":"bad", "verify-tls": false}]}`) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","showspinner":"bad", "verify-tls": false}]}`) cmd = &cobra.Command{} cmd.Flags().String(ConfigFlag, "imagetest", "") isSpinner, verifyTLS, err = GetCliConfigOptions(cmd) So(err, ShouldNotBeNil) So(isSpinner, ShouldBeFalse) So(verifyTLS, ShouldBeFalse) - os.Remove(configPath) // bad verify-tls - configPath = makeConfigFile(`{"configs":[{"_name":"imagetest","showspinner":false, "verify-tls": "bad"}]}`) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest","showspinner":false, "verify-tls": "bad"}]}`) cmd = &cobra.Command{} cmd.Flags().String(ConfigFlag, "imagetest", "") isSpinner, verifyTLS, err = GetCliConfigOptions(cmd) So(err, ShouldNotBeNil) So(isSpinner, ShouldBeFalse) So(verifyTLS, ShouldBeFalse) - os.Remove(configPath) }) Convey("GetServerURLFromFlags", t, func() { @@ -893,22 +890,20 @@ func TestUtils(t *testing.T) { So(err, ShouldNotBeNil) // err ulr from config is empty - configPath := makeConfigFile(`{"configs":[{"_name":"imagetest"}]}`) + _ = makeConfigFile(t, `{"configs":[{"_name":"imagetest"}]}`) cmd = &cobra.Command{} cmd.Flags().String(ConfigFlag, "imagetest", "") url, err = GetServerURLFromFlags(cmd) So(url, ShouldResemble, "") So(err, ShouldNotBeNil) - os.Remove(configPath) // err reading the server url from config - configPath = makeConfigFile("{}") + _ = makeConfigFile(t, "{}") cmd = &cobra.Command{} cmd.Flags().String(ConfigFlag, "imagetest", "") url, err = GetServerURLFromFlags(cmd) So(url, ShouldResemble, "") So(err, ShouldNotBeNil) - os.Remove(configPath) }) Convey("CheckExtEndPointQuery", t, func() { diff --git a/pkg/cli/client/server_info_cmd_test.go b/pkg/cli/client/server_info_cmd_test.go index 543c6b65..f87ce46e 100644 --- a/pkg/cli/client/server_info_cmd_test.go +++ b/pkg/cli/client/server_info_cmd_test.go @@ -40,9 +40,8 @@ func TestServerStatusCommand(t *testing.T) { cm.StartAndWait(conf.HTTP.Port) defer cm.StopServer() - configPath := makeConfigFile(fmt.Sprintf(`{"configs":[{"_name":"status-test","url":"%s","showspinner":false}]}`, + _ = makeConfigFile(t, fmt.Sprintf(`{"configs":[{"_name":"status-test","url":"%s","showspinner":false}]}`, baseURL)) - defer os.Remove(configPath) args := []string{"status", "--config", "status-test"} cmd := NewCliRootCmd() diff --git a/pkg/cli/server/config_reloader_test.go b/pkg/cli/server/config_reloader_test.go index 3b0c681b..60e73a20 100644 --- a/pkg/cli/server/config_reloader_test.go +++ b/pkg/cli/server/config_reloader_test.go @@ -24,16 +24,12 @@ func TestConfigReloader(t *testing.T) { port := test.GetFreePort() baseURL := test.GetBaseURL(port) - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") username := "alice" password := "alice" - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - defer os.Remove(htpasswdPath) - - defer os.Remove(logFile.Name()) // clean up + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", @@ -72,19 +68,13 @@ func TestConfigReloader(t *testing.T) { "level": "debug", "output": "%s" } - }`, t.TempDir(), port, htpasswdPath, logFile.Name()) + }`, t.TempDir(), port, htpasswdPath, logPath) - cfgfile, err := os.CreateTemp("", "zot-test*.json") + cfgfile := test.MakeTempFile(t, "zot-test.json") + defer cfgfile.Close() + _, err := cfgfile.WriteString(content) So(err, ShouldBeNil) - defer os.Remove(cfgfile.Name()) // clean up - - _, err = cfgfile.WriteString(content) - So(err, ShouldBeNil) - - // err = cfgfile.Close() - // So(err, ShouldBeNil) - os.Args = []string{"cli_test", "serve", cfgfile.Name()} go func() { @@ -95,7 +85,7 @@ func TestConfigReloader(t *testing.T) { test.WaitTillServerReady(baseURL) // verify initial startup authentication logs - initialData, err := os.ReadFile(logFile.Name()) + initialData, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(initialData), ShouldContainSubstring, "configuration settings") // verify authentication methods status messages are present in initial startup @@ -145,7 +135,7 @@ func TestConfigReloader(t *testing.T) { "level": "debug", "output": "%s" } - }`, t.TempDir(), port, htpasswdPath, logFile.Name()) + }`, t.TempDir(), port, htpasswdPath, logPath) err = cfgfile.Truncate(0) So(err, ShouldBeNil) @@ -162,7 +152,7 @@ func TestConfigReloader(t *testing.T) { // wait for config reload time.Sleep(2 * time.Second) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Logf("log file: %s", data) @@ -185,10 +175,8 @@ func TestConfigReloader(t *testing.T) { port := test.GetFreePort() baseURL := test.GetBaseURL(port) - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", @@ -214,17 +202,12 @@ func TestConfigReloader(t *testing.T) { } }`, t.TempDir(), t.TempDir(), port, logFile.Name()) - cfgfile, err := os.CreateTemp("", "zot-test*.json") + cfgfile := test.MakeTempFile(t, "zot-test.json") + defer cfgfile.Close() + + _, err := cfgfile.WriteString(content) So(err, ShouldBeNil) - defer os.Remove(cfgfile.Name()) // clean up - - _, err = cfgfile.WriteString(content) - So(err, ShouldBeNil) - - // err = cfgfile.Close() - // So(err, ShouldBeNil) - os.Args = []string{"cli_test", "serve", cfgfile.Name()} go func() { @@ -280,6 +263,8 @@ func TestConfigReloader(t *testing.T) { // truncate log before changing config, for the ShouldNotContainString So(logFile.Truncate(0), ShouldBeNil) + err = logFile.Close() + So(err, ShouldBeNil) _, err = cfgfile.WriteString(content) So(err, ShouldBeNil) @@ -315,10 +300,7 @@ func TestConfigReloader(t *testing.T) { port := test.GetFreePort() baseURL := test.GetBaseURL(port) - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", @@ -354,19 +336,14 @@ func TestConfigReloader(t *testing.T) { }] } } - }`, t.TempDir(), port, logFile.Name()) + }`, t.TempDir(), port, logPath) - cfgfile, err := os.CreateTemp("", "zot-test*.json") + cfgfile := test.MakeTempFile(t, "zot-test.json") + defer cfgfile.Close() + + _, err := cfgfile.WriteString(content) So(err, ShouldBeNil) - defer os.Remove(cfgfile.Name()) // clean up - - _, err = cfgfile.WriteString(content) - So(err, ShouldBeNil) - - // err = cfgfile.Close() - // So(err, ShouldBeNil) - os.Args = []string{"cli_test", "serve", cfgfile.Name()} go func() { @@ -377,7 +354,7 @@ func TestConfigReloader(t *testing.T) { test.WaitTillServerReady(baseURL) // verify initial startup authentication logs (no auth configured) - initialData, err := os.ReadFile(logFile.Name()) + initialData, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(initialData), ShouldContainSubstring, "configuration settings") // verify authentication methods status messages are present in initial startup @@ -424,7 +401,7 @@ func TestConfigReloader(t *testing.T) { }] } } - }`, t.TempDir(), port, logFile.Name()) + }`, t.TempDir(), port, logPath) err = cfgfile.Truncate(0) So(err, ShouldBeNil) @@ -441,7 +418,7 @@ func TestConfigReloader(t *testing.T) { // wait for config reload time.Sleep(2 * time.Second) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Logf("log file: %s", data) @@ -471,10 +448,7 @@ func TestConfigReloader(t *testing.T) { port := test.GetFreePort() baseURL := test.GetBaseURL(port) - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", @@ -503,14 +477,12 @@ func TestConfigReloader(t *testing.T) { "interval": "24h" } } - }`, t.TempDir(), port, logFile.Name()) + }`, t.TempDir(), port, logPath) - cfgfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) + cfgfile := test.MakeTempFile(t, "zot-test.json") + defer cfgfile.Close() - defer os.Remove(cfgfile.Name()) // clean up - - _, err = cfgfile.WriteString(content) + _, err := cfgfile.WriteString(content) So(err, ShouldBeNil) os.Args = []string{"cli_test", "serve", cfgfile.Name()} @@ -523,7 +495,7 @@ func TestConfigReloader(t *testing.T) { test.WaitTillServerReady(baseURL) // verify initial startup authentication logs (no auth configured) - initialData, err := os.ReadFile(logFile.Name()) + initialData, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(initialData), ShouldContainSubstring, "configuration settings") // verify authentication methods status messages are present in initial startup @@ -559,7 +531,7 @@ func TestConfigReloader(t *testing.T) { } } } - }`, t.TempDir(), port, logFile.Name()) + }`, t.TempDir(), port, logPath) err = cfgfile.Truncate(0) So(err, ShouldBeNil) @@ -577,13 +549,13 @@ func TestConfigReloader(t *testing.T) { time.Sleep(5 * time.Second) // Wait for the async trivy download to fail and log the error - found, err := test.ReadLogFileAndSearchString(logFile.Name(), + found, err := test.ReadLogFileAndSearchString(logPath, "failed to download trivy-db to destination dir", 30*time.Second) So(err, ShouldBeNil) So(found, ShouldBeTrue) // Now read the file once and check all the expected log content - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Logf("log file: %s", data) @@ -605,7 +577,7 @@ func TestConfigReloader(t *testing.T) { // Just verify the new URL appears in the logs to confirm config reload worked and ignore // the order of json message formatting that can change independent of this functional // test. - found, err = test.ReadLogFileAndSearchString(logFile.Name(), + found, err = test.ReadLogFileAndSearchString(logPath, "index.docker.io/another/unreachable/trivy/url2", 1*time.Minute) So(err, ShouldBeNil) So(found, ShouldBeTrue) @@ -615,10 +587,7 @@ func TestConfigReloader(t *testing.T) { port := test.GetFreePort() baseURL := test.GetBaseURL(port) - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", @@ -654,19 +623,14 @@ func TestConfigReloader(t *testing.T) { }] } } - }`, t.TempDir(), port, logFile.Name()) + }`, t.TempDir(), port, logPath) - cfgfile, err := os.CreateTemp("", "zot-test*.json") + cfgfile := test.MakeTempFile(t, "zot-test.json") + defer cfgfile.Close() + + _, err := cfgfile.WriteString(content) So(err, ShouldBeNil) - defer os.Remove(cfgfile.Name()) // clean up - - _, err = cfgfile.WriteString(content) - So(err, ShouldBeNil) - - // err = cfgfile.Close() - // So(err, ShouldBeNil) - os.Args = []string{"cli_test", "serve", cfgfile.Name()} go func() { @@ -693,7 +657,7 @@ func TestConfigReloader(t *testing.T) { // wait for config reload time.Sleep(2 * time.Second) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Logf("log file: %s", data) diff --git a/pkg/cli/server/extensions_test.go b/pkg/cli/server/extensions_test.go index 0cb75bd1..3e2551b4 100644 --- a/pkg/cli/server/extensions_test.go +++ b/pkg/cli/server/extensions_test.go @@ -26,10 +26,6 @@ func TestVerifyExtensionsConfig(t *testing.T) { defer func() { os.Args = oldArgs }() Convey("Test verify CVE warn for remote storage", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := fmt.Sprintf(`{ "storage":{ "rootDirectory":"%s", @@ -58,10 +54,9 @@ func TestVerifyExtensionsConfig(t *testing.T) { } }`, t.TempDir()) - err = os.WriteFile(tmpfile.Name(), []byte(content), 0o0600) - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} So(cli.NewServerRootCmd().Execute(), ShouldNotBeNil) @@ -98,149 +93,99 @@ func TestVerifyExtensionsConfig(t *testing.T) { } } }`, t.TempDir(), t.TempDir()) - err = os.WriteFile(tmpfile.Name(), []byte(content), 0o0600) - So(err, ShouldBeNil) + tmpfile = MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} So(cli.NewServerRootCmd().Execute(), ShouldNotBeNil) }) Convey("Test verify w/ sync and w/o filesystem storage", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := fmt.Sprintf(`{"storage":{"rootDirectory":"%s", "storageDriver": {"name": "s3"}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 1, "retryDelay": "10s"}]}}}`, t.TempDir()) - _, err = tmpfile.WriteString(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) + os.Args = []string{"cli_test", "verify", tmpfile} So(cli.NewServerRootCmd().Execute(), ShouldNotBeNil) }) Convey("Test verify w/ sync and w/ filesystem storage", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := fmt.Sprintf(`{"storage":{"rootDirectory":"%s"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 1, "retryDelay": "10s"}]}}}`, t.TempDir()) - _, err = tmpfile.WriteString(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} So(cli.NewServerRootCmd().Execute(), ShouldBeNil) }) Convey("Test verify with bad sync prefixes", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := fmt.Sprintf(`{"storage":{"rootDirectory":"%s"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 1, "retryDelay": "10s", "content": [{"prefix":"[repo^&["}]}]}}}`, t.TempDir()) - _, err = tmpfile.WriteString(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} So(cli.NewServerRootCmd().Execute(), ShouldNotBeNil) }) Convey("Test verify with bad sync content config", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := fmt.Sprintf(`{"storage":{"rootDirectory":"%s"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 1, "retryDelay": "10s", "content": [{"prefix":"zot-repo","stripPrefix":true,"destination":"/"}]}]}}}`, t.TempDir()) - _, err = tmpfile.WriteString(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) + os.Args = []string{"cli_test", "verify", tmpfile} So(cli.NewServerRootCmd().Execute(), ShouldNotBeNil) }) Convey("Test verify with good sync content config", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := fmt.Sprintf(`{"storage":{"rootDirectory":"%s"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 1, "retryDelay": "10s", "content": [{"prefix":"zot-repo/*","stripPrefix":true,"destination":"/"}]}]}}}`, t.TempDir()) - _, err = tmpfile.WriteString(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify sync config default tls value", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := fmt.Sprintf(`{"storage":{"rootDirectory":"%s"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 1, "retryDelay": "10s", "content": [{"prefix":"repo**"}]}]}}}`, t.TempDir()) - _, err = tmpfile.WriteString(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify sync without retry options", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := fmt.Sprintf(`{"storage":{"rootDirectory":"%s"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 10, "content": [{"prefix":"repo**"}]}]}}}`, t.TempDir()) - _, err = tmpfile.WriteString(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) + os.Args = []string{"cli_test", "verify", tmpfile} So(cli.NewServerRootCmd().Execute(), ShouldNotBeNil) }) @@ -249,12 +194,8 @@ func TestVerifyExtensionsConfig(t *testing.T) { func TestValidateExtensionsConfig(t *testing.T) { Convey("Legacy extensions should not error", t, func(c C) { config := config.New() - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) - - content := []byte(`{ + content := `{ "storage": { "rootDirectory": "%/tmp/zot" }, @@ -273,22 +214,16 @@ func TestValidateExtensionsConfig(t *testing.T) { "enable": "true" } } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + }` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) + err := cli.LoadConfiguration(config, tmpfile) So(err, ShouldBeNil) }) Convey("Test missing extensions for UI to work", t, func(c C) { config := config.New() - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) - - content := []byte(`{ + content := `{ "storage": { "rootDirectory": "%/tmp/zot" }, @@ -304,21 +239,15 @@ func TestValidateExtensionsConfig(t *testing.T) { "enable": "true" } } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + }` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) + err := cli.LoadConfiguration(config, tmpfile) So(err, ShouldNotBeNil) }) Convey("Test enabling UI extension with all prerequisites", t, func(c C) { config := config.New() - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) - - content := []byte(`{ + content := `{ "storage": { "rootDirectory": "%/tmp/zot" }, @@ -337,21 +266,15 @@ func TestValidateExtensionsConfig(t *testing.T) { "enable": "true" } } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + }` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) + err := cli.LoadConfiguration(config, tmpfile) So(err, ShouldBeNil) }) Convey("Test extension are implicitly enabled", t, func(c C) { config := config.New() - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) - - content := []byte(`{ + content := `{ "storage": { "rootDirectory": "%/tmp/zot" }, @@ -369,10 +292,9 @@ func TestValidateExtensionsConfig(t *testing.T) { "trust": {}, "scrub": {} } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + }` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) + err := cli.LoadConfiguration(config, tmpfile) So(err, ShouldBeNil) So(config.Extensions.UI, ShouldNotBeNil) So(*config.Extensions.UI.Enable, ShouldBeTrue) @@ -395,10 +317,7 @@ func TestServeExtensions(t *testing.T) { Convey("config file with no extensions", t, func(c C) { port := GetFreePort() baseURL := GetBaseURL(port) - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logPath := MakeTempFilePath(t, "zot-log.txt") tmpFile := t.TempDir() @@ -414,29 +333,22 @@ func TestServeExtensions(t *testing.T) { "level": "debug", "output": "%s" } - }`, tmpFile, port, logFile.Name()) + }`, tmpFile, port, logPath) - cfgfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(cfgfile.Name()) // clean up + cfgfile := MakeTempFileWithContent(t, "zot-test.json", content) - _, err = cfgfile.WriteString(content) - So(err, ShouldBeNil) - err = cfgfile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "serve", cfgfile.Name()} + os.Args = []string{"cli_test", "serve", cfgfile} go func() { Convey("run", t, func() { - err = cli.NewServerRootCmd().Execute() + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) }() WaitTillServerReady(baseURL) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "\"Extensions\":null") @@ -445,10 +357,7 @@ func TestServeExtensions(t *testing.T) { Convey("config file with empty extensions", t, func(c C) { port := GetFreePort() baseURL := GetBaseURL(port) - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logPath := MakeTempFilePath(t, "zot-log.txt") tmpFile := t.TempDir() @@ -466,28 +375,21 @@ func TestServeExtensions(t *testing.T) { }, "extensions": { } - }`, tmpFile, port, logFile.Name()) + }`, tmpFile, port, logPath) - cfgfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(cfgfile.Name()) // clean up + cfgfile := MakeTempFileWithContent(t, "zot-test.json", content) - _, err = cfgfile.WriteString(content) - So(err, ShouldBeNil) - err = cfgfile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "serve", cfgfile.Name()} + os.Args = []string{"cli_test", "serve", cfgfile} go func() { Convey("run", t, func() { - err = cli.NewServerRootCmd().Execute() + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) }() WaitTillServerReady(baseURL) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "\"Extensions\":{\"Search\":null,\"Sync\":null,\"Metrics\":null,\"Scrub\":null,\"Lint\":null,\"UI\":null,\"Mgmt\":null") //nolint:lll // gofumpt conflicts with lll @@ -498,27 +400,16 @@ func testWithMetricsEnabled(t *testing.T, rootDir string, cfgContentFormat strin t.Helper() port := GetFreePort() baseURL := GetBaseURL(port) - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up + content := fmt.Sprintf(cfgContentFormat, rootDir, port, logPath) + cfgfile := MakeTempFileWithContent(t, "zot-test.json", content) - content := fmt.Sprintf(cfgContentFormat, rootDir, port, logFile.Name()) - cfgfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(cfgfile.Name()) // clean up - - _, err = cfgfile.WriteString(content) - So(err, ShouldBeNil) - err = cfgfile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "serve", cfgfile.Name()} + os.Args = []string{"cli_test", "serve", cfgfile} go func() { Convey("run", t, func() { - err = cli.NewServerRootCmd().Execute() + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) }() @@ -532,7 +423,7 @@ func testWithMetricsEnabled(t *testing.T, rootDir string, cfgContentFormat strin respStr := string(resp.Body()) So(respStr, ShouldContainSubstring, "zot_info") - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "\"Metrics\":{\"Enable\":true,\"Prometheus\":{\"Path\":\"/metrics\"}}") @@ -619,11 +510,9 @@ func TestServeMetricsExtension(t *testing.T) { Convey("with explicit disable", t, func(c C) { port := GetFreePort() baseURL := GetBaseURL(port) - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - tmpFile := t.TempDir() + logPath := MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up + tmpFile := t.TempDir() content := fmt.Sprintf(`{ "storage": { @@ -642,22 +531,15 @@ func TestServeMetricsExtension(t *testing.T) { "enable": false } } - }`, tmpFile, port, logFile.Name()) + }`, tmpFile, port, logPath) - cfgfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(cfgfile.Name()) // clean up + cfgfile := MakeTempFileWithContent(t, "zot-test.json", content) - _, err = cfgfile.WriteString(content) - So(err, ShouldBeNil) - err = cfgfile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "serve", cfgfile.Name()} + os.Args = []string{"cli_test", "serve", cfgfile} go func() { Convey("run", t, func() { - err = cli.NewServerRootCmd().Execute() + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) }() @@ -669,7 +551,7 @@ func TestServeMetricsExtension(t *testing.T) { So(resp, ShouldNotBeNil) So(resp.StatusCode(), ShouldEqual, http.StatusNotFound) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "\"Metrics\":{\"Enable\":false,\"Prometheus\":{\"Path\":\"/metrics\"}}") //nolint:lll // gofumpt conflicts with lll @@ -717,13 +599,11 @@ func TestServeSyncExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - So(string(data), ShouldContainSubstring, "\"Extensions\":{\"Search\":null,\"Sync\":{\"Enable\":true") }) @@ -765,13 +645,11 @@ func TestServeSyncExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - So(string(data), ShouldContainSubstring, "\"Extensions\":{\"Search\":null,\"Sync\":{\"Enable\":true") }) @@ -803,13 +681,11 @@ func TestServeSyncExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - So(string(data), ShouldContainSubstring, "\"Extensions\":{\"Search\":null,\"Sync\":{\"Enable\":false") }) @@ -839,13 +715,11 @@ func TestServeScrubExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - dataStr := string(data) So(dataStr, ShouldContainSubstring, "\"Extensions\":{\"Search\":null,\"Sync\":null,\"Metrics\":null,\"Scrub\":{\"Enable\":true,\"Interval\":86400000000000},\"Lint\":null") //nolint:lll // gofumpt conflicts with lll @@ -873,13 +747,11 @@ func TestServeScrubExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - // Even if in config we specified scrub interval=1h, the minimum interval is 2h dataStr := string(data) So(dataStr, ShouldContainSubstring, "\"Scrub\":{\"Enable\":true,\"Interval\":7200000000000}") @@ -907,13 +779,11 @@ func TestServeScrubExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - dataStr := string(data) So(dataStr, ShouldContainSubstring, "\"Extensions\":{\"Search\":null,\"Sync\":null,\"Metrics\":null,\"Scrub\":{\"Enable\":true,\"Interval\":86400000000000},\"Lint\":null") //nolint:lll // gofumpt conflicts with lll @@ -941,13 +811,11 @@ func TestServeScrubExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - dataStr := string(data) So(dataStr, ShouldContainSubstring, "\"Scrub\":{\"Enable\":false,\"Interval\":86400000000000}") So(dataStr, ShouldContainSubstring, "scrub config not provided, skipping scrub") @@ -982,13 +850,11 @@ func TestServeLintExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - So(string(data), ShouldContainSubstring, "\"Extensions\":{\"Search\":null,\"Sync\":null,\"Metrics\":null,\"Scrub\":null,\"Lint\":{\"Enable\":true,\"MandatoryAnnotations\":") //nolint:lll // gofumpt conflicts with lll }) @@ -1013,13 +879,11 @@ func TestServeLintExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - So(string(data), ShouldContainSubstring, "\"Extensions\":{\"Search\":null,\"Sync\":null,\"Metrics\":null,\"Scrub\":null,\"Lint\":{\"Enable\":false,\"MandatoryAnnotations\":null}") //nolint:lll // gofumpt conflicts with lll }) @@ -1049,11 +913,9 @@ func TestServeSearchEnabled(t *testing.T) { } }` - tempDir := t.TempDir() - logPath, err := runCLIWithConfig(tempDir, content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) // to avoid data race when multiple go routines write to trivy DB instance. - defer os.Remove(logPath) // clean up substring := `"Extensions":{"Search":{"Enable":true,"CVE":null}` @@ -1097,14 +959,11 @@ func TestServeSearchEnabledDefaultCVEDB(t *testing.T) { } }` - tempDir := t.TempDir() - logPath, err := runCLIWithConfig(tempDir, content) + logPath, rootDir, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - // to avoid data race when multiple go routines write to trivy DB instance. - WaitTillTrivyDBDownloadStarted(tempDir) + WaitTillTrivyDBDownloadStarted(rootDir) // The default config handling logic will convert the 1h interval to a 2h interval substring := "\"Search\":{\"Enable\":true,\"CVE\":{\"UpdateInterval\":7200000000000,\"Trivy\":" + @@ -1154,12 +1013,9 @@ func TestServeSearchEnabledNoCVE(t *testing.T) { } }` - tempDir := t.TempDir() - logPath, err := runCLIWithConfig(tempDir, content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - substring := `"Extensions":{"Search":{"Enable":true,"CVE":null}` //nolint:lll // gofumpt conflicts with lll found, err := ReadLogFileAndSearchString(logPath, substring, readLogFileTimeout) @@ -1202,13 +1058,11 @@ func TestServeSearchDisabled(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - dataStr := string(data) So(dataStr, ShouldContainSubstring, `"Search":{"Enable":false,"CVE":{"UpdateInterval":10800000000000,"Trivy":null}`) @@ -1243,9 +1097,8 @@ func TestServeMgmtExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up found, err := ReadLogFileAndSearchString(logPath, "setting up mgmt routes", 10*time.Second) @@ -1276,9 +1129,8 @@ func TestServeMgmtExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up found, err := ReadLogFileAndSearchString(logPath, "skip enabling the mgmt route as the config prerequisites are not met", 10*time.Second) @@ -1308,9 +1160,8 @@ func TestServeMgmtExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up found, err := ReadLogFileAndSearchString(logPath, "skip enabling the mgmt route as the config prerequisites are not met", 10*time.Second) @@ -1351,9 +1202,8 @@ func TestServeImageTrustExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up found, err := ReadLogFileAndSearchString(logPath, "skip enabling the image trust routes as the config prerequisites are not met", 10*time.Second) @@ -1388,9 +1238,8 @@ func TestServeImageTrustExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up found, err := ReadLogFileAndSearchString(logPath, "skip enabling the image trust routes as the config prerequisites are not met", 10*time.Second) @@ -1427,9 +1276,8 @@ func TestServeImageTrustExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up found, err := ReadLogFileAndSearchString(logPath, "setting up image trust routes", 10*time.Second) @@ -1463,10 +1311,6 @@ func TestOverlappingSyncRetentionConfig(t *testing.T) { defer func() { os.Args = oldArgs }() Convey("Test verify without overlapping sync and retention", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := `{ "distSpecVersion": "1.1.1", "storage": { @@ -1521,21 +1365,15 @@ func TestOverlappingSyncRetentionConfig(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - So(string(data), ShouldNotContainSubstring, "overlapping sync content") }) Convey("Test verify with overlapping sync and retention - retention would remove v4 tags", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := `{ "distSpecVersion": "1.1.1", "storage": { @@ -1588,21 +1426,15 @@ func TestOverlappingSyncRetentionConfig(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - So(string(data), ShouldContainSubstring, "overlapping sync content\":{\"Prefix\":\"infra/*") }) Convey("Test verify with overlapping sync and retention - retention would remove tags from repo", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := `{ "distSpecVersion": "1.1.1", "storage": { @@ -1653,21 +1485,15 @@ func TestOverlappingSyncRetentionConfig(t *testing.T) { } ` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - So(string(data), ShouldContainSubstring, "overlapping sync content\":{\"Prefix\":\"**") }) Convey("Test verify with overlapping sync and retention - retention would remove tags from subpath", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := `{ "distSpecVersion": "1.1.1", "storage": { @@ -1721,13 +1547,11 @@ func TestOverlappingSyncRetentionConfig(t *testing.T) { } ` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - So(string(data), ShouldContainSubstring, "overlapping sync content\":{\"Prefix\":\"prod/*") }) } @@ -1738,10 +1562,6 @@ func TestSyncWithRemoteStorageConfig(t *testing.T) { defer func() { os.Args = oldArgs }() Convey("Test verify sync with remote storage works if sync.tmpdir is provided", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - content := `{ "distSpecVersion": "1.1.1", "storage": { @@ -1787,29 +1607,19 @@ func TestSyncWithRemoteStorageConfig(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up - So(string(data), ShouldNotContainSubstring, "using both sync and remote storage features needs config.Extensions.Sync.DownloadDir to be specified") }) Convey("Test verify sync with remote storage panics if sync.tmpdir is not provided", t, func(c C) { port := GetFreePort() - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up - - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up + logPath := MakeTempFilePath(t, "zot-log.txt") content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", @@ -1853,35 +1663,24 @@ func TestSyncWithRemoteStorageConfig(t *testing.T) { ] } } - }`, t.TempDir(), port, logFile.Name()) + }`, t.TempDir(), port, logPath) - err = os.WriteFile(tmpfile.Name(), []byte(content), 0o0600) - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "serve", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "serve", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logFile.Name()) // clean up - So(string(data), ShouldContainSubstring, "using both sync and remote storage features needs config.Extensions.Sync.DownloadDir to be specified") }) Convey("Test verify sync with remote storage on subpath panics if sync.tmpdir is not provided", t, func(c C) { port := GetFreePort() - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up - - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up + logPath := MakeTempFilePath(t, "zot-log.txt") content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", @@ -1929,18 +1728,16 @@ func TestSyncWithRemoteStorageConfig(t *testing.T) { ] } } - }`, t.TempDir(), t.TempDir(), port, logFile.Name()) + }`, t.TempDir(), t.TempDir(), port, logPath) - err = os.WriteFile(tmpfile.Name(), []byte(content), 0o0600) - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "serve", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "serve", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logFile.Name()) // clean up So(string(data), ShouldContainSubstring, "using both sync and remote storage features needs config.Extensions.Sync.DownloadDir to be specified") @@ -1972,9 +1769,8 @@ func TestEventsExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up found, err := ReadLogFileAndSearchString(logPath, "events disabled in configuration", 10*time.Second) @@ -2012,12 +1808,7 @@ func TestEventsExtension(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) - defer func(p string) { - if p != "" { - os.Remove(p) - } - }(logPath) // clean up + _, _, err := runCLIWithConfig(t, content) So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, zerr.ErrUnsupportedEventSink.Error()) }) diff --git a/pkg/cli/server/root_test.go b/pkg/cli/server/root_test.go index c03aa3c4..c0946917 100644 --- a/pkg/cli/server/root_test.go +++ b/pkg/cli/server/root_test.go @@ -110,33 +110,29 @@ func TestServe(t *testing.T) { }) Convey("unknown config", func(c C) { - os.Args = []string{"cli_test", "serve", path.Join(os.TempDir(), "/x")} + tempDir := t.TempDir() + os.Args = []string{"cli_test", "serve", path.Join(tempDir, "/x")} err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("non-existent config", func(c C) { - os.Args = []string{"cli_test", "serve", path.Join(os.TempDir(), "/x.yaml")} + tempDir := t.TempDir() + os.Args = []string{"cli_test", "serve", path.Join(tempDir, "/x.yaml")} err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("bad config", func(c C) { - rootDir := t.TempDir() - - tmpFile := path.Join(rootDir, "zot-test.json") - err := os.WriteFile(tmpFile, []byte(`{"log":{}}`), 0o0600) - So(err, ShouldBeNil) + tmpFile := MakeTempFileWithContent(t, "zot-test.json", `{"log":{}}`) os.Args = []string{"cli_test", "serve", tmpFile} - err = cli.NewServerRootCmd().Execute() + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("config with missing rootDir", func(c C) { - rootDir := t.TempDir() - // missing storage config should result in an error in Controller.Init() content := []byte(`{ "distSpecVersion": "1.1.1", @@ -146,13 +142,12 @@ func TestServe(t *testing.T) { } }`) - tmpFile := path.Join(rootDir, "zot-test.json") - err := os.WriteFile(tmpFile, content, 0o0600) - So(err, ShouldBeNil) + contentStr := string(content) + tmpFile := MakeTempFileWithContent(t, "zot-test.json", contentStr) os.Args = []string{"cli_test", "serve", tmpFile} - err = cli.NewServerRootCmd().Execute() + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // wait for the config reloader goroutine to start watching the config file @@ -169,48 +164,26 @@ func TestVerify(t *testing.T) { defer func() { os.Args = oldArgs }() Convey("Test verify bad config", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", `{"log":{}}`) - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"log":{}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify config with no extension", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, + content := `{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot"}, - "log":{"level":"debug"}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "log":{"level":"debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify config with dotted config name", t, func(c C) { - tmpfile, err := os.CreateTemp("", ".zot-test*") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(` + content := ` distspecversion: 1.1.1 http: address: 127.0.0.1 @@ -220,23 +193,16 @@ log: level: debug storage: rootdirectory: /tmp/zot -`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) +` + tmpfile := MakeTempFileWithContent(t, ".zot-test", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify CVE warn for remote storage", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{ + content := `{ "storage":{ "rootDirectory":"/tmp/zot", "dedupe":true, @@ -262,15 +228,14 @@ storage: } } } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) + }` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) - content = []byte(`{ + contentBytes := []byte(`{ "storage":{ "rootDirectory":"/tmp/zot", "dedupe":true, @@ -303,21 +268,17 @@ storage: } } }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + err = os.WriteFile(tmpfile, contentBytes, 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test cached db config", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - // dedupe true, remote storage, remoteCache true, but no cacheDriver (remote) - content := []byte(`{ + content := `{ "storage":{ "rootDirectory":"/tmp/zot", "dedupe":true, @@ -342,16 +303,15 @@ storage: "failDelay":1 } } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) + }` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // local storage with remote caching - content = []byte(`{ + content = `{ "storage":{ "rootDirectory":"/tmp/zot", "dedupe":true, @@ -374,16 +334,16 @@ storage: "failDelay":1 } } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + }` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // unsupported cache driver - content = []byte(`{ + content = `{ "storage":{ "rootDirectory":"/tmp/zot", "dedupe":true, @@ -411,16 +371,16 @@ storage: "failDelay":1 } } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + }` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // remoteCache false but provided cacheDriver config, ignored - content = []byte(`{ + content = `{ "storage":{ "rootDirectory":"/tmp/zot", "dedupe":true, @@ -451,18 +411,18 @@ storage: "failDelay":1 } } - }`) + }` - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) // SubPaths // dedupe true, remote storage, remoteCache true, but no cacheDriver (remote) - content = []byte(`{ + content = `{ "storage":{ "rootDirectory":"/tmp/zot", "dedupe":false, @@ -493,16 +453,16 @@ storage: "failDelay":1 } } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + }` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // local storage with remote caching - content = []byte(`{ + content = `{ "storage":{ "rootDirectory":"/tmp/zot", "dedupe":false, @@ -531,16 +491,16 @@ storage: "failDelay":1 } } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + }` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // unsupported cache driver - content = []byte(`{ + content = `{ "storage":{ "rootDirectory":"/tmp/zot", "dedupe":false, @@ -574,16 +534,16 @@ storage: "failDelay":1 } } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + }` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // remoteCache false but provided cacheDriver config, ignored - content = []byte(`{ + content = `{ "storage":{ "rootDirectory":"/tmp/zot", "dedupe":false, @@ -612,32 +572,23 @@ storage: "failDelay":1 } } - }`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + }` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test session store config", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", "") - defer os.Remove(tmpfile.Name()) - - tmpSessionKeysFile, err := os.CreateTemp("/tmp", "keys-*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpSessionKeysFile.Name()) - - _, err = tmpSessionKeysFile.WriteString(`{ + keysContent := `{ "hashKey": "my-very-secret", "encryptKey": "another-secret" - }`, - ) - So(err, ShouldBeNil) + }` + tmpSessionKeysFile := MakeTempFileWithContent(t, "keys.json", keysContent) testCases := []struct { name string @@ -746,7 +697,7 @@ storage: "enable": true } } - }`, tmpSessionKeysFile.Name()), + }`, tmpSessionKeysFile), false, zerr.ErrBadConfig.Error() + ": session keys not supported when redis session driver is used!", }, @@ -854,10 +805,10 @@ storage: for _, testCase := range testCases { Convey(testCase.name, func() { - err = os.WriteFile(tmpfile.Name(), testCase.config, 0o0600) + err := os.WriteFile(tmpfile, testCase.config, 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() if testCase.isValid { @@ -871,12 +822,7 @@ storage: }) Convey("Test verify with bad gc retention repo patterns", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{ + content := `{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "/tmp/zot", @@ -910,25 +856,16 @@ storage: "log": { "level": "debug" } - }`) + }` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} So(cli.NewServerRootCmd().Execute(), ShouldNotBeNil) }) Convey("Test verify with bad gc image retention tag regex", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{ + content := `{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "/tmp/zot", @@ -954,37 +891,29 @@ storage: "log": { "level": "debug" } - }`) + }` - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} So(cli.NewServerRootCmd().Execute(), ShouldNotBeNil) }) Convey("Test apply defaults cache db", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpfile.Name()) // clean up - // s3 dedup=false, check for previous dedup usage and set to true if cachedb found cacheDir := t.TempDir() existingDBPath := path.Join(cacheDir, storageConstants.BoltdbName+storageConstants.DBExtensionName) - _, err = os.Create(existingDBPath) + _, err := os.Create(existingDBPath) So(err, ShouldBeNil) - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot", "dedupe": false, - "storageDriver": {"rootDirectory": "` + cacheDir + `"}}, + content := fmt.Sprintf(`{"storage":{"rootDirectory":"/tmp/zot", "dedupe": false, + "storageDriver": {"rootDirectory": "%s"}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`, cacheDir) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) @@ -994,88 +923,66 @@ storage: _, err = os.Create(existingDBPath) So(err, ShouldBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", "dedupe": true, + content = fmt.Sprintf(`{"storage":{"rootDirectory":"/tmp/zot", "dedupe": true, "subpaths": {"/a": {"rootDirectory":"/tmp/zot1", "dedupe": false, - "storageDriver": {"rootDirectory": "` + cacheDir + `"}}}}, + "storageDriver": {"rootDirectory": "%s"}}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`, cacheDir) + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // subpath s3 dedup=false, check for previous dedup usage and set to true if cachedb found cacheDir = t.TempDir() - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", "dedupe": true, + content = fmt.Sprintf(`{"storage":{"rootDirectory":"/tmp/zot", "dedupe": true, "subpaths": {"/a": {"rootDirectory":"/tmp/zot1", "dedupe": true, - "storageDriver": {"rootDirectory": "` + cacheDir + `"}}}}, + "storageDriver": {"rootDirectory": "%s"}}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`, cacheDir) + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify storage driver different than s3", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot", "storageDriver": {"name": "gcs"}}, + content := `{"storage":{"rootDirectory":"/tmp/zot", "storageDriver": {"name": "gcs"}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify subpath storage driver different than s3", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot", "storageDriver": {"name": "s3"}, + content := `{"storage":{"rootDirectory":"/tmp/zot", "storageDriver": {"name": "s3"}, "subPaths": {"/a": {"rootDirectory": "/zot-a","storageDriver": {"name": "gcs"}}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify subpath storage config", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content := `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a"},"/b": {"rootDirectory": "/zot-a"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() // Two substores of the same type cannot use the same root directory So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "cannot use the same root directory") @@ -1083,15 +990,15 @@ storage: So(err.Error(), ShouldContainSubstring, "substore (route: /b)") // sub paths that point to same directory should have same storage config. - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + contentBytes := []byte(`{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true"}, "/b": {"rootDirectory": "/zot-a","dedupe":"false"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + err = os.WriteFile(tmpfile, contentBytes, 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // Two substores of the same type cannot use the same root directory @@ -1100,95 +1007,89 @@ storage: So(err.Error(), ShouldContainSubstring, "substore (route: /b)") // sub paths that point to default root directory should not be allowed. - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + contentBytes = []byte(`{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/tmp/zot","dedupe":"true"},"/b": {"rootDirectory": "/zot-a"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + err = os.WriteFile(tmpfile, contentBytes, 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + contentBytes = []byte(`{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true","gc":"true"}, "/b": {"rootDirectory": "/zot-a","dedupe":"true","gc":"false"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + err = os.WriteFile(tmpfile, contentBytes, 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + contentBytes = []byte(`{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true","gc":"true"}, "/b": {"rootDirectory": "/zot-a","dedupe":"true","gc":"true","gcDelay":"1s"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + err = os.WriteFile(tmpfile, contentBytes, 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + contentBytes = []byte(`{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true","gc":"true","gcDelay":"1s","gcInterval":"1s"}, "/b": {"rootDirectory": "/zot-a","dedupe":"true","gc":"true","gcDelay":"1s"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + err = os.WriteFile(tmpfile, contentBytes, 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + contentBytes = []byte(`{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/tmp/zot","dedupe":"true","gc":"true","gcDelay":"1s","gcInterval":"1s"}, "/b": {"rootDirectory": "/zot-a","dedupe":"true","gc":"true","gcDelay":"1s"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + err = os.WriteFile(tmpfile, contentBytes, 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify storage config with different storage types", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - // Local and S3 stores with same rootDir should be allowed (different storage types) - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content := `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/tmp/zot", "storageDriver":{"name":"s3","rootdirectory":"/tmp/zot","region":"us-east-2", "bucket":"zot-storage","secure":true,"skipverify":false}}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) // Two local stores with same rootDir should be rejected (same storage type) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/tmp/zot"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // Two stores of the same type cannot use the same root directory @@ -1197,7 +1098,7 @@ storage: So(err.Error(), ShouldContainSubstring, "substore (route: /a)") // Two S3 stores with same rootDir should be rejected (same storage type) - content = []byte(`{"storage":{"rootDirectory":"/zot", + content = `{"storage":{"rootDirectory":"/zot", "storageDriver":{"name":"s3","rootdirectory":"/zot","region":"us-east-2", "bucket":"zot-storage","secure":true,"skipverify":false}, "dedupe":false, @@ -1206,11 +1107,11 @@ storage: "bucket":"zot-storage","secure":true,"skipverify":false}, "dedupe":false}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // Two stores of the same type cannot use the same root directory @@ -1219,21 +1120,21 @@ storage: So(err.Error(), ShouldContainSubstring, "substore (route: /a)") // Local store with nested path inside default local store should be rejected - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/tmp/zot/subdir"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "invalid storage config, substore (route: /a) root directory cannot be inside default storage root directory") // S3 store with nested path inside default S3 store should be rejected - content = []byte(`{"storage":{"rootDirectory":"/zot", + content = `{"storage":{"rootDirectory":"/zot", "storageDriver":{"name":"s3","rootdirectory":"/zot","region":"us-east-2", "bucket":"zot-storage","secure":true,"skipverify":false}, "dedupe":false, @@ -1242,57 +1143,57 @@ storage: "bucket":"zot-storage","secure":true,"skipverify":false}, "dedupe":false}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "invalid storage config, substore (route: /a) root directory cannot be inside default storage root directory") // Local store with nested path inside S3 store should be allowed (different storage types) - content = []byte(`{"storage":{"rootDirectory":"/zot", + content = `{"storage":{"rootDirectory":"/zot", "storageDriver":{"name":"s3","rootdirectory":"/zot","region":"us-east-2", "bucket":"zot-storage","secure":true,"skipverify":false}, "dedupe":false, "subPaths": {"/a": {"rootDirectory": "/zot/subdir"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) // S3 store with nested path inside local store should be allowed (different storage types) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/tmp/zot/subdir", "storageDriver":{"name":"s3","rootdirectory":"/tmp/zot/subdir","region":"us-east-2", "bucket":"zot-storage","secure":true,"skipverify":false}, "dedupe":false}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) // Two local substores with nested paths should be rejected // /a is at /tmp/zot-a (not nested in default), /b is nested inside /a - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/tmp/zot-a"}, "/b": {"rootDirectory": "/tmp/zot-a/subdir"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // /b is nested inside /a, validation reports this conflict @@ -1301,7 +1202,7 @@ storage: // Two S3 substores with nested paths should be rejected // /a is at /zot-a (not nested in default), /b is nested inside /a - content = []byte(`{"storage":{"rootDirectory":"/zot", + content = `{"storage":{"rootDirectory":"/zot", "storageDriver":{"name":"s3","rootdirectory":"/zot","region":"us-east-2", "bucket":"zot-storage","secure":true,"skipverify":false}, "dedupe":false, @@ -1314,11 +1215,11 @@ storage: "bucket":"zot-storage","secure":true,"skipverify":false}, "dedupe":false}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) // /b is nested inside /a, validation reports this conflict @@ -1327,91 +1228,62 @@ storage: // Local and S3 substores with nested paths should be allowed (different storage types) // /a is local at /tmp/zot-a (not nested in default), /b is S3 nested inside /a - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/tmp/zot-a"}, "/b": {"rootDirectory": "/tmp/zot-a/subdir", "storageDriver":{"name":"s3","rootdirectory":"/tmp/zot-a/subdir","region":"us-east-2", "bucket":"zot-storage","secure":true,"skipverify":false}, "dedupe":false}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} + os.Args = []string{"cli_test", "verify", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify w/ authorization and w/o authentication", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "accessControl":{"repositories":{},"adminPolicy":{"users":["admin"], - "actions":["read","create","update","delete"]}}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "actions":["read","create","update","delete"]}}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify w/ authorization and w/ authentication", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}, "accessControl":{"repositories":{},"adminPolicy":{"users":["admin"], - "actions":["read","create","update","delete"]}}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "actions":["read","create","update","delete"]}}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify anonymous authorization", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "accessControl":{"repositories":{"**":{"anonymousPolicy": ["read", "create"]}, "/repo":{"anonymousPolicy": ["read", "create"]}} - }}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + }}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify admin policy authz is not allowed if no authn is configured", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "accessControl":{ "repositories":{ @@ -1423,24 +1295,16 @@ storage: "actions":["read","create","update","delete"] } } - }`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + }` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify default policy authz is not allowed if no authn is configured", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "accessControl":{ "repositories": { @@ -1448,24 +1312,16 @@ storage: "/repo":{"anonymousPolicy": ["read", "create"]} } } - }}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + }}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify authz per user policies fail if no authn is configured", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "accessControl":{ "repositories": { @@ -1478,683 +1334,414 @@ storage: } } } - }}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + }}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify w/ sync and w/o filesystem storage", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot", "storageDriver": {"name": "s3"}}, + content := `{"storage":{"rootDirectory":"/tmp/zot", "storageDriver": {"name": "s3"}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], - "maxRetries": 1, "retryDelay": "10s"}]}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "maxRetries": 1, "retryDelay": "10s"}]}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify w/ sync and w/ filesystem storage", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], - "maxRetries": 1, "retryDelay": "10s"}]}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "maxRetries": 1, "retryDelay": "10s"}]}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify with bad sync prefixes", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 1, "retryDelay": "10s", - "content": [{"prefix":"[repo%^&"}]}]}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "content": [{"prefix":"[repo%^&"}]}]}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify with bad preserve digest and no compat", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 1, "retryDelay": "10s", - "preserveDigest": true}]}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "preserveDigest": true}]}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify with bad sync content config", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 1, "retryDelay": "10s", - "content": [{"prefix":"zot-repo","stripPrefix":true,"destination":"/"}]}]}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "content": [{"prefix":"zot-repo","stripPrefix":true,"destination":"/"}]}]}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify with good sync content config", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 1, "retryDelay": "10s", - "content": [{"prefix":"zot-repo/*","stripPrefix":true,"destination":"/"}]}]}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "content": [{"prefix":"zot-repo/*","stripPrefix":true,"destination":"/"}]}]}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify with bad authorization repo patterns", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}, - "accessControl":{"repositories":{"[":{"policies":[],"anonymousPolicy":[]}}}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "accessControl":{"repositories":{"[":{"policies":[],"anonymousPolicy":[]}}}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify sync config default tls value", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], "maxRetries": 1, "retryDelay": "10s", - "content": [{"prefix":"repo**"}]}]}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "content": [{"prefix":"repo**"}]}]}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify sync without retry options", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot"}, + content := `{"storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}, "extensions":{"sync": {"registries": [{"urls":["localhost:9999"], - "maxRetries": 10, "content": [{"prefix":"repo**"}]}]}}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "maxRetries": 10, "content": [{"prefix":"repo**"}]}]}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify config with unknown keys", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot"}, + content := `{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot"}, "http": {"url": "127.0.0.1", "port": "8080"}, - "log": {"level": "debug"}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "log": {"level": "debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify openid config with missing parameter", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, + content := `{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"openid":{"providers":{"oidc":{"issuer":"http://127.0.0.1:5556/dex"}}}}}, - "log":{"level":"debug"}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "log":{"level":"debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify oauth2 config with missing parameter scopes", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, + content := `{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"openid":{"providers":{"github":{"clientid":"client_id"}}}}}, - "log":{"level":"debug"}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "log":{"level":"debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify oauth2 config with missing parameter clientid", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, + content := `{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"openid":{"providers":{"github":{"scopes":["openid"]}}}}}, - "log":{"level":"debug"}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "log":{"level":"debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify openid config with unsupported provider", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, + content := `{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"openid":{"providers":{"unsupported":{"issuer":"http://127.0.0.1:5556/dex"}}}}}, - "log":{"level":"debug"}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "log":{"level":"debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify openid config without apikey extension enabled", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - tmpCredsFile, err := os.CreateTemp("", "zot-cred*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpCredsFile.Name()) - - content := []byte(`{ + //nolint:gosec // test credentials + credsContent := `{ "clientid":"client-id", "clientsecret":"client-secret" - }`) + }` + tmpCredsFile := MakeTempFileWithContent(t, "zot-cred.json", credsContent) - _, err = tmpCredsFile.Write(content) - So(err, ShouldBeNil) - err = tmpCredsFile.Close() - So(err, ShouldBeNil) - - content = fmt.Appendf([]byte{}, `{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, + configContent := fmt.Sprintf(`{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"openid":{"providers":{"oidc":{"issuer":"http://127.0.0.1:5556/dex", "credentialsFile":"%s","scopes":["openid"]}}}}}, "log":{"level":"debug"}}`, - tmpCredsFile.Name(), + tmpCredsFile, ) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", configContent) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify config with missing basedn key", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot"}, + content := `{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot"}, "http": {"auth": {"ldap": {"address": "ldap", "userattribute": "uid"}}, "address": "127.0.0.1", "port": "8080"}, - "log": {"level": "debug"}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "log": {"level": "debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify config with missing address key", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot"}, + content := `{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot"}, "http": {"auth": {"ldap": {"basedn": "ou=Users,dc=example,dc=org", "userattribute": "uid"}}, "address": "127.0.0.1", "port": "8080"}, - "log": {"level": "debug"}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "log": {"level": "debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify config with missing userattribute key", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot"}, + content := `{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot"}, "http": {"auth": {"ldap": {"basedn": "ou=Users,dc=example,dc=org", "address": "ldap"}}, "address": "127.0.0.1", "port": "8080"}, - "log": {"level": "debug"}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "log": {"level": "debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("Test verify good config", t, func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot"}, + content := `{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot"}, "http": {"address": "127.0.0.1", "port": "8080"}, - "log": {"level": "debug"}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + "log": {"level": "debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "verify", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify good session keys config with both keys", t, func(c C) { - tmpFile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpFile.Name()) - - tmpCredsFile, err := os.CreateTemp("", "zot-cred*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpCredsFile.Name()) - - content := []byte(`{ + //nolint:gosec // test credentials + credsContent := `{ "hashKey":"very-secret", "encryptKey":"another-secret" - }`) + }` + tmpCredsFile := MakeTempFileWithContent(t, "zot-cred.json", credsContent) - _, err = tmpCredsFile.Write(content) - So(err, ShouldBeNil) - err = tmpCredsFile.Close() - So(err, ShouldBeNil) - - content = fmt.Appendf([]byte{}, `{ "distSpecVersion": "1.1.1", + configContent := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "/tmp/zot" }, "http": { "address": "127.0.0.1", "port": "8080", "auth":{"htpasswd":{"path":"test/data/htpasswd"}, "sessionKeysFile": "%s", "failDelay": 5 } }, "log": { "level": "debug" } }`, - tmpCredsFile.Name(), + tmpCredsFile, ) + tmpFile := MakeTempFileWithContent(t, "zot-test.json", configContent) - _, err = tmpFile.Write(content) - So(err, ShouldBeNil) - err = tmpFile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "verify", tmpFile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpFile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify good session keys config with one key", t, func(c C) { - tmpFile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpFile.Name()) - - tmpCredsFile, err := os.CreateTemp("", "zot-cred*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpCredsFile.Name()) - - content := []byte(`{ + //nolint:gosec // test credentials + credsContent := `{ "hashKey":"very-secret" - }`) + }` + tmpCredsFile := MakeTempFileWithContent(t, "zot-cred.json", credsContent) - _, err = tmpCredsFile.Write(content) - So(err, ShouldBeNil) - err = tmpCredsFile.Close() - So(err, ShouldBeNil) - - content = fmt.Appendf([]byte{}, `{ "distSpecVersion": "1.1.1", + configContent := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "/tmp/zot" }, "http": { "address": "127.0.0.1", "port": "8080", "auth":{"htpasswd":{"path":"test/data/htpasswd"}, "sessionKeysFile": "%s", "failDelay": 5 } }, "log": { "level": "debug" } }`, - tmpCredsFile.Name(), + tmpCredsFile, ) + tmpFile := MakeTempFileWithContent(t, "zot-test.json", configContent) - _, err = tmpFile.Write(content) - So(err, ShouldBeNil) - err = tmpFile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "verify", tmpFile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpFile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify good ldap config", t, func(c C) { - tmpFile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpFile.Name()) - - tmpCredsFile, err := os.CreateTemp("", "zot-cred*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpCredsFile.Name()) - - content := []byte(`{ + //nolint:gosec // test credentials + credsContent := `{ "bindDN":"cn=ldap-searcher,ou=Users,dc=example,dc=org", "bindPassword":"ldap-searcher-password" - }`) + }` + tmpCredsFile := MakeTempFileWithContent(t, "zot-cred.json", credsContent) - _, err = tmpCredsFile.Write(content) - So(err, ShouldBeNil) - err = tmpCredsFile.Close() - So(err, ShouldBeNil) - - content = fmt.Appendf([]byte{}, `{ "distSpecVersion": "1.1.1", + configContent := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "/tmp/zot" }, "http": { "address": "127.0.0.1", "port": "8080", "auth": { "ldap": { "credentialsFile": "%v", "address": "ldap.example.org", "port": 389, "startTLS": false, "baseDN": "ou=Users,dc=example,dc=org", "userAttribute": "uid", "userGroupAttribute": "memberOf", "skipVerify": true, "subtreeSearch": true }, "failDelay": 5 } }, "log": { "level": "debug" } }`, - tmpCredsFile.Name(), + tmpCredsFile, ) + tmpFile := MakeTempFileWithContent(t, "zot-test.json", configContent) - _, err = tmpFile.Write(content) - So(err, ShouldBeNil) - err = tmpFile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "verify", tmpFile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpFile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) }) Convey("Test verify bad ldap config: key is missing", t, func(c C) { - tmpFile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpFile.Name()) - - tmpCredsFile, err := os.CreateTemp("", "zot-cred*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpCredsFile.Name()) - // `bindDN` key is missing - content := []byte(`{ + //nolint:gosec // test credentials + credsContent := `{ "bindPassword":"ldap-searcher-password" - }`) + }` + tmpCredsFile := MakeTempFileWithContent(t, "zot-cred.json", credsContent) - _, err = tmpCredsFile.Write(content) - So(err, ShouldBeNil) - err = tmpCredsFile.Close() - So(err, ShouldBeNil) - - content = fmt.Appendf([]byte{}, `{ "distSpecVersion": "1.1.1", + configContent := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "/tmp/zot" }, "http": { "address": "127.0.0.1", "port": "8080", "auth": { "ldap": { "credentialsFile": "%v", "address": "ldap.example.org", "port": 389, "startTLS": false, "baseDN": "ou=Users,dc=example,dc=org", "userAttribute": "uid", "userGroupAttribute": "memberOf", "skipVerify": true, "subtreeSearch": true }, "failDelay": 5 } }, "log": { "level": "debug" } }`, - tmpCredsFile.Name(), + tmpCredsFile, ) + tmpFile := MakeTempFileWithContent(t, "zot-test.json", configContent) - _, err = tmpFile.Write(content) - So(err, ShouldBeNil) - err = tmpFile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "verify", tmpFile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpFile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "invalid server config") }) Convey("Test verify bad ldap config: unused key", t, func(c C) { - tmpFile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpFile.Name()) - - tmpCredsFile, err := os.CreateTemp("", "zot-cred*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpCredsFile.Name()) - - content := []byte(`{ + //nolint:gosec // test credentials + credsContent := `{ "bindDN":"cn=ldap-searcher,ou=Users,dc=example,dc=org", "bindPassword":"ldap-searcher-password", "extraKey": "extraValue" - }`) + }` + tmpCredsFile := MakeTempFileWithContent(t, "zot-cred.json", credsContent) - _, err = tmpCredsFile.Write(content) - So(err, ShouldBeNil) - err = tmpCredsFile.Close() - So(err, ShouldBeNil) - - content = fmt.Appendf([]byte{}, `{ "distSpecVersion": "1.1.1", + configContent := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "/tmp/zot" }, "http": { "address": "127.0.0.1", "port": "8080", "auth": { "ldap": { "credentialsFile": "%v", "address": "ldap.example.org", "port": 389, "startTLS": false, "baseDN": "ou=Users,dc=example,dc=org", "userAttribute": "uid", "userGroupAttribute": "memberOf", "skipVerify": true, "subtreeSearch": true }, "failDelay": 5 } }, "log": { "level": "debug" } }`, - tmpCredsFile.Name(), + tmpCredsFile, ) + tmpFile := MakeTempFileWithContent(t, "zot-test.json", configContent) - _, err = tmpFile.Write(content) - So(err, ShouldBeNil) - err = tmpFile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "verify", tmpFile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpFile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "invalid server config") }) Convey("Test verify bad ldap config: empty credentials file", t, func(c C) { - tmpFile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpFile.Name()) - - tmpCredsFile, err := os.CreateTemp("", "zot-cred*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpCredsFile.Name()) - // `bindDN` key is missing - content := []byte(``) + credsContent := `` + tmpCredsFile := MakeTempFileWithContent(t, "zot-cred.json", credsContent) - _, err = tmpCredsFile.Write(content) - So(err, ShouldBeNil) - err = tmpCredsFile.Close() - So(err, ShouldBeNil) - - content = fmt.Appendf([]byte{}, `{ "distSpecVersion": "1.1.1", + configContent := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "/tmp/zot" }, "http": { "address": "127.0.0.1", "port": "8080", "auth": { "ldap": { "credentialsFile": "%v", "address": "ldap.example.org", "port": 389, "startTLS": false, "baseDN": "ou=Users,dc=example,dc=org", "userAttribute": "uid", "userGroupAttribute": "memberOf", "skipVerify": true, "subtreeSearch": true }, "failDelay": 5 } }, "log": { "level": "debug" } }`, - tmpCredsFile.Name(), + tmpCredsFile, ) + tmpFile := MakeTempFileWithContent(t, "zot-test.json", configContent) - _, err = tmpFile.Write(content) - So(err, ShouldBeNil) - err = tmpFile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "verify", tmpFile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpFile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "invalid server config") }) Convey("Test verify bad ldap config: no keys set in credentials file", t, func(c C) { - tmpFile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpFile.Name()) - - tmpCredsFile, err := os.CreateTemp("", "zot-cred*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpCredsFile.Name()) - // empty json - content := []byte(`{}`) + credsContent := `{}` + tmpCredsFile := MakeTempFileWithContent(t, "zot-cred.json", credsContent) - _, err = tmpCredsFile.Write(content) - So(err, ShouldBeNil) - err = tmpCredsFile.Close() - So(err, ShouldBeNil) - - content = fmt.Appendf([]byte{}, `{ "distSpecVersion": "1.1.1", + configContent := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "/tmp/zot" }, "http": { "address": "127.0.0.1", "port": "8080", "auth": { "ldap": { "credentialsFile": "%v", "address": "ldap.example.org", "port": 389, "startTLS": false, "baseDN": "ou=Users,dc=example,dc=org", "userAttribute": "uid", "userGroupAttribute": "memberOf", "skipVerify": true, "subtreeSearch": true }, "failDelay": 5 } }, "log": { "level": "debug" } }`, - tmpCredsFile.Name(), + tmpCredsFile, ) + tmpFile := MakeTempFileWithContent(t, "zot-test.json", configContent) - _, err = tmpFile.Write(content) - So(err, ShouldBeNil) - err = tmpFile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "verify", tmpFile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "verify", tmpFile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "invalid server config") }) @@ -2163,38 +1750,23 @@ storage: func TestApiKeyConfig(t *testing.T) { Convey("Test API Keys are enabled if OpenID is enabled", t, func(c C) { config := config.New() - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - tmpCredsFile, err := os.CreateTemp("", "zot-cred*.json") - So(err, ShouldBeNil) - defer os.Remove(tmpCredsFile.Name()) - - content := []byte(`{ + //nolint:gosec // test credentials + credsContent := `{ "clientid":"client-id", "clientsecret":"client-secret" - }`) + }` + tmpCredsFile := MakeTempFileWithContent(t, "zot-cred.json", credsContent) - _, err = tmpCredsFile.Write(content) - So(err, ShouldBeNil) - err = tmpCredsFile.Close() - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) - - content = fmt.Appendf([]byte{}, `{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, + configContent := fmt.Sprintf(`{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"openid":{"providers":{"oidc":{"issuer":"http://127.0.0.1:5556/dex", "credentialsFile":"%s","scopes":["openid"]}}}}}, "log":{"level":"debug"}}`, - tmpCredsFile.Name(), + tmpCredsFile, ) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", configContent) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + err := cli.LoadConfiguration(config, tmpfile) So(err, ShouldBeNil) So(config.HTTP.Auth, ShouldNotBeNil) So(config.HTTP.Auth.APIKey, ShouldBeTrue) @@ -2202,18 +1774,12 @@ func TestApiKeyConfig(t *testing.T) { Convey("Test API Keys are not enabled by default", t, func(c C) { config := config.New() - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) - - content := []byte(`{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, + content := `{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot"}, - "log":{"level":"debug"}}`) + "log":{"level":"debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + err := cli.LoadConfiguration(config, tmpfile) So(err, ShouldBeNil) So(config.HTTP.Auth, ShouldNotBeNil) So(config.HTTP.Auth.APIKey, ShouldBeFalse) @@ -2221,19 +1787,13 @@ func TestApiKeyConfig(t *testing.T) { Convey("Test API Keys are not enabled if OpenID is not enabled", t, func(c C) { config := config.New() - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) - - content := []byte(`{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, + content := `{"distSpecVersion":"1.1.1","storage":{"rootDirectory":"/tmp/zot"}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", "auth":{"htpasswd":{"path":"test/data/htpasswd"}}}, - "log":{"level":"debug"}}`) + "log":{"level":"debug"}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + err := cli.LoadConfiguration(config, tmpfile) So(err, ShouldBeNil) So(config.HTTP.Auth, ShouldNotBeNil) So(config.HTTP.Auth.APIKey, ShouldBeFalse) @@ -2263,12 +1823,11 @@ func TestServeAPIKey(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up So(string(data), ShouldContainSubstring, "\"APIKey\":true") // verify configuration settings message is present So(string(data), ShouldContainSubstring, "configuration settings") @@ -2301,12 +1860,11 @@ func TestServeAPIKey(t *testing.T) { } }` - logPath, err := runCLIWithConfig(t.TempDir(), content) + logPath, _, err := runCLIWithConfig(t, content) So(err, ShouldBeNil) data, err := os.ReadFile(logPath) So(err, ShouldBeNil) - defer os.Remove(logPath) // clean up So(string(data), ShouldContainSubstring, "\"APIKey\":false") // verify configuration settings message is present So(string(data), ShouldContainSubstring, "configuration settings") @@ -2330,69 +1888,63 @@ func TestLoadConfig(t *testing.T) { }) Convey("Test subpath config combination", t, func(c C) { config := config.New() - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content := `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/tmp/zot","dedupe":"true","gc":"true","gcDelay":"1s","gcInterval":"1s"}, "/b": {"rootDirectory": "/zot-a","dedupe":"true","gc":"true","gcDelay":"1s"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) + err := cli.LoadConfiguration(config, tmpfile) So(err, ShouldNotBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true","gc":"true","gcDelay":"1s","gcInterval":"1s"}, "/b": {"rootDirectory": "/zot-a","dedupe":"true","gc":"true","gcDelay":"1s"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + err = cli.LoadConfiguration(config, tmpfile) So(err, ShouldNotBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true"}, "/b": {"rootDirectory": "/zot-a","dedupe":"false"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + err = cli.LoadConfiguration(config, tmpfile) So(err, ShouldNotBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true","gc":"true","gcDelay":"0s"}, "/b": {"rootDirectory": "/zot-a","dedupe":"true"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + err = cli.LoadConfiguration(config, tmpfile) So(err, ShouldNotBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true","gc":"true"}, "/b": {"rootDirectory": "/b","dedupe":"true"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + err = cli.LoadConfiguration(config, tmpfile) So(err, ShouldBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true"}, "/b": {"rootDirectory": "/zot-a","dedupe":"true"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + err = cli.LoadConfiguration(config, tmpfile) // Two substores of the same type cannot use the same root directory So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "cannot use the same root directory") @@ -2402,39 +1954,33 @@ func TestLoadConfig(t *testing.T) { Convey("Test HTTP port", t, func() { config := config.New() - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) - - content := []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content := `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true"}, "/b": {"rootDirectory": "/zot-b","dedupe":"true"}}}, "http":{"address":"127.0.0.1","port":"8080","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) + err := cli.LoadConfiguration(config, tmpfile) So(err, ShouldBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true"}, "/b": {"rootDirectory": "/zot-b","dedupe":"true"}}}, "http":{"address":"127.0.0.1","port":"-1","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + err = cli.LoadConfiguration(config, tmpfile) So(err, ShouldNotBeNil) - content = []byte(`{"storage":{"rootDirectory":"/tmp/zot", + content = `{"storage":{"rootDirectory":"/tmp/zot", "subPaths": {"/a": {"rootDirectory": "/zot-a","dedupe":"true"}, "/b": {"rootDirectory": "/zot-a","dedupe":"true"}}}, "http":{"address":"127.0.0.1","port":"65536","realm":"zot", - "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}`) - err = os.WriteFile(tmpfile.Name(), content, 0o0600) + "auth":{"htpasswd":{"path":"test/data/htpasswd"},"failDelay":1}}}` + err = os.WriteFile(tmpfile, []byte(content), 0o0600) So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, tmpfile.Name()) + err = cli.LoadConfiguration(config, tmpfile) So(err, ShouldNotBeNil) }) } @@ -2461,16 +2007,11 @@ func TestGC(t *testing.T) { err = json.Unmarshal(contents, config) config.Storage.GC = false - file, err := os.CreateTemp("", "gc-config-*.json") - So(err, ShouldBeNil) - defer os.Remove(file.Name()) - contents, err = json.MarshalIndent(config, "", " ") So(err, ShouldBeNil) - err = os.WriteFile(file.Name(), contents, 0o600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, file.Name()) + file := MakeTempFileWithContent(t, "gc-config.json", string(contents)) + err = cli.LoadConfiguration(config, file) So(err, ShouldBeNil) }) @@ -2481,16 +2022,11 @@ func TestGC(t *testing.T) { config.Storage.GCDelay = 0 config.Storage.GCInterval = 24 * time.Hour - file, err := os.CreateTemp("", "gc-config-*.json") - So(err, ShouldBeNil) - defer os.Remove(file.Name()) - contents, err = json.MarshalIndent(config, "", " ") So(err, ShouldBeNil) - err = os.WriteFile(file.Name(), contents, 0o600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, file.Name()) + file := MakeTempFileWithContent(t, "gc-config.json", string(contents)) + err = cli.LoadConfiguration(config, file) So(err, ShouldBeNil) }) @@ -2499,33 +2035,23 @@ func TestGC(t *testing.T) { err = json.Unmarshal(contents, config) config.Storage.GCDelay = -1 * time.Second - file, err := os.CreateTemp("", "gc-config-*.json") - So(err, ShouldBeNil) - defer os.Remove(file.Name()) - contents, err = json.MarshalIndent(config, "", " ") So(err, ShouldBeNil) - err = os.WriteFile(file.Name(), contents, 0o600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, file.Name()) + file := MakeTempFileWithContent(t, "gc-config.json", string(contents)) + err = cli.LoadConfiguration(config, file) So(err, ShouldNotBeNil) }) Convey("GC delay when GC = false", func() { config := config.New() - file, err := os.CreateTemp("", "gc-false-config-*.json") - So(err, ShouldBeNil) - defer os.Remove(file.Name()) - - content := []byte(`{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot", + content := `{"distSpecVersion": "1.0.0", "storage": {"rootDirectory": "/tmp/zot", "gc": false}, "http": {"address": "127.0.0.1", "port": "8080"}, - "log": {"level": "debug"}}`) + "log": {"level": "debug"}}` - err = os.WriteFile(file.Name(), content, 0o600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, file.Name()) + file := MakeTempFileWithContent(t, "gc-false-config.json", content) + err = cli.LoadConfiguration(config, file) So(err, ShouldBeNil) So(config.Storage.GCDelay, ShouldEqual, 0) }) @@ -2535,16 +2061,11 @@ func TestGC(t *testing.T) { err = json.Unmarshal(contents, config) config.Storage.GCInterval = -1 * time.Second - file, err := os.CreateTemp("", "gc-config-*.json") - So(err, ShouldBeNil) - defer os.Remove(file.Name()) - contents, err = json.MarshalIndent(config, "", " ") So(err, ShouldBeNil) - err = os.WriteFile(file.Name(), contents, 0o600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(config, file.Name()) + file := MakeTempFileWithContent(t, "gc-config.json", string(contents)) + err = cli.LoadConfiguration(config, file) So(err, ShouldNotBeNil) }) }) @@ -2569,31 +2090,25 @@ func TestScrub(t *testing.T) { Convey("Test scrub config", t, func(c C) { Convey("non-existent config", func(c C) { - os.Args = []string{"cli_test", "scrub", path.Join(os.TempDir(), "/x.yaml")} + tempDir := t.TempDir() + os.Args = []string{"cli_test", "scrub", path.Join(tempDir, "/x.yaml")} err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("unknown config", func(c C) { - os.Args = []string{"cli_test", "scrub", path.Join(os.TempDir(), "/x")} + tempDir := t.TempDir() + os.Args = []string{"cli_test", "scrub", path.Join(tempDir, "/x")} err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("bad config", func(c C) { - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) + content := `{"log":{}}` + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - defer os.Remove(tmpfile.Name()) // clean up - - content := []byte(`{"log":{}}`) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) - - os.Args = []string{"cli_test", "scrub", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "scrub", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) @@ -2609,12 +2124,7 @@ func TestScrub(t *testing.T) { ctrlManager := NewControllerManager(controller) ctrlManager.StartAndWait(port) - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "storage": { "rootDirectory": "%s" }, @@ -2626,13 +2136,10 @@ func TestScrub(t *testing.T) { } } `, dir, port) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "scrub", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "scrub", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) defer ctrlManager.StopServer() @@ -2641,12 +2148,7 @@ func TestScrub(t *testing.T) { Convey("no image store provided", func(c C) { port := GetFreePort() - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "storage": { "rootDirectory": "" }, @@ -2658,13 +2160,10 @@ func TestScrub(t *testing.T) { } } `, port) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "scrub", tmpfile.Name()} - err = cli.NewServerRootCmd().Execute() + os.Args = []string{"cli_test", "scrub", tmpfile} + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) @@ -2675,15 +2174,12 @@ func TestScrub(t *testing.T) { repoName := "badindex" - repo, err := os.MkdirTemp(dir, repoName) - if err != nil { - panic(err) - } - - if err := os.MkdirAll(repo+"/blobs", 0o755); err != nil { + repo := filepath.Join(dir, repoName) + if err := os.MkdirAll(filepath.Join(repo, "blobs"), 0o755); err != nil { panic(err) } + var err error if _, err = os.Stat(repo + "/oci-layout"); err != nil { content := []byte(`{"imageLayoutVersion": "1.0.0"}`) if err = os.WriteFile(repo+"/oci-layout", content, 0o600); err != nil { @@ -2698,12 +2194,7 @@ func TestScrub(t *testing.T) { } } - tmpfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(tmpfile.Name()) // clean up - - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "storage": { "rootDirectory": "%s" }, @@ -2715,12 +2206,9 @@ func TestScrub(t *testing.T) { } } `, dir, port) - _, err = tmpfile.Write(content) - So(err, ShouldBeNil) - err = tmpfile.Close() - So(err, ShouldBeNil) + tmpfile := MakeTempFileWithContent(t, "zot-test.json", content) - os.Args = []string{"cli_test", "scrub", tmpfile.Name()} + os.Args = []string{"cli_test", "scrub", tmpfile} err = cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) @@ -2729,12 +2217,8 @@ func TestScrub(t *testing.T) { func TestUpdateLDAPConfig(t *testing.T) { Convey("updateLDAPConfig errors while unmarshaling ldap config", t, func() { - tempDir := t.TempDir() ldapConfigContent := "bad-json" - ldapConfigPath := filepath.Join(tempDir, "ldap.json") - - err := os.WriteFile(ldapConfigPath, []byte(ldapConfigContent), 0o000) - So(err, ShouldBeNil) + ldapConfigPath := MakeTempFileWithContent(t, "ldap.json", ldapConfigContent) configStr := fmt.Sprintf(` { @@ -2756,18 +2240,15 @@ func TestUpdateLDAPConfig(t *testing.T) { } } } - }`, tempDir, "127.0.0.1", "8000", ldapConfigPath, "LDAPBaseDN", "LDAPAddress", 1000) + }`, t.TempDir(), "127.0.0.1", "8000", ldapConfigPath, "LDAPBaseDN", "LDAPAddress", 1000) - configPath := filepath.Join(tempDir, "config.json") - - err = os.WriteFile(configPath, []byte(configStr), 0o0600) - So(err, ShouldBeNil) + configPath := MakeTempFileWithContent(t, "config.json", configStr) server := cli.NewServerRootCmd() server.SetArgs([]string{"serve", configPath}) So(server.Execute(), ShouldNotBeNil) - err = os.Chmod(ldapConfigPath, 0o600) + err := os.Chmod(ldapConfigPath, 0o600) So(err, ShouldBeNil) server = cli.NewServerRootCmd() @@ -2799,12 +2280,9 @@ func TestUpdateLDAPConfig(t *testing.T) { } }`, tempDir, "127.0.0.1", "8000", "LDAPBaseDN", "LDAPAddress", 1000) - configPath := filepath.Join(tempDir, "config.json") + configPath := MakeTempFileWithContent(t, "config.json", configStr) - err := os.WriteFile(configPath, []byte(configStr), 0o0600) - So(err, ShouldBeNil) - - err = cli.LoadConfiguration(config.New(), configPath) + err := cli.LoadConfiguration(config.New(), configPath) So(err, ShouldBeNil) }) } @@ -2842,16 +2320,11 @@ func TestClusterConfig(t *testing.T) { // set the members to an empty list cfg.Cluster.Members = []string{} - file, err := os.CreateTemp("", "cluster-config-*.json") - So(err, ShouldBeNil) - defer os.Remove(file.Name()) - cfgFileContents, err := json.MarshalIndent(cfg, "", " ") So(err, ShouldBeNil) - err = os.WriteFile(file.Name(), cfgFileContents, 0o600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(cfg, file.Name()) + file := MakeTempFileWithContent(t, "cluster-config.json", string(cfgFileContents)) + err = cli.LoadConfiguration(cfg, file) So(err, ShouldNotBeNil) }) @@ -2872,13 +2345,8 @@ func TestClusterConfig(t *testing.T) { } }` - file, err := os.CreateTemp("", "cluster-config-*.json") - So(err, ShouldBeNil) - defer os.Remove(file.Name()) - - err = os.WriteFile(file.Name(), []byte(configStr), 0o600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(cfg, file.Name()) + file := MakeTempFileWithContent(t, "cluster-config.json", configStr) + err = cli.LoadConfiguration(cfg, file) So(err, ShouldNotBeNil) }) @@ -2899,13 +2367,8 @@ func TestClusterConfig(t *testing.T) { } }` - file, err := os.CreateTemp("", "cluster-config-*.json") - So(err, ShouldBeNil) - defer os.Remove(file.Name()) - - err = os.WriteFile(file.Name(), []byte(configStr), 0o600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(cfg, file.Name()) + file := MakeTempFileWithContent(t, "cluster-config.json", configStr) + err = cli.LoadConfiguration(cfg, file) So(err, ShouldNotBeNil) }) @@ -2917,16 +2380,11 @@ func TestClusterConfig(t *testing.T) { // set the hashkey to a string shorter than 16 characters cfg.Cluster.HashKey = "fifteencharacte" - file, err := os.CreateTemp("", "cluster-config-*.json") - So(err, ShouldBeNil) - defer os.Remove(file.Name()) - cfgFileContents, err := json.MarshalIndent(cfg, "", " ") So(err, ShouldBeNil) - err = os.WriteFile(file.Name(), cfgFileContents, 0o600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(cfg, file.Name()) + file := MakeTempFileWithContent(t, "cluster-config.json", string(cfgFileContents)) + err = cli.LoadConfiguration(cfg, file) So(err, ShouldNotBeNil) }) @@ -2938,49 +2396,32 @@ func TestClusterConfig(t *testing.T) { // set the hashkey to a string longer than 16 characters cfg.Cluster.HashKey = "seventeencharacte" - file, err := os.CreateTemp("", "cluster-config-*.json") - So(err, ShouldBeNil) - defer os.Remove(file.Name()) - cfgFileContents, err := json.MarshalIndent(cfg, "", " ") So(err, ShouldBeNil) - err = os.WriteFile(file.Name(), cfgFileContents, 0o600) - So(err, ShouldBeNil) - err = cli.LoadConfiguration(cfg, file.Name()) + file := MakeTempFileWithContent(t, "cluster-config.json", string(cfgFileContents)) + err = cli.LoadConfiguration(cfg, file) So(err, ShouldNotBeNil) }) }) } -// run cli and return output. -func runCLIWithConfig(tempDir string, config string) (string, error) { +// run cli and return output (logPath, rootDir, error). +// +//nolint:unparam // rootDir used by callers waiting for Trivy DB, build tags may not be available. +func runCLIWithConfig(t *testing.T, config string) (string, string, error) { + t.Helper() port := GetFreePort() baseURL := GetBaseURL(port) - logFile, err := os.CreateTemp(tempDir, "zot-log*.txt") - if err != nil { - return "", err - } + logPath := MakeTempFilePath(t, "zot-log.txt") - cfgfile, err := os.CreateTemp(tempDir, "zot-test*.json") - if err != nil { - return "", err - } + rootDir := t.TempDir() + config = fmt.Sprintf(config, rootDir, port, logPath) - config = fmt.Sprintf(config, tempDir, port, logFile.Name()) + cfgfile := MakeTempFileWithContent(t, "zot-test.json", config) - _, err = cfgfile.WriteString(config) - if err != nil { - return "", err - } - - err = cfgfile.Close() - if err != nil { - return "", err - } - - os.Args = []string{"cli_test", "serve", cfgfile.Name()} + os.Args = []string{"cli_test", "serve", cfgfile} // Run CLI in a goroutine, but handle errors via a channel errCh := make(chan error, 1) @@ -2992,24 +2433,23 @@ func runCLIWithConfig(tempDir string, config string) (string, error) { select { case err := <-errCh: if err != nil { - return "", err + return "", "", err } case <-time.After(250 * time.Millisecond): // No startup error } WaitTillServerReady(baseURL) - return logFile.Name(), nil + return logPath, rootDir, nil } func TestRetentionDelayDefaults(t *testing.T) { Convey("Test retention delay defaults to GC delay", t, func() { Convey("When retention delay is not specified, it should default to GC delay", func() { config := config.New() - tempDir := t.TempDir() // Config with GC enabled but no retention delay specified - content := []byte(`{ + content := `{ "storage": { "rootDirectory": "/tmp/zot", "gc": true, @@ -3019,12 +2459,10 @@ func TestRetentionDelayDefaults(t *testing.T) { "address": "127.0.0.1", "port": "8080" } - }`) - tmpfile := path.Join(tempDir, "config.json") - err := os.WriteFile(tmpfile, content, 0o0600) - So(err, ShouldBeNil) + }` + configPath := MakeTempFileWithContent(t, "zot-test.json", content) - err = cli.LoadConfiguration(config, tmpfile) + err := cli.LoadConfiguration(config, configPath) So(err, ShouldBeNil) // Verify GC delay is set correctly @@ -3035,10 +2473,9 @@ func TestRetentionDelayDefaults(t *testing.T) { Convey("When retention delay is explicitly specified, it should use that value", func() { config := config.New() - tempDir := t.TempDir() // Config with explicit retention delay - content := []byte(`{ + content := `{ "storage": { "rootDirectory": "/tmp/zot", "gc": true, @@ -3051,12 +2488,10 @@ func TestRetentionDelayDefaults(t *testing.T) { "address": "127.0.0.1", "port": "8080" } - }`) - tmpfile := path.Join(tempDir, "config.json") - err := os.WriteFile(tmpfile, content, 0o0600) - So(err, ShouldBeNil) + }` + configPath := MakeTempFileWithContent(t, "zot-test.json", content) - err = cli.LoadConfiguration(config, tmpfile) + err := cli.LoadConfiguration(config, configPath) So(err, ShouldBeNil) // Verify GC delay is set correctly @@ -3067,10 +2502,9 @@ func TestRetentionDelayDefaults(t *testing.T) { Convey("When GC is disabled, retention delay should be 0", func() { config := config.New() - tempDir := t.TempDir() // Config with GC disabled - content := []byte(`{ + content := `{ "storage": { "rootDirectory": "/tmp/zot", "gc": false @@ -3079,12 +2513,10 @@ func TestRetentionDelayDefaults(t *testing.T) { "address": "127.0.0.1", "port": "8080" } - }`) - tmpfile := path.Join(tempDir, "config.json") - err := os.WriteFile(tmpfile, content, 0o0600) - So(err, ShouldBeNil) + }` + configPath := MakeTempFileWithContent(t, "zot-test.json", content) - err = cli.LoadConfiguration(config, tmpfile) + err := cli.LoadConfiguration(config, configPath) So(err, ShouldBeNil) // Verify GC delay is 0 when GC is disabled @@ -3095,10 +2527,9 @@ func TestRetentionDelayDefaults(t *testing.T) { Convey("When GC delay is not specified, retention delay should default to default GC delay", func() { config := config.New() - tempDir := t.TempDir() // Config with GC enabled but no gcDelay specified - content := []byte(`{ + content := `{ "storage": { "rootDirectory": "/tmp/zot", "gc": true @@ -3107,12 +2538,10 @@ func TestRetentionDelayDefaults(t *testing.T) { "address": "127.0.0.1", "port": "8080" } - }`) - tmpfile := path.Join(tempDir, "config.json") - err := os.WriteFile(tmpfile, content, 0o0600) - So(err, ShouldBeNil) + }` + configPath := MakeTempFileWithContent(t, "zot-test.json", content) - err = cli.LoadConfiguration(config, tmpfile) + err := cli.LoadConfiguration(config, configPath) So(err, ShouldBeNil) // Verify GC delay defaults to default value @@ -3125,10 +2554,9 @@ func TestRetentionDelayDefaults(t *testing.T) { Convey("Test subpath retention delay defaults to subpath GC delay", t, func() { Convey("When subpath retention delay is not specified, it should default to subpath GC delay", func() { config := config.New() - tempDir := t.TempDir() // Config with subpath GC enabled but no retention delay specified - content := []byte(`{ + content := `{ "storage": { "rootDirectory": "/tmp/zot", "subPaths": { @@ -3143,12 +2571,10 @@ func TestRetentionDelayDefaults(t *testing.T) { "address": "127.0.0.1", "port": "8080" } - }`) - tmpfile := path.Join(tempDir, "config.json") - err := os.WriteFile(tmpfile, content, 0o0600) - So(err, ShouldBeNil) + }` + configPath := MakeTempFileWithContent(t, "zot-test.json", content) - err = cli.LoadConfiguration(config, tmpfile) + err := cli.LoadConfiguration(config, configPath) So(err, ShouldBeNil) // Verify subpath GC delay is set correctly @@ -3159,10 +2585,9 @@ func TestRetentionDelayDefaults(t *testing.T) { Convey("When subpath retention delay is explicitly specified, it should use that value", func() { config := config.New() - tempDir := t.TempDir() // Config with explicit subpath retention delay - content := []byte(`{ + content := `{ "storage": { "rootDirectory": "/tmp/zot", "subPaths": { @@ -3180,12 +2605,10 @@ func TestRetentionDelayDefaults(t *testing.T) { "address": "127.0.0.1", "port": "8080" } - }`) - tmpfile := path.Join(tempDir, "config.json") - err := os.WriteFile(tmpfile, content, 0o0600) - So(err, ShouldBeNil) + }` + configPath := MakeTempFileWithContent(t, "zot-test.json", content) - err = cli.LoadConfiguration(config, tmpfile) + err := cli.LoadConfiguration(config, configPath) So(err, ShouldBeNil) // Verify subpath GC delay is set correctly @@ -3196,10 +2619,9 @@ func TestRetentionDelayDefaults(t *testing.T) { Convey("When subpath GC is not specified, retention delay should default to default GC delay", func() { config := config.New() - tempDir := t.TempDir() // Config with subpath but no GC settings - content := []byte(`{ + content := `{ "storage": { "rootDirectory": "/tmp/zot", "subPaths": { @@ -3213,12 +2635,10 @@ func TestRetentionDelayDefaults(t *testing.T) { "address": "127.0.0.1", "port": "8080" } - }`) - tmpfile := path.Join(tempDir, "config.json") - err := os.WriteFile(tmpfile, content, 0o0600) - So(err, ShouldBeNil) + }` + configPath := MakeTempFileWithContent(t, "zot-test.json", content) - err = cli.LoadConfiguration(config, tmpfile) + err := cli.LoadConfiguration(config, configPath) So(err, ShouldBeNil) // Verify subpath GC delay defaults to default value diff --git a/pkg/cli/server/stress_test.go b/pkg/cli/server/stress_test.go index 8791cb49..c2f68d52 100644 --- a/pkg/cli/server/stress_test.go +++ b/pkg/cli/server/stress_test.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "os/exec" + "path/filepath" "sync" "syscall" "testing" @@ -43,20 +44,19 @@ func TestStressTooManyOpenFiles(t *testing.T) { conf.Storage.Dedupe = false conf.Storage.GC = true - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + tempDir := t.TempDir() + logPath := test.MakeTempFilePath(t, "zot-log.txt") defer func() { - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) if err != nil { t.Logf("error when reading zot log file:\n%s\n", err) } t.Logf("\n\n Zot log file content:\n%s\n", string(data)) - os.Remove(logFile.Name()) }() - t.Log("Log file is: ", logFile.Name()) - conf.Log.Output = logFile.Name() + t.Log("Log file is: ", logPath) + conf.Log.Output = logPath ctlr := api.NewController(conf) dir := t.TempDir() @@ -92,16 +92,9 @@ func TestStressTooManyOpenFiles(t *testing.T) { "level": "debug", "output": "%s" } - }`, dir, conf.Storage.Dedupe, conf.Storage.GC, port, logFile.Name()) + }`, dir, conf.Storage.Dedupe, conf.Storage.GC, port, logPath) - cfgfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) - - defer os.Remove(cfgfile.Name()) // clean up - _, err = cfgfile.WriteString(content) - So(err, ShouldBeNil) - err = cfgfile.Close() - So(err, ShouldBeNil) + cfgfile := test.MakeTempFileWithContent(t, "zot-test.json", content) skopeoArgs := []string{ "copy", "--format=oci", "--insecure-policy", "--dest-tls-verify=false", @@ -134,14 +127,14 @@ func TestStressTooManyOpenFiles(t *testing.T) { _, err = setMaxOpenFilesLimit(initialLimit) So(err, ShouldBeNil) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "too many open files") ctrlManager.StopServer() time.Sleep(2 * time.Second) - scrubFile, err := os.CreateTemp("", "zot-scrub*.txt") + scrubFile, err := os.Create(filepath.Join(tempDir, "zot-scrub.txt")) So(err, ShouldBeNil) defer func() { @@ -151,11 +144,10 @@ func TestStressTooManyOpenFiles(t *testing.T) { } t.Logf("\n\n Zot scrub file content:\n%s\n", string(data)) - os.Remove(scrubFile.Name()) }() t.Log("Scrub file is: ", scrubFile.Name()) - os.Args = []string{"cli_test", "scrub", cfgfile.Name()} + os.Args = []string{"cli_test", "scrub", cfgfile} cobraCmd := cli.NewServerRootCmd() cobraCmd.SetOut(scrubFile) err = cobraCmd.Execute() diff --git a/pkg/cli/server/verify_retention_test.go b/pkg/cli/server/verify_retention_test.go index 2431b366..2850663c 100644 --- a/pkg/cli/server/verify_retention_test.go +++ b/pkg/cli/server/verify_retention_test.go @@ -50,37 +50,33 @@ func TestRetentionCheckNegative(t *testing.T) { }) Convey("non-existent config", t, func(c C) { - os.Args = []string{"cli_test", "verify-feature", "retention", path.Join(os.TempDir(), "/x.yaml")} + tempDir := t.TempDir() + os.Args = []string{"cli_test", "verify-feature", "retention", path.Join(tempDir, "/x.yaml")} err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("unknown config", t, func(c C) { - os.Args = []string{"cli_test", "verify-feature", "retention", path.Join(os.TempDir(), "/x")} + tempDir := t.TempDir() + os.Args = []string{"cli_test", "verify-feature", "retention", path.Join(tempDir, "/x")} err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("bad config", t, func(c C) { - testDir := t.TempDir() - configFile := path.Join(testDir, "zot-config.json") - - content := []byte(`{"log":{}}`) - err := os.WriteFile(configFile, content, 0o600) - So(err, ShouldBeNil) + configFile := MakeTempFileWithContent(t, "zot-config.json", `{"log":{}}`) os.Args = []string{"cli_test", "verify-feature", "retention", "-t", "30s", configFile} - err = cli.NewServerRootCmd().Execute() + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) }) Convey("config with GC disabled", t, func(c C) { testDir := t.TempDir() - configFile := path.Join(testDir, "zot-config.json") - logFile := path.Join(testDir, "retention-check.log") + logFile := MakeTempFilePath(t, "retention-check.log") port := GetFreePort() - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "%s", @@ -91,11 +87,10 @@ func TestRetentionCheckNegative(t *testing.T) { "port": "%s" } }`, testDir, port) - err := os.WriteFile(configFile, content, 0o600) - So(err, ShouldBeNil) + configFile := MakeTempFileWithContent(t, "zot-config.json", content) os.Args = []string{"cli_test", "verify-feature", "retention", "-l", logFile, "-t", "30s", configFile} - err = cli.NewServerRootCmd().Execute() + err := cli.NewServerRootCmd().Execute() // Verify the specific error So(err, ShouldNotBeNil) @@ -118,8 +113,7 @@ func TestRetentionCheckNegative(t *testing.T) { testDir := t.TempDir() storageDir := path.Join(testDir, "storage") - configFile := path.Join(testDir, "zot-config.json") - logFile := path.Join(testDir, "retention-check.log") + logFile := MakeTempFilePath(t, "retention-check.log") controller.Config.Storage.RootDirectory = storageDir controller.Config.Storage.GC = true @@ -128,7 +122,7 @@ func TestRetentionCheckNegative(t *testing.T) { defer ctrlManager.StopServer() - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "storage": { "rootDirectory": "%s", "gc": true, @@ -155,11 +149,10 @@ func TestRetentionCheckNegative(t *testing.T) { } } `, storageDir, port) - err := os.WriteFile(configFile, content, 0o600) - So(err, ShouldBeNil) + configFile := MakeTempFileWithContent(t, "zot-config.json", content) os.Args = []string{"cli_test", "verify-feature", "retention", "-l", logFile, "-t", "30s", configFile} - err = cli.NewServerRootCmd().Execute() + err := cli.NewServerRootCmd().Execute() So(err, ShouldNotBeNil) So(err, ShouldEqual, zerr.ErrServerIsRunning) @@ -184,10 +177,9 @@ func TestRetentionCheckNegative(t *testing.T) { for _, testCase := range testCases { Convey(testCase.name, func() { testDir := t.TempDir() - configFile := path.Join(testDir, "zot-config.json") port := GetFreePort() - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "%s", @@ -198,8 +190,7 @@ func TestRetentionCheckNegative(t *testing.T) { "port": "%s" } }`, testDir, port) - err := os.WriteFile(configFile, content, 0o600) - So(err, ShouldBeNil) + configFile := MakeTempFileWithContent(t, "zot-config.json", content) os.Args = []string{"cli_test", "verify-feature", "retention", "-l", testCase.logFile, "-t", "30s", configFile} // This panics during logger initialization due to invalid log file location @@ -223,11 +214,10 @@ func TestRetentionCheckNegative(t *testing.T) { for _, testCase := range testCases { Convey(testCase.name, func() { testDir := t.TempDir() - configFile := path.Join(testDir, "zot-config.json") - logFile := path.Join(testDir, "retention-check.log") + logFile := MakeTempFilePath(t, "retention-check.log") port := GetFreePort() - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "%s", @@ -238,8 +228,7 @@ func TestRetentionCheckNegative(t *testing.T) { "port": "%s" } }`, testDir, port) - err := os.WriteFile(configFile, content, 0o600) - So(err, ShouldBeNil) + configFile := MakeTempFileWithContent(t, "zot-config.json", content) args := []string{ "cli_test", "verify-feature", "retention", "-l", logFile, @@ -253,7 +242,7 @@ func TestRetentionCheckNegative(t *testing.T) { args = append(args, configFile) os.Args = args - err = cli.NewServerRootCmd().Execute() + err := cli.NewServerRootCmd().Execute() // Flag parsing should fail before reaching RunE So(err, ShouldNotBeNil) So(err.Error(), ShouldContainSubstring, "invalid duration") @@ -272,10 +261,9 @@ func TestRetentionCheckWithRetentionEnabledAndRedisDriver(t *testing.T) { port := GetFreePort() testDir := t.TempDir() storageDir := path.Join(testDir, "storage") - configFile := path.Join(testDir, "zot-config.json") - logFile := path.Join(testDir, "retention-check.log") + logFile := MakeTempFilePath(t, "retention-check.log") - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "%s", @@ -311,12 +299,11 @@ func TestRetentionCheckWithRetentionEnabledAndRedisDriver(t *testing.T) { } } `, storageDir, testGCDelay, miniRedis.Addr(), port) - err := os.WriteFile(configFile, content, 0o600) - So(err, ShouldBeNil) + configFile := MakeTempFileWithContent(t, "zot-config.json", content) // Create complex image setup before running verify-feature retention conf := config.New() - err = cli.LoadConfiguration(conf, configFile) + err := cli.LoadConfiguration(conf, configFile) So(err, ShouldBeNil) // Initialize storage and metaDB using the same approach as gc tests @@ -510,10 +497,9 @@ func TestRetentionCheckWithRetentionEnabled(t *testing.T) { port := GetFreePort() testDir := t.TempDir() storageDir := path.Join(testDir, "storage") - configFile := path.Join(testDir, "zot-config.json") - logFile := path.Join(testDir, "retention-check.log") + logFile := MakeTempFilePath(t, "retention-check.log") - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "%s", @@ -544,12 +530,11 @@ func TestRetentionCheckWithRetentionEnabled(t *testing.T) { } } `, storageDir, testGCDelay, port) - err := os.WriteFile(configFile, content, 0o600) - So(err, ShouldBeNil) + configFile := MakeTempFileWithContent(t, "zot-config.json", content) // Create complex image setup before running verify-feature retention conf := config.New() - err = cli.LoadConfiguration(conf, configFile) + err := cli.LoadConfiguration(conf, configFile) So(err, ShouldBeNil) // Initialize storage and metaDB using the same approach as gc tests @@ -801,10 +786,9 @@ func TestRetentionCheckWithDeleteReferrers(t *testing.T) { port := GetFreePort() testDir := t.TempDir() storageDir := path.Join(testDir, "storage") - configFile := path.Join(testDir, "zot-config.json") - logFile := path.Join(testDir, "retention-check.log") + logFile := MakeTempFilePath(t, "retention-check.log") - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "%s", @@ -836,12 +820,11 @@ func TestRetentionCheckWithDeleteReferrers(t *testing.T) { } } `, storageDir, testGCDelay, port) - err := os.WriteFile(configFile, content, 0o600) - So(err, ShouldBeNil) + configFile := MakeTempFileWithContent(t, "zot-config.json", content) // Create image setup before running verify-feature retention conf := config.New() - err = cli.LoadConfiguration(conf, configFile) + err := cli.LoadConfiguration(conf, configFile) So(err, ShouldBeNil) // Initialize storage and metaDB @@ -982,10 +965,9 @@ func TestRetentionCheckWithRetentionDisabled(t *testing.T) { port := GetFreePort() testDir := t.TempDir() storageDir := path.Join(testDir, "storage") - configFile := path.Join(testDir, "zot-config.json") - logFile := path.Join(testDir, "retention-check.log") + logFile := MakeTempFilePath(t, "retention-check.log") - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "%s", @@ -1002,12 +984,11 @@ func TestRetentionCheckWithRetentionDisabled(t *testing.T) { } } `, storageDir, testGCDelay, port) - err := os.WriteFile(configFile, content, 0o600) - So(err, ShouldBeNil) + configFile := MakeTempFileWithContent(t, "zot-config.json", content) // Create image setup for GC testing (no retention, no MetaDB needed) conf := config.New() - err = cli.LoadConfiguration(conf, configFile) + err := cli.LoadConfiguration(conf, configFile) So(err, ShouldBeNil) // Initialize storage only (no MetaDB needed when retention is disabled) @@ -1139,10 +1120,9 @@ func TestRetentionCheckWithSubpaths(t *testing.T) { testDir := t.TempDir() storageDir := path.Join(testDir, "storage") subpathStoreDir := path.Join(testDir, "storage2") - configFile := path.Join(testDir, "zot-config.json") - logFile := path.Join(testDir, "retention-check.log") + logFile := MakeTempFilePath(t, "retention-check.log") - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "%s", @@ -1197,12 +1177,11 @@ func TestRetentionCheckWithSubpaths(t *testing.T) { } } `, storageDir, testGCDelay, subpathStoreDir, testGCDelay, port) - err := os.WriteFile(configFile, content, 0o600) - So(err, ShouldBeNil) + configFile := MakeTempFileWithContent(t, "zot-config.json", content) // Create image setup before running verify-feature retention conf := config.New() - err = cli.LoadConfiguration(conf, configFile) + err := cli.LoadConfiguration(conf, configFile) So(err, ShouldBeNil) // Initialize storage and metaDB @@ -1440,11 +1419,10 @@ func TestRetentionCheckWithGCIntervalOverride(t *testing.T) { testDir := t.TempDir() storageDir := path.Join(testDir, "storage") subpathStoreDir := path.Join(testDir, "storage2") - configFile := path.Join(testDir, "zot-config.json") - logFile := path.Join(testDir, "retention-check.log") + logFile := MakeTempFilePath(t, "retention-check.log") port := GetFreePort() - content := fmt.Appendf([]byte{}, `{ + content := fmt.Sprintf(`{ "distSpecVersion": "1.1.1", "storage": { "rootDirectory": "%s", @@ -1469,15 +1447,14 @@ func TestRetentionCheckWithGCIntervalOverride(t *testing.T) { } } `, storageDir, testGCDelay, subpathStoreDir, testGCDelay, port) - err := os.WriteFile(configFile, content, 0o600) - So(err, ShouldBeNil) + configFile := MakeTempFileWithContent(t, "zot-config.json", content) gcDelay, _ := time.ParseDuration(testGCDelay) time.Sleep(gcDelay + 50*time.Millisecond) // wait for GC delay to pass // Override GC interval from 1m to 30s using -i flag os.Args = []string{"cli_test", "verify-feature", "retention", "-l", logFile, "-i", "30s", "-t", "5ms", configFile} - err = cli.NewServerRootCmd().Execute() + err := cli.NewServerRootCmd().Execute() So(err, ShouldBeNil) // Verify log file was created and contains expected messages diff --git a/pkg/debug/pprof/pprof_test.go b/pkg/debug/pprof/pprof_test.go index 35748e66..9cd3e8a0 100644 --- a/pkg/debug/pprof/pprof_test.go +++ b/pkg/debug/pprof/pprof_test.go @@ -4,7 +4,6 @@ package pprof_test import ( "net/http" - "os" "testing" . "github.com/smartystreets/goconvey/convey" @@ -29,9 +28,7 @@ func TestProfilingAuthz(t *testing.T) { testCreds := test.GetBcryptCredString(adminUsername, adminPassword) + test.GetBcryptCredString(username, password) - htpasswdPath := test.MakeHtpasswdFileFromString(testCreds) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, testCreds) conf := config.New() conf.HTTP.Port = port diff --git a/pkg/extensions/extension_events_disabled_test.go b/pkg/extensions/extension_events_disabled_test.go index 27c86685..f7cbfc42 100644 --- a/pkg/extensions/extension_events_disabled_test.go +++ b/pkg/extensions/extension_events_disabled_test.go @@ -23,9 +23,7 @@ func TestEventsExtension(t *testing.T) { globalDir := t.TempDir() defaultValue := true - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - So(err, ShouldBeNil) - defer os.Remove(logFile.Name()) + logPath := test.MakeTempFilePath(t, "zot-log.txt") conf.HTTP.Port = port conf.Storage.RootDirectory = globalDir @@ -35,7 +33,7 @@ func TestEventsExtension(t *testing.T) { Enable: &defaultValue, } conf.Log.Level = "warn" - conf.Log.Output = logFile.Name() + conf.Log.Output = logPath ctlr := api.NewController(conf) ctlrManager := test.NewControllerManager(ctlr) @@ -43,7 +41,7 @@ func TestEventsExtension(t *testing.T) { ctlrManager.StartAndWait(port) defer ctlrManager.StopServer() - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, diff --git a/pkg/extensions/extension_image_trust_disabled_test.go b/pkg/extensions/extension_image_trust_disabled_test.go index 1c7f0f40..1c5de1cd 100644 --- a/pkg/extensions/extension_image_trust_disabled_test.go +++ b/pkg/extensions/extension_image_trust_disabled_test.go @@ -22,9 +22,7 @@ func TestImageTrustExtension(t *testing.T) { globalDir := t.TempDir() defaultValue := true - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - So(err, ShouldBeNil) - defer os.Remove(logFile.Name()) + logFile := test.MakeTempFile(t, "zot-log.txt") conf.HTTP.Port = port conf.Storage.RootDirectory = globalDir diff --git a/pkg/extensions/extension_image_trust_test.go b/pkg/extensions/extension_image_trust_test.go index 43295fb6..4c1cae24 100644 --- a/pkg/extensions/extension_image_trust_test.go +++ b/pkg/extensions/extension_image_trust_test.go @@ -204,9 +204,8 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ baseURL := test.GetBaseURL(port) - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - defer os.Remove(logFile.Name()) // cleanup - So(err, ShouldBeNil) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() writers := io.MultiWriter(os.Stdout, logFile) logger := log.NewLoggerWithWriter("debug", writers) @@ -219,7 +218,7 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ } image := CreateRandomImage() - err = WriteImageToFileSystem(image, repo, tag, storeController) + err := WriteImageToFileSystem(image, repo, tag, storeController) So(err, ShouldBeNil) ctlr := api.NewController(conf) @@ -324,9 +323,8 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ baseURL := test.GetBaseURL(port) - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - defer os.Remove(logFile.Name()) // cleanup - So(err, ShouldBeNil) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() writers := io.MultiWriter(os.Stdout, logFile) logger := log.NewLoggerWithWriter("debug", writers) @@ -339,7 +337,7 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ } image := CreateRandomImage() - err = WriteImageToFileSystem(image, repo, tag, storeController) + err := WriteImageToFileSystem(image, repo, tag, storeController) So(err, ShouldBeNil) ctlr := api.NewController(conf) @@ -431,9 +429,8 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ baseURL := test.GetBaseURL(port) gqlEndpoint := fmt.Sprintf("%s%s?query=", baseURL, constants.FullSearchPrefix) - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - defer os.Remove(logFile.Name()) // cleanup - So(err, ShouldBeNil) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() writers := io.MultiWriter(os.Stdout, logFile) logger := log.NewLoggerWithWriter("debug", writers) @@ -446,7 +443,7 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ } image := CreateRandomImage() - err = WriteImageToFileSystem(image, repo, tag, storeController) + err := WriteImageToFileSystem(image, repo, tag, storeController) So(err, ShouldBeNil) ctlr := api.NewController(conf) @@ -593,9 +590,8 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ baseURL := test.GetBaseURL(port) gqlEndpoint := fmt.Sprintf("%s%s?query=", baseURL, constants.FullSearchPrefix) - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - defer os.Remove(logFile.Name()) // cleanup - So(err, ShouldBeNil) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() writers := io.MultiWriter(os.Stdout, logFile) logger := log.NewLoggerWithWriter("debug", writers) @@ -608,7 +604,7 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ } image := CreateRandomImage() - err = WriteImageToFileSystem(image, repo, tag, storeController) + err := WriteImageToFileSystem(image, repo, tag, storeController) So(err, ShouldBeNil) ctlr := api.NewController(conf) @@ -744,8 +740,7 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ port := test.GetFreePort() testCreds := test.GetBcryptCredString("admin", "admin") + "\n" + test.GetBcryptCredString("test", "test") - htpasswdPath := test.MakeHtpasswdFileFromString(testCreds) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, testCreds) conf := config.New() conf.HTTP.Port = port @@ -770,9 +765,8 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ baseURL := test.GetBaseURL(port) - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - defer os.Remove(logFile.Name()) // cleanup - So(err, ShouldBeNil) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() writers := io.MultiWriter(os.Stdout, logFile) @@ -854,9 +848,8 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ baseURL := test.GetBaseURL(port) gqlEndpoint := fmt.Sprintf("%s%s?query=", baseURL, constants.FullSearchPrefix) - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - defer os.Remove(logFile.Name()) // cleanup - So(err, ShouldBeNil) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() writers := io.MultiWriter(os.Stdout, logFile) logger := log.NewLoggerWithWriter("debug", writers) @@ -871,7 +864,7 @@ func RunSignatureUploadAndVerificationTests(t *testing.T, cacheDriverParams map[ // Write image image := CreateRandomImage() - err = WriteImageToFileSystem(image, repo, tag, storeController) + err := WriteImageToFileSystem(image, repo, tag, storeController) So(err, ShouldBeNil) // Write signature diff --git a/pkg/extensions/extension_ui_test.go b/pkg/extensions/extension_ui_test.go index eae793db..cb3d202e 100644 --- a/pkg/extensions/extension_ui_test.go +++ b/pkg/extensions/extension_ui_test.go @@ -29,11 +29,10 @@ func TestUIExtension(t *testing.T) { // we won't use the logging config feature as we want logs in both // stdout and a file - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - So(err, ShouldBeNil) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() logPath := logFile.Name() - defer os.Remove(logPath) writers := io.MultiWriter(os.Stdout, logFile) diff --git a/pkg/extensions/extensions_test.go b/pkg/extensions/extensions_test.go index 63289785..dd2df33d 100644 --- a/pkg/extensions/extensions_test.go +++ b/pkg/extensions/extensions_test.go @@ -46,12 +46,9 @@ func TestEnableExtension(t *testing.T) { conf.Extensions.Sync = syncConfig conf.HTTP.Port = port - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") conf.Log.Level = "info" - conf.Log.Output = logFile.Name() - - defer os.Remove(logFile.Name()) // cleanup + conf.Log.Output = logPath ctlr := api.NewController(conf) ctlrManager := test.NewControllerManager(ctlr) @@ -62,7 +59,7 @@ func TestEnableExtension(t *testing.T) { ctlrManager.StartAndWait(port) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "sync config not provided or disabled, so not enabling sync") @@ -76,8 +73,7 @@ func TestMetricsExtension(t *testing.T) { port := test.GetFreePort() conf.HTTP.Port = port - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") defaultValue := true conf.Extensions = &extconf.ExtensionConfig{} @@ -86,9 +82,7 @@ func TestMetricsExtension(t *testing.T) { Prometheus: &extconf.PrometheusConfig{}, } conf.Log.Level = "info" - conf.Log.Output = logFile.Name() - - defer os.Remove(logFile.Name()) // cleanup + conf.Log.Output = logPath ctlr := api.NewController(conf) ctlrManager := test.NewControllerManager(ctlr) @@ -104,7 +98,7 @@ func TestMetricsExtension(t *testing.T) { ctlrManager.StartAndWait(port) - data, _ := os.ReadFile(logFile.Name()) + data, _ := os.ReadFile(logPath) So(string(data), ShouldContainSubstring, "metrics extension enabled") }) @@ -116,11 +110,6 @@ func TestMgmtExtension(t *testing.T) { port := test.GetFreePort() conf.HTTP.Port = port baseURL := test.GetBaseURL(port) - - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - if err != nil { - panic(err) - } mgmtReadyTimeout := 5 * time.Second defaultValue := true @@ -142,12 +131,10 @@ func TestMgmtExtension(t *testing.T) { Convey("Verify mgmt auth info route enabled with htpasswd", t, func() { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) defer func() { conf.HTTP.Auth.HTPasswd.Path = "" - - os.Remove(htpasswdPath) }() conf.HTTP.Auth.HTPasswd.Path = htpasswdPath @@ -159,8 +146,8 @@ func TestMgmtExtension(t *testing.T) { conf.Extensions.UI = &extconf.UIConfig{} conf.Extensions.UI.Enable = &defaultValue - conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // cleanup + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath ctlr := api.NewController(conf) ctlr.Log.Info().Int64("seedUser", seedUser).Int64("seedPass", seedPass).Msg("random seed for username & password") @@ -175,13 +162,13 @@ func TestMgmtExtension(t *testing.T) { ctlrManager.StartAndWait(port) defer ctlrManager.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), + found, err := test.ReadLogFileAndSearchString(logPath, "setting up mgmt routes", mgmtReadyTimeout) So(err, ShouldBeNil) defer func() { if !found { - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Log(string(data)) } @@ -189,7 +176,7 @@ func TestMgmtExtension(t *testing.T) { So(found, ShouldBeTrue) So(err, ShouldBeNil) - found, err = test.ReadLogFileAndSearchString(logFile.Name(), + found, err = test.ReadLogFileAndSearchString(logPath, "finished setting up mgmt routes", mgmtReadyTimeout) So(found, ShouldBeTrue) So(err, ShouldBeNil) @@ -246,8 +233,8 @@ func TestMgmtExtension(t *testing.T) { conf.Extensions.UI = &extconf.UIConfig{} conf.Extensions.UI.Enable = &defaultValue - conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // cleanup + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath ctlr := api.NewController(conf) @@ -261,11 +248,11 @@ func TestMgmtExtension(t *testing.T) { ctlrManager.StartAndWait(port) defer ctlrManager.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), + found, err := test.ReadLogFileAndSearchString(logPath, "setting up mgmt routes", mgmtReadyTimeout) defer func() { if !found { - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Log(string(data)) } @@ -273,7 +260,7 @@ func TestMgmtExtension(t *testing.T) { So(found, ShouldBeTrue) So(err, ShouldBeNil) - found, err = test.ReadLogFileAndSearchString(logFile.Name(), + found, err = test.ReadLogFileAndSearchString(logPath, "finished setting up mgmt routes", mgmtReadyTimeout) So(found, ShouldBeTrue) So(err, ShouldBeNil) @@ -311,8 +298,8 @@ func TestMgmtExtension(t *testing.T) { conf.Extensions.UI = &extconf.UIConfig{} conf.Extensions.UI.Enable = &defaultValue - conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // cleanup + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath ctlr := api.NewController(conf) @@ -326,11 +313,11 @@ func TestMgmtExtension(t *testing.T) { ctlrManager.StartAndWait(port) defer ctlrManager.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), + found, err := test.ReadLogFileAndSearchString(logPath, "setting up mgmt routes", mgmtReadyTimeout) defer func() { if !found { - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Log(string(data)) } @@ -338,7 +325,7 @@ func TestMgmtExtension(t *testing.T) { So(found, ShouldBeTrue) So(err, ShouldBeNil) - found, err = test.ReadLogFileAndSearchString(logFile.Name(), + found, err = test.ReadLogFileAndSearchString(logPath, "finished setting up mgmt routes", mgmtReadyTimeout) So(found, ShouldBeTrue) So(err, ShouldBeNil) @@ -361,12 +348,10 @@ func TestMgmtExtension(t *testing.T) { Convey("Verify mgmt auth info route enabled with htpasswd + ldap", t, func() { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) defer func() { conf.HTTP.Auth.HTPasswd.Path = "" - - os.Remove(htpasswdPath) }() conf.HTTP.Auth.HTPasswd.Path = htpasswdPath @@ -382,8 +367,8 @@ func TestMgmtExtension(t *testing.T) { conf.Extensions.UI = &extconf.UIConfig{} conf.Extensions.UI.Enable = &defaultValue - conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // cleanup + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath ctlr := api.NewController(conf) ctlr.Log.Info().Int64("seedUser", seedUser).Int64("seedPass", seedPass).Msg("random seed for username & password") @@ -398,11 +383,11 @@ func TestMgmtExtension(t *testing.T) { ctlrManager.StartAndWait(port) defer ctlrManager.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), + found, err := test.ReadLogFileAndSearchString(logPath, "setting up mgmt routes", mgmtReadyTimeout) defer func() { if !found { - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Log(string(data)) } @@ -410,7 +395,7 @@ func TestMgmtExtension(t *testing.T) { So(found, ShouldBeTrue) So(err, ShouldBeNil) - found, err = test.ReadLogFileAndSearchString(logFile.Name(), + found, err = test.ReadLogFileAndSearchString(logPath, "finished setting up mgmt routes", mgmtReadyTimeout) So(found, ShouldBeTrue) So(err, ShouldBeNil) @@ -447,12 +432,10 @@ func TestMgmtExtension(t *testing.T) { Convey("Verify mgmt auth info route enabled with htpasswd + ldap + bearer", t, func() { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) defer func() { conf.HTTP.Auth.HTPasswd.Path = "" - - os.Remove(htpasswdPath) }() conf.HTTP.Auth.HTPasswd.Path = htpasswdPath @@ -473,8 +456,8 @@ func TestMgmtExtension(t *testing.T) { conf.Extensions.UI = &extconf.UIConfig{} conf.Extensions.UI.Enable = &defaultValue - conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // cleanup + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath ctlr := api.NewController(conf) ctlr.Log.Info().Int64("seedUser", seedUser).Int64("seedPass", seedPass).Msg("random seed for username & password") @@ -485,11 +468,11 @@ func TestMgmtExtension(t *testing.T) { ctlrManager.StartAndWait(port) defer ctlrManager.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), + found, err := test.ReadLogFileAndSearchString(logPath, "setting up mgmt routes", mgmtReadyTimeout) defer func() { if !found { - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Log(string(data)) } @@ -497,7 +480,7 @@ func TestMgmtExtension(t *testing.T) { So(found, ShouldBeTrue) So(err, ShouldBeNil) - found, err = test.ReadLogFileAndSearchString(logFile.Name(), + found, err = test.ReadLogFileAndSearchString(logPath, "finished setting up mgmt routes", mgmtReadyTimeout) So(found, ShouldBeTrue) So(err, ShouldBeNil) @@ -554,8 +537,8 @@ func TestMgmtExtension(t *testing.T) { conf.Extensions.UI = &extconf.UIConfig{} conf.Extensions.UI.Enable = &defaultValue - conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // cleanup + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath ctlr := api.NewController(conf) @@ -569,11 +552,11 @@ func TestMgmtExtension(t *testing.T) { ctlrManager.StartAndWait(port) defer ctlrManager.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), + found, err := test.ReadLogFileAndSearchString(logPath, "setting up mgmt routes", mgmtReadyTimeout) defer func() { if !found { - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Log(string(data)) } @@ -581,7 +564,7 @@ func TestMgmtExtension(t *testing.T) { So(found, ShouldBeTrue) So(err, ShouldBeNil) - found, err = test.ReadLogFileAndSearchString(logFile.Name(), + found, err = test.ReadLogFileAndSearchString(logPath, "finished setting up mgmt routes", mgmtReadyTimeout) So(found, ShouldBeTrue) So(err, ShouldBeNil) @@ -618,8 +601,8 @@ func TestMgmtExtension(t *testing.T) { conf.Extensions.UI = &extconf.UIConfig{} conf.Extensions.UI.Enable = &defaultValue - conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // cleanup + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath ctlr := api.NewController(conf) @@ -629,11 +612,11 @@ func TestMgmtExtension(t *testing.T) { ctlrManager.StartAndWait(port) defer ctlrManager.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), + found, err := test.ReadLogFileAndSearchString(logPath, "setting up mgmt routes", mgmtReadyTimeout) defer func() { if !found { - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Log(string(data)) } @@ -641,7 +624,7 @@ func TestMgmtExtension(t *testing.T) { So(found, ShouldBeTrue) So(err, ShouldBeNil) - found, err = test.ReadLogFileAndSearchString(logFile.Name(), + found, err = test.ReadLogFileAndSearchString(logPath, "finished setting up mgmt routes", mgmtReadyTimeout) So(found, ShouldBeTrue) So(err, ShouldBeNil) @@ -685,8 +668,8 @@ func TestMgmtExtension(t *testing.T) { conf.Extensions.UI = &extconf.UIConfig{} conf.Extensions.UI.Enable = &defaultValue - conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // cleanup + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath ctlr := api.NewController(conf) @@ -696,11 +679,11 @@ func TestMgmtExtension(t *testing.T) { ctlrManager.StartAndWait(port) defer ctlrManager.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), + found, err := test.ReadLogFileAndSearchString(logPath, "setting up mgmt routes", mgmtReadyTimeout) defer func() { if !found { - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Log(string(data)) } @@ -708,7 +691,7 @@ func TestMgmtExtension(t *testing.T) { So(found, ShouldBeTrue) So(err, ShouldBeNil) - found, err = test.ReadLogFileAndSearchString(logFile.Name(), + found, err = test.ReadLogFileAndSearchString(logPath, "finished setting up mgmt routes", mgmtReadyTimeout) So(found, ShouldBeTrue) So(err, ShouldBeNil) @@ -733,12 +716,10 @@ func TestMgmtExtension(t *testing.T) { Convey("Verify mgmt auth info route enabled with empty openID provider list", t, func() { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) defer func() { conf.HTTP.Auth.HTPasswd.Path = "" - - os.Remove(htpasswdPath) }() conf.HTTP.Auth.HTPasswd.Path = htpasswdPath @@ -758,8 +739,8 @@ func TestMgmtExtension(t *testing.T) { conf.Extensions.UI = &extconf.UIConfig{} conf.Extensions.UI.Enable = &defaultValue - conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // cleanup + logPath := test.MakeTempFilePath(t, "zot-log.txt") + conf.Log.Output = logPath ctlr := api.NewController(conf) ctlr.Log.Info().Int64("seedUser", seedUser).Int64("seedPass", seedPass).Msg("random seed for username & password") @@ -770,11 +751,11 @@ func TestMgmtExtension(t *testing.T) { ctlrManager.StartAndWait(port) defer ctlrManager.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), + found, err := test.ReadLogFileAndSearchString(logPath, "setting up mgmt routes", mgmtReadyTimeout) defer func() { if !found { - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Log(string(data)) } @@ -782,7 +763,7 @@ func TestMgmtExtension(t *testing.T) { So(found, ShouldBeTrue) So(err, ShouldBeNil) - found, err = test.ReadLogFileAndSearchString(logFile.Name(), + found, err = test.ReadLogFileAndSearchString(logPath, "finished setting up mgmt routes", mgmtReadyTimeout) So(found, ShouldBeTrue) So(err, ShouldBeNil) @@ -804,14 +785,12 @@ func TestMgmtExtension(t *testing.T) { }) Convey("Verify mgmt auth info route enabled without any auth", t, func() { - globalDir := t.TempDir() conf := config.New() port := test.GetFreePort() conf.HTTP.Port = port baseURL := test.GetBaseURL(port) - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") defaultValue := true conf.Commit = "v1.0.0" @@ -823,8 +802,7 @@ func TestMgmtExtension(t *testing.T) { conf.Extensions.UI = &extconf.UIConfig{} conf.Extensions.UI.Enable = &defaultValue - conf.Log.Output = logFile.Name() - defer os.Remove(logFile.Name()) // cleanup + conf.Log.Output = logPath ctlr := api.NewController(conf) @@ -847,11 +825,11 @@ func TestMgmtExtension(t *testing.T) { So(mgmtResp.HTTP.Auth.LDAP, ShouldBeNil) So(mgmtResp.HTTP.Auth.APIKey, ShouldBeFalse) - found, err := test.ReadLogFileAndSearchString(logFile.Name(), + found, err := test.ReadLogFileAndSearchString(logPath, "setting up mgmt routes", mgmtReadyTimeout) defer func() { if !found { - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) t.Log(string(data)) } @@ -859,7 +837,7 @@ func TestMgmtExtension(t *testing.T) { So(found, ShouldBeTrue) So(err, ShouldBeNil) - found, err = test.ReadLogFileAndSearchString(logFile.Name(), + found, err = test.ReadLogFileAndSearchString(logPath, "finished setting up mgmt routes", mgmtReadyTimeout) So(found, ShouldBeTrue) So(err, ShouldBeNil) diff --git a/pkg/extensions/get_extensions_disabled_test.go b/pkg/extensions/get_extensions_disabled_test.go index 8e791193..80297923 100644 --- a/pkg/extensions/get_extensions_disabled_test.go +++ b/pkg/extensions/get_extensions_disabled_test.go @@ -4,7 +4,6 @@ package extensions_test import ( "encoding/json" - "os" "testing" distext "github.com/opencontainers/distribution-spec/specs-go/v1/extensions" @@ -35,12 +34,9 @@ func TestGetExensionsDisabled(t *testing.T) { conf.Extensions.UI = &extconf.UIConfig{} conf.Extensions.UI.Enable = &defaultVal - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") - conf.Log.Output = logFile.Name() - - defer os.Remove(logFile.Name()) // clean up + conf.Log.Output = logPath ctlr := makeController(conf, t.TempDir()) diff --git a/pkg/extensions/imagetrust/image_trust_test.go b/pkg/extensions/imagetrust/image_trust_test.go index af91afd3..aff98a7e 100644 --- a/pkg/extensions/imagetrust/image_trust_test.go +++ b/pkg/extensions/imagetrust/image_trust_test.go @@ -1208,11 +1208,8 @@ func RunVerificationTests(t *testing.T, dbDriverParams map[string]any) { //nolin Convey("verify signatures are trusted", func() { defaultValue := true rootDir := t.TempDir() - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - So(err, ShouldBeNil) - - logPath := logFile.Name() - defer os.Remove(logPath) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() writers := io.MultiWriter(os.Stdout, logFile) @@ -1247,14 +1244,14 @@ func RunVerificationTests(t *testing.T, dbDriverParams map[string]any) { //nolin Convey("verify running an image trust with context done", func() { image := CreateRandomImage() - err = UploadImage(image, baseURL, repo, tag) + err := UploadImage(image, baseURL, repo, tag) So(err, ShouldBeNil) }) Convey("verify cosign signature is trusted", func() { image := CreateRandomImage() - err = UploadImage(image, baseURL, repo, tag) + err := UploadImage(image, baseURL, repo, tag) So(err, ShouldBeNil) cwd, err := os.Getwd() @@ -1347,7 +1344,7 @@ func RunVerificationTests(t *testing.T, dbDriverParams map[string]any) { //nolin Convey("verify notation signature is trusted", func() { image := CreateRandomImage() - err = UploadImage(image, baseURL, repo, tag) + err := UploadImage(image, baseURL, repo, tag) So(err, ShouldBeNil) notationDir := t.TempDir() diff --git a/pkg/extensions/monitoring/monitoring_test.go b/pkg/extensions/monitoring/monitoring_test.go index 76c9e4cc..c63f8589 100644 --- a/pkg/extensions/monitoring/monitoring_test.go +++ b/pkg/extensions/monitoring/monitoring_test.go @@ -172,8 +172,7 @@ func TestMetricsAuthentication(t *testing.T) { metricspass := generateRandomString() content := test.GetBcryptCredString(username, password) + "\n" + test.GetBcryptCredString(metricsuser, metricspass) - htpasswdPath := test.MakeHtpasswdFileFromString(content) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, content) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -237,8 +236,7 @@ func TestMetricsAuthorization(t *testing.T) { metricspass := generateRandomString() content := test.GetBcryptCredString(username, password) + "\n" + test.GetBcryptCredString(metricsuser, metricspass) - htpasswdPath := test.MakeHtpasswdFileFromString(content) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, content) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -439,13 +437,10 @@ func TestPopulateStorageMetrics(t *testing.T) { Prometheus: &extconf.PrometheusConfig{Path: "/metrics"}, } - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - if err != nil { - panic(err) - } + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() logPath := logFile.Name() - defer os.Remove(logPath) writers := io.MultiWriter(os.Stdout, logFile) @@ -455,7 +450,7 @@ func TestPopulateStorageMetrics(t *testing.T) { // Write images before starting controller to avoid race condition with garbage collection srcStorageCtlr := ociutils.GetDefaultStoreController(rootDir, ctlr.Log) - err = WriteImageToFileSystem(CreateDefaultImage(), "alpine", "0.0.1", srcStorageCtlr) + err := WriteImageToFileSystem(CreateDefaultImage(), "alpine", "0.0.1", srcStorageCtlr) So(err, ShouldBeNil) err = WriteImageToFileSystem(CreateDefaultImage(), "busybox", "0.0.1", srcStorageCtlr) So(err, ShouldBeNil) diff --git a/pkg/extensions/scrub/scrub_test.go b/pkg/extensions/scrub/scrub_test.go index 86b15ebb..2870cb3e 100644 --- a/pkg/extensions/scrub/scrub_test.go +++ b/pkg/extensions/scrub/scrub_test.go @@ -33,10 +33,7 @@ func TestScrubExtension(t *testing.T) { Convey("Blobs integrity not affected", t, func(c C) { port := test.GetFreePort() - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") conf := config.New() conf.HTTP.Port = port @@ -50,7 +47,7 @@ func TestScrubExtension(t *testing.T) { substore := config.StorageConfig{RootDirectory: subdir} conf.Storage.SubPaths = map[string]config.StorageConfig{"/a": substore} - conf.Log.Output = logFile.Name() + conf.Log.Output = logPath trueValue := true scrubConfig := &extconf.ScrubConfig{ BaseConfig: extconf.BaseConfig{Enable: &trueValue}, @@ -63,14 +60,14 @@ func TestScrubExtension(t *testing.T) { ctlr := api.NewController(conf) srcStorageCtlr := ociutils.GetDefaultStoreController(dir, log.NewTestLogger()) - err = WriteImageToFileSystem(CreateDefaultVulnerableImage(), repoName, "0.0.1", srcStorageCtlr) + err := WriteImageToFileSystem(CreateDefaultVulnerableImage(), repoName, "0.0.1", srcStorageCtlr) So(err, ShouldBeNil) cm := test.NewControllerManager(ctlr) cm.StartAndWait(port) defer cm.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), "blobs/manifest ok", 60*time.Second) + found, err := test.ReadLogFileAndSearchString(logPath, "blobs/manifest ok", 60*time.Second) So(found, ShouldBeTrue) So(err, ShouldBeNil) }) @@ -78,10 +75,7 @@ func TestScrubExtension(t *testing.T) { Convey("Blobs integrity affected", t, func(c C) { port := test.GetFreePort() - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") conf := config.New() conf.HTTP.Port = port @@ -92,7 +86,7 @@ func TestScrubExtension(t *testing.T) { conf.Storage.Dedupe = false conf.Storage.GC = false - conf.Log.Output = logFile.Name() + conf.Log.Output = logPath trueValue := true scrubConfig := &extconf.ScrubConfig{ BaseConfig: extconf.BaseConfig{Enable: &trueValue}, @@ -106,7 +100,7 @@ func TestScrubExtension(t *testing.T) { srcStorageCtlr := ociutils.GetDefaultStoreController(dir, log.NewTestLogger()) image := CreateDefaultVulnerableImage() - err = WriteImageToFileSystem(image, repoName, "0.0.1", srcStorageCtlr) + err := WriteImageToFileSystem(image, repoName, "0.0.1", srcStorageCtlr) So(err, ShouldBeNil) layerDigest := image.Manifest.Layers[0].Digest @@ -120,7 +114,7 @@ func TestScrubExtension(t *testing.T) { cm.StartAndWait(port) defer cm.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), "blobs/manifest affected", 60*time.Second) + found, err := test.ReadLogFileAndSearchString(logPath, "blobs/manifest affected", 60*time.Second) So(found, ShouldBeTrue) So(err, ShouldBeNil) }) @@ -128,10 +122,7 @@ func TestScrubExtension(t *testing.T) { Convey("Generator error - not enough permissions to access root directory", t, func(c C) { port := test.GetFreePort() - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") conf := config.New() conf.HTTP.Port = port @@ -142,7 +133,7 @@ func TestScrubExtension(t *testing.T) { conf.Storage.Dedupe = false conf.Storage.GC = false - conf.Log.Output = logFile.Name() + conf.Log.Output = logPath trueValue := true scrubConfig := &extconf.ScrubConfig{ BaseConfig: extconf.BaseConfig{Enable: &trueValue}, @@ -157,7 +148,7 @@ func TestScrubExtension(t *testing.T) { srcStorageCtlr := ociutils.GetDefaultStoreController(dir, log.NewTestLogger()) image := CreateDefaultVulnerableImage() - err = WriteImageToFileSystem(image, repoName, "0.0.1", srcStorageCtlr) + err := WriteImageToFileSystem(image, repoName, "0.0.1", srcStorageCtlr) So(err, ShouldBeNil) So(os.Chmod(path.Join(dir, repoName), 0o000), ShouldBeNil) @@ -166,7 +157,7 @@ func TestScrubExtension(t *testing.T) { cm.StartAndWait(port) defer cm.StopServer() - found, err := test.ReadLogFileAndSearchString(logFile.Name(), "failed to execute generator", 60*time.Second) + found, err := test.ReadLogFileAndSearchString(logPath, "failed to execute generator", 60*time.Second) So(found, ShouldBeTrue) So(err, ShouldBeNil) @@ -176,17 +167,14 @@ func TestScrubExtension(t *testing.T) { func TestRunScrubRepo(t *testing.T) { Convey("Blobs integrity not affected", t, func(c C) { - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") conf := config.New() conf.Extensions = &extconf.ExtensionConfig{} conf.Extensions.Lint = &extconf.LintConfig{} dir := t.TempDir() - log := log.NewLogger("debug", logFile.Name()) + log := log.NewLogger("debug", logPath) metrics := monitoring.NewMetricsServer(false, log) cacheDriver, _ := storage.Create("boltdb", cache.BoltDBDriverParameters{ RootDir: dir, @@ -199,22 +187,19 @@ func TestRunScrubRepo(t *testing.T) { srcStorageCtlr := ociutils.GetDefaultStoreController(dir, log) image := CreateDefaultVulnerableImage() - err = WriteImageToFileSystem(image, repoName, "0.0.1", srcStorageCtlr) + err := WriteImageToFileSystem(image, repoName, "0.0.1", srcStorageCtlr) So(err, ShouldBeNil) err = scrub.RunScrubRepo(context.Background(), imgStore, repoName, log) So(err, ShouldBeNil) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "blobs/manifest ok") }) Convey("Blobs integrity affected", t, func(c C) { - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") conf := config.New() @@ -222,7 +207,7 @@ func TestRunScrubRepo(t *testing.T) { conf.Extensions.Lint = &extconf.LintConfig{} dir := t.TempDir() - log := log.NewLogger("debug", logFile.Name()) + log := log.NewLogger("debug", logPath) metrics := monitoring.NewMetricsServer(false, log) cacheDriver, _ := storage.Create("boltdb", cache.BoltDBDriverParameters{ RootDir: dir, @@ -235,7 +220,7 @@ func TestRunScrubRepo(t *testing.T) { srcStorageCtlr := ociutils.GetDefaultStoreController(dir, log) image := CreateDefaultVulnerableImage() - err = WriteImageToFileSystem(image, repoName, "0.0.1", srcStorageCtlr) + err := WriteImageToFileSystem(image, repoName, "0.0.1", srcStorageCtlr) So(err, ShouldBeNil) layerDigest := image.Manifest.Layers[0].Digest @@ -248,23 +233,20 @@ func TestRunScrubRepo(t *testing.T) { err = scrub.RunScrubRepo(context.Background(), imgStore, repoName, log) So(err, ShouldBeNil) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "blobs/manifest affected") }) Convey("CheckRepo error - not enough permissions to access root directory", t, func(c C) { - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up + logPath := test.MakeTempFilePath(t, "zot-log.txt") conf := config.New() conf.Extensions = &extconf.ExtensionConfig{} conf.Extensions.Lint = &extconf.LintConfig{} dir := t.TempDir() - log := log.NewLogger("debug", logFile.Name()) + log := log.NewLogger("debug", logPath) metrics := monitoring.NewMetricsServer(false, log) cacheDriver, _ := storage.Create("boltdb", cache.BoltDBDriverParameters{ RootDir: dir, @@ -276,7 +258,7 @@ func TestRunScrubRepo(t *testing.T) { srcStorageCtlr := ociutils.GetDefaultStoreController(dir, log) image := CreateDefaultVulnerableImage() - err = WriteImageToFileSystem(image, repoName, "0.0.1", srcStorageCtlr) + err := WriteImageToFileSystem(image, repoName, "0.0.1", srcStorageCtlr) So(err, ShouldBeNil) So(os.Chmod(path.Join(dir, repoName), 0o000), ShouldBeNil) @@ -284,7 +266,7 @@ func TestRunScrubRepo(t *testing.T) { err = scrub.RunScrubRepo(context.Background(), imgStore, repoName, log) So(err, ShouldNotBeNil) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "failed to run scrub for "+imgStore.RootDir()) diff --git a/pkg/extensions/search/cve/cve_test.go b/pkg/extensions/search/cve/cve_test.go index 8e950811..c43369e8 100644 --- a/pkg/extensions/search/cve/cve_test.go +++ b/pkg/extensions/search/cve/cve_test.go @@ -424,8 +424,7 @@ func TestCVESearchDisabled(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -444,13 +443,10 @@ func TestCVESearchDisabled(t *testing.T) { Search: searchConfig, } - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - if err != nil { - panic(err) - } + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() logPath := logFile.Name() - defer os.Remove(logPath) writers := io.MultiWriter(os.Stdout, logFile) @@ -493,8 +489,7 @@ func TestCVESearch(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) dbDir, err := testSetup(t) So(err, ShouldBeNil) @@ -523,13 +518,10 @@ func TestCVESearch(t *testing.T) { Search: searchConfig, } - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - if err != nil { - panic(err) - } + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() logPath := logFile.Name() - defer os.Remove(logPath) writers := io.MultiWriter(os.Stdout, logFile) @@ -1753,11 +1745,10 @@ func TestFixedTagsWithIndex(t *testing.T) { }, } - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - So(err, ShouldBeNil) + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() logPath := logFile.Name() - defer os.Remove(logPath) writers := io.MultiWriter(os.Stdout, logFile) @@ -1782,7 +1773,7 @@ func TestFixedTagsWithIndex(t *testing.T) { multiArchImage := CreateMultiarchWith().Images([]Image{vulnSingleArchImage, fixedSingleArchImage}).Build() - err = UploadMultiarchImage(multiArchImage, baseURL, "repo", "multi-arch-tag") + err := UploadMultiarchImage(multiArchImage, baseURL, "repo", "multi-arch-tag") So(err, ShouldBeNil) // oldest vulnerability diff --git a/pkg/extensions/search/cve/scan_test.go b/pkg/extensions/search/cve/scan_test.go index f1df966c..649641c8 100644 --- a/pkg/extensions/search/cve/scan_test.go +++ b/pkg/extensions/search/cve/scan_test.go @@ -45,13 +45,11 @@ func TestScanGeneratorWithMockedData(t *testing.T) { //nolint: gocyclo repo1 := "repo1" repoIndex := "repoIndex" - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() + logPath := logFile.Name() - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up - writers := io.MultiWriter(os.Stdout, logFile) logger := log.NewLoggerWithWriter("debug", writers) @@ -485,13 +483,11 @@ func TestScanGeneratorWithRealData(t *testing.T) { Convey("Test CVE scanning task scheduler real data", t, func() { rootDir := t.TempDir() - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() + logPath := logFile.Name() - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up - writers := io.MultiWriter(os.Stdout, logFile) logger := log.NewLoggerWithWriter("debug", writers) diff --git a/pkg/extensions/search/cve/update_test.go b/pkg/extensions/search/cve/update_test.go index cbe5ceb8..634aca56 100644 --- a/pkg/extensions/search/cve/update_test.go +++ b/pkg/extensions/search/cve/update_test.go @@ -25,13 +25,11 @@ import ( func TestCVEDBGenerator(t *testing.T) { Convey("Test CVE DB task scheduler reset", t, func() { - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") + logFile := test.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() + logPath := logFile.Name() - So(err, ShouldBeNil) - - defer os.Remove(logFile.Name()) // clean up - writers := io.MultiWriter(os.Stdout, logFile) logger := log.NewLoggerWithWriter("debug", writers) diff --git a/pkg/extensions/search/search_test.go b/pkg/extensions/search/search_test.go index c26f2c9d..979d554d 100644 --- a/pkg/extensions/search/search_test.go +++ b/pkg/extensions/search/search_test.go @@ -678,11 +678,10 @@ func TestRepoListWithNewestImage(t *testing.T) { // we won't use the logging config feature as we want logs in both // stdout and a file - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - So(err, ShouldBeNil) + logFile := MakeTempFile(t, "zot-log.txt") + defer logFile.Close() logPath := logFile.Name() - defer os.Remove(logPath) writers := io.MultiWriter(os.Stdout, logFile) @@ -3619,11 +3618,10 @@ func TestGlobalSearch(t *testing.T) { //nolint: gocyclo // we won't use the logging config feature as we want logs in both // stdout and a file - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - So(err, ShouldBeNil) + logFile := MakeTempFile(t, "zot-log.txt") + defer logFile.Close() logPath := logFile.Name() - defer os.Remove(logPath) writers := io.MultiWriter(os.Stdout, logFile) diff --git a/pkg/extensions/search/userprefs_test.go b/pkg/extensions/search/userprefs_test.go index cf215368..2c9cc7aa 100644 --- a/pkg/extensions/search/userprefs_test.go +++ b/pkg/extensions/search/userprefs_test.go @@ -7,7 +7,6 @@ import ( "fmt" "net/http" "net/url" - "os" "testing" . "github.com/smartystreets/goconvey/convey" @@ -43,11 +42,11 @@ func TestUserData(t *testing.T) { content := test.GetBcryptCredString(adminUser, adminPassword) + test.GetBcryptCredString(simpleUser, simpleUserPassword) - htpasswdPath := test.MakeHtpasswdFileFromString(content) - defer os.Remove(htpasswdPath) + tempDir := t.TempDir() + htpasswdPath := test.MakeHtpasswdFileFromString(t, content) conf := config.New() - conf.Storage.RootDirectory = t.TempDir() + conf.Storage.RootDirectory = tempDir conf.HTTP.Port = port conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -455,11 +454,11 @@ func TestChangingRepoState(t *testing.T) { forbiddenRepo := "forbidden" accesibleRepo := "accesible" - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(simpleUser, simpleUserPassword)) - defer os.Remove(htpasswdPath) + tempDir := t.TempDir() + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(simpleUser, simpleUserPassword)) conf := config.New() - conf.Storage.RootDirectory = t.TempDir() + conf.Storage.RootDirectory = tempDir conf.HTTP.Port = port conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -606,8 +605,7 @@ func TestGlobalSearchWithUserPrefFiltering(t *testing.T) { simpleUser := "simpleUser" simpleUserPassword := "simpleUserPass" - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(simpleUser, simpleUserPassword)) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(simpleUser, simpleUserPassword)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ @@ -801,8 +799,7 @@ func TestExpandedRepoInfoWithUserPrefs(t *testing.T) { simpleUser := "simpleUser" simpleUserPassword := "simpleUserPass" - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(simpleUser, simpleUserPassword)) - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(simpleUser, simpleUserPassword)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ diff --git a/pkg/extensions/sync/sync_disabled_test.go b/pkg/extensions/sync/sync_disabled_test.go index b2cc7f0c..851a507b 100644 --- a/pkg/extensions/sync/sync_disabled_test.go +++ b/pkg/extensions/sync/sync_disabled_test.go @@ -25,9 +25,7 @@ func TestSyncExtension(t *testing.T) { globalDir := t.TempDir() defaultValue := true - logFile, err := os.CreateTemp(globalDir, "zot-log*.txt") - So(err, ShouldBeNil) - defer os.Remove(logFile.Name()) + logPath := test.MakeTempFilePath(t, "zot-log.txt") conf.HTTP.Port = port conf.Storage.RootDirectory = globalDir @@ -37,7 +35,7 @@ func TestSyncExtension(t *testing.T) { Enable: &defaultValue, } conf.Log.Level = "warn" - conf.Log.Output = logFile.Name() + conf.Log.Output = logPath ctlr := api.NewController(conf) ctlrManager := test.NewControllerManager(ctlr) @@ -58,7 +56,7 @@ func TestSyncExtension(t *testing.T) { So(err, ShouldBeNil) So(resp, ShouldNotBeNil) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, diff --git a/pkg/extensions/sync/sync_internal_test.go b/pkg/extensions/sync/sync_internal_test.go index 5bc914d0..99c853c0 100644 --- a/pkg/extensions/sync/sync_internal_test.go +++ b/pkg/extensions/sync/sync_internal_test.go @@ -42,7 +42,7 @@ func TestService(t *testing.T) { URLs: []string{"http://localhost"}, } - service, err := New(conf, "", nil, os.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) + service, err := New(conf, "", nil, t.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) So(err, ShouldBeNil) err = service.SyncRepo(context.Background(), "repo") @@ -54,7 +54,7 @@ func TestService(t *testing.T) { URLs: []string{"http://localhost"}, } - service, err := New(conf, "", nil, os.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) + service, err := New(conf, "", nil, t.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) So(err, ShouldBeNil) // Create a context that's already cancelled @@ -71,7 +71,7 @@ func TestService(t *testing.T) { URLs: []string{"http://localhost"}, } - service, err := New(conf, "", nil, os.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) + service, err := New(conf, "", nil, t.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) So(err, ShouldBeNil) // Create a mock remote that returns tags so we can reach the loop @@ -96,7 +96,7 @@ func TestService(t *testing.T) { URLs: []string{"http://localhost"}, } - service, err := New(conf, "", nil, os.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) + service, err := New(conf, "", nil, t.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) So(err, ShouldBeNil) // Create a minimal mock remote that only returns tags @@ -133,7 +133,7 @@ func TestService(t *testing.T) { OnlySigned: &onlySigned, } - service, err := New(conf, "", nil, os.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) + service, err := New(conf, "", nil, t.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) So(err, ShouldBeNil) // Create a mock remote that returns an invalid reference to trigger ReferrerList error @@ -169,7 +169,7 @@ func TestService(t *testing.T) { URLs: []string{"http://localhost"}, } - service, err := New(conf, "", nil, os.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) + service, err := New(conf, "", nil, t.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) So(err, ShouldBeNil) // Create a mock remote that returns valid references @@ -215,7 +215,7 @@ func TestService(t *testing.T) { RetryDelay: &retryDelay, } - service, err := New(conf, "", nil, os.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) + service, err := New(conf, "", nil, t.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) So(err, ShouldBeNil) onDemand := NewOnDemand(log.NewTestLogger()) @@ -333,7 +333,7 @@ func TestService(t *testing.T) { }}, } - service1, err := New(conf1, "", nil, os.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) + service1, err := New(conf1, "", nil, t.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) So(err, ShouldBeNil) // Create second service for normal processing @@ -346,7 +346,7 @@ func TestService(t *testing.T) { }}, } - service2, err := New(conf2, "", nil, os.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) + service2, err := New(conf2, "", nil, t.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) So(err, ShouldBeNil) onDemand := NewOnDemand(log.NewTestLogger()) @@ -378,7 +378,7 @@ func TestService(t *testing.T) { }}, } - service, err := New(conf, "", nil, os.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) + service, err := New(conf, "", nil, t.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) So(err, ShouldBeNil) onDemand := NewOnDemand(log.NewTestLogger()) @@ -418,7 +418,7 @@ func TestService(t *testing.T) { }}, } - service, err := New(conf, "", nil, os.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) + service, err := New(conf, "", nil, t.TempDir(), storage.StoreController{}, mocks.MetaDBMock{}, log.NewTestLogger()) So(err, ShouldBeNil) onDemand := NewOnDemand(log.NewTestLogger()) diff --git a/pkg/extensions/sync/sync_test.go b/pkg/extensions/sync/sync_test.go index b90d0e4e..66690865 100644 --- a/pkg/extensions/sync/sync_test.go +++ b/pkg/extensions/sync/sync_test.go @@ -14,6 +14,7 @@ import ( "net/url" "os" "path" + "path/filepath" "reflect" "strconv" "strings" @@ -97,7 +98,7 @@ type catalog struct { func makeUpstreamServer( t *testing.T, secure, basicAuth bool, -) (*api.Controller, string, string, string, *resty.Client) { +) (*api.Controller, string, string, *resty.Client) { t.Helper() srcPort := test.GetFreePort() @@ -136,7 +137,7 @@ func makeUpstreamServer( var htpasswdPath string if basicAuth { - htpasswdPath = test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) + htpasswdPath = test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) srcConfig.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ Path: htpasswdPath, @@ -170,7 +171,7 @@ func makeUpstreamServer( sctlr := api.NewController(srcConfig) - return sctlr, srcBaseURL, srcDir, htpasswdPath, client + return sctlr, srcBaseURL, srcDir, client } func makeDownstreamServer( @@ -271,7 +272,7 @@ func makeInsecureDownstreamServerFixedPort( func TestOnDemand(t *testing.T) { Convey("Verify sync on demand feature", t, func() { - sctlr, srcBaseURL, _, _, srcClient := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, srcClient := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -416,7 +417,7 @@ func TestOnDemand(t *testing.T) { }) Convey("Verify sync on demand feature with multiple registryConfig", func() { // make a new upstream server - sctlr, newSrcBaseURL, srcDir, _, srcClient := makeUpstreamServer(t, false, false) + sctlr, newSrcBaseURL, srcDir, srcClient := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -783,7 +784,7 @@ func TestOnDemand(t *testing.T) { func TestOnDemandWithScaleOutCluster(t *testing.T) { Convey("Given 2 downstream zots and one upstream, test that the cluster can sync images", t, func() { - sctlr, srcBaseURL, _, _, srcClient := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, srcClient := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -958,7 +959,7 @@ func TestOnDemandWithScaleOutCluster(t *testing.T) { func TestOnDemandWithScaleOutClusterWithReposNotAddedForSync(t *testing.T) { Convey("When repos are not added for sync, cluster should not sync images", t, func() { - sctlr, srcBaseURL, _, _, srcClient := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, srcClient := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -1093,7 +1094,7 @@ func TestOnDemandWithScaleOutClusterWithReposNotAddedForSync(t *testing.T) { func TestSyncReferenceInLoop(t *testing.T) { Convey("Verify sync doesn't end up in an infinite loop when syncing image references", t, func() { - sctlr, srcBaseURL, srcDir, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, srcDir, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -1239,7 +1240,7 @@ func TestSyncReferenceInLoop(t *testing.T) { func TestSyncWithNonDistributableBlob(t *testing.T) { Convey("Verify sync doesn't copy non distributable blobs", t, func() { - sctlr, srcBaseURL, srcDir, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, srcDir, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -1331,7 +1332,7 @@ func TestDockerImagesAreSkipped(t *testing.T) { Convey("Verify docker images are skipped when they are already synced, preserveDigest: "+testCase.name, t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, srcDir, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, srcDir, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -1656,7 +1657,7 @@ func TestPeriodically(t *testing.T) { Convey("Verify sync feature", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, srcClient := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, srcClient := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -1841,7 +1842,7 @@ func TestPeriodicallyWithScaleOutCluster(t *testing.T) { const zotAlpineTestImageName = "zot-alpine-test" - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -1961,7 +1962,7 @@ func TestPermsDenied(t *testing.T) { Convey("Verify sync feature without perm on sync cache", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -2058,7 +2059,7 @@ func TestPermsDenied(t *testing.T) { func TestConfigReloader(t *testing.T) { Convey("Verify periodically sync config reloader works", t, func() { - sctlr, srcBaseURL, srcDir, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, srcDir, _ := makeUpstreamServer(t, false, false) defer os.RemoveAll(srcDir) scm := test.NewControllerManager(sctlr) @@ -2108,12 +2109,9 @@ func TestConfigReloader(t *testing.T) { destConfig.Extensions.Search = nil destConfig.Extensions.Sync = syncConfig - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - destConfig.Log.Output = logFile.Name() + destConfig.Log.Output = logPath dctlr := api.NewController(destConfig) @@ -2121,14 +2119,12 @@ func TestConfigReloader(t *testing.T) { Convey("Reload config without sync", func() { content := fmt.Sprintf(`{"distSpecVersion": "1.1.1", "storage": {"rootDirectory": "%s"}, "http": {"address": "127.0.0.1", "port": "%s"}, - "log": {"level": "debug", "output": "%s"}}`, destDir, destPort, logFile.Name()) + "log": {"level": "debug", "output": "%s"}}`, destDir, destPort, logPath) - cfgfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) + cfgfile := test.MakeTempFile(t, "zot-test.json") + defer cfgfile.Close() - defer os.Remove(cfgfile.Name()) // clean up - - _, err = cfgfile.WriteString(content) + _, err := cfgfile.WriteString(content) So(err, ShouldBeNil) hotReloader, err := cli.NewHotReloader(dctlr, cfgfile.Name(), "") @@ -2168,7 +2164,7 @@ func TestConfigReloader(t *testing.T) { time.Sleep(2 * time.Second) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) t.Logf("downstream log: %s", string(data)) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "reloaded params") @@ -2207,7 +2203,7 @@ func TestConfigReloader(t *testing.T) { }] } } - }`, destDir, destPort, logFile.Name()) + }`, destDir, destPort, logPath) err = cfgfile.Truncate(0) So(err, ShouldBeNil) @@ -2225,7 +2221,7 @@ func TestConfigReloader(t *testing.T) { time.Sleep(2 * time.Second) - data, err = os.ReadFile(logFile.Name()) + data, err = os.ReadFile(logPath) t.Logf("downstream log: %s", string(data)) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "reloaded params") @@ -2271,14 +2267,12 @@ func TestConfigReloader(t *testing.T) { }] } } - }`, destDir, destPort, logFile.Name()) + }`, destDir, destPort, logPath) - cfgfile, err := os.CreateTemp("", "zot-test*.json") - So(err, ShouldBeNil) + cfgfile := test.MakeTempFile(t, "zot-test.json") + defer cfgfile.Close() - defer os.Remove(cfgfile.Name()) // clean up - - _, err = cfgfile.WriteString(content) + _, err := cfgfile.WriteString(content) So(err, ShouldBeNil) hotReloader, err := cli.NewHotReloader(dctlr, cfgfile.Name(), "") @@ -2321,7 +2315,7 @@ func TestConfigReloader(t *testing.T) { time.Sleep(2 * time.Second) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) t.Logf("downstream log: %s", string(data)) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "failed to start sync extension") @@ -2335,7 +2329,7 @@ func TestMandatoryAnnotations(t *testing.T) { Convey("Verify mandatory annotations failing - on demand disabled", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -2387,11 +2381,9 @@ func TestMandatoryAnnotations(t *testing.T) { destConfig.Extensions = &extconf.ExtensionConfig{} destConfig.Extensions.Sync = syncConfig - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) - defer os.Remove(logFile.Name()) + logPath := test.MakeTempFilePath(t, "zot-log.txt") - destConfig.Log.Output = logFile.Name() + destConfig.Log.Output = logPath lintEnable := true destConfig.Extensions.Lint = &extconf.LintConfig{} @@ -2433,7 +2425,7 @@ func TestBadTLS(t *testing.T) { Convey("Verify sync TLS feature", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, true, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, true, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -2508,7 +2500,7 @@ func TestTLS(t *testing.T) { Convey("Verify sync TLS feature", t, func() { updateDuration, _ := time.ParseDuration("1h") - sctlr, srcBaseURL, srcDir, _, _ := makeUpstreamServer(t, true, false) + sctlr, srcBaseURL, srcDir, _ := makeUpstreamServer(t, true, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -2650,7 +2642,7 @@ func TestBearerAuth(t *testing.T) { } defer authTestServer.Close() - sctlr, srcBaseURL, _, _, srcClient := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, srcClient := makeUpstreamServer(t, false, false) aurl, err := url.Parse(authTestServer.URL) So(err, ShouldBeNil) @@ -2669,7 +2661,7 @@ func TestBearerAuth(t *testing.T) { defer scm.StopServer() registryName := sync.StripRegistryTransport(srcBaseURL) - credentialsFile := makeCredentialsFile(fmt.Sprintf(`{"%s":{"username": "%s", "password": "%s"}}`, + credentialsFile := makeCredentialsFile(t.TempDir(), fmt.Sprintf(`{"%s":{"username": "%s", "password": "%s"}}`, registryName, username, password)) var tlsVerify bool @@ -2804,7 +2796,7 @@ func TestBearerAuth(t *testing.T) { } defer authTestServer.Close() - sctlr, srcBaseURL, _, _, srcClient := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, srcClient := makeUpstreamServer(t, false, false) aurl, err := url.Parse(authTestServer.URL) So(err, ShouldBeNil) @@ -2823,7 +2815,7 @@ func TestBearerAuth(t *testing.T) { defer scm.StopServer() registryName := sync.StripRegistryTransport(srcBaseURL) - credentialsFile := makeCredentialsFile(fmt.Sprintf(`{"%s":{"username": "%s", "password": "%s"}}`, + credentialsFile := makeCredentialsFile(t.TempDir(), fmt.Sprintf(`{"%s":{"username": "%s", "password": "%s"}}`, registryName, username, password)) var tlsVerify bool @@ -2944,15 +2936,14 @@ func TestBasicAuth(t *testing.T) { updateDuration, _ := time.ParseDuration("1h") Convey("Verify sync basic auth with file credentials", func() { - sctlr, srcBaseURL, _, htpasswdPath, srcClient := makeUpstreamServer(t, false, true) - defer os.Remove(htpasswdPath) + sctlr, srcBaseURL, _, srcClient := makeUpstreamServer(t, false, true) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) defer scm.StopServer() registryName := sync.StripRegistryTransport(srcBaseURL) - credentialsFile := makeCredentialsFile(fmt.Sprintf(`{"%s":{"username": "%s", "password": "%s"}}`, + credentialsFile := makeCredentialsFile(t.TempDir(), fmt.Sprintf(`{"%s":{"username": "%s", "password": "%s"}}`, registryName, username, password)) var tlsVerify bool @@ -3021,8 +3012,7 @@ func TestBasicAuth(t *testing.T) { }) Convey("Verify sync basic auth with wrong file credentials", func() { - sctlr, srcBaseURL, _, htpasswdPath, _ := makeUpstreamServer(t, false, true) - defer os.Remove(htpasswdPath) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, true) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -3055,7 +3045,7 @@ func TestBasicAuth(t *testing.T) { registryName := sync.StripRegistryTransport(srcBaseURL) - credentialsFile := makeCredentialsFile(fmt.Sprintf(`{"%s":{"username": "%s", "password": "invalid"}}`, + credentialsFile := makeCredentialsFile(t.TempDir(), fmt.Sprintf(`{"%s":{"username": "%s", "password": "invalid"}}`, registryName, username)) var tlsVerify bool @@ -3115,8 +3105,7 @@ func TestBasicAuth(t *testing.T) { }) Convey("Verify sync basic auth with bad file credentials", func() { - sctlr, srcBaseURL, _, htpasswdPath, _ := makeUpstreamServer(t, false, true) - defer os.Remove(htpasswdPath) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, true) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -3124,7 +3113,7 @@ func TestBasicAuth(t *testing.T) { registryName := sync.StripRegistryTransport(srcBaseURL) - credentialsFile := makeCredentialsFile(fmt.Sprintf(`{"%s":{"username": "%s", "password": "%s"}}`, + credentialsFile := makeCredentialsFile(t.TempDir(), fmt.Sprintf(`{"%s":{"username": "%s", "password": "%s"}}`, registryName, username, password)) err := os.Chmod(credentialsFile, 0o000) @@ -3193,15 +3182,14 @@ func TestBasicAuth(t *testing.T) { }) Convey("Verify on demand sync with basic auth", func() { - sctlr, srcBaseURL, _, htpasswdPath, srcClient := makeUpstreamServer(t, false, true) - defer os.Remove(htpasswdPath) + sctlr, srcBaseURL, _, srcClient := makeUpstreamServer(t, false, true) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) defer scm.StopServer() registryName := sync.StripRegistryTransport(srcBaseURL) - credentialsFile := makeCredentialsFile(fmt.Sprintf(`{"%s":{"username": "%s", "password": "%s"}}`, + credentialsFile := makeCredentialsFile(t.TempDir(), fmt.Sprintf(`{"%s":{"username": "%s", "password": "%s"}}`, registryName, username, password)) defaultValue := false @@ -3350,7 +3338,7 @@ func TestNoImagesByRegex(t *testing.T) { Convey("Verify sync with no images on source based on regex", t, func() { updateDuration, _ := time.ParseDuration("1h") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -3414,7 +3402,7 @@ func TestInvalidRegex(t *testing.T) { Convey("Verify sync with invalid regex", t, func() { updateDuration, _ := time.ParseDuration("1h") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -3476,7 +3464,7 @@ func TestNotSemver(t *testing.T) { Convey("Verify sync feature semver compliant", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -3559,7 +3547,7 @@ func TestInvalidCerts(t *testing.T) { Convey("Verify sync with bad certs", t, func() { updateDuration, _ := time.ParseDuration("1h") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, true, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, true, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -3713,8 +3701,8 @@ func TestCertsWithWrongPerms(t *testing.T) { }) } -func makeCredentialsFile(fileContent string) string { - tmpfile, err := os.CreateTemp("", "sync-credentials-") +func makeCredentialsFile(tempDir string, fileContent string) string { + tmpfile, err := os.Create(filepath.Join(tempDir, "sync-credentials.json")) if err != nil { panic(err) } @@ -3779,7 +3767,7 @@ func TestInvalidTags(t *testing.T) { Convey("Verify sync invalid tags", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -3999,7 +3987,7 @@ func TestOnDemandRepoErr(t *testing.T) { func TestOnDemandContentFiltering(t *testing.T) { Convey("Verify sync on demand feature", t, func() { - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -4095,7 +4083,7 @@ func TestOnDemandContentFiltering(t *testing.T) { func TestConfigRules(t *testing.T) { Convey("Verify sync config rules", t, func() { - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -4209,7 +4197,7 @@ func TestMultipleURLs(t *testing.T) { Convey("Verify sync feature", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, srcClient := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, srcClient := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -4339,7 +4327,7 @@ func TestPeriodicallySignaturesErr(t *testing.T) { Convey("Verify sync periodically signatures errors", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, srcDir, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, srcDir, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -4651,7 +4639,7 @@ func TestSignatures(t *testing.T) { Convey("Verify sync signatures", t, func() { updateDuration, _ := time.ParseDuration("1m") - sctlr, srcBaseURL, srcDir, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, srcDir, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) @@ -5180,7 +5168,7 @@ func TestSignatures(t *testing.T) { Convey("Verify sync oci1.1 cosign signatures", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -5294,7 +5282,7 @@ func TestSyncedSignaturesMetaDB(t *testing.T) { // Create source registry - sctlr, srcBaseURL, srcDir, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, srcDir, _ := makeUpstreamServer(t, false, false) t.Log(srcDir) srcPort := getPortFromBaseURL(srcBaseURL) @@ -5481,7 +5469,7 @@ func TestOnDemandRetryGoroutine(t *testing.T) { func TestOnDemandWithDigest(t *testing.T) { Convey("Verify ondemand sync works with both digests and tags", t, func() { - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -5719,7 +5707,7 @@ func TestOnDemandMultipleImage(t *testing.T) { func TestOnDemandPullsReferrersOnce(t *testing.T) { Convey("Verify sync on demand pulls only one time", t, func(conv C) { - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -5897,7 +5885,7 @@ func TestOnDemandPullsReferrersOnce(t *testing.T) { func TestOnDemandPullsOnce(t *testing.T) { Convey("Verify sync on demand pulls only one time", t, func(conv C) { - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -6012,7 +6000,7 @@ func TestOnDemandPullsOnce(t *testing.T) { func TestSignaturesOnDemand(t *testing.T) { Convey("Verify sync signatures on demand feature", t, func() { - sctlr, srcBaseURL, srcDir, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, srcDir, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -6139,7 +6127,7 @@ func TestSignaturesOnDemand(t *testing.T) { }) Convey("Verify sync signatures on demand feature: notation - negative cases", t, func() { - sctlr, srcBaseURL, srcDir, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, srcDir, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -6258,7 +6246,7 @@ func TestSignaturesOnDemand(t *testing.T) { func TestOnlySignaturesOnDemand(t *testing.T) { Convey("Verify sync signatures on demand feature when we already have the image", t, func() { - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -6373,7 +6361,7 @@ func TestSyncOnlyDiff(t *testing.T) { Convey("Verify sync only difference between local and upstream", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -6461,7 +6449,7 @@ func TestSyncWithDiffDigest(t *testing.T) { Convey("Verify sync correctly detects changes in upstream images", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -6608,7 +6596,7 @@ func TestSyncSignaturesDiff(t *testing.T) { Convey("Verify sync detects changes in the upstream signatures", t, func() { updateDuration, _ := time.ParseDuration("10s") - sctlr, srcBaseURL, srcDir, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, srcDir, _ := makeUpstreamServer(t, false, false) defer os.RemoveAll(srcDir) scm := test.NewControllerManager(sctlr) @@ -6855,7 +6843,7 @@ func TestSyncSignaturesDiff(t *testing.T) { func TestOnlySignedFlag(t *testing.T) { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) //nolint: dogsled + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) //nolint: dogsled scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) @@ -6988,7 +6976,7 @@ func TestSyncWithDestination(t *testing.T) { }, } - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) err := os.MkdirAll(path.Join(sctlr.Config.Storage.RootDirectory, "/zot-fold"), storageConstants.DefaultDirPerms) So(err, ShouldBeNil) @@ -7153,7 +7141,7 @@ func TestSyncImageIndex(t *testing.T) { Convey("Verify syncing image indexes works", t, func() { updateDuration, _ := time.ParseDuration("30m") - sctlr, srcBaseURL, _, _, _ := makeUpstreamServer(t, false, false) + sctlr, srcBaseURL, _, _ := makeUpstreamServer(t, false, false) scm := test.NewControllerManager(sctlr) scm.StartAndWait(sctlr.Config.HTTP.Port) diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index d9869e52..908d7320 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -52,9 +52,7 @@ func TestAuditLogMessages(t *testing.T) { username, seedUser := test.GenerateRandomString() password, seedPass := test.GenerateRandomString() - htpasswdPath := test.MakeHtpasswdFileFromString(test.GetBcryptCredString(username, password)) - - defer os.Remove(htpasswdPath) + htpasswdPath := test.MakeHtpasswdFileFromString(t, test.GetBcryptCredString(username, password)) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ diff --git a/pkg/scheduler/scheduler_test.go b/pkg/scheduler/scheduler_test.go index cb011629..194b158a 100644 --- a/pkg/scheduler/scheduler_test.go +++ b/pkg/scheduler/scheduler_test.go @@ -16,6 +16,7 @@ import ( "zotregistry.dev/zot/v2/pkg/extensions/monitoring" "zotregistry.dev/zot/v2/pkg/log" "zotregistry.dev/zot/v2/pkg/scheduler" + test "zotregistry.dev/zot/v2/pkg/test/common" ) type task struct { @@ -137,12 +138,9 @@ func (g *shortGenerator) Reset() { func TestScheduler(t *testing.T) { Convey("Test active to waiting periodic generator", t, func() { - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - logger := log.NewLogger("debug", logFile.Name()) + logger := log.NewLogger("debug", logPath) metrics := monitoring.NewMetricsServer(true, logger) sch := scheduler.NewScheduler(config.New(), metrics, logger) @@ -154,18 +152,15 @@ func TestScheduler(t *testing.T) { time.Sleep(2 * time.Second) sch.Shutdown() - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "waiting generator is ready, pushing to ready generators") }) Convey("Test order of generators in queue", t, func() { - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - logger := log.NewLogger("debug", logFile.Name()) + logger := log.NewLogger("debug", logPath) cfg := config.New() cfg.Scheduler = &config.SchedulerConfig{NumWorkers: 3} metrics := monitoring.NewMetricsServer(true, logger) @@ -185,7 +180,7 @@ func TestScheduler(t *testing.T) { time.Sleep(4 * time.Second) sch.Shutdown() - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "executing high priority task; index: 1") @@ -195,12 +190,9 @@ func TestScheduler(t *testing.T) { }) Convey("Test reordering of generators in queue", t, func() { - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - logger := log.NewLogger("debug", logFile.Name()) + logger := log.NewLogger("debug", logPath) cfg := config.New() cfg.Scheduler = &config.SchedulerConfig{NumWorkers: 3} metrics := monitoring.NewMetricsServer(true, logger) @@ -223,7 +215,7 @@ func TestScheduler(t *testing.T) { time.Sleep(2 * time.Second) // Increased from 1 second to 2 seconds for stability sch.Shutdown() - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) // Check all tasks show up in the logs @@ -298,12 +290,9 @@ func TestScheduler(t *testing.T) { }) Convey("Test task returning an error", t, func() { - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - logger := log.NewLogger("debug", logFile.Name()) + logger := log.NewLogger("debug", logPath) metrics := monitoring.NewMetricsServer(true, logger) sch := scheduler.NewScheduler(config.New(), metrics, logger) @@ -314,19 +303,16 @@ func TestScheduler(t *testing.T) { time.Sleep(500 * time.Millisecond) sch.Shutdown() - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "adding a new task") So(string(data), ShouldContainSubstring, "failed to execute task") }) Convey("Test resubmit generator", t, func() { - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - logger := log.NewLogger("debug", logFile.Name()) + logger := log.NewLogger("debug", logPath) metrics := monitoring.NewMetricsServer(true, logger) sch := scheduler.NewScheduler(config.New(), metrics, logger) @@ -337,37 +323,31 @@ func TestScheduler(t *testing.T) { time.Sleep(1 * time.Second) sch.Shutdown() - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "executing low priority task; index: 1") So(string(data), ShouldContainSubstring, "executing low priority task; index: 2") }) Convey("Try to add a task with wrong priority", t, func() { - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - logger := log.NewLogger("debug", logFile.Name()) + logger := log.NewLogger("debug", logPath) metrics := monitoring.NewMetricsServer(true, logger) sch := scheduler.NewScheduler(config.New(), metrics, logger) t := &task{log: logger, msg: "", err: false} sch.SubmitTask(t, -1) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldNotContainSubstring, "adding a new task") }) Convey("Test adding a new task when context is done", t, func() { - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - logger := log.NewLogger("debug", logFile.Name()) + logger := log.NewLogger("debug", logPath) metrics := monitoring.NewMetricsServer(true, logger) sch := scheduler.NewScheduler(config.New(), metrics, logger) @@ -378,18 +358,15 @@ func TestScheduler(t *testing.T) { t := &task{log: logger, msg: "", err: false} sch.SubmitTask(t, scheduler.LowPriority) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldNotContainSubstring, "adding a new task") }) Convey("Test stopping scheduler by calling Shutdown()", t, func() { - logFile, err := os.CreateTemp("", "zot-log*.txt") - So(err, ShouldBeNil) + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - logger := log.NewLogger("debug", logFile.Name()) + logger := log.NewLogger("debug", logPath) metrics := monitoring.NewMetricsServer(true, logger) sch := scheduler.NewScheduler(config.New(), metrics, logger) @@ -400,7 +377,7 @@ func TestScheduler(t *testing.T) { time.Sleep(1 * time.Second) sch.Shutdown() - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "executing medium priority task; index: 1") So(string(data), ShouldContainSubstring, "executing medium priority task; index: 2") @@ -436,22 +413,23 @@ func TestScheduler(t *testing.T) { func TestGetNumWorkers(t *testing.T) { Convey("Test setting the number of workers - default value", t, func() { - logger := log.NewLogger("debug", "logFile") + logPath := test.MakeTempFilePath(t, "zot-log.txt") + logger := log.NewLogger("debug", logPath) + metrics := monitoring.NewMetricsServer(true, logger) sch := scheduler.NewScheduler(config.New(), metrics, logger) - defer os.Remove("logFile") So(sch.NumWorkers, ShouldEqual, runtime.NumCPU()*4) }) Convey("Test setting the number of workers - getting the value from config", t, func() { cfg := config.New() cfg.Scheduler = &config.SchedulerConfig{NumWorkers: 3} - logger := log.NewLogger("debug", "logFile") + logPath := test.MakeTempFilePath(t, "zot-log.txt") + logger := log.NewLogger("debug", logPath) metrics := monitoring.NewMetricsServer(true, logger) sch := scheduler.NewScheduler(cfg, metrics, logger) - defer os.Remove("logFile") So(sch.NumWorkers, ShouldEqual, 3) }) } diff --git a/pkg/storage/local/local_test.go b/pkg/storage/local/local_test.go index 1708fdf7..cea78376 100644 --- a/pkg/storage/local/local_test.go +++ b/pkg/storage/local/local_test.go @@ -35,6 +35,7 @@ import ( "zotregistry.dev/zot/v2/pkg/storage/gc" "zotregistry.dev/zot/v2/pkg/storage/local" storageTypes "zotregistry.dev/zot/v2/pkg/storage/types" + test "zotregistry.dev/zot/v2/pkg/test/common" . "zotregistry.dev/zot/v2/pkg/test/image-utils" "zotregistry.dev/zot/v2/pkg/test/mocks" "zotregistry.dev/zot/v2/pkg/test/signature" @@ -1970,11 +1971,9 @@ func TestGarbageCollectForImageStore(t *testing.T) { ctx := context.Background() Convey("Garbage collect continues when manifest blob is missing", func() { - logFile, _ := os.CreateTemp("", "zot-log*.txt") + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - log := zlog.NewLogger("debug", logFile.Name()) + log := zlog.NewLogger("debug", logPath) audit := zlog.NewAuditLogger("debug", "") metrics := monitoring.NewMetricsServer(false, log) @@ -2013,7 +2012,7 @@ func TestGarbageCollectForImageStore(t *testing.T) { time.Sleep(500 * time.Millisecond) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) // Verify that GC logged a warning about skipping the missing manifest So(string(data), ShouldContainSubstring, "skipping missing") @@ -2021,11 +2020,9 @@ func TestGarbageCollectForImageStore(t *testing.T) { }) Convey("Garbage collect error - not enough permissions to access index.json", func() { - logFile, _ := os.CreateTemp("", "zot-log*.txt") + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - log := zlog.NewLogger("debug", logFile.Name()) + log := zlog.NewLogger("debug", logPath) audit := zlog.NewAuditLogger("debug", "") metrics := monitoring.NewMetricsServer(false, log) @@ -2056,7 +2053,7 @@ func TestGarbageCollectForImageStore(t *testing.T) { time.Sleep(500 * time.Millisecond) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "failed to run GC for "+path.Join(imgStore.RootDir(), repoName)) @@ -2137,11 +2134,9 @@ func TestGarbageCollectForImageStore(t *testing.T) { }) Convey("Garbage collect error - not enough permissions to access blob upload", func() { - logFile, _ := os.CreateTemp("", "zot-log*.txt") + logPath := test.MakeTempFilePath(t, "zot-log.txt") - defer os.Remove(logFile.Name()) // clean up - - log := zlog.NewLogger("debug", logFile.Name()) + log := zlog.NewLogger("debug", logPath) audit := zlog.NewAuditLogger("debug", "") metrics := monitoring.NewMetricsServer(false, log) @@ -2202,7 +2197,7 @@ func TestGarbageCollectForImageStore(t *testing.T) { So(err, ShouldNotBeNil) So(isPresent, ShouldBeFalse) - data, err := os.ReadFile(logFile.Name()) + data, err := os.ReadFile(logPath) So(err, ShouldBeNil) So(string(data), ShouldContainSubstring, "failed to run GC for "+path.Join(imgStore.RootDir(), repoName)) diff --git a/pkg/test/common/fs.go b/pkg/test/common/fs.go index 69aaad9c..4de81ad9 100644 --- a/pkg/test/common/fs.go +++ b/pkg/test/common/fs.go @@ -12,6 +12,7 @@ import ( "path" "path/filepath" "strings" + "testing" "time" "github.com/GehirnInc/crypt" @@ -308,8 +309,41 @@ func GetSHA512CredString(username, password string) string { return usernameAndHash } -func MakeHtpasswdFileFromString(fileContent string) string { - htpasswdFile, err := os.CreateTemp("", "htpasswd-") +func MakeTempFile(tb testing.TB, filename string) *os.File { + tb.Helper() + tempDir := tb.TempDir() + file, err := os.Create(filepath.Join(tempDir, filename)) + if err != nil { + panic(err) + } + + return file +} + +// MakeTempFilePath creates an empty temporary file and returns its path. +func MakeTempFilePath(tb testing.TB, filename string) string { + tb.Helper() + + return filepath.Join(tb.TempDir(), filename) +} + +// MakeTempFileWithContent creates a temporary file with the given filename and content, and returns its path. +func MakeTempFileWithContent(tb testing.TB, filename, content string) string { + tb.Helper() + tmpfile := MakeTempFile(tb, filename) + path := tmpfile.Name() + tmpfile.Close() // Close immediately, we'll write using os.WriteFile + if err := os.WriteFile(path, []byte(content), 0o0600); err != nil { + panic(err) + } + + return path +} + +func MakeHtpasswdFileFromString(tb testing.TB, fileContent string) string { + tb.Helper() + tempDir := tb.TempDir() + htpasswdFile, err := os.Create(filepath.Join(tempDir, "htpasswd")) if err != nil { panic(err) } diff --git a/pkg/test/common/fs_test.go b/pkg/test/common/fs_test.go index 991913c1..57d2ac99 100644 --- a/pkg/test/common/fs_test.go +++ b/pkg/test/common/fs_test.go @@ -20,7 +20,7 @@ var ErrTestError = errors.New("ErrTestError") func TestCopyFiles(t *testing.T) { Convey("sourceDir does not exist", t, func() { - err := tcommon.CopyFiles("/path/to/some/unexisting/directory", os.TempDir()) + err := tcommon.CopyFiles("/path/to/some/unexisting/directory", t.TempDir()) So(err, ShouldNotBeNil) }) Convey("destDir is a file", t, func() { @@ -38,7 +38,7 @@ func TestCopyFiles(t *testing.T) { err := os.Chmod(dir, 0o300) So(err, ShouldBeNil) - err = tcommon.CopyFiles(dir, os.TempDir()) + err = tcommon.CopyFiles(dir, t.TempDir()) So(err, ShouldNotBeNil) }) Convey("sourceDir has a subfolder that does not have read permissions", t, func() { @@ -48,7 +48,7 @@ func TestCopyFiles(t *testing.T) { err := os.Mkdir(path.Join(dir, sdir), 0o300) So(err, ShouldBeNil) - err = tcommon.CopyFiles(dir, os.TempDir()) + err = tcommon.CopyFiles(dir, t.TempDir()) So(err, ShouldNotBeNil) }) Convey("sourceDir has a file that does not have read permissions", t, func() { @@ -64,7 +64,7 @@ func TestCopyFiles(t *testing.T) { err = os.Chmod(filePath, 0o300) So(err, ShouldBeNil) - err = tcommon.CopyFiles(dir, os.TempDir()) + err = tcommon.CopyFiles(dir, t.TempDir()) So(err, ShouldNotBeNil) }) Convey("sourceDir contains a folder starting with invalid characters", t, func() { @@ -125,21 +125,22 @@ func TestCopyFile(t *testing.T) { } func TestReadLogFileAndSearchString(t *testing.T) { - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - if err != nil { - panic(err) - } - - logPath := logFile.Name() - defer os.Remove(logPath) + logPath := tcommon.MakeTempFilePath(t, "zot-log.txt") Convey("Invalid path", t, func() { - _, err = tcommon.ReadLogFileAndSearchString("invalidPath", + _, err := tcommon.ReadLogFileAndSearchString("invalidPath", "cve-db update completed, next update scheduled after interval", 1*time.Second) So(err, ShouldNotBeNil) }) Convey("Time too short", t, func() { + // Create an empty file so ReadLogFileAndSearchString can read it + file, err := os.Create(logPath) + if err != nil { + panic(err) + } + file.Close() + ok, err := tcommon.ReadLogFileAndSearchString(logPath, "invalid string", time.Microsecond) So(err, ShouldBeNil) So(ok, ShouldBeFalse) @@ -147,18 +148,15 @@ func TestReadLogFileAndSearchString(t *testing.T) { } func TestReadLogFileAndCountStringOccurence(t *testing.T) { - logFile, err := os.CreateTemp(t.TempDir(), "zot-log*.txt") - if err != nil { - panic(err) - } + logFile := tcommon.MakeTempFile(t, "zot-log.txt") + defer logFile.Close() - _, err = logFile.WriteString("line1\n line2\n line3 line1 line2\n line1") + _, err := logFile.WriteString("line1\n line2\n line3 line1 line2\n line1") if err != nil { panic(err) } logPath := logFile.Name() - defer os.Remove(logPath) Convey("Invalid path", t, func() { _, err = tcommon.ReadLogFileAndCountStringOccurence("invalidPath", @@ -239,9 +237,10 @@ func TestCopyTestKeysAndCerts(t *testing.T) { So(err.Error(), ShouldContainSubstring, "CopyFiles os.Stat failed") // --- GetProjectRootDir call fails ----- - err = os.Chdir(os.TempDir()) + tempDir := t.TempDir() + err = os.Chdir(tempDir) So(err, ShouldBeNil) - err = tcommon.CopyTestKeysAndCerts(os.TempDir()) + err = tcommon.CopyTestKeysAndCerts(tempDir) So(err, ShouldNotBeNil) So(err, ShouldEqual, tcommon.ErrNoGoModFileFound) }) @@ -259,7 +258,8 @@ func TestGetProjectRootDir(t *testing.T) { defer func() { _ = os.Chdir(workDir) }() - err = os.Chdir(os.TempDir()) + tempDir := t.TempDir() + err = os.Chdir(tempDir) So(err, ShouldBeNil) path, err := tcommon.GetProjectRootDir() So(err, ShouldNotBeNil) diff --git a/pkg/test/image-utils/upload_test.go b/pkg/test/image-utils/upload_test.go index 98dd8fb9..c388cc56 100644 --- a/pkg/test/image-utils/upload_test.go +++ b/pkg/test/image-utils/upload_test.go @@ -180,8 +180,7 @@ func TestUploadImage(t *testing.T) { password1 := "test" testString1 := tcommon.GetBcryptCredString(user1, password1) - htpasswdPath := tcommon.MakeHtpasswdFileFromString(testString1) - defer os.Remove(htpasswdPath) + htpasswdPath := tcommon.MakeHtpasswdFileFromString(t, testString1) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ Path: htpasswdPath, @@ -497,8 +496,7 @@ func TestInjectUploadImageWithBasicAuth(t *testing.T) { password := "password" testString := tcommon.GetBcryptCredString(user, password) - htpasswdPath := tcommon.MakeHtpasswdFileFromString(testString) - defer os.Remove(htpasswdPath) + htpasswdPath := tcommon.MakeHtpasswdFileFromString(t, testString) conf.HTTP.Auth = &config.AuthConfig{ HTPasswd: config.AuthHTPasswd{ Path: htpasswdPath,