Skip to content

Commit

Permalink
test(registry): create namespace with random name (#4377)
Browse files Browse the repository at this point in the history
  • Loading branch information
Codelax authored Dec 23, 2024
1 parent 43cb2cc commit 2109482
Show file tree
Hide file tree
Showing 4 changed files with 1,845 additions and 257 deletions.
50 changes: 32 additions & 18 deletions core/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import (
"flag"
"fmt"
"io"
"math/rand/v2"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"testing"
"text/template"
Expand Down Expand Up @@ -64,7 +66,7 @@ type CheckFuncCtx struct {
Result interface{}

// Meta bag
Meta testMetadata
Meta TestMetadata

// Scaleway client
Client *scw.Client
Expand All @@ -78,14 +80,20 @@ type CheckFuncCtx struct {
LogBuffer string
}

// testMetadata contains arbitrary data that can be passed along a test lifecycle.
type testMetadata map[string]interface{}
var testRenderHelpers = map[string]any{
"randint": func() string {
return strconv.FormatUint(rand.Uint64(), 10) //nolint:gosec // Use weak random for a non-important use
},
}

// TestMetadata contains arbitrary data that can be passed along a test lifecycle.
type TestMetadata map[string]interface{}

// render renders a go template using where content of Meta can be used
func (meta testMetadata) render(strTpl string) string {
// Render renders a go template using where content of Meta can be used
func (meta TestMetadata) Render(strTpl string) string {
t := meta["t"].(*testing.T)
buf := &bytes.Buffer{}
require.NoError(t, template.Must(template.New("tpl").Parse(strTpl)).Execute(buf, meta))
require.NoError(t, template.Must(template.New("tpl").Funcs(testRenderHelpers).Parse(strTpl)).Execute(buf, meta))
return buf.String()
}

Expand All @@ -105,7 +113,7 @@ type AfterFunc func(ctx *AfterFuncCtx) error

type ExecFuncCtx struct {
T *testing.T
Meta testMetadata
Meta TestMetadata
Client *scw.Client
}

Expand All @@ -115,7 +123,7 @@ type BeforeFuncCtx struct {
T *testing.T
Client *scw.Client
ExecuteCmd func(args []string) interface{}
Meta testMetadata
Meta TestMetadata
OverrideEnv map[string]string
Logger *Logger
}
Expand All @@ -124,7 +132,7 @@ type AfterFuncCtx struct {
T *testing.T
Client *scw.Client
ExecuteCmd func(args []string) interface{}
Meta testMetadata
Meta TestMetadata
CmdResult interface{}
OverrideEnv map[string]string
Logger *Logger
Expand Down Expand Up @@ -326,7 +334,7 @@ func Test(config *TestConfig) func(t *testing.T) {
client = createTestClient(t, config, httpClient)
}

meta := testMetadata{
meta := TestMetadata{
"t": t,
}

Expand Down Expand Up @@ -412,7 +420,7 @@ func Test(config *TestConfig) func(t *testing.T) {
Meta: meta,
OverrideEnv: overrideEnv,
Logger: testLogger,
}))
}), "error executing BeforeFunc")
testLogger.Debug("End BeforeFunc")
}

Expand All @@ -424,9 +432,9 @@ func Test(config *TestConfig) func(t *testing.T) {
if config.Cmd != "" {
renderedArgs = cmdToArgs(meta, config.Cmd)
} else {
// We render raw arguments from meta
// We Render raw arguments from meta
for _, arg := range rawArgs {
renderedArgs = append(renderedArgs, meta.render(arg))
renderedArgs = append(renderedArgs, meta.Render(arg))
}
}

Expand Down Expand Up @@ -491,8 +499,8 @@ func Test(config *TestConfig) func(t *testing.T) {
}
}

func cmdToArgs(meta testMetadata, s string) []string {
return strings.Split(meta.render(s), " ")
func cmdToArgs(meta TestMetadata, s string) []string {
return strings.Split(meta.Render(s), " ")
}

// BeforeFuncCombine combines multiple before functions into one.
Expand Down Expand Up @@ -553,7 +561,13 @@ func ExecStoreBeforeCmd(metaKey, cmd string) BeforeFunc {
func BeforeFuncOsExec(cmd string, args ...string) BeforeFunc {
return func(ctx *BeforeFuncCtx) error {
ctx.Logger.Debugf("BeforeFuncOsExec: cmd=%s args=%s\n", cmd, args)
return exec.Command(cmd, args...).Run()
err := exec.Command(cmd, args...).Run()
if err != nil {
formattedCmd := strings.Join(append([]string{cmd}, args...), " ")
return fmt.Errorf("failed to execute cmd %q: %w", formattedCmd, err)
}

return nil
}
}

Expand All @@ -571,7 +585,7 @@ func ExecBeforeCmd(cmd string) BeforeFunc {
func ExecBeforeCmdArgs(args []string) BeforeFunc {
return func(ctx *BeforeFuncCtx) error {
for i := range args {
args[i] = ctx.Meta.render(args[i])
args[i] = ctx.Meta.Render(args[i])
}
ctx.Logger.Debugf("ExecBeforeCmdArgs: args=%s\n", args)
ctx.ExecuteCmd(args)
Expand Down Expand Up @@ -734,7 +748,7 @@ func TestCheckStdout(stdout string) TestCheck {

func OverrideExecSimple(cmdStr string, exitCode int) OverrideExecTestFunc {
return func(ctx *ExecFuncCtx, cmd *exec.Cmd) (int, error) {
assert.Equal(ctx.T, ctx.Meta.render(cmdStr), strings.Join(cmd.Args, " "))
assert.Equal(ctx.T, ctx.Meta.Render(cmdStr), strings.Join(cmd.Args, " "))
return exitCode, nil
}
}
Expand Down
36 changes: 20 additions & 16 deletions internal/namespaces/registry/v1/custom_image_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ func Test_ImageList(t *testing.T) {
t.Run("Simple", core.Test(&core.TestConfig{
Commands: registry.GetCommands(),
BeforeFunc: core.BeforeFuncCombine(
core.ExecStoreBeforeCmd("PublicNamespace", "scw registry namespace create name=cli-public-namespace is-public=true"),
core.ExecStoreBeforeCmd("PrivateNamespace", "scw registry namespace create name=cli-private-namespace is-public=false"),
core.ExecStoreBeforeCmd("PublicNamespace", "scw registry namespace create name=cli-public-namespace-{{randint}} is-public=true"),
core.ExecStoreBeforeCmd("PrivateNamespace", "scw registry namespace create name=cli-private-namespace-{{randint}} is-public=false"),
core.BeforeFuncWhenUpdatingCassette(
core.ExecBeforeCmd("scw registry login"),
),
Expand All @@ -23,43 +23,43 @@ func Test_ImageList(t *testing.T) {
core.BeforeFuncCombine(
setupImage(
"busybox:1.31",
"rg.fr-par.scw.cloud/cli-public-namespace",
"{{ .PublicNamespace.Endpoint }}",
fmt.Sprintf("visibility_%s", registrySDK.ImageVisibilityPublic),
registrySDK.ImageVisibilityPublic,
),

setupImage(
"busybox:1.30",
"rg.fr-par.scw.cloud/cli-public-namespace",
"{{ .PublicNamespace.Endpoint }}",
fmt.Sprintf("visibility_%s", registrySDK.ImageVisibilityPrivate),
registrySDK.ImageVisibilityPrivate,
),

setupImage(
"busybox:1.29",
"rg.fr-par.scw.cloud/cli-public-namespace",
"{{ .PublicNamespace.Endpoint }}",
fmt.Sprintf("visibility_%s", registrySDK.ImageVisibilityInherit),
registrySDK.ImageVisibilityInherit,
),

setupImage(
"busybox:1.28",
"rg.fr-par.scw.cloud/cli-private-namespace",
"{{ .PrivateNamespace.Endpoint }}",
fmt.Sprintf("visibility_%s", registrySDK.ImageVisibilityPublic),
registrySDK.ImageVisibilityPublic,
),

setupImage(
"busybox:1.27",
"rg.fr-par.scw.cloud/cli-private-namespace",
"{{ .PrivateNamespace.Endpoint }}",
fmt.Sprintf("visibility_%s", registrySDK.ImageVisibilityPrivate),
registrySDK.ImageVisibilityPrivate,
),

// namespace_policy: private, image_policy:inherit
setupImage(
"busybox:1.26",
"rg.fr-par.scw.cloud/cli-private-namespace",
"{{ .PrivateNamespace.Endpoint }}",
fmt.Sprintf("visibility_%s", registrySDK.ImageVisibilityInherit),
registrySDK.ImageVisibilityInherit,
),
Expand All @@ -79,12 +79,16 @@ func Test_ImageList(t *testing.T) {
}

func setupImage(dockerImage string, namespaceEndpoint string, imageName string, visibility registrySDK.ImageVisibility) core.BeforeFunc {
remote := fmt.Sprintf("%s/%s:latest", namespaceEndpoint, imageName)
return core.BeforeFuncCombine(
core.BeforeFuncOsExec("docker", "pull", dockerImage),
core.BeforeFuncOsExec("docker", "tag", dockerImage, remote),
core.BeforeFuncOsExec("docker", "push", remote),
core.ExecStoreBeforeCmd("ImageListResult", "scw registry image list name="+imageName),
core.ExecBeforeCmd("scw registry image update {{ (index .ImageListResult 0).ID }} visibility="+visibility.String()),
)
return func(ctx *core.BeforeFuncCtx) error {
namespaceEndpoint := ctx.Meta.Render(namespaceEndpoint)
remote := fmt.Sprintf("%s/%s:latest", namespaceEndpoint, imageName)

return core.BeforeFuncCombine(
core.BeforeFuncOsExec("docker", "pull", dockerImage),
core.BeforeFuncOsExec("docker", "tag", dockerImage, remote),
core.BeforeFuncOsExec("docker", "push", remote),
core.ExecStoreBeforeCmd("ImageListResult", "scw registry image list name="+imageName),
core.ExecBeforeCmd("scw registry image update {{ (index .ImageListResult 0).ID }} visibility="+visibility.String()),
)(ctx)
}
}
Loading

0 comments on commit 2109482

Please sign in to comment.