cmd/gitbay-runner/init_test.go

32a5f76e5b270097b63a5bba9a43557cf50ad63d
gitbay/cmd/gitbay-runner/init_test.go history · blame · raw

73 lines · 2450 bytes

 1package main
 2
 3import (
 4	"bytes"
 5	"os"
 6	"os/exec"
 7	"path/filepath"
 8	"strings"
 9	"testing"
10)
11
12// init creates the key and config once, prints the key and the attach
13// command, and running it again changes nothing.
14func TestInitWritesKeyAndConfigOnce(t *testing.T) {
15	if _, err := exec.LookPath("ssh-keygen"); err != nil {
16		t.Skip("ssh-keygen not on PATH")
17	}
18	dir := t.TempDir()
19	t.Setenv("XDG_CONFIG_HOME", dir)
20	var out bytes.Buffer
21	initOut = &out
22	defer func() { initOut = os.Stdout }()
23
24	if code := runInit([]string{"-remote", "git@example.test"}); code != 0 {
25		t.Fatalf("init: exit %d\n%s", code, out.String())
26	}
27	cdir := filepath.Join(dir, "gitbay-runner")
28	key := filepath.Join(cdir, "id_ed25519")
29	pub, err := os.ReadFile(key + ".pub")
30	if err != nil || !strings.HasPrefix(string(pub), "ssh-ed25519 ") {
31		t.Fatalf("public key: %v %q", err, pub)
32	}
33	if fi, _ := os.Stat(key); fi.Mode().Perm() != 0o600 {
34		t.Fatalf("private key mode %o", fi.Mode().Perm())
35	}
36	if fi, _ := os.Stat(cdir); fi.Mode().Perm() != 0o700 {
37		t.Fatalf("config dir mode %o", fi.Mode().Perm())
38	}
39	cfg, _ := os.ReadFile(filepath.Join(cdir, "config.toml"))
40	for _, want := range []string{"remote = \"git@example.test\"", "isolation = \"none\"", "untrusted = false", "identity = \"" + key + "\""} {
41		if !strings.Contains(string(cfg), want) {
42			t.Fatalf("config lacks %q:\n%s", want, cfg)
43		}
44	}
45	for _, want := range []string{strings.TrimSpace(string(pub)), "gitbay repo runner add owner/name < " + key + ".pub", "https://example.test/owner/name/settings"} {
46		if !strings.Contains(out.String(), want) {
47			t.Fatalf("output lacks %q:\n%s", want, out.String())
48		}
49	}
50
51	out.Reset()
52	if code := runInit([]string{"-remote", "git@other.test"}); code != 0 {
53		t.Fatalf("second init: exit %d\n%s", code, out.String())
54	}
55	if pub2, _ := os.ReadFile(key + ".pub"); string(pub2) != string(pub) {
56		t.Fatal("second init replaced the key")
57	}
58	if cfg2, _ := os.ReadFile(filepath.Join(cdir, "config.toml")); string(cfg2) != string(cfg) {
59		t.Fatal("second init rewrote the config")
60	}
61}
62
63// podman needs an image; init refuses to write a config the runner would
64// refuse to start with.
65func TestInitPodmanNeedsImage(t *testing.T) {
66	t.Setenv("XDG_CONFIG_HOME", t.TempDir())
67	var out bytes.Buffer
68	initOut = &out
69	defer func() { initOut = os.Stdout }()
70	if code := runInit([]string{"-isolation", "podman"}); code != 2 {
71		t.Fatalf("exit %d, want 2:\n%s", code, out.String())
72	}
73}