Repository navigation
Expand file tree
/
Copy pathbinary_test.go
More file actions
1152 lines (1056 loc) · 33.2 KB
/
Copy pathbinary_test.go
File metadata and controls
1152 lines (1056 loc) · 33.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
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 binary
import (
"archive/tar"
"archive/zip"
"bytes"
"compress/gzip"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/fentas/b/pkg/fetch"
"github.com/fentas/b/pkg/provider"
)
func TestMain(m *testing.M) {
// Short retry waits: some tests serve 5xx or dial a closed port. The
// retry policy itself is tested in pkg/fetch.
fetch.DefaultPolicy = fetch.Policy{
Attempts: 3,
BaseDelay: time.Millisecond,
MaxDelay: 10 * time.Millisecond,
MaxWait: time.Second,
}
os.Exit(m.Run())
}
// --- test helpers ---
// makeTarGz builds a gzip+tar archive in memory from the given (name, mode,
// content) tuples. All I/O errors are checked via t.Fatalf so bad fixtures
// fail fast with actionable errors.
type tarEntry struct {
name string
mode int64
content []byte
}
func makeTarGz(t *testing.T, entries ...tarEntry) *bytes.Buffer {
t.Helper()
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
tw := tar.NewWriter(gz)
for _, e := range entries {
hdr := &tar.Header{
Name: e.name,
Mode: e.mode,
Size: int64(len(e.content)),
Typeflag: tar.TypeReg,
}
if err := tw.WriteHeader(hdr); err != nil {
t.Fatalf("tar WriteHeader %q: %v", e.name, err)
}
if _, err := tw.Write(e.content); err != nil {
t.Fatalf("tar Write %q: %v", e.name, err)
}
}
if err := tw.Close(); err != nil {
t.Fatalf("tar Close: %v", err)
}
if err := gz.Close(); err != nil {
t.Fatalf("gzip Close: %v", err)
}
return &buf
}
// makeZip builds a zip archive in memory from (name, content) tuples.
func makeZip(t *testing.T, entries map[string][]byte) *bytes.Buffer {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for name, content := range entries {
w, err := zw.Create(name)
if err != nil {
t.Fatalf("zip Create %q: %v", name, err)
}
if _, err := w.Write(content); err != nil {
t.Fatalf("zip Write %q: %v", name, err)
}
}
if err := zw.Close(); err != nil {
t.Fatalf("zip Close: %v", err)
}
return &buf
}
// --- helper.go ---
func TestGetFileExtensionFromURL(t *testing.T) {
cases := []struct {
url string
want string
err bool
}{
{"https://example.com/foo.tar.gz", "tar.gz", false},
{"https://example.com/foo.tar.xz", "tar.xz", false},
{"https://example.com/foo.zip", "zip", false},
{"https://example.com/foo.bin", "bin", false},
{"https://example.com/noext", "", true},
{"://bad", "", true},
}
for _, c := range cases {
got, err := GetFileExtensionFromURL(c.url)
if c.err {
if err == nil {
t.Errorf("%s: expected error", c.url)
}
continue
}
if err != nil {
t.Errorf("%s: unexpected error %v", c.url, err)
}
if got != c.want {
t.Errorf("%s: got %q, want %q", c.url, got, c.want)
}
}
}
func TestGithubLatest(t *testing.T) {
// Missing repo
b := &Binary{Version: "v0"}
v, err := GithubLatest(b)
if err == nil {
t.Error("expected error for empty repo")
}
if v != "v0" {
t.Errorf("got %q", v)
}
// With a fake redirect server
final := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("ok"))
}))
defer final.Close()
redirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, final.URL+"/v1.2.3", http.StatusFound)
}))
defer redirect.Close()
// Stub GithubLatestURL with direct http.Get by patching via a package-level var isn't possible;
// call GetBody against the real fake server to exercise helpers.
body, err := GetBody(final.URL + "/v1.2.3")
if err != nil || body != "ok" {
t.Errorf("GetBody: body=%q err=%v", body, err)
}
// GetBody error path
if _, err := GetBody("http://127.0.0.1:1/unreachable"); err == nil {
t.Error("expected GetBody error")
}
}
// --- util.go ---
func TestGetGitRootDirectory(t *testing.T) {
// Best-effort — just ensure it does not panic.
_, _ = GetGitRootDirectory()
}
// --- binary.go ---
func TestBinary_PathAndExists(t *testing.T) {
tmp := t.TempDir()
t.Setenv("PATH_BIN", tmp)
b := &Binary{Name: "fake"}
path := b.BinaryPath()
if path != filepath.Join(tmp, "fake") {
t.Errorf("BinaryPath() = %q", path)
}
// Calling again should be idempotent
if got := b.BinaryPath(); got != path {
t.Errorf("second call got %q", got)
}
if b.BinaryExists() {
t.Error("should not exist yet")
}
// Create file and check exists
if err := os.WriteFile(path, []byte("x"), 0755); err != nil {
t.Fatal(err)
}
if !b.BinaryExists() {
t.Error("should exist")
}
// Alias
b2 := &Binary{Name: "fake", Alias: "other"}
if got := b2.BinaryPath(); got != filepath.Join(tmp, "other") {
t.Errorf("alias path = %q", got)
}
// Pre-set File
b3 := &Binary{File: "/pre/set"}
if got := b3.BinaryPath(); got != "/pre/set" {
t.Errorf("preset path = %q", got)
}
}
func TestBinary_LocalBinary(t *testing.T) {
tmp := t.TempDir()
t.Setenv("PATH_BIN", tmp)
b := &Binary{
Name: "fake",
Version: "v1",
VersionF: func(b *Binary) (string, error) {
return "v2", nil
},
VersionLocalF: func(b *Binary) (string, error) {
return "v1", nil
},
}
lb := b.LocalBinary(true)
if lb.Name != "fake" || lb.Latest != "v2" || lb.Version != "v1" || lb.Enforced != "v1" {
t.Errorf("LocalBinary = %+v", lb)
}
if lb.File != "" {
t.Errorf("expected empty File when not present, got %q", lb.File)
}
// Create the binary file so File is populated
if err := os.WriteFile(filepath.Join(tmp, "fake"), []byte("x"), 0755); err != nil {
t.Fatal(err)
}
b.File = "" // reset cached
lb = b.LocalBinary(false) // skip remote
if lb.File == "" || lb.Latest != "" {
t.Errorf("LocalBinary = %+v", lb)
}
}
func TestBinary_EnsureBinary_NoopExisting(t *testing.T) {
tmp := t.TempDir()
t.Setenv("PATH_BIN", tmp)
if err := os.WriteFile(filepath.Join(tmp, "fake"), []byte("x"), 0755); err != nil {
t.Fatal(err)
}
b := &Binary{Name: "fake"}
if err := b.EnsureBinary(false); err != nil {
t.Errorf("EnsureBinary: %v", err)
}
}
func TestBinary_EnsureBinary_UpdateUpToDate(t *testing.T) {
tmp := t.TempDir()
t.Setenv("PATH_BIN", tmp)
if err := os.WriteFile(filepath.Join(tmp, "fake"), []byte("x"), 0755); err != nil {
t.Fatal(err)
}
b := &Binary{
Name: "fake",
Version: "v1",
VersionF: func(b *Binary) (string, error) {
return "v1", nil
},
VersionLocalF: func(b *Binary) (string, error) {
return "v1", nil
},
}
if err := b.EnsureBinary(true); err != nil {
t.Errorf("EnsureBinary: %v", err)
}
}
// TestBinary_EnsureBinary_UpdateSkipsWhenVersionUnknown verifies that
// when VersionLocalF fails (returns empty version), EnsureBinary skips
// the download — the binary is on disk and we can't prove it's stale.
// This avoids re-downloading large binaries (e.g. tilt, 41MB) every
// time just because the version probe fails (e.g. missing `getent` in
// PATH). The trade-off: a genuinely outdated binary with a broken
// version probe won't auto-update until the probe is fixed or the user
// runs `b update --force`.
func TestBinary_EnsureBinary_UpdateSkipsWhenVersionUnknown(t *testing.T) {
tmp := t.TempDir()
t.Setenv("PATH_BIN", tmp)
if err := os.WriteFile(filepath.Join(tmp, "broken"), []byte("stale"), 0755); err != nil {
t.Fatal(err)
}
b := &Binary{
Name: "broken",
Version: "",
VersionF: func(b *Binary) (string, error) {
return "v2", nil
},
VersionLocalF: func(b *Binary) (string, error) {
return "", os.ErrNotExist
},
}
err := b.EnsureBinary(true)
if err != nil {
t.Errorf("expected skip (nil), got: %v — broken version probe should not trigger re-download", err)
}
}
// --- exec.go ---
func TestBinary_Env(t *testing.T) {
b := &Binary{Envs: map[string]string{"A": "1"}}
env := b.Env()
if len(env) != 1 || env[0] != "A=1" {
t.Errorf("Env = %v", env)
}
}
func TestBinary_Cmd_MissingBinary(t *testing.T) {
tmp := t.TempDir()
t.Setenv("PATH_BIN", tmp)
b := &Binary{Name: "missing"}
if cmd := b.Cmd("--version"); cmd != nil {
t.Error("expected nil Cmd when binary missing")
}
if _, err := b.Exec("--version"); err == nil {
t.Error("expected Exec error")
}
}
func TestBinary_Cmd_Exec(t *testing.T) {
// Use the system 'sh' as our "binary"
shPath, err := exeLookup("sh")
if err != nil {
t.Skip("sh not available")
}
tmp := t.TempDir()
t.Setenv("PATH_BIN", tmp)
b := &Binary{Name: "sh", File: shPath, Context: context.Background()}
out, err := b.Exec("-c", "echo hello")
if err != nil || out != "hello" {
t.Errorf("Exec = %q err=%v", out, err)
}
// Context nil path
b2 := &Binary{Name: "sh", File: shPath}
cmd := b2.Cmd("-c", "true")
if cmd == nil {
t.Error("Cmd nil")
}
}
func exeLookup(name string) (string, error) {
return exec.LookPath(name)
}
// --- download.go preset path ---
func TestDownloadPreset_PlainBinary(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("#!/bin/sh\necho hi"))
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{
Name: "fake",
File: filepath.Join(tmp, "fake"),
URL: srv.URL + "/fake",
Version: "v1",
}
if err := b.downloadPreset(); err != nil {
t.Fatalf("downloadPreset: %v", err)
}
if _, err := os.Stat(b.File); err != nil {
t.Error("file missing")
}
}
func TestDownloadPreset_URLF_NoURL(t *testing.T) {
tmp := t.TempDir()
b := &Binary{Name: "x", File: filepath.Join(tmp, "x"), Version: "v1"}
if err := b.downloadPreset(); err == nil {
t.Error("expected no URL error")
}
}
func TestDownloadPreset_VersionFUsed(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("ok"))
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{
Name: "x",
File: filepath.Join(tmp, "x"),
URLF: func(b *Binary) (string, error) { return srv.URL, nil },
VersionF: func(b *Binary) (string, error) {
return "v2", nil
},
}
if err := b.downloadPreset(); err != nil {
t.Errorf("%v", err)
}
if b.Version != "v2" {
t.Errorf("version = %q", b.Version)
}
}
func TestDownloadPreset_HTTP404(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{
Name: "x",
File: filepath.Join(tmp, "x"),
URL: srv.URL,
Version: "v1",
VersionF: func(b *Binary) (string, error) {
return "v2", nil
},
}
if err := b.downloadPreset(); err == nil {
t.Error("expected 404 error")
}
}
func TestDownloadPreset_IsDynamicUnknown(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("ok"))
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{
Name: "x",
File: filepath.Join(tmp, "x"),
URL: srv.URL + "/foo.unknown",
Version: "v1",
IsDynamic: true,
}
if err := b.downloadPreset(); err == nil {
t.Error("expected unknown ext error")
}
}
func TestDownloadPreset_IsTarGz(t *testing.T) {
tmp := t.TempDir()
content := []byte("binary-data")
buf := makeTarGz(t, tarEntry{name: "foo", mode: 0755, content: content})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(buf.Bytes())
}))
defer srv.Close()
b := &Binary{
Name: "foo",
File: filepath.Join(tmp, "foo"),
URL: srv.URL + "/foo.tar.gz",
Version: "v1",
IsTarGz: true,
}
if err := b.downloadPreset(); err != nil {
t.Fatalf("%v", err)
}
data, err := os.ReadFile(b.File)
if err != nil || !bytes.Equal(data, content) {
t.Errorf("extracted content = %q err=%v", data, err)
}
}
func TestDownloadPreset_IsZip(t *testing.T) {
tmp := t.TempDir()
buf := makeZip(t, map[string][]byte{"foo": []byte("zip-data")})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(buf.Bytes())
}))
defer srv.Close()
b := &Binary{
Name: "foo",
File: filepath.Join(tmp, "foo"),
URL: srv.URL + "/foo.zip",
Version: "v1",
IsZip: true,
}
if err := b.downloadPreset(); err != nil {
t.Fatalf("%v", err)
}
}
func TestExtractSingleFileFromTar_UnknownComp(t *testing.T) {
b := &Binary{Name: "foo"}
if err := b.extractSingleFileFromTar(bytes.NewReader(nil), "bogus", "test.tar"); err == nil {
t.Error("expected error")
}
}
func TestExtractSingleFileFromTar_BadGzip(t *testing.T) {
b := &Binary{Name: "foo"}
if err := b.extractSingleFileFromTar(bytes.NewReader([]byte("not-gzip")), "gz", "test.tar.gz"); err == nil {
t.Error("expected error")
}
}
func TestExtractSingleFileFromTar_FileNotFound(t *testing.T) {
buf := makeTarGz(t, tarEntry{name: "other", mode: 0755, content: []byte("x")})
tmp := t.TempDir()
b := &Binary{Name: "foo", File: filepath.Join(tmp, "foo")}
err := b.extractSingleFileFromTar(bytes.NewReader(buf.Bytes()), "gz", "test.tar.gz")
if err == nil || !strings.Contains(err.Error(), "not found") {
t.Errorf("err = %v", err)
}
}
func TestExtractFromTarAuto_NameMatch(t *testing.T) {
buf := makeTarGz(t, tarEntry{name: "foo", mode: 0755, content: []byte("bin")})
tmp := t.TempDir()
b := &Binary{Name: "foo", File: filepath.Join(tmp, "foo")}
if err := b.extractFromTarAuto(bytes.NewReader(buf.Bytes()), "gz", "test.tar.gz"); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(b.File)
if err != nil {
t.Fatalf("ReadFile: %v", err)
}
if string(data) != "bin" {
t.Errorf("got %q", data)
}
}
func TestExtractFromTarAuto_NoExecutables(t *testing.T) {
buf := makeTarGz(t, tarEntry{name: "readme", mode: 0644, content: []byte("x")})
tmp := t.TempDir()
b := &Binary{Name: "foo", File: filepath.Join(tmp, "foo")}
if err := b.extractFromTarAuto(bytes.NewReader(buf.Bytes()), "gz", "test.tar.gz"); err == nil {
t.Error("expected error")
}
}
func TestExtractFromTarAuto_PicksLargest(t *testing.T) {
buf := makeTarGz(t,
tarEntry{name: "a", mode: 0755, content: []byte("xx")},
tarEntry{name: "b", mode: 0755, content: []byte("xxxxxxxx")},
)
tmp := t.TempDir()
b := &Binary{Name: "foo", File: filepath.Join(tmp, "foo")}
if err := b.extractFromTarAuto(bytes.NewReader(buf.Bytes()), "gz", "test.tar.gz"); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(b.File)
if err != nil {
t.Fatalf("ReadFile: %v", err)
}
if string(data) != "xxxxxxxx" {
t.Errorf("got %q", data)
}
}
func TestExtractFromTarAuto_BadComp(t *testing.T) {
b := &Binary{Name: "foo"}
if err := b.extractFromTarAuto(bytes.NewReader(nil), "bogus", "test.tar"); err == nil {
t.Error("expected error")
}
}
func TestExtractFromZipAuto_NameMatch(t *testing.T) {
buf := makeZip(t, map[string][]byte{"foo": []byte("bin")})
tmp := t.TempDir()
b := &Binary{Name: "foo", File: filepath.Join(tmp, "foo")}
if err := b.extractFromZipAuto(bytes.NewReader(buf.Bytes()), "test.zip"); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(b.File)
if err != nil {
t.Fatalf("ReadFile: %v", err)
}
if string(data) != "bin" {
t.Errorf("got %q", data)
}
}
func TestExtractFromZipAuto_BadZip(t *testing.T) {
b := &Binary{Name: "foo"}
if err := b.extractFromZipAuto(bytes.NewReader([]byte("not-zip")), "test.zip"); err == nil {
t.Error("expected error")
}
}
func TestExtractFromZipAuto_PicksLargest(t *testing.T) {
buf := makeZip(t, map[string][]byte{"a": []byte("xx"), "b": []byte("xxxxxxxx")})
tmp := t.TempDir()
b := &Binary{Name: "none", File: filepath.Join(tmp, "out")}
if err := b.extractFromZipAuto(bytes.NewReader(buf.Bytes()), "test.zip"); err != nil {
t.Fatal(err)
}
}
func TestGithubURL(t *testing.T) {
b := &Binary{GitHubRepo: "foo/bar", GitHubFile: "file", Version: "v1"}
u, err := b.githubURL()
if err != nil || !strings.Contains(u, "foo/bar") {
t.Errorf("u=%q err=%v", u, err)
}
// With GitHubFileF error
bErr := &Binary{GitHubRepo: "f/b", Version: "v1", GitHubFileF: func(b *Binary) (string, error) {
return "", fmt.Errorf("fail")
}}
if _, err := bErr.githubURL(); err == nil {
t.Error("expected error")
}
}
func TestDownloadAsset_PlainBinary(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(w, bytes.NewReader([]byte("raw")))
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{Name: "x", File: filepath.Join(tmp, "x")}
// asset with .bin suffix → DetectArchiveType returns "" → plain path
err := b.downloadAsset(&provider.Asset{URL: srv.URL + "/file.bin", Name: "file.bin"})
if err != nil {
t.Fatal(err)
}
}
func TestDownloadAsset_TarGz(t *testing.T) {
buf := makeTarGz(t, tarEntry{name: "foo", mode: 0755, content: []byte("bin")})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(buf.Bytes())
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{Name: "foo", File: filepath.Join(tmp, "foo")}
if err := b.downloadAsset(&provider.Asset{URL: srv.URL + "/file.tar.gz", Name: "file.tar.gz"}); err != nil {
t.Fatal(err)
}
}
func TestDownloadAsset_HTTPError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
}))
defer srv.Close()
b := &Binary{Name: "x"}
if err := b.downloadAsset(&provider.Asset{URL: srv.URL, Name: "x"}); err == nil {
t.Error("expected error")
}
}
func TestBinary_DownloadBinary_MkdirErr(t *testing.T) {
// Unreachable parent to trigger MkdirAll error
b := &Binary{Name: "x", File: "/proc/1/cannot/create/x"}
if err := b.DownloadBinary(); err == nil {
t.Error("expected error when MkdirAll cannot create parent directory")
}
}
func TestExtractSingleFileFromTar_SuccessMatch(t *testing.T) {
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
tw := tar.NewWriter(gz)
// Include a non-reg entry (directory) to exercise the skip branch.
if err := tw.WriteHeader(&tar.Header{Name: "dir/", Mode: 0755, Typeflag: tar.TypeDir}); err != nil {
t.Fatalf("WriteHeader dir: %v", err)
}
// Include match on b.Name
if err := tw.WriteHeader(&tar.Header{Name: "foo", Mode: 0755, Size: 3, Typeflag: tar.TypeReg}); err != nil {
t.Fatalf("WriteHeader foo: %v", err)
}
if _, err := tw.Write([]byte("bin")); err != nil {
t.Fatalf("Write: %v", err)
}
if err := tw.Close(); err != nil {
t.Fatalf("tar Close: %v", err)
}
if err := gz.Close(); err != nil {
t.Fatalf("gzip Close: %v", err)
}
tmp := t.TempDir()
b := &Binary{Name: "foo", File: filepath.Join(tmp, "foo")}
if err := b.extractSingleFileFromTar(bytes.NewReader(buf.Bytes()), "gz", "test.tar.gz"); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(b.File)
if err != nil {
t.Fatalf("ReadFile: %v", err)
}
if string(data) != "bin" {
t.Errorf("got %q", data)
}
}
func TestExtractSingleFileFromTar_GitHubFileStripExt(t *testing.T) {
buf := makeTarGz(t, tarEntry{name: "mytool-linux", mode: 0755, content: []byte("xy")})
tmp := t.TempDir()
b := &Binary{Name: "other", GitHubFile: "mytool-linux.tar.gz", File: filepath.Join(tmp, "out")}
if err := b.extractSingleFileFromTar(bytes.NewReader(buf.Bytes()), "gz", "test.tar.gz"); err != nil {
t.Fatal(err)
}
}
func TestBinary_DownloadViaProvider_ResolvedAsset(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("raw-bin"))
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{
Name: "foo",
File: filepath.Join(tmp, "foo"),
AutoDetect: true,
ProviderRef: "github.com/org/foo",
ResolvedAsset: &provider.Asset{URL: srv.URL + "/foo.bin", Name: "foo.bin"},
}
if err := b.downloadViaProvider(); err != nil {
t.Fatalf("downloadViaProvider: %v", err)
}
data, err := os.ReadFile(b.File)
if err != nil {
t.Fatalf("ReadFile: %v", err)
}
if string(data) != "raw-bin" {
t.Errorf("got %q", data)
}
}
func TestBinary_DownloadViaProvider_GitLocal(t *testing.T) {
// Set up a local git repo with a script file
tmp := t.TempDir()
work := filepath.Join(tmp, "repo")
bare := filepath.Join(tmp, "bare.git")
run := func(args ...string) {
t.Helper()
if out, err := exec.Command(args[0], args[1:]...).CombinedOutput(); err != nil {
t.Fatalf("%v: %v\n%s", args, err, out)
}
}
run("git", "init", "-q", work)
run("git", "-C", work, "config", "user.email", "t@t.com")
run("git", "-C", work, "config", "user.name", "T")
run("git", "-C", work, "config", "commit.gpgsign", "false")
if err := os.WriteFile(filepath.Join(work, "tool.sh"), []byte("#!/bin/sh\necho hi"), 0755); err != nil {
t.Fatal(err)
}
run("git", "-C", work, "add", "-A")
run("git", "-C", work, "commit", "-m", "init", "--no-gpg-sign")
run("git", "clone", "--bare", "-q", work, bare)
destDir := t.TempDir()
b := &Binary{
Name: "tool.sh",
File: filepath.Join(destDir, "tool.sh"),
AutoDetect: true,
ProviderRef: "git://" + bare + ":tool.sh",
}
if err := b.downloadViaProvider(); err != nil {
t.Fatalf("downloadViaProvider: %v", err)
}
if _, err := os.Stat(b.File); err != nil {
t.Errorf("missing: %v", err)
}
}
func TestBinary_DownloadBinary_UnknownProvider(t *testing.T) {
tmp := t.TempDir()
b := &Binary{
Name: "foo",
File: filepath.Join(tmp, "foo"),
AutoDetect: true,
ProviderRef: "some-bogus-ref-that-matches-nothing-!!",
}
// downloadViaProvider → provider.Detect should fail
if err := b.downloadViaProvider(); err == nil {
t.Error("expected provider detect error")
}
}
func TestBinary_DownloadBinary_Switch(t *testing.T) {
// DownloadBinary calls downloadBinary which routes to provider or preset
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("ok"))
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{
Name: "foo",
File: filepath.Join(tmp, "foo"),
URL: srv.URL,
Version: "v1",
}
if err := b.DownloadBinary(); err != nil {
t.Errorf("%v", err)
}
}
// --- download trust: 401/403 and 0-byte downloads (#161, #163) ---
func TestDownloadPreset_HTTP403RateLimitHeader(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-RateLimit-Remaining", "0")
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"message":"API rate limit exceeded"}`))
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{Name: "x", File: filepath.Join(tmp, "x"), URL: srv.URL, Version: "v1"}
err := b.downloadPreset()
if err == nil {
t.Fatal("expected error for 403, got nil")
}
if !strings.Contains(err.Error(), "GITHUB_TOKEN") {
t.Errorf("403 rate-limit error should hint GITHUB_TOKEN, got: %v", err)
}
if _, statErr := os.Stat(b.File); statErr == nil {
t.Error("no file should be written on a 403 response")
}
}
func TestDownloadPreset_HTTP403RateLimitBody(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"message":"API rate limit exceeded for 1.2.3.4"}`))
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{Name: "x", File: filepath.Join(tmp, "x"), URL: srv.URL, Version: "v1"}
err := b.downloadPreset()
if err == nil {
t.Fatal("expected error for 403, got nil")
}
if !strings.Contains(err.Error(), "GITHUB_TOKEN") {
t.Errorf("403 rate-limit error should hint GITHUB_TOKEN, got: %v", err)
}
}
func TestDownloadPreset_HTTP403Plain(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte("no access"))
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{Name: "x", File: filepath.Join(tmp, "x"), URL: srv.URL, Version: "v1"}
err := b.downloadPreset()
if err == nil {
t.Fatal("expected error for 403, got nil")
}
if !strings.Contains(err.Error(), "403") {
t.Errorf("error should name the status, got: %v", err)
}
}
func TestDownloadPreset_HTTP401(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{Name: "x", File: filepath.Join(tmp, "x"), URL: srv.URL, Version: "v1"}
err := b.downloadPreset()
if err == nil {
t.Fatal("expected error for 401, got nil")
}
if !strings.Contains(err.Error(), "401") {
t.Errorf("error should name the status, got: %v", err)
}
}
func TestDownloadPreset_EmptyBody(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 200 OK with an empty body: must NOT be reported as success.
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{Name: "x", File: filepath.Join(tmp, "x"), URL: srv.URL, Version: "v1"}
err := b.downloadPreset()
if err == nil {
t.Fatal("expected error for 0-byte download, got nil")
}
if !strings.Contains(err.Error(), "0 bytes") || !strings.Contains(err.Error(), b.File) {
t.Errorf("error should name the file and the 0-byte size, got: %v", err)
}
}
func TestDownloadPreset_ContentLengthMatch(t *testing.T) {
content := []byte("#!/bin/sh\necho real binary\n")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(content)))
_, _ = w.Write(content)
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{Name: "x", File: filepath.Join(tmp, "x"), URL: srv.URL, Version: "v1"}
if err := b.downloadPreset(); err != nil {
t.Fatalf("downloadPreset: %v", err)
}
got, err := os.ReadFile(b.File)
if err != nil {
t.Fatalf("reading downloaded file: %v", err)
}
if !bytes.Equal(got, content) {
t.Errorf("file content mismatch: got %d bytes, want %d", len(got), len(content))
}
}
func TestDownloadAsset_HTTP403RateLimit(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-RateLimit-Remaining", "0")
w.WriteHeader(http.StatusForbidden)
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{Name: "x", File: filepath.Join(tmp, "x")}
err := b.downloadAsset(&provider.Asset{URL: srv.URL + "/file.bin", Name: "file.bin"})
if err == nil {
t.Fatal("expected error for 403, got nil")
}
if !strings.Contains(err.Error(), "GITHUB_TOKEN") {
t.Errorf("403 rate-limit error should hint GITHUB_TOKEN, got: %v", err)
}
}
func TestDownloadAsset_EmptyBody(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 200 OK, empty body
}))
defer srv.Close()
tmp := t.TempDir()
b := &Binary{Name: "x", File: filepath.Join(tmp, "x")}
err := b.downloadAsset(&provider.Asset{URL: srv.URL + "/file.bin", Name: "file.bin"})
if err == nil {
t.Fatal("expected error for 0-byte download, got nil")
}
if !strings.Contains(err.Error(), "0 bytes") {
t.Errorf("error should name the 0-byte size, got: %v", err)
}
}
// --- transient failures are retried (fetch) ---
// flakyServer answers 504 to the first request and body to the next ones.
func flakyServer(t *testing.T, body []byte) (*httptest.Server, *int32) {
t.Helper()
var n int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if atomic.AddInt32(&n, 1) == 1 {
w.WriteHeader(http.StatusGatewayTimeout)
return
}
_, _ = w.Write(body)
}))
t.Cleanup(srv.Close)
return srv, &n
}
func TestDownloadPreset_RetriesGatewayTimeout(t *testing.T) {
content := []byte("#!/bin/sh\necho retried\n")
srv, n := flakyServer(t, content)
tmp := t.TempDir()
b := &Binary{Name: "x", File: filepath.Join(tmp, "x"), URL: srv.URL, Version: "v1"}
if err := b.downloadPreset(); err != nil {
t.Fatalf("downloadPreset after one 504: %v", err)
}
got, err := os.ReadFile(b.File)
if err != nil {
t.Fatalf("reading downloaded file: %v", err)
}
if !bytes.Equal(got, content) {
t.Errorf("file content = %q, want %q", got, content)
}
if c := atomic.LoadInt32(n); c != 2 {
t.Errorf("server got %d requests, want 2", c)
}
}
func TestDownloadAsset_RetriesGatewayTimeout(t *testing.T) {
buf := makeTarGz(t, tarEntry{name: "foo", mode: 0755, content: []byte("bin")})
srv, n := flakyServer(t, buf.Bytes())
tmp := t.TempDir()
b := &Binary{Name: "foo", File: filepath.Join(tmp, "foo")}
if err := b.downloadAsset(&provider.Asset{URL: srv.URL + "/foo.tar.gz", Name: "foo.tar.gz"}); err != nil {
t.Fatalf("downloadAsset after one 504: %v", err)
}
got, err := os.ReadFile(b.File)
if err != nil {
t.Fatalf("reading extracted file: %v", err)
}
if string(got) != "bin" {
t.Errorf("file content = %q, want %q", got, "bin")
}
if c := atomic.LoadInt32(n); c != 2 {
t.Errorf("server got %d requests, want 2", c)
}
}