internal/control/control_test.go

v1.35.1
gitbay/internal/control/control_test.go history · blame · raw

282 lines · 10448 bytes

  1package control
  2
  3import (
  4	"bytes"
  5	"encoding/json"
  6	"errors"
  7	"fmt"
  8	"io"
  9	"io/fs"
 10	"slices"
 11	"strings"
 12	"testing"
 13
 14	"gitbay.org/gitbay/internal/protocol"
 15	"gitbay.org/gitbay/internal/store"
 16)
 17
 18// TestEveryCommandReachableFromBareSSH asserts that each registered command's
 19// path, rendered exactly as a user would type it after `ssh <host>`, resolves
 20// back to that command through the tokenizer and Lookup. This is the guard
 21// that keeps the forge CLI optional.
 22func TestEveryCommandReachableFromBareSSH(t *testing.T) {
 23	cmds := Commands()
 24	if len(cmds) == 0 {
 25		t.Fatal("no commands registered")
 26	}
 27	for _, cmd := range cmds {
 28		line := strings.Join(cmd.Path, " ")
 29		argv, err := protocol.Tokenize(line)
 30		if err != nil {
 31			t.Errorf("command %q not tokenizable: %v", line, err)
 32			continue
 33		}
 34		got, rest, ok := Lookup(argv)
 35		if !ok {
 36			t.Errorf("command %q not found by Lookup", line)
 37			continue
 38		}
 39		if strings.Join(got.Path, " ") != line || len(rest) != 0 {
 40			t.Errorf("Lookup(%q) resolved to %q with rest %v", line, strings.Join(got.Path, " "), rest)
 41		}
 42		if cmd.Run == nil {
 43			t.Errorf("command %q has no Run", line)
 44		}
 45		if cmd.Summary == "" {
 46			t.Errorf("command %q has no summary", line)
 47		}
 48	}
 49}
 50
 51func TestLookupLongestMatch(t *testing.T) {
 52	// "keys list" must not resolve to a hypothetical shorter prefix and
 53	// unknown commands must not match.
 54	if _, _, ok := Lookup([]string{"keys"}); ok {
 55		t.Error("bare \"keys\" resolved; group prefixes must not be runnable")
 56	}
 57	if _, _, ok := Lookup([]string{"nope"}); ok {
 58		t.Error("unknown command resolved")
 59	}
 60	cmd, rest, ok := Lookup([]string{"keys", "list", "--json"})
 61	if !ok || strings.Join(cmd.Path, " ") != "keys list" || len(rest) != 1 {
 62		t.Errorf("Lookup keys list --json = %v %v %v", cmd.Path, rest, ok)
 63	}
 64}
 65
 66// TestBuildJobsIsAReadCommand pins the properties the surfaces depend on:
 67// the web build page and a read-scoped API token both need it over GET.
 68func TestBuildJobsIsAReadCommand(t *testing.T) {
 69	cmd, _, ok := Lookup([]string{"build", "jobs"})
 70	if !ok {
 71		t.Fatal("build jobs not registered")
 72	}
 73	if !cmd.ReadOnly {
 74		t.Error("build jobs must be ReadOnly; listing jobs changes nothing")
 75	}
 76}
 77
 78// Nothing in the registry is reachable over SSH alone (#234). The flag
 79// that held commands back is gone, so this pins the replacement rule:
 80// every command runs on every surface, and what a caller may do is
 81// decided by the account, the key's scope, and the token's scope.
 82func TestNoCommandIsHeldBackFromTheWeb(t *testing.T) {
 83	for _, cmd := range Commands() {
 84		if cmd.Run == nil {
 85			t.Errorf("%s has no handler", joinPath(cmd.Path))
 86		}
 87	}
 88}
 89
 90// A merge request's dedup key must not collide with a commit sha. It did:
 91// a bare "#N" in a commit message recorded (issue, sha) first, and the
 92// description's "Closes #N" then found the key taken and silently gave
 93// up. That is how krz/gitbay-ios#8 stayed open after its own MR merged.
 94func TestMRDedupKeyCannotCollideWithASHA(t *testing.T) {
 95	key := mrRefKey(24)
 96	if key == "51b6a14eab49ab08e890597653fcf02f8f38f3d6" || len(key) == 40 {
 97		t.Errorf("mrRefKey(24) = %q, which is shaped like a sha", key)
 98	}
 99	if key != "mr-24" {
100		t.Errorf("mrRefKey(24) = %q, want \"mr-24\"", key)
101	}
102	if mrRefKey(24) == mrRefKey(25) {
103		t.Error("different merge requests share a dedup key")
104	}
105}
106
107// TestEveryCommandDocumentsItsUsage is what makes `help <prefix>` and
108// `gitbay <cmd> --help` worth typing: both render Usage, so a command that
109// omits it documents nothing. Usage opens with the command path so the
110// printed line can be typed as-is, and the summary must not carry the
111// argument syntax it used to.
112func TestEveryCommandDocumentsItsUsage(t *testing.T) {
113	for _, cmd := range Commands() {
114		path := strings.Join(cmd.Path, " ")
115		if cmd.Usage == "" {
116			t.Errorf("command %q has no Usage", path)
117			continue
118		}
119		if cmd.Usage != path && !strings.HasPrefix(cmd.Usage, path+" ") {
120			t.Errorf("command %q has Usage %q, which does not open with the command path", path, cmd.Usage)
121		}
122		if strings.Contains(cmd.Summary, ": "+path) {
123			t.Errorf("command %q still carries its usage in the summary: %q", path, cmd.Summary)
124		}
125	}
126}
127
128// TestHelpPrefixNarrowsAndShowsFlags covers the reason the command exists:
129// before this, reading one command's flags meant reading all of them.
130func TestHelpPrefixNarrowsAndShowsFlags(t *testing.T) {
131	var buf bytes.Buffer
132	c := &Ctx{Stdout: &buf, Stderr: io.Discard}
133	if code := runHelp(c, []string{"issue"}); code != protocol.ExitOK {
134		t.Fatalf("help issue exited %d", code)
135	}
136	out := buf.String()
137	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
138		if strings.HasPrefix(line, "  ") {
139			continue // the indented usage line
140		}
141		if !strings.HasPrefix(line, "issue ") {
142			t.Errorf("help issue listed an unrelated command: %q", line)
143		}
144	}
145	if !strings.Contains(out, "--state open|closed|all") {
146		t.Error("help issue did not print issue list's flags")
147	}
148}
149
150func TestHelpUnknownPrefixIsNotFound(t *testing.T) {
151	var buf bytes.Buffer
152	c := &Ctx{Stdout: &buf, Stderr: io.Discard}
153	if code := runHelp(c, []string{"nope"}); code != protocol.ExitNotFound {
154		t.Errorf("help nope exited %d, want %d", code, protocol.ExitNotFound)
155	}
156}
157
158// TestHelpListsEveryCommandSorted pins the unfiltered listing: one row per
159// registered command, ordered so a noun's commands sit together.
160func TestHelpListsEveryCommandSorted(t *testing.T) {
161	var buf bytes.Buffer
162	c := &Ctx{Stdout: &buf, Stderr: io.Discard, JSON: true}
163	if code := runHelp(c, nil); code != protocol.ExitOK {
164		t.Fatalf("help exited %d", code)
165	}
166	var env struct {
167		Data []helpEntry `json:"data"`
168	}
169	if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
170		t.Fatalf("help --json: %v", err)
171	}
172	if len(env.Data) != len(Commands()) {
173		t.Errorf("help listed %d commands, registry has %d", len(env.Data), len(Commands()))
174	}
175	if !slices.IsSortedFunc(env.Data, func(a, b helpEntry) int { return strings.Compare(a.Path, b.Path) }) {
176		t.Error("help output is not sorted by path")
177	}
178}
179
180// TestStdinCommandsReadStdin: a command whose usage says its input arrives
181// on stdin must set ReadsStdin, or Dispatch hands it an empty reader and
182// --file - silently stores nothing (#127).
183func TestStdinCommandsReadStdin(t *testing.T) {
184	for _, cmd := range Commands() {
185		u := cmd.Usage
186		wants := strings.Contains(u, "--file -") || strings.Contains(u, "< ") ||
187			strings.Contains(u, "stdin") || strings.Contains(u, "--key -")
188		if wants && !cmd.ReadsStdin {
189			t.Errorf("%s: usage %q reads stdin but ReadsStdin is not set", strings.Join(cmd.Path, " "), u)
190		}
191	}
192}
193
194// TestAdminNounGatedInDispatch: every admin command is refused for a
195// non-admin by the dispatcher itself, before any handler runs.
196func TestAdminNounGatedInDispatch(t *testing.T) {
197	for _, cmd := range Commands() {
198		if cmd.Path[0] != "admin" {
199			continue
200		}
201		var out, errOut bytes.Buffer
202		c := &Ctx{User: store.User{Username: "nobody"}, Scope: "full", Stdout: &out, Stderr: &errOut}
203		if code := Dispatch(c, cmd.Path); code != protocol.ExitDenied {
204			t.Errorf("%s: non-admin got exit %d, want %d", strings.Join(cmd.Path, " "), code, protocol.ExitDenied)
205		}
206	}
207}
208
209// TestRefusalsHonourJSON: a refusal from the dispatcher's own checks is a
210// JSON envelope when --json was given, like any other failure. The flag
211// used to be stripped after those checks, so a read-only token or a
212// pending account got plain text on stderr exactly when a script needed
213// to parse the error (#109).
214func TestRefusalsHonourJSON(t *testing.T) {
215	cases := []struct {
216		name string
217		ctx  Ctx
218		argv []string
219	}{
220		{"read-only token", Ctx{ReadOnly: true, Scope: "full", ViaAPI: true}, []string{"repo", "create", "a/b", "--json"}},
221		{"pending account", Ctx{User: store.User{Pending: true}, Scope: "full"}, []string{"repo", "list", "--json"}},
222		{"git-scoped key", Ctx{Scope: "git"}, []string{"whoami", "--json"}},
223		{"non-admin", Ctx{Scope: "full"}, []string{"admin", "stats", "--json"}},
224	}
225	for _, tc := range cases {
226		var out, errOut bytes.Buffer
227		c := tc.ctx
228		c.Stdout, c.Stderr = &out, &errOut
229		if code := Dispatch(&c, tc.argv); code != protocol.ExitDenied {
230			t.Errorf("%s: exit %d, want %d", tc.name, code, protocol.ExitDenied)
231		}
232		var env protocol.Envelope
233		if err := json.Unmarshal(out.Bytes(), &env); err != nil || env.Error == "" {
234			t.Errorf("%s: no JSON envelope on stdout: %q (stderr %q)", tc.name, out.String(), errOut.String())
235		}
236	}
237}
238
239// TestFailErrExitCodes: a store error is not-found or a failure, never
240// usage (#211); an input error is usage unless the I/O beneath it failed
241// (#107).
242func TestFailErrExitCodes(t *testing.T) {
243	ctx := func() *Ctx { return &Ctx{Stdout: &bytes.Buffer{}, Stderr: &bytes.Buffer{}} }
244	notFound := fmt.Errorf("looking up: %w", store.ErrNotFound)
245	refused := errors.New("the name is taken")
246	ioErr := &fs.PathError{Op: "open", Path: "/x", Err: fs.ErrPermission}
247	for _, tc := range []struct {
248		name string
249		fn   func(*Ctx, error) int
250		err  error
251		want int
252	}{
253		{"failErr not found", (*Ctx).failErr, store.ErrNotFound, protocol.ExitNotFound},
254		{"failErr wrapped not found", (*Ctx).failErr, notFound, protocol.ExitNotFound},
255		{"failErr refusal", (*Ctx).failErr, refused, protocol.ExitFailure},
256		{"failErr i/o", (*Ctx).failErr, ioErr, protocol.ExitFailure},
257		{"failInput not found", (*Ctx).failInput, notFound, protocol.ExitNotFound},
258		{"failInput caller's mistake", (*Ctx).failInput, errors.New("name must be lowercase"), protocol.ExitUsage},
259		{"failInput i/o", (*Ctx).failInput, ioErr, protocol.ExitFailure},
260	} {
261		if got := tc.fn(ctx(), tc.err); got != tc.want {
262			t.Errorf("%s: exit %d, want %d", tc.name, got, tc.want)
263		}
264	}
265}
266
267// TestArgumentRefusalsNameTheUsage: a missing positional argument is a
268// usage error that prints the registered usage, the shared reference
269// helpers included (#215).
270func TestArgumentRefusalsNameTheUsage(t *testing.T) {
271	for _, argv := range [][]string{{"build", "show"}, {"release", "show"}, {"mr", "resolve"}, {"issue", "show"}} {
272		var out, errOut bytes.Buffer
273		c := &Ctx{Scope: "full", Stdout: &out, Stderr: &errOut}
274		if code := Dispatch(c, argv); code != protocol.ExitUsage {
275			t.Errorf("%v: exit %d, want %d (%s)", argv, code, protocol.ExitUsage, errOut.String())
276			continue
277		}
278		if !strings.Contains(errOut.String(), "usage: "+strings.Join(argv, " ")) {
279			t.Errorf("%v: no usage line: %q", argv, errOut.String())
280		}
281	}
282}