summaryrefslogtreecommitdiff
path: root/internal/taskproxy/run_test.go
blob: aa710232235b001818a83b568a9327497938bc3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package taskproxy

import (
	"bytes"
	"context"
	"errors"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"strings"
	"testing"
)

func TestRunnerRun_InjectsProjectFilterAndAgentTag(t *testing.T) {
	var gotName string
	var gotArgs []string
	runner := Runner{
		CommandName:    "ask",
		findTaskBinary: func() (string, error) { return "/usr/bin/task", nil },
		detectRepoRoot: func(context.Context) (string, error) { return "/tmp/work/hexai", nil },
		runCommand: func(_ context.Context, name string, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
			gotName = name
			gotArgs = append([]string(nil), args...)
			return nil
		},
	}

	exitCode, err := runner.Run(context.Background(), []string{"list", "limit:1"}, strings.NewReader("in"), &bytes.Buffer{}, &bytes.Buffer{})
	if err != nil {
		t.Fatalf("Run returned error: %v", err)
	}
	if exitCode != 0 {
		t.Fatalf("exitCode = %d, want 0", exitCode)
	}
	if gotName != "/usr/bin/task" {
		t.Fatalf("task binary = %q, want /usr/bin/task", gotName)
	}
	wantArgs := []string{"project:hexai", "+agent", "list", "limit:1"}
	if !reflect.DeepEqual(gotArgs, wantArgs) {
		t.Fatalf("task args = %v, want %v", gotArgs, wantArgs)
	}
}

func TestRunnerRun_OutsideGitRepo_IsActionable(t *testing.T) {
	runner := Runner{
		CommandName:    "ask",
		findTaskBinary: func() (string, error) { return "/usr/bin/task", nil },
		detectRepoRoot: func(context.Context) (string, error) { return "", errors.New("git failed") },
		runCommand: func(context.Context, string, []string, io.Reader, io.Writer, io.Writer) error {
			t.Fatal("runCommand should not be called when repo detection fails")
			return nil
		},
	}

	exitCode, err := runner.Run(context.Background(), []string{"list"}, strings.NewReader(""), &bytes.Buffer{}, &bytes.Buffer{})
	if exitCode != 1 {
		t.Fatalf("exitCode = %d, want 1", exitCode)
	}
	if err == nil || !strings.Contains(err.Error(), "must be run inside a git repository") {
		t.Fatalf("expected actionable git-repo error, got %v", err)
	}
}

func TestRunnerRun_PreservesTaskwarriorExitCode(t *testing.T) {
	runner := Runner{
		CommandName:    "ask",
		findTaskBinary: func() (string, error) { return "/usr/bin/task", nil },
		detectRepoRoot: func(context.Context) (string, error) { return "/tmp/work/hexai", nil },
		runCommand: func(context.Context, string, []string, io.Reader, io.Writer, io.Writer) error {
			return exec.Command("sh", "-c", "exit 7").Run()
		},
	}

	exitCode, err := runner.Run(context.Background(), []string{"list"}, strings.NewReader(""), &bytes.Buffer{}, &bytes.Buffer{})
	if err != nil {
		t.Fatalf("expected nil error for subprocess exit, got %v", err)
	}
	if exitCode != 7 {
		t.Fatalf("exitCode = %d, want 7", exitCode)
	}
}

func TestRunnerRun_PreservesStdoutAndStderr(t *testing.T) {
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	runner := Runner{
		CommandName:    "ask",
		findTaskBinary: func() (string, error) { return "/usr/bin/task", nil },
		detectRepoRoot: func(context.Context) (string, error) { return "/tmp/work/hexai", nil },
		runCommand: func(_ context.Context, name string, args []string, stdin io.Reader, out, errOut io.Writer) error {
			_, _ = io.WriteString(out, "task stdout")
			_, _ = io.WriteString(errOut, "task stderr")
			return nil
		},
	}

	exitCode, err := runner.Run(context.Background(), []string{"list"}, strings.NewReader(""), &stdout, &stderr)
	if err != nil {
		t.Fatalf("Run returned error: %v", err)
	}
	if exitCode != 0 {
		t.Fatalf("exitCode = %d, want 0", exitCode)
	}
	if stdout.String() != "task stdout" {
		t.Fatalf("stdout = %q, want %q", stdout.String(), "task stdout")
	}
	if stderr.String() != "task stderr" {
		t.Fatalf("stderr = %q, want %q", stderr.String(), "task stderr")
	}
}

func TestRunnerRun_TaskLookupFailure_IsActionable(t *testing.T) {
	runner := Runner{
		CommandName:    "ask",
		findTaskBinary: func() (string, error) { return "", errors.New("not found") },
	}

	exitCode, err := runner.Run(context.Background(), []string{"list"}, strings.NewReader(""), &bytes.Buffer{}, &bytes.Buffer{})
	if exitCode != 1 {
		t.Fatalf("exitCode = %d, want 1", exitCode)
	}
	if err == nil || !strings.Contains(err.Error(), "Taskwarrior binary lookup failed") {
		t.Fatalf("expected actionable task lookup error, got %v", err)
	}
}

func TestRunnerRun_EmptyRepoName_IsActionable(t *testing.T) {
	runner := Runner{
		CommandName:    "ask",
		findTaskBinary: func() (string, error) { return "/usr/bin/task", nil },
		detectRepoRoot: func(context.Context) (string, error) { return "/", nil },
	}

	exitCode, err := runner.Run(context.Background(), []string{"list"}, strings.NewReader(""), &bytes.Buffer{}, &bytes.Buffer{})
	if exitCode != 1 {
		t.Fatalf("exitCode = %d, want 1", exitCode)
	}
	if err == nil || !strings.Contains(err.Error(), "could not derive project name") {
		t.Fatalf("expected actionable project-name error, got %v", err)
	}
}

// NewRunner must wire all three function-typed fields and trim the command
// name; the rest of Runner relies on these defaults when callers don't
// override them in tests.
func TestNewRunner_DefaultsAreWiredAndCommandTrimmed(t *testing.T) {
	r := NewRunner("  ask  ")
	if r.CommandName != "ask" {
		t.Fatalf("CommandName = %q, want %q", r.CommandName, "ask")
	}
	if r.findTaskBinary == nil || r.detectRepoRoot == nil || r.runCommand == nil {
		t.Fatalf("NewRunner did not wire all defaults: %+v", r)
	}
}

// normalizeRunner must fall back to "task" when CommandName is empty; the
// branch is otherwise unreachable through the public Run path because callers
// always pass a label.
func TestNormalizeRunner_FillsDefaultsForZeroValue(t *testing.T) {
	got := normalizeRunner(Runner{})
	if got.CommandName != "task" {
		t.Fatalf("CommandName = %q, want %q", got.CommandName, "task")
	}
	if got.findTaskBinary == nil || got.detectRepoRoot == nil || got.runCommand == nil {
		t.Fatalf("normalizeRunner left a nil func field: %+v", got)
	}
	if label := got.commandLabel(); label != "task" {
		t.Fatalf("commandLabel = %q, want %q", label, "task")
	}
}

// Whitespace-only CommandName must be treated as unset by commandLabel; this
// keeps error messages readable when callers accidentally pass "   ".
func TestCommandLabel_TrimsToFallback(t *testing.T) {
	r := Runner{CommandName: "   "}
	if got := r.commandLabel(); got != "task" {
		t.Fatalf("commandLabel = %q, want %q", got, "task")
	}
}

// exitCodeFor must wrap non-ExitError failures (e.g. fork/exec errors) so the
// caller can distinguish "Taskwarrior ran and exited N" from "we never got to
// run Taskwarrior at all".
func TestExitCodeFor_NonExitError(t *testing.T) {
	r := Runner{CommandName: "ask"}
	code, err := r.exitCodeFor(errors.New("fork failed"))
	if code != 1 {
		t.Fatalf("exitCodeFor(non-ExitError) code = %d, want 1", code)
	}
	if err == nil || !strings.Contains(err.Error(), "failed to run Taskwarrior") {
		t.Fatalf("expected wrap message, got %v", err)
	}
}

// findTaskBinary success path: stage a fake "task" executable on PATH and
// confirm LookPath resolves to it.
func TestFindTaskBinary_FoundInPath(t *testing.T) {
	dir := t.TempDir()
	fake := filepath.Join(dir, "task")
	if err := os.WriteFile(fake, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
		t.Fatal(err)
	}
	t.Setenv("PATH", dir)
	got, err := findTaskBinary()
	if err != nil {
		t.Fatalf("findTaskBinary: %v", err)
	}
	if got != fake {
		t.Fatalf("findTaskBinary = %q, want %q", got, fake)
	}
}

// findTaskBinary failure path: an empty PATH must yield the actionable
// "install Taskwarrior" error users see when the binary is missing.
func TestFindTaskBinary_NotFound_IsActionable(t *testing.T) {
	t.Setenv("PATH", "")
	_, err := findTaskBinary()
	if err == nil {
		t.Fatalf("expected error for missing task binary")
	}
	if !strings.Contains(err.Error(), "install Taskwarrior and retry") {
		t.Fatalf("error not actionable: %v", err)
	}
}

// detectRepoRoot must return the repo top level when invoked inside a real
// git checkout. Reuses the current process' git repository (this test file
// lives inside the hexai checkout) to avoid needing to git-init a temp dir.
func TestDetectRepoRoot_InsideGitRepo(t *testing.T) {
	if _, err := exec.LookPath("git"); err != nil {
		t.Skip("git not available")
	}
	root, err := detectRepoRoot(context.Background())
	if err != nil {
		t.Fatalf("detectRepoRoot: %v", err)
	}
	if root == "" || !strings.Contains(root, "hexai") {
		t.Fatalf("unexpected repo root %q", root)
	}
}

// detectRepoRoot outside a git repo: chdir into a temp dir that has no .git
// and confirm the actionable error fires. We restore cwd via t.Chdir which
// the test runner reverts automatically on test exit.
func TestDetectRepoRoot_OutsideGitRepo(t *testing.T) {
	if _, err := exec.LookPath("git"); err != nil {
		t.Skip("git not available")
	}
	dir := t.TempDir()
	t.Chdir(dir)
	t.Setenv("GIT_CEILING_DIRECTORIES", filepath.Dir(dir))
	_, err := detectRepoRoot(context.Background())
	if err == nil {
		t.Fatalf("expected error outside git repo")
	}
	if !strings.Contains(err.Error(), "must be run inside a git repository") {
		t.Fatalf("error not actionable: %v", err)
	}
}

// runTaskCommand must wire stdin/stdout/stderr to the spawned process. We
// invoke /bin/sh to echo from stdin and confirm both streams round-trip.
func TestRunTaskCommand_StreamsAndReturnNil(t *testing.T) {
	if _, err := exec.LookPath("sh"); err != nil {
		t.Skip("sh not available")
	}
	var stdout, stderr bytes.Buffer
	err := runTaskCommand(
		context.Background(),
		"sh",
		[]string{"-c", "cat; echo err 1>&2"},
		strings.NewReader("hello\n"),
		&stdout,
		&stderr,
	)
	if err != nil {
		t.Fatalf("runTaskCommand returned error: %v", err)
	}
	if got := stdout.String(); got != "hello\n" {
		t.Fatalf("stdout = %q, want %q", got, "hello\n")
	}
	if got := stderr.String(); got != "err\n" {
		t.Fatalf("stderr = %q, want %q", got, "err\n")
	}
}

// runTaskCommand surfaces the underlying exec error when the binary doesn't
// exist; Run() relies on this to map to a non-zero exit code.
func TestRunTaskCommand_BinaryNotFound(t *testing.T) {
	err := runTaskCommand(context.Background(), "/no/such/binary", nil, nil, &bytes.Buffer{}, &bytes.Buffer{})
	if err == nil {
		t.Fatalf("expected error from missing binary")
	}
}