Files
RenewCMS/test/image_variants_config_test.go
T
2026-10-08 02:33:32 +02:00

103 lines
2.8 KiB
Go

package test
import (
"RenewCMS/internal/infrastructure/config"
"os"
"strings"
"testing"
)
const maxSourceEnv = "IMAGE_VARIANT_MAX_SOURCE_BYTES"
func readRepositoryFile(t *testing.T, relative string) string {
t.Helper()
content, err := os.ReadFile("../" + relative)
if err != nil {
t.Fatalf("cannot read %s: %v", relative, err)
}
return string(content)
}
func between(source string, opening string, closing string) string {
start := strings.Index(source, opening)
if start < 0 {
return ""
}
rest := source[start+len(opening):]
end := strings.Index(rest, closing)
if end < 0 {
return rest
}
return rest[:end]
}
func TestImageVariantMaxSourceBytesSetting(t *testing.T) {
rows := []struct {
value string
unset bool
want int64
failure bool
}{
{unset: true, want: 10485760},
{value: "2048", want: 2048},
{value: "1", want: 1},
{value: "0", failure: true},
{value: "-5", failure: true},
{value: "many", failure: true},
{value: "1.5", failure: true},
}
for _, row := range rows {
name := row.value
if row.unset {
name = "unset"
}
t.Run("The env var is loaded: "+name, func(t *testing.T) {
setBaseSettingsEnv(t)
if row.unset {
t.Setenv(maxSourceEnv, "")
} else {
t.Setenv(maxSourceEnv, row.value)
}
settings, err := config.NewSettingsFromEnv()
if row.failure {
if err == nil || !strings.Contains(err.Error(), maxSourceEnv) {
t.Errorf("err = %v", err)
}
return
}
if err != nil || settings.ImageVariantMaxSourceBytes != row.want {
t.Errorf("value = %d, err = %v", settings.ImageVariantMaxSourceBytes, err)
}
})
}
}
func TestImageVariantMaxSourceBytesDocumentation(t *testing.T) {
t.Run("The default is listed in envDefaults and not in requiredEnvVars", func(t *testing.T) {
main := readRepositoryFile(t, "cmd/server/main.go")
defaults := between(main, "var envDefaults = map[string]string{", "\n}")
required := between(main, "var requiredEnvVars = []string{", "\n}")
if !strings.Contains(defaults, "config.EnvImageVariantMaxSourceBytes") || strings.Contains(required, "ImageVariant") || strings.Contains(required, maxSourceEnv) {
t.Error("the default is misplaced")
}
})
t.Run("The constant name and default are the documented ones", func(t *testing.T) {
if config.EnvImageVariantMaxSourceBytes != maxSourceEnv || config.DefaultImageVariantMaxSourceBytes != "10485760" {
t.Errorf("constants = %q %q", config.EnvImageVariantMaxSourceBytes, config.DefaultImageVariantMaxSourceBytes)
}
})
for _, document := range []string{".env.example", "docs/configuration.md"} {
t.Run("The env var is documented in "+document, func(t *testing.T) {
if !strings.Contains(readRepositoryFile(t, document), maxSourceEnv) {
t.Errorf("%s does not mention %s", document, maxSourceEnv)
}
})
}
}