-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecute_test.go
More file actions
476 lines (426 loc) · 13.2 KB
/
Copy pathexecute_test.go
File metadata and controls
476 lines (426 loc) · 13.2 KB
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package ax
import (
"bytes"
"context"
"encoding/json"
"strings"
"testing"
"time"
"github.com/spf13/cobra"
)
func TestExecuteLogLinesCarryRootSpanContextWithoutCollector(t *testing.T) {
var stdout bytes.Buffer
var stderr bytes.Buffer
var runTraceID string
var runSpanID string
root := &cobra.Command{
Use: "app",
RunE: func(cmd *cobra.Command, _ []string) error {
runTraceID = TraceIDFromContext(cmd.Context())
runSpanID = SpanIDFromContext(cmd.Context())
logger := NewLogger(cmd.Context(), WithLoggerWriter(cmd.ErrOrStderr()))
logger.Info(cmd.Context()).Str("event", "first").Msg("ran")
logger.Info(cmd.Context()).Str("event", "second").Msg("ran")
return WriteJSON(cmd.OutOrStdout(), struct {
OK bool `json:"ok"`
}{OK: true})
},
}
code := Execute(
context.Background(),
root,
WithStdout(&stdout),
WithStderr(&stderr),
WithEnv(func(string) string { return "" }),
WithStdoutIsTTY(false),
)
if code != ExitSuccess {
t.Fatalf("Execute exit code = %d, want %d; stderr=%s", code, ExitSuccess, stderr.String())
}
if runTraceID == ZeroTraceID {
t.Fatalf("TraceIDFromContext during run = %q, want non-zero", runTraceID)
}
if runSpanID == ZeroSpanID {
t.Fatalf("SpanIDFromContext during run = %q, want non-zero", runSpanID)
}
records := decodeLogRecords(t, stderr.String())
if len(records) != 2 {
t.Fatalf("log records = %d, want 2; stderr=%s", len(records), stderr.String())
}
for _, record := range records {
if record["trace_id"] != runTraceID {
t.Fatalf("log trace_id = %v, want active trace %q", record["trace_id"], runTraceID)
}
if record["span_id"] != runSpanID {
t.Fatalf("log span_id = %v, want active span %q", record["span_id"], runSpanID)
}
}
if strings.Contains(stdout.String(), runTraceID) {
t.Fatalf("stdout contains trace_id %q: %s", runTraceID, stdout.String())
}
if strings.Contains(stdout.String(), runSpanID) {
t.Fatalf("stdout contains span_id %q: %s", runSpanID, stdout.String())
}
}
func TestExecuteContinuesInboundTraceparent(t *testing.T) {
const traceID = "4bf92f3577b34da6a3ce929d0e0e4736"
var stdout bytes.Buffer
var stderr bytes.Buffer
var runTraceID string
root := &cobra.Command{
Use: "app",
RunE: func(cmd *cobra.Command, _ []string) error {
runTraceID = TraceIDFromContext(cmd.Context())
logger := NewLogger(cmd.Context(), WithLoggerWriter(cmd.ErrOrStderr()))
logger.Info(cmd.Context()).Msg("ran")
return WriteJSON(cmd.OutOrStdout(), struct {
OK bool `json:"ok"`
}{OK: true})
},
}
code := Execute(
context.Background(),
root,
WithStdout(&stdout),
WithStderr(&stderr),
WithEnv(func(key string) string {
if key == "TRACEPARENT" {
return "00-" + traceID + "-00f067aa0ba902b7-01"
}
return ""
}),
WithStdoutIsTTY(false),
)
if code != ExitSuccess {
t.Fatalf("Execute exit code = %d, want %d; stderr=%s", code, ExitSuccess, stderr.String())
}
if runTraceID != traceID {
t.Fatalf("TraceIDFromContext during run = %q, want inbound trace %q", runTraceID, traceID)
}
records := decodeLogRecords(t, stderr.String())
if len(records) != 1 {
t.Fatalf("log records = %d, want 1; stderr=%s", len(records), stderr.String())
}
if records[0]["trace_id"] != traceID {
t.Fatalf("log trace_id = %v, want inbound trace %q", records[0]["trace_id"], traceID)
}
if strings.Contains(stdout.String(), traceID) {
t.Fatalf("stdout contains trace_id %q: %s", traceID, stdout.String())
}
}
func TestExecuteTelemetryFailOpen(t *testing.T) {
baselineStdout, _, baselineCode := executeTelemetryCommand(t, map[string]string{}, defaultTelemetryShutdownTimeout)
tests := []struct {
name string
env map[string]string
}{
{
name: "malformed endpoint",
env: map[string]string{
"OTEL_EXPORTER_OTLP_ENDPOINT": "://bad-endpoint",
},
},
{
name: "unreachable collector",
env: map[string]string{
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://127.0.0.1:1",
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
stdout, stderr, code := executeTelemetryCommand(t, tc.env, 100*time.Millisecond)
if code != baselineCode {
t.Fatalf("Execute exit code = %d, want baseline %d; stderr=%s", code, baselineCode, stderr)
}
if !bytes.Equal(stdout, baselineStdout) {
t.Fatalf("stdout changed under telemetry failure\nbaseline: %s\ngot: %s", baselineStdout, stdout)
}
if !strings.Contains(stderr, "ax: otel") {
t.Fatalf("stderr = %q, want telemetry diagnostic", stderr)
}
})
}
}
func TestExecuteInjectsAXContext(t *testing.T) {
var stdout bytes.Buffer
var stderr bytes.Buffer
root := &cobra.Command{
Use: "app",
RunE: func(cmd *cobra.Command, _ []string) error {
mode, ok := ModeFromContext(cmd.Context())
if !ok {
t.Fatal("mode missing from context")
}
key, ok := IdempotencyKeyFromContext(cmd.Context())
if !ok {
t.Fatal("idempotency key missing from context")
}
return WriteJSON(cmd.OutOrStdout(), map[string]any{
"mode": mode,
"dry_run": DryRunFromContext(cmd.Context()),
"key": key,
})
},
}
root.SetArgs([]string{"--format=json", "--dry-run", "--idempotency-key=abc"})
code := Execute(
context.Background(),
root,
WithStdout(&stdout),
WithStderr(&stderr),
WithStdoutIsTTY(true),
WithEnv(func(string) string { return "" }),
)
if code != ExitSuccess {
t.Fatalf("Execute exit code = %d, want %d; stderr=%s", code, ExitSuccess, stderr.String())
}
if stderr.Len() != 0 {
t.Fatalf("stderr = %q, want empty", stderr.String())
}
var got map[string]any
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatalf("stdout was not JSON: %v", err)
}
if got["mode"] != string(ModeJSON) {
t.Fatalf("mode = %v, want %q", got["mode"], ModeJSON)
}
if got["dry_run"] != true {
t.Fatalf("dry_run = %v, want true", got["dry_run"])
}
if got["key"] != "abc" {
t.Fatalf("key = %v, want abc", got["key"])
}
}
func decodeLogRecords(t *testing.T, logs string) []map[string]any {
t.Helper()
lines := strings.Split(strings.TrimSpace(logs), "\n")
records := make([]map[string]any, 0, len(lines))
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
var record map[string]any
if err := json.Unmarshal([]byte(line), &record); err != nil {
t.Fatalf("log line was not JSON: %v; line=%q", err, line)
}
records = append(records, record)
}
return records
}
func TestExecuteWritesErrorsToStderr(t *testing.T) {
var stdout bytes.Buffer
var stderr bytes.Buffer
root := &cobra.Command{
Use: "app",
RunE: func(cmd *cobra.Command, _ []string) error {
return NewError(cmd.Context(), "validation_error", "bad input", WithErrorExitCode(ExitValidation))
},
}
code := Execute(
context.Background(),
root,
WithStdout(&stdout),
WithStderr(&stderr),
WithVersion("v0.1.0"),
WithEnv(func(string) string { return "" }),
WithStdoutIsTTY(false),
)
if code != ExitValidation {
t.Fatalf("Execute exit code = %d, want %d", code, ExitValidation)
}
if stdout.Len() != 0 {
t.Fatalf("stdout = %q, want empty", stdout.String())
}
var got map[string]any
if err := json.Unmarshal(stderr.Bytes(), &got); err != nil {
t.Fatalf("stderr was not JSON: %v", err)
}
if got["error_code"] != "validation_error" {
t.Fatalf("error_code = %v, want validation_error", got["error_code"])
}
if got["tool"] != "app" {
t.Fatalf("tool = %v, want app", got["tool"])
}
if got["version"] != "v0.1.0" {
t.Fatalf("version = %v, want v0.1.0", got["version"])
}
}
// TestExecuteResolvesVersionWhenWithVersionOmitted verifies that Execute never
// ships an empty version to agent-visible surfaces: when the caller does not
// pass WithVersion, the error envelope and __schema must carry the
// ResolveVersion build-info/vcs fallback, which is non-empty by contract.
func TestExecuteResolvesVersionWhenWithVersionOmitted(t *testing.T) {
t.Run("error envelope", func(t *testing.T) {
var stdout bytes.Buffer
var stderr bytes.Buffer
root := &cobra.Command{
Use: "app",
RunE: func(cmd *cobra.Command, _ []string) error {
return NewError(cmd.Context(), "validation_error", "bad input", WithErrorExitCode(ExitValidation))
},
}
code := Execute(
context.Background(),
root,
WithStdout(&stdout),
WithStderr(&stderr),
WithEnv(func(string) string { return "" }),
WithStdoutIsTTY(false),
)
if code != ExitValidation {
t.Fatalf("Execute exit code = %d, want %d", code, ExitValidation)
}
var got map[string]any
if err := json.Unmarshal(stderr.Bytes(), &got); err != nil {
t.Fatalf("stderr was not JSON: %v", err)
}
if got["version"] == "" || got["version"] == nil {
t.Fatalf("error envelope version = %v, want non-empty ResolveVersion fallback", got["version"])
}
})
t.Run("schema", func(t *testing.T) {
var stdout bytes.Buffer
var stderr bytes.Buffer
root := &cobra.Command{
Use: "app",
Short: "test app",
}
root.SetArgs([]string{"__schema"})
code := Execute(
context.Background(),
root,
WithStdout(&stdout),
WithStderr(&stderr),
WithEnv(func(string) string { return "" }),
WithStdoutIsTTY(false),
)
if code != ExitSuccess {
t.Fatalf("Execute exit code = %d, want %d; stderr=%s", code, ExitSuccess, stderr.String())
}
var got Schema
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatalf("stdout was not schema JSON: %v", err)
}
if got.Version == "" {
t.Fatal("__schema version is empty, want non-empty ResolveVersion fallback")
}
})
}
// TestExecuteDoesNotMutateCallerError verifies the non-mutation guarantee:
// normalizing a caller-returned *Error (filling trace_id, tool, version) must
// not modify the caller's value, while the emitted envelope still carries the
// normalized fields and the exit code still maps from the original error.
func TestExecuteDoesNotMutateCallerError(t *testing.T) {
var stdout bytes.Buffer
var stderr bytes.Buffer
callerErr := NewError(context.Background(), "validation_error", "bad input", WithErrorExitCode(ExitValidation))
// NewError stamps ZeroTraceID for a span-less context at construction;
// normalization must leave that value — and the empty Tool/Version — as-is.
wantTraceID := callerErr.TraceID
root := &cobra.Command{
Use: "app",
RunE: func(cmd *cobra.Command, _ []string) error {
return callerErr
},
}
code := Execute(
context.Background(),
root,
WithStdout(&stdout),
WithStderr(&stderr),
WithVersion("v0.1.0"),
WithEnv(func(string) string { return "" }),
WithStdoutIsTTY(false),
)
if code != ExitValidation {
t.Fatalf("Execute exit code = %d, want %d", code, ExitValidation)
}
if callerErr.TraceID != wantTraceID {
t.Fatalf("caller error TraceID mutated to %q, want unchanged %q", callerErr.TraceID, wantTraceID)
}
if callerErr.Tool != "" {
t.Fatalf("caller error Tool mutated to %q, want unchanged (empty)", callerErr.Tool)
}
if callerErr.Version != "" {
t.Fatalf("caller error Version mutated to %q, want unchanged (empty)", callerErr.Version)
}
var got map[string]any
if err := json.Unmarshal(stderr.Bytes(), &got); err != nil {
t.Fatalf("stderr was not JSON: %v", err)
}
if got["tool"] != "app" {
t.Fatalf("envelope tool = %v, want normalized value app", got["tool"])
}
if got["version"] != "v0.1.0" {
t.Fatalf("envelope version = %v, want normalized value v0.1.0", got["version"])
}
if got["trace_id"] == "" || got["trace_id"] == nil {
t.Fatalf("envelope trace_id = %v, want normalized non-empty value", got["trace_id"])
}
}
// TestExecuteErrorSpanStatusDescriptionCarriesMessage verifies that a failed
// command sets the root span's error status description to the error message,
// not an empty string. The AX_OTEL_DEBUG exporter serializes the span status
// to stderr, where the description must appear.
func TestExecuteErrorSpanStatusDescriptionCarriesMessage(t *testing.T) {
var stdout bytes.Buffer
var stderr bytes.Buffer
root := &cobra.Command{
Use: "app",
RunE: func(cmd *cobra.Command, _ []string) error {
return NewError(cmd.Context(), "validation_error", "bad input", WithErrorExitCode(ExitValidation))
},
}
code := Execute(
context.Background(),
root,
WithStdout(&stdout),
WithStderr(&stderr),
WithEnv(func(key string) string {
if key == "AX_OTEL_DEBUG" {
return "1"
}
return ""
}),
WithStdoutIsTTY(false),
)
if code != ExitValidation {
t.Fatalf("Execute exit code = %d, want %d", code, ExitValidation)
}
if !strings.Contains(stderr.String(), `"Description": "bad input"`) {
t.Fatalf("stderr = %q, want span status description carrying the error message", stderr.String())
}
}
func TestExecuteSchemaCommandWritesStdout(t *testing.T) {
var stdout bytes.Buffer
var stderr bytes.Buffer
root := &cobra.Command{
Use: "app",
Short: "test app",
Example: "app __schema",
}
root.SetArgs([]string{"__schema"})
code := Execute(
context.Background(),
root,
WithStdout(&stdout),
WithStderr(&stderr),
WithVersion("v0.1.0"),
WithEnv(func(string) string { return "" }),
WithStdoutIsTTY(false),
)
if code != ExitSuccess {
t.Fatalf("Execute exit code = %d, want %d; stderr=%s", code, ExitSuccess, stderr.String())
}
if stderr.Len() != 0 {
t.Fatalf("stderr = %q, want empty", stderr.String())
}
var got Schema
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatalf("stdout was not schema JSON: %v", err)
}
if got.Tool != "app" {
t.Fatalf("Tool = %q, want app", got.Tool)
}
}