package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// maxClientBytes is the most a client download may weigh: the forge's own
// program is 135 MB and needs cgo, and the point of the small build is
// that nobody downloads that.
const maxClientBytes = 12 << 20
// The client carries no server: none of the packages that make the forge
// a forge, and nothing that needs cgo (the server's DuckDB does).
func TestClientImportsNoServer(t *testing.T) {
out, err := exec.Command("go", "list", "-deps", "-f", "{{.ImportPath}} {{len .CgoFiles}}", ".").Output()
if err != nil {
t.Fatalf("FAIL: go list: %v", err)
}
const mod = "craftdesign.group/quarry/"
server := []string{"internal/web", "internal/api", "internal/oltp", "internal/xfer", "cmd/quarry"}
seen := 0
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
f := strings.Fields(line)
if len(f) != 2 {
continue
}
seen++
for _, s := range server {
if f[0] == mod+s || strings.HasPrefix(f[0], mod+s+"/") {
t.Errorf("FAIL: the client imports %s", f[0])
}
}
if f[1] != "0" {
t.Errorf("FAIL: %s needs cgo", f[0])
}
}
if seen < 10 {
t.Errorf("FAIL: the walk saw %d packages; go list did not run as expected", seen)
}
if !t.Failed() {
t.Log("ok")
}
}
// A client build as the forge serves it (static, stripped) stays small.
func TestClientBuildStaysSmall(t *testing.T) {
if testing.Short() {
t.Skip("builds the program")
}
bin := filepath.Join(t.TempDir(), "quarry")
cmd := exec.Command("go", "build", "-trimpath", "-ldflags", "-s -w", "-o", bin, ".")
cmd.Env = append(os.Environ(), "CGO_ENABLED=0")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("FAIL: build: %v\n%s", err, out)
}
st, err := os.Stat(bin)
if err != nil {
t.Fatal(err)
}
if st.Size() > maxClientBytes {
t.Errorf("FAIL: the client is %d bytes, over %d", st.Size(), maxClientBytes)
}
if !t.Failed() {
t.Logf("ok: %d bytes", st.Size())
}
}
// Started as quarry the program is the client; as quarry-runner, the runner.
func TestProgramIsRunnerOnlyUnderTheRunnersName(t *testing.T) {
for name, want := range map[string]bool{
"quarry-runner": true, "/usr/local/bin/quarry-runner": true,
"quarry-runner-linux-amd64": true, "quarry-runner-windows-amd64.exe": true,
"quarry": false, "/home/a/.local/bin/quarry": false, "quarry-darwin-arm64": false, "quarry.exe": false,
} {
if got := isRunnerName(name); got != want {
t.Errorf("FAIL: isRunnerName(%q) = %v", name, got)
}
}
if !t.Failed() {
t.Log("ok")
}
}