Files
RenewCMS/test/server_version_flag_test.go
T

87 lines
2.5 KiB
Go

package test
import (
infraUpdate "RenewCMS/internal/infrastructure/update"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
)
func buildServerBinary(t *testing.T, ldflags string) string {
t.Helper()
if _, err := exec.LookPath("go"); err != nil {
t.Skip("the go tool is not on PATH")
}
name := "server"
if runtime.GOOS == "windows" {
name += ".exe"
}
output := filepath.Join(t.TempDir(), name)
arguments := []string{"build", "-tags", "nofrontend"}
if ldflags != "" {
arguments = append(arguments, "-ldflags", ldflags)
}
arguments = append(arguments, "-o", output, "RenewCMS/cmd/server")
build := exec.Command("go", arguments...)
build.Env = append(os.Environ(), "CGO_ENABLED=0")
if combined, err := build.CombinedOutput(); err != nil {
t.Fatalf("build failed: %v\n%s", err, combined)
}
return output
}
func emptyEnvironment() []string {
if runtime.GOOS == "windows" {
return []string{"SystemRoot=" + os.Getenv("SystemRoot")}
}
return []string{}
}
func TestServerVersionFlag(t *testing.T) {
t.Run("it prints the build version and exits 0 without reading .env or the database", func(t *testing.T) {
binary := buildServerBinary(t, "-X main.version=v9.9.9")
workDir := t.TempDir()
command := exec.Command(binary, "--version")
command.Dir = workDir
command.Env = emptyEnvironment()
output, err := command.Output()
if err != nil || strings.TrimSpace(string(output)) != "v9.9.9" {
t.Fatalf("output = %q, err = %v", output, err)
}
if entries, _ := os.ReadDir(workDir); len(entries) != 0 {
t.Errorf("the working directory must stay empty, got %d entries", len(entries))
}
})
t.Run("with no ldflags version it prints dev", func(t *testing.T) {
binary := buildServerBinary(t, "")
command := exec.Command(binary, "--version")
command.Dir = t.TempDir()
command.Env = emptyEnvironment()
output, err := command.Output()
if err != nil || strings.TrimSpace(string(output)) != "dev" {
t.Errorf("output = %q, err = %v", output, err)
}
})
t.Run("the staged binary runner returns what the binary prints", func(t *testing.T) {
binary := buildServerBinary(t, "-X main.version=v9.9.9")
version, err := infraUpdate.NewExecStagedBinaryRunner().Version(binary)
if err != nil || version != "v9.9.9" {
t.Errorf("version = %q, err = %v", version, err)
}
if _, err := infraUpdate.NewExecStagedBinaryRunner().Version(filepath.Join(t.TempDir(), "missing")); err == nil {
t.Error("a binary that cannot be run must be an error")
}
})
}