-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathhelpers.go
More file actions
1335 lines (1149 loc) · 45.7 KB
/
helpers.go
File metadata and controls
1335 lines (1149 loc) · 45.7 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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package acceptance
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// defaultAPIUpstream is the real Hookdeck API base URL used by the recording proxy.
const defaultAPIUpstream = "https://api.hookdeck.com"
// acceptance502MaxAttempts is how many times CLIRunner runs a command when the
// combined output looks like a transient Hookdeck API error (HTTP 502 gateway or
// occasional HTTP 500 from upstream).
const acceptance502MaxAttempts = 4
// acceptance502RetryDelay is the pause between transient-error retries.
const acceptance502RetryDelay = 2 * time.Second
// acceptance502LogExcerpt is the max chars of stdout/stderr to include in retry logs.
const acceptance502LogExcerpt = 800
// combinedOutputLooksLikeHTTP502 returns true when stdout+stderr match patterns
// emitted by the CLI/API client for transient HTTP 502/500 (503/504 are not retried here).
func combinedOutputLooksLikeHTTP502(stdout, stderr string) bool {
combined := stdout + "\n" + stderr
return strings.Contains(combined, "status code: 502") ||
strings.Contains(combined, "status=502") ||
strings.Contains(combined, "error code: 502") ||
strings.Contains(combined, "status code: 500") ||
strings.Contains(combined, "status=500") ||
strings.Contains(combined, "error code: 500")
}
func excerptFor502Log(s string, max int) string {
s = strings.TrimSpace(s)
if s == "" {
return "(empty)"
}
if len(s) <= max {
return s
}
return "…" + s[len(s)-max:]
}
func commandSummaryFor502Log(args []string) string {
const max = 200
s := strings.Join(args, " ")
if len(s) <= max {
return s
}
return s[:max] + "…"
}
// runWithHTTP502Retry re-runs run() when the process exits with an error and
// output looks like a transient Hookdeck API HTTP 502/500. Logs each retry clearly via t.Logf.
func (r *CLIRunner) runWithHTTP502Retry(commandSummary string, run func() (stdout, stderr string, err error)) (stdout, stderr string, err error) {
r.t.Helper()
var lastStdout, lastStderr string
var lastErr error
for attempt := 1; attempt <= acceptance502MaxAttempts; attempt++ {
lastStdout, lastStderr, lastErr = run()
if lastErr == nil || !combinedOutputLooksLikeHTTP502(lastStdout, lastStderr) {
return lastStdout, lastStderr, lastErr
}
if attempt < acceptance502MaxAttempts {
r.t.Logf("acceptance: Hookdeck API transient HTTP 502/500; retrying CLI command [%s] (attempt %d/%d, next retry after %v)\nstderr excerpt:\n%s\nstdout excerpt:\n%s",
commandSummary, attempt, acceptance502MaxAttempts, acceptance502RetryDelay,
excerptFor502Log(lastStderr, acceptance502LogExcerpt),
excerptFor502Log(lastStdout, acceptance502LogExcerpt))
time.Sleep(acceptance502RetryDelay)
}
}
if lastErr != nil && combinedOutputLooksLikeHTTP502(lastStdout, lastStderr) {
r.t.Logf("acceptance: Hookdeck API transient HTTP 502/500 still failing after %d attempts (command [%s]); giving up. stderr excerpt:\n%s\nstdout excerpt:\n%s",
acceptance502MaxAttempts, commandSummary,
excerptFor502Log(lastStderr, acceptance502LogExcerpt),
excerptFor502Log(lastStdout, acceptance502LogExcerpt))
}
return lastStdout, lastStderr, lastErr
}
// RecordedRequest holds a single HTTP request as captured by the recording proxy.
type RecordedRequest struct {
Method string
Path string
Telemetry string
}
// RecordingProxy is an HTTP server that forwards requests to the real API and
// records each request (including X-Hookdeck-CLI-Telemetry). Use it to run the
// CLI with --api-base pointing at the proxy so all API traffic is captured
// while still hitting the real backend.
type RecordingProxy struct {
t *testing.T
server *httptest.Server
upstream string
mu sync.Mutex
recorded []RecordedRequest
}
// URL returns the proxy base URL (e.g. http://127.0.0.1:port). Pass this to
// the CLI as --api-base so requests go through the proxy.
func (p *RecordingProxy) URL() string {
return p.server.URL
}
// Recorded returns a copy of the slice of recorded requests. Safe to call
// after the CLI command has finished.
func (p *RecordingProxy) Recorded() []RecordedRequest {
p.mu.Lock()
defer p.mu.Unlock()
out := make([]RecordedRequest, len(p.recorded))
copy(out, p.recorded)
return out
}
// Close shuts down the proxy server.
func (p *RecordingProxy) Close() {
p.server.Close()
}
// StartRecordingProxy starts an httptest.Server that acts as a reverse proxy to
// upstreamBase (e.g. https://api.hookdeck.com). Every request is recorded
// (method, path, X-Hookdeck-CLI-Telemetry) and then forwarded to the upstream;
// the upstream response is returned to the client. Use with CLIRunner.Run("--api-base", proxy.URL(), "gateway", ...).
func StartRecordingProxy(t *testing.T, upstreamBase string) *RecordingProxy {
t.Helper()
upstream, err := url.Parse(strings.TrimSuffix(upstreamBase, "/"))
require.NoError(t, err, "parse upstream URL")
p := &RecordingProxy{
t: t,
upstream: upstream.String(),
recorded: make([]RecordedRequest, 0),
}
p.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Record before forwarding
p.mu.Lock()
p.recorded = append(p.recorded, RecordedRequest{
Method: r.Method,
Path: r.URL.Path,
Telemetry: r.Header.Get("X-Hookdeck-CLI-Telemetry"),
})
p.mu.Unlock()
// Build upstream request: same method, path, query, body
targetPath := r.URL.Path
if r.URL.RawQuery != "" {
targetPath += "?" + r.URL.RawQuery
}
dest, err := url.Parse(upstream.String() + targetPath)
require.NoError(p.t, err)
var bodyReader io.Reader
if r.Body != nil {
bodyReader = r.Body
}
req, err := http.NewRequest(r.Method, dest.String(), bodyReader)
require.NoError(p.t, err)
// Copy headers that the API cares about
for _, k := range []string{
"Authorization", "Content-Type", "X-Team-ID", "X-Project-ID",
"X-Hookdeck-CLI-Telemetry", "X-Hookdeck-Client-User-Agent", "User-Agent",
} {
if v := r.Header.Get(k); v != "" {
req.Header.Set(k, v)
}
}
resp, err := http.DefaultClient.Do(req)
require.NoError(p.t, err)
defer resp.Body.Close()
// Copy response back
for k, v := range resp.Header {
for _, vv := range v {
w.Header().Add(k, vv)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
}))
return p
}
// telemetryPayload is the structure of the X-Hookdeck-CLI-Telemetry header (JSON).
type telemetryPayload struct {
CommandPath string `json:"command_path"`
InvocationID string `json:"invocation_id"`
}
// AssertTelemetryConsistent checks that every recorded request that has a
// telemetry header shares the same invocation_id and command_path, and that
// command_path equals expectedCommandPath.
func AssertTelemetryConsistent(t *testing.T, recorded []RecordedRequest, expectedCommandPath string) {
t.Helper()
var invocationID, commandPath string
for i, r := range recorded {
if r.Telemetry == "" {
continue
}
var p telemetryPayload
require.NoError(t, json.Unmarshal([]byte(r.Telemetry), &p), "request %d: invalid telemetry JSON: %s", i, r.Telemetry)
if invocationID == "" {
invocationID = p.InvocationID
commandPath = p.CommandPath
}
require.Equal(t, invocationID, p.InvocationID, "request %d (%s %s): invocation_id should be consistent", i, r.Method, r.Path)
require.Equal(t, commandPath, p.CommandPath, "request %d (%s %s): command_path should be consistent", i, r.Method, r.Path)
}
if invocationID == "" && len(recorded) > 0 {
t.Fatalf("telemetry: %d HTTP request(s) recorded but X-Hookdeck-CLI-Telemetry was empty on every one (unset HOOKDECK_CLI_TELEMETRY_DISABLED / config telemetry_disabled for these tests)", len(recorded))
}
require.Equal(t, expectedCommandPath, commandPath, "command_path should match expected")
require.NotEmpty(t, invocationID, "at least one request should have invocation_id")
}
func init() {
// Attempt to load .env file from test/acceptance/.env for local development
// In CI, the environment variable will be set directly
loadEnvFile()
}
// loadEnvFile loads environment variables from test/acceptance/.env if it exists
func loadEnvFile() {
envPath := filepath.Join(".", ".env")
file, err := os.Open(envPath)
if err != nil {
// .env file doesn't exist, which is fine (env var might be set directly)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) == 2 {
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
// Only set if not already set
if os.Getenv(key) == "" {
os.Setenv(key, value)
}
}
}
}
// CLIRunner provides utilities for running CLI commands in tests
type CLIRunner struct {
t *testing.T
apiKey string
projectRoot string
configPath string // when set (ACCEPTANCE_SLICE), HOOKDECK_CONFIG_FILE is set so each slice uses its own config file
}
// NewCLIRunner creates a new CLI runner for tests
// It requires HOOKDECK_CLI_TESTING_API_KEY (and optionally HOOKDECK_CLI_TESTING_API_KEY_2 for slice 1, HOOKDECK_CLI_TESTING_API_KEY_3 for slice 2) to be set
func NewCLIRunner(t *testing.T) *CLIRunner {
t.Helper()
apiKey := getAcceptanceAPIKey(t)
require.NotEmpty(t, apiKey, "HOOKDECK_CLI_TESTING_API_KEY (or HOOKDECK_CLI_TESTING_API_KEY_2 for slice 1, HOOKDECK_CLI_TESTING_API_KEY_3 for slice 2) must be set")
// Get and store the absolute project root path before any directory changes
projectRoot, err := filepath.Abs("../..")
require.NoError(t, err, "Failed to get project root path")
runner := &CLIRunner{
t: t,
apiKey: apiKey,
projectRoot: projectRoot,
configPath: getAcceptanceConfigPath(),
}
// Authenticate in CI mode for tests
stdout, stderr, err := runner.Run("ci", "--api-key", apiKey)
require.NoError(t, err, "Failed to authenticate CLI: stdout=%s, stderr=%s", stdout, stderr)
return runner
}
// NewCLIRunnerWithConfigPath creates a CLI runner that uses the given config file path.
// It runs "ci --api-key" so the config is populated (api_key, project_id, project_mode, etc.).
// Use this when a test needs a known config path (e.g. to write a minimal variant for another run).
func NewCLIRunnerWithConfigPath(t *testing.T, configPath string) *CLIRunner {
t.Helper()
apiKey := getAcceptanceAPIKey(t)
require.NotEmpty(t, apiKey, "HOOKDECK_CLI_TESTING_API_KEY must be set")
projectRoot, err := filepath.Abs("../..")
require.NoError(t, err, "Failed to get project root path")
runner := &CLIRunner{
t: t,
apiKey: apiKey,
projectRoot: projectRoot,
configPath: configPath,
}
stdout, stderr, err := runner.Run("ci", "--api-key", apiKey)
require.NoError(t, err, "Failed to authenticate CLI with config at %s: stdout=%s stderr=%s", configPath, stdout, stderr)
return runner
}
// NewCLIRunnerWithConfigPathNoCI creates a CLI runner that uses the given config file path,
// without running "ci". Use when the config file is already populated (e.g. a minimal config
// written by the test). The runner will pass HOOKDECK_CONFIG_FILE to all Run() calls.
func NewCLIRunnerWithConfigPathNoCI(t *testing.T, configPath string) *CLIRunner {
t.Helper()
apiKey := getAcceptanceAPIKey(t)
require.NotEmpty(t, apiKey, "HOOKDECK_CLI_TESTING_API_KEY must be set")
projectRoot, err := filepath.Abs("../..")
require.NoError(t, err, "Failed to get project root path")
return &CLIRunner{
t: t,
apiKey: apiKey,
projectRoot: projectRoot,
configPath: configPath,
}
}
// getAcceptanceAPIKey returns the API key for the current acceptance slice.
// When ACCEPTANCE_SLICE=1 and HOOKDECK_CLI_TESTING_API_KEY_2 is set, use it; when ACCEPTANCE_SLICE=2 and HOOKDECK_CLI_TESTING_API_KEY_3 is set, use that; else HOOKDECK_CLI_TESTING_API_KEY.
func getAcceptanceAPIKey(t *testing.T) string {
t.Helper()
switch os.Getenv("ACCEPTANCE_SLICE") {
case "1":
if k := os.Getenv("HOOKDECK_CLI_TESTING_API_KEY_2"); k != "" {
return k
}
case "2":
if k := os.Getenv("HOOKDECK_CLI_TESTING_API_KEY_3"); k != "" {
return k
}
}
return os.Getenv("HOOKDECK_CLI_TESTING_API_KEY")
}
// NewCLIRunnerWithKey creates a new CLI runner authenticated with the given CLI key via
// hookdeck login --api-key. Used only for project list/use tests (HOOKDECK_CLI_TESTING_CLI_KEY);
// API and CI keys cannot list or switch projects, so those tests require a CLI key and login auth.
func NewCLIRunnerWithKey(t *testing.T, apiKey string) *CLIRunner {
t.Helper()
require.NotEmpty(t, apiKey, "api key must be non-empty for NewCLIRunnerWithKey")
projectRoot, err := filepath.Abs("../..")
require.NoError(t, err, "Failed to get project root path")
runner := &CLIRunner{
t: t,
apiKey: apiKey,
projectRoot: projectRoot,
configPath: getAcceptanceConfigPath(),
}
stdout, stderr, err := runner.Run("login", "--api-key", apiKey)
require.NoError(t, err, "Failed to authenticate CLI (login --api-key): stdout=%s, stderr=%s", stdout, stderr)
return runner
}
// getAcceptanceConfigPath returns a per-slice config path when ACCEPTANCE_SLICE is set,
// so parallel runs do not overwrite the same config file. Empty when not in sliced mode.
func getAcceptanceConfigPath() string {
slice := os.Getenv("ACCEPTANCE_SLICE")
if slice == "" {
return ""
}
return filepath.Join(os.TempDir(), "hookdeck-acceptance-slice"+slice+"-config.toml")
}
// appendEnvOverride returns a copy of env with key=value set, replacing any existing key.
func appendEnvOverride(env []string, key, value string) []string {
prefix := key + "="
out := make([]string, 0, len(env)+1)
for _, e := range env {
if !strings.HasPrefix(e, prefix) {
out = append(out, e)
}
}
out = append(out, prefix+value)
return out
}
// NewManualCLIRunner creates a CLI runner for manual tests that use human authentication.
// Unlike NewCLIRunner, this does NOT run `hookdeck ci` and relies on existing CLI credentials
// from `hookdeck login`.
func NewManualCLIRunner(t *testing.T) *CLIRunner {
t.Helper()
// Get and store the absolute project root path before any directory changes
projectRoot, err := filepath.Abs("../..")
require.NoError(t, err, "Failed to get project root path")
runner := &CLIRunner{
t: t,
apiKey: "", // No API key - using CLI credentials from `hookdeck login`
projectRoot: projectRoot,
}
// Do NOT run `hookdeck ci` - manual tests use credentials from `hookdeck login`
return runner
}
// Run executes the CLI with the given arguments and returns stdout, stderr, and error
// The CLI is executed via `go run main.go` from the project root.
// When configPath is set (parallel slice mode), HOOKDECK_CONFIG_FILE env is set so each slice uses its own config file.
func (r *CLIRunner) Run(args ...string) (stdout, stderr string, err error) {
r.t.Helper()
summary := commandSummaryFor502Log(args)
return r.runWithHTTP502Retry(summary, func() (string, string, error) {
mainGoPath := filepath.Join(r.projectRoot, "main.go")
cmdArgs := append([]string{"run", mainGoPath}, args...)
cmd := exec.Command("go", cmdArgs...)
cmd.Dir = r.projectRoot
if r.configPath != "" {
cmd.Env = appendEnvOverride(os.Environ(), "HOOKDECK_CONFIG_FILE", r.configPath)
}
var stdoutBuf, stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
runErr := cmd.Run()
return stdoutBuf.String(), stderrBuf.String(), runErr
})
}
// RunWithEnv is like Run but merges extraEnv into the process environment (e.g. for HOOKDECK_CLI_USE_SYSTEM_BINARY).
// When extraEnv["HOOKDECK_CLI_USE_SYSTEM_BINARY"] == "1", runs the installed "hookdeck" binary on PATH instead of "go run main.go"
// (e.g. to run tests against 2.0.0 or another installed version).
func (r *CLIRunner) RunWithEnv(extraEnv map[string]string, args ...string) (stdout, stderr string, err error) {
r.t.Helper()
summary := commandSummaryFor502Log(args)
return r.runWithHTTP502Retry(summary, func() (string, string, error) {
env := os.Environ()
if r.configPath != "" {
env = appendEnvOverride(env, "HOOKDECK_CONFIG_FILE", r.configPath)
}
for k, v := range extraEnv {
env = appendEnvOverride(env, k, v)
}
var cmd *exec.Cmd
if extraEnv != nil && extraEnv["HOOKDECK_CLI_USE_SYSTEM_BINARY"] == "1" {
hookdeckPath, lookErr := exec.LookPath("hookdeck")
if lookErr != nil {
return "", "", fmt.Errorf("HOOKDECK_CLI_USE_SYSTEM_BINARY=1 but hookdeck not on PATH: %w", lookErr)
}
cmd = exec.Command(hookdeckPath, args...)
cmd.Dir = r.projectRoot
} else {
mainGoPath := filepath.Join(r.projectRoot, "main.go")
cmdArgs := append([]string{"run", mainGoPath}, args...)
cmd = exec.Command("go", cmdArgs...)
cmd.Dir = r.projectRoot
}
cmd.Env = env
var stdoutBuf, stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
runErr := cmd.Run()
return stdoutBuf.String(), stderrBuf.String(), runErr
})
}
// RunListenWithTimeout starts the CLI with the given args (e.g. "--api-base", proxyURL,
// "listen", port, sourceName, "--output", "compact"), lets it run for runDuration, then
// kills the process. Uses a pre-built binary so we terminate the actual listen process
// (not a "go run" parent). Returns stdout, stderr, and the error from Wait (often
// non-nil because the process was killed). Uses the same project root and config env as Run().
func (r *CLIRunner) RunListenWithTimeout(args []string, runDuration time.Duration) (stdout, stderr string, err error) {
r.t.Helper()
tmpBinary := filepath.Join(r.projectRoot, "hookdeck-listen-test-"+generateTimestamp())
defer os.Remove(tmpBinary)
buildCmd := exec.Command("go", "build", "-o", tmpBinary, ".")
buildCmd.Dir = r.projectRoot
if err := buildCmd.Run(); err != nil {
return "", "", fmt.Errorf("build CLI for listen test: %w", err)
}
cmd := exec.Command(tmpBinary, args...)
cmd.Dir = r.projectRoot
if r.configPath != "" {
cmd.Env = appendEnvOverride(os.Environ(), "HOOKDECK_CONFIG_FILE", r.configPath)
}
var stdoutBuf, stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
if err := cmd.Start(); err != nil {
return "", "", err
}
timer := time.AfterFunc(runDuration, func() {
if cmd.Process != nil {
_ = cmd.Process.Kill()
}
})
defer timer.Stop()
waitErr := cmd.Wait()
return stdoutBuf.String(), stderrBuf.String(), waitErr
}
// RunGatewayMCPSubprocess builds the CLI binary, runs `gateway mcp` with optional stdin,
// lets it run for runDuration, then kills the process. Returns stdout, stderr, and the
// error from Wait (often non-nil because the process was killed). configPath, when non-empty,
// is passed as HOOKDECK_CONFIG_FILE. extraEnv entries override the process environment.
func RunGatewayMCPSubprocess(t *testing.T, projectRoot, configPath string, extraEnv map[string]string, stdin string, runDuration time.Duration) (stdout, stderr string, err error) {
t.Helper()
tmpBinary := filepath.Join(projectRoot, "hookdeck-mcp-test-"+generateTimestamp())
defer os.Remove(tmpBinary)
buildCmd := exec.Command("go", "build", "-o", tmpBinary, ".")
buildCmd.Dir = projectRoot
if buildErr := buildCmd.Run(); buildErr != nil {
return "", "", fmt.Errorf("build CLI for gateway mcp test: %w", buildErr)
}
cmd := exec.Command(tmpBinary, "gateway", "mcp")
cmd.Dir = projectRoot
env := os.Environ()
if configPath != "" {
env = appendEnvOverride(env, "HOOKDECK_CONFIG_FILE", configPath)
}
for k, v := range extraEnv {
env = appendEnvOverride(env, k, v)
}
cmd.Env = env
var stdoutBuf, stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
closeStdin := func() {}
if stdin != "" {
pr, pw, pipeErr := os.Pipe()
if pipeErr != nil {
return "", "", pipeErr
}
cmd.Stdin = pr
if _, werr := io.WriteString(pw, stdin); werr != nil {
_ = pr.Close()
_ = pw.Close()
return "", "", werr
}
if !strings.HasSuffix(stdin, "\n") {
_, _ = pw.Write([]byte("\n"))
}
closeStdin = func() {
_ = pw.Close()
_ = pr.Close()
}
}
if err := cmd.Start(); err != nil {
closeStdin()
return "", "", err
}
timer := time.AfterFunc(runDuration, func() {
if cmd.Process != nil {
_ = cmd.Process.Kill()
}
})
defer timer.Stop()
waitErr := cmd.Wait()
closeStdin()
return stdoutBuf.String(), stderrBuf.String(), waitErr
}
// RunFromCwd executes the CLI from the current working directory.
// This is useful for tests that need to test --local flag behavior,
// which creates config in the current directory.
//
// This builds a temporary binary in the project root, then runs it from
// the current working directory.
func (r *CLIRunner) RunFromCwd(args ...string) (stdout, stderr string, err error) {
r.t.Helper()
tmpBinary := filepath.Join(r.projectRoot, "hookdeck-test-"+generateTimestamp())
defer os.Remove(tmpBinary)
buildCmd := exec.Command("go", "build", "-o", tmpBinary, ".")
buildCmd.Dir = r.projectRoot
if err := buildCmd.Run(); err != nil {
return "", "", fmt.Errorf("failed to build CLI binary: %w", err)
}
summary := commandSummaryFor502Log(args)
return r.runWithHTTP502Retry(summary, func() (string, string, error) {
cmd := exec.Command(tmpBinary, args...)
if r.configPath != "" {
cmd.Env = appendEnvOverride(os.Environ(), "HOOKDECK_CONFIG_FILE", r.configPath)
}
var stdoutBuf, stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
cmd.Stdin = os.Stdin
runErr := cmd.Run()
return stdoutBuf.String(), stderrBuf.String(), runErr
})
}
// RunExpectSuccess runs the CLI command and fails the test if it returns an error
// Returns only stdout for convenience
func (r *CLIRunner) RunExpectSuccess(args ...string) string {
r.t.Helper()
stdout, stderr, err := r.Run(args...)
require.NoError(r.t, err, "CLI command failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr)
return stdout
}
// RunJSON runs the CLI command with --output json flag and unmarshals the result
// Automatically adds --output json to the arguments
func (r *CLIRunner) RunJSON(result interface{}, args ...string) error {
r.t.Helper()
// Append --output json to arguments
argsWithJSON := append(args, "--output", "json")
stdout, stderr, err := r.Run(argsWithJSON...)
if err != nil {
return fmt.Errorf("CLI command failed: %w\nstdout: %s\nstderr: %s", err, stdout, stderr)
}
// Unmarshal JSON output
if err := json.Unmarshal([]byte(stdout), result); err != nil {
return fmt.Errorf("failed to unmarshal JSON output: %w\noutput: %s", err, stdout)
}
return nil
}
// assertFilterRuleFieldMatches asserts that a filter rule field (body or headers) matches the expected JSON.
// The API may return the field as either a string or a parsed map; both are accepted.
func assertFilterRuleFieldMatches(t *testing.T, actual interface{}, expectedJSON string, fieldName string) {
t.Helper()
var expectedMap map[string]interface{}
require.NoError(t, json.Unmarshal([]byte(expectedJSON), &expectedMap), "expectedJSON should be valid JSON")
var actualMap map[string]interface{}
switch v := actual.(type) {
case string:
require.NoError(t, json.Unmarshal([]byte(v), &actualMap), "actual string should be valid JSON")
case map[string]interface{}:
actualMap = v
default:
t.Fatalf("%s should be string or map, got %T", fieldName, actual)
}
assert.Equal(t, expectedMap, actualMap, "%s should match expected JSON", fieldName)
}
// assertResponseStatusCodesMatch asserts that response_status_codes from the API match expected values.
// The API may return codes as strings or numbers; both are accepted.
func assertResponseStatusCodesMatch(t *testing.T, statusCodes interface{}, expected ...string) {
t.Helper()
slice, ok := statusCodes.([]interface{})
require.True(t, ok, "response_status_codes should be an array, got %T", statusCodes)
require.Len(t, slice, len(expected), "response_status_codes length")
for i, exp := range expected {
var actual string
switch v := slice[i].(type) {
case string:
actual = v
case float64:
actual = fmt.Sprintf("%.0f", v)
case int:
actual = fmt.Sprintf("%d", v)
default:
actual = fmt.Sprintf("%v", slice[i])
}
assert.Equal(t, exp, actual, "response_status_codes[%d]", i)
}
}
// generateTimestamp returns a timestamp string in the format YYYYMMDDHHMMSS plus microseconds
// This is used for creating unique test resource names
func generateTimestamp() string {
now := time.Now()
// Format: YYYYMMDDHHMMSS plus last 6 digits of Unix nano for uniqueness
return fmt.Sprintf("%s%d", now.Format("20060102150405"), now.UnixNano()%1000000)
}
// Connection represents a Hookdeck connection for testing
type Connection struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Source struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
} `json:"source"`
Destination struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Config interface{} `json:"config"`
} `json:"destination"`
Rules []map[string]interface{} `json:"rules"`
}
// Source represents a Hookdeck source for testing
type Source struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
URL string `json:"url"`
}
// Destination represents a Hookdeck destination for testing
type Destination struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Config interface{} `json:"config"`
}
// Transformation represents a Hookdeck transformation for testing
type Transformation struct {
ID string `json:"id"`
Name string `json:"name"`
Code string `json:"code"`
}
// Event represents a Hookdeck event for testing
type Event struct {
ID string `json:"id"`
Status string `json:"status"`
WebhookID string `json:"webhook_id"`
}
// Request represents a Hookdeck request for testing
type Request struct {
ID string `json:"id"`
}
// Attempt represents a Hookdeck attempt for testing
type Attempt struct {
ID string `json:"id"`
EventID string `json:"event_id"`
AttemptNumber int `json:"attempt_number"`
Status string `json:"status"`
}
// createTestConnection creates a basic test connection and returns its ID
// The connection uses a WEBHOOK source and CLI destination
func createTestConnection(t *testing.T, cli *CLIRunner) string {
t.Helper()
timestamp := generateTimestamp()
connName := fmt.Sprintf("test-conn-%s", timestamp)
sourceName := fmt.Sprintf("test-src-%s", timestamp)
destName := fmt.Sprintf("test-dst-%s", timestamp)
var conn Connection
err := cli.RunJSON(&conn,
"gateway", "connection", "create",
"--name", connName,
"--source-name", sourceName,
"--source-type", "WEBHOOK",
"--destination-name", destName,
"--destination-type", "CLI",
"--destination-cli-path", "/webhooks",
)
require.NoError(t, err, "Failed to create test connection")
require.NotEmpty(t, conn.ID, "Connection ID should not be empty")
t.Logf("Created test connection: %s (ID: %s)", connName, conn.ID)
return conn.ID
}
// createTestConnectionWithMockDestination creates a test connection with a MOCK_API destination.
// Events and attempts are generated by the backend without needing a live CLI. Use this for
// inspection tests (event/request/attempt) that need to trigger and then list/get events.
func createTestConnectionWithMockDestination(t *testing.T, cli *CLIRunner) string {
t.Helper()
timestamp := generateTimestamp()
connName := fmt.Sprintf("test-conn-%s", timestamp)
sourceName := fmt.Sprintf("test-src-%s", timestamp)
destName := fmt.Sprintf("test-dst-%s", timestamp)
var conn Connection
err := cli.RunJSON(&conn,
"gateway", "connection", "create",
"--name", connName,
"--source-name", sourceName,
"--source-type", "WEBHOOK",
"--destination-name", destName,
"--destination-type", "MOCK_API",
)
require.NoError(t, err, "Failed to create test connection with mock destination")
require.NotEmpty(t, conn.ID, "Connection ID should not be empty")
t.Logf("Created test connection (mock dest): %s (ID: %s)", connName, conn.ID)
return conn.ID
}
// deleteConnection deletes a connection by ID using the --force flag
// This is safe to use in cleanup functions and won't prompt for confirmation
func deleteConnection(t *testing.T, cli *CLIRunner, id string) {
t.Helper()
stdout, stderr, err := cli.Run("gateway", "connection", "delete", id, "--force")
if err != nil {
// Log but don't fail the test on cleanup errors
t.Logf("Warning: Failed to delete connection %s: %v\nstdout: %s\nstderr: %s",
id, err, stdout, stderr)
return
}
t.Logf("Deleted connection: %s", id)
}
// cleanupConnections deletes multiple connections
// Useful for cleaning up test resources
func cleanupConnections(t *testing.T, cli *CLIRunner, ids []string) {
t.Helper()
for _, id := range ids {
deleteConnection(t, cli, id)
}
}
// createTestSource creates a WEBHOOK source and returns its ID
func createTestSource(t *testing.T, cli *CLIRunner) string {
t.Helper()
timestamp := generateTimestamp()
name := fmt.Sprintf("test-src-%s", timestamp)
var src Source
err := cli.RunJSON(&src,
"gateway", "source", "create",
"--name", name,
"--type", "WEBHOOK",
)
require.NoError(t, err, "Failed to create test source")
require.NotEmpty(t, src.ID, "Source ID should not be empty")
t.Logf("Created test source: %s (ID: %s)", name, src.ID)
return src.ID
}
// deleteSource deletes a source by ID using the --force flag
func deleteSource(t *testing.T, cli *CLIRunner, id string) {
t.Helper()
stdout, stderr, err := cli.Run("gateway", "source", "delete", id, "--force")
if err != nil {
t.Logf("Warning: Failed to delete source %s: %v\nstdout: %s\nstderr: %s",
id, err, stdout, stderr)
return
}
t.Logf("Deleted source: %s", id)
}
// createTestDestination creates an HTTP destination with a test URL and returns its ID
func createTestDestination(t *testing.T, cli *CLIRunner) string {
t.Helper()
timestamp := generateTimestamp()
name := fmt.Sprintf("test-dst-%s", timestamp)
var dst Destination
err := cli.RunJSON(&dst,
"gateway", "destination", "create",
"--name", name,
"--type", "HTTP",
"--url", "https://example.com/webhooks",
)
require.NoError(t, err, "Failed to create test destination")
require.NotEmpty(t, dst.ID, "Destination ID should not be empty")
t.Logf("Created test destination: %s (ID: %s)", name, dst.ID)
return dst.ID
}
// deleteDestination deletes a destination by ID using the --force flag
func deleteDestination(t *testing.T, cli *CLIRunner, id string) {
t.Helper()
stdout, stderr, err := cli.Run("gateway", "destination", "delete", id, "--force")
if err != nil {
t.Logf("Warning: Failed to delete destination %s: %v\nstdout: %s\nstderr: %s",
id, err, stdout, stderr)
return
}
t.Logf("Deleted destination: %s", id)
}
// createTestTransformation creates a transformation with minimal code and returns its ID
func createTestTransformation(t *testing.T, cli *CLIRunner) string {
t.Helper()
timestamp := generateTimestamp()
name := fmt.Sprintf("test-trn-%s", timestamp)
code := `addHandler("transform", (request, context) => { return request; });`
var trn Transformation
err := cli.RunJSON(&trn,
"gateway", "transformation", "create",
"--name", name,
"--code", code,
)
require.NoError(t, err, "Failed to create test transformation")
require.NotEmpty(t, trn.ID, "Transformation ID should not be empty")
t.Logf("Created test transformation: %s (ID: %s)", name, trn.ID)
return trn.ID
}
// deleteTransformation deletes a transformation by ID using the --force flag
func deleteTransformation(t *testing.T, cli *CLIRunner, id string) {
t.Helper()
stdout, stderr, err := cli.Run("gateway", "transformation", "delete", id, "--force")
if err != nil {
t.Logf("Warning: Failed to delete transformation %s: %v\nstdout: %s\nstderr: %s",
id, err, stdout, stderr)
return
}
t.Logf("Deleted transformation: %s", id)
}
// triggerTestEvent sends a POST request to the given source URL to create a request and event.
// Use after creating a connection; then list events with --connection-id to find the new event.
func triggerTestEvent(t *testing.T, sourceURL string) {
t.Helper()
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Post(sourceURL, "application/json", strings.NewReader(`{"test":true}`))
require.NoError(t, err, "POST to source URL failed")
defer resp.Body.Close()
require.True(t, resp.StatusCode >= 200 && resp.StatusCode < 300,
"POST to source URL returned %d", resp.StatusCode)
}
// createConnectionAndTriggerEvent creates a test connection with a MOCK_API destination (so events
// are generated without a live CLI), triggers one request via the source URL, then polls for the
// event to appear. Returns connection ID and event ID. Caller should cleanup with deleteConnection(t, cli, connID).
func createConnectionAndTriggerEvent(t *testing.T, cli *CLIRunner) (connID, eventID string) {
t.Helper()
connID = createTestConnectionWithMockDestination(t, cli)
var conn Connection
require.NoError(t, cli.RunJSON(&conn, "gateway", "connection", "get", connID))
require.NotEmpty(t, conn.Source.ID, "connection source ID")
var src Source
require.NoError(t, cli.RunJSON(&src, "gateway", "source", "get", conn.Source.ID))
require.NotEmpty(t, src.URL, "source URL")
triggerTestEvent(t, src.URL)
// Poll for event to appear (API may take a few seconds)
type EventListResponse struct {
Models []Event `json:"models"`
}
for i := 0; i < 10; i++ {
time.Sleep(2 * time.Second)
var resp EventListResponse
require.NoError(t, cli.RunJSON(&resp, "gateway", "event", "list", "--connection-id", connID, "--limit", "1"))
if len(resp.Models) > 0 {
return connID, resp.Models[0].ID
}
}
require.Fail(t, "expected at least one event after trigger (waited ~20s)")
return "", ""
}