-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage_test.go
More file actions
1475 lines (1344 loc) · 43.6 KB
/
Copy pathcoverage_test.go
File metadata and controls
1475 lines (1344 loc) · 43.6 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 main
// Targeted tests filling the coverage gaps left by the focused suites.
// Each test exists to exercise a specific branch that was uncovered in
// the `go tool cover` report.
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
// ── check.go ────────────────────────────────────────────────────────────
func TestCheckFlatpakPackagesPartition(t *testing.T) {
defer resetMocks()
hasCmd = func(name string) bool { return name == "flatpak" }
probe = func(argv []string, _ time.Duration) (CmdResult, bool) {
// Only "installed.app" is installed.
if argv[len(argv)-1] == "installed.app" {
return CmdResult{ExitCode: 0}, true
}
return CmdResult{ExitCode: 1}, true
}
res := checkFlatpakPackages([]string{"a.app", "installed.app", "b.app"})
if !equalStringSlices(res.alreadyInstalled, []string{"installed.app"}) {
t.Errorf("alreadyInstalled: want [installed.app], got %v", res.alreadyInstalled)
}
if !equalStringSlices(res.toInstall, []string{"a.app", "b.app"}) {
t.Errorf("toInstall: want [a.app b.app], got %v", res.toInstall)
}
}
func TestCheckFlatpakPackagesEmpty(t *testing.T) {
defer resetMocks()
res := checkFlatpakPackages(nil)
if len(res.toInstall) != 0 || len(res.alreadyInstalled) != 0 {
t.Errorf("expected empty results, got %+v", res)
}
}
func TestCheckAllInParallelCombinations(t *testing.T) {
defer resetMocks()
pkgMgr = "dnf"
hasCmd = func(name string) bool { return true }
probe = func(_ []string, _ time.Duration) (CmdResult, bool) {
return CmdResult{ExitCode: 0}, true
}
osStat = func(_ string) (os.FileInfo, error) { return nil, nil }
// All three on.
sys, flat, cust := checkAllInParallel(
true, []string{"git"},
true, []string{"a.app"},
true, []*CustomPackage{{Name: "go"}},
)
if len(sys.alreadyInstalled) == 0 {
t.Errorf("expected system pkgs marked installed, got %+v", sys)
}
if len(flat.alreadyInstalled) == 0 {
t.Errorf("expected flatpak pkgs marked installed, got %+v", flat)
}
if len(cust.alreadyInstalled) == 0 {
t.Errorf("expected custom pkgs marked installed, got %+v", cust)
}
// All three off (no goroutines spawned).
sys2, flat2, cust2 := checkAllInParallel(false, nil, false, nil, false, nil)
if len(sys2.toInstallRegular) != 0 || len(flat2.toInstall) != 0 || len(cust2.toInstall) != 0 {
t.Errorf("expected empty results when all flags are off")
}
}
func TestFmtListOverLimit(t *testing.T) {
got := fmtList([]string{"a", "b", "c", "d", "e"}, 2)
if !strings.Contains(got, "a b") || !strings.Contains(got, "+3 more") {
t.Errorf("expected truncated list with '+3 more', got %q", got)
}
}
func TestPrintCheckSummaryAllSections(t *testing.T) {
defer resetMocks()
captureStdout(t, func() {
sys := systemCheckResult{
toInstallRegular: []string{"a", "b"},
toInstallSpecial: []string{"sp1"},
alreadyInstalled: []string{"ok1"},
skipped: []string{"sk1"},
remapped: []remap{{From: "x", To: []string{"y", "z"}}},
}
flat := flatpakCheckResult{
toInstall: []string{"app1"},
alreadyInstalled: []string{"app-ok"},
}
cust := customCheckResult{
toInstall: []*CustomPackage{{Name: "go", InstallPath: "/usr/local/go"}},
alreadyInstalled: []customStatus{{pkg: &CustomPackage{Name: "zig"}, path: "/usr/local/zig"}},
}
osStat = func(_ string) (os.FileInfo, error) { return nil, os.ErrNotExist }
hasCmd = func(_ string) bool { return false }
total := printCheckSummary(sys, flat, cust, "")
if total != 4 { // 3 system + 1 flatpak + 1 custom — wait recalc
// 2 regular + 1 special + 1 flatpak + 1 custom = 5
if total != 5 {
t.Errorf("expected total 5, got %d", total)
}
}
})
}
func TestPrintCheckSummaryOnlySystem(t *testing.T) {
defer resetMocks()
captureStdout(t, func() {
sys := systemCheckResult{toInstallRegular: []string{"a"}}
flat := flatpakCheckResult{}
cust := customCheckResult{}
_ = printCheckSummary(sys, flat, cust, "system")
})
}
func TestPrintCheckSummaryOnlyFlatpak(t *testing.T) {
defer resetMocks()
captureStdout(t, func() {
flat := flatpakCheckResult{toInstall: []string{"a.app"}, alreadyInstalled: []string{"b.app"}}
_ = printCheckSummary(systemCheckResult{}, flat, customCheckResult{}, "flatpak")
})
}
// ── custom.go ───────────────────────────────────────────────────────────
func TestResolveURLEmpty(t *testing.T) {
p := &CustomPackage{Name: "x"}
if p.resolveURL() != "" {
t.Error("expected empty URL for empty template")
}
}
func TestResolveSHA256URLEmpty(t *testing.T) {
p := &CustomPackage{Name: "x"}
if p.resolveSHA256URL() != "" {
t.Error("expected empty SHA URL for empty template")
}
}
func TestResolvedSHA256MapMiss(t *testing.T) {
defer resetMocks()
osName = "linux"
archName = "x86_64"
p := &CustomPackage{
Name: "x",
SHA256Map: map[string]string{"macos-aarch64": "abc"},
}
if got := p.resolvedSHA256(); got != "" {
t.Errorf("expected empty when map has no entry for current OS/arch, got %q", got)
}
}
func TestPipInstalledNoPython(t *testing.T) {
defer resetMocks()
hasCmd = func(name string) bool { return false }
if pipInstalled() {
t.Error("expected pipInstalled false when python3 missing")
}
}
func TestNpmInstalledOnPath(t *testing.T) {
defer resetMocks()
// Pretend "echo" (which definitely exists) is the npm command.
hasCmd = func(name string) bool { return name == "echo" }
installed, path := npmInstalled("echo")
if !installed {
t.Error("expected installed when hasCmd returns true")
}
// path may or may not be set depending on resolved PATH, but
// LookPath for echo should normally succeed.
if path == "" {
t.Log("note: exec.LookPath did not resolve a path; that's OK")
}
}
func TestNpmInstalledViaPnpmDir(t *testing.T) {
defer resetMocks()
tmp := t.TempDir()
t.Setenv("HOME", tmp)
binDir := filepath.Join(tmp, ".local/share/pnpm/bin")
if err := os.MkdirAll(binDir, 0o755); err != nil {
t.Fatal(err)
}
binPath := filepath.Join(binDir, "fakebin")
if err := os.WriteFile(binPath, []byte{}, 0o755); err != nil {
t.Fatal(err)
}
hasCmd = func(_ string) bool { return false }
installed, path := npmInstalled("fakebin")
if !installed || path != binPath {
t.Errorf("expected fakebin found in pnpm dir; got installed=%v path=%q", installed, path)
}
}
func TestNpmInstalledViaNvmDir(t *testing.T) {
defer resetMocks()
tmp := t.TempDir()
t.Setenv("HOME", tmp)
binDir := filepath.Join(tmp, ".nvm/versions/node/v20.10.0/bin")
if err := os.MkdirAll(binDir, 0o755); err != nil {
t.Fatal(err)
}
binPath := filepath.Join(binDir, "fakebin")
if err := os.WriteFile(binPath, []byte{}, 0o755); err != nil {
t.Fatal(err)
}
hasCmd = func(_ string) bool { return false }
installed, path := npmInstalled("fakebin")
if !installed || path != binPath {
t.Errorf("expected fakebin found in nvm dir; got installed=%v path=%q", installed, path)
}
}
func TestNpmInstalledNotFound(t *testing.T) {
defer resetMocks()
tmp := t.TempDir()
t.Setenv("HOME", tmp)
hasCmd = func(_ string) bool { return false }
installed, path := npmInstalled("absolutely-not-here")
if installed || path != "" {
t.Errorf("expected not-installed and empty path; got %v %q", installed, path)
}
}
func TestIsCustomPkgInstalledNpmNames(t *testing.T) {
defer resetMocks()
hasCmd = func(name string) bool {
return name == "claude" || name == "codex" || name == "copilot" || name == "playwright" || name == "mdts"
}
for _, name := range []string{"claude", "codex", "copilot", "playwright", "mdts"} {
ok, _ := isCustomPkgInstalled(&CustomPackage{Name: name})
if !ok {
t.Errorf("expected %s detected as installed", name)
}
}
}
func TestIsCustomPkgInstalledNoPath(t *testing.T) {
defer resetMocks()
hasCmd = func(_ string) bool { return false }
// Unknown package with no install path → returns false, "".
ok, path := isCustomPkgInstalled(&CustomPackage{Name: "no-such-pkg"})
if ok || path != "" {
t.Errorf("expected (false, \"\") for unknown pkg, got (%v, %q)", ok, path)
}
}
func TestVerifyArchiveHashError(t *testing.T) {
defer resetMocks()
// SHA256 set but file doesn't exist — sha256Of returns an error.
p := &CustomPackage{Name: "x", SHA256: "deadbeef"}
if verifyArchive("/no/such/file", p) {
t.Error("expected verifyArchive false when hash computation fails")
}
if !hasErrors() {
t.Error("expected error logged for hash failure")
}
}
func TestVerifyArchiveNoSHANoSig(t *testing.T) {
defer resetMocks()
p := &CustomPackage{Name: "x"}
if !verifyArchive("/no/such/file", p) {
t.Error("expected verifyArchive true when nothing to verify")
}
}
func TestVerifyArchiveMinisignDownloadFail(t *testing.T) {
defer resetMocks()
p := &CustomPackage{Name: "x", SHA256URLTemplate: "http://example.com/{version}.sig", Version: "1"}
download = func(_, _ string) bool { return false }
if verifyArchive("/tmp/foo", p) {
t.Error("expected verifyArchive false when signature download fails")
}
}
func TestVerifyArchiveMinisignNotInstalled(t *testing.T) {
defer resetMocks()
p := &CustomPackage{Name: "x", SHA256URLTemplate: "http://example.com/{version}.sig", Version: "1"}
download = func(_, _ string) bool { return true }
hasCmd = func(name string) bool { return name != "minisign" }
if !verifyArchive("/tmp/foo", p) {
t.Error("expected verifyArchive true (skip-with-warning) when minisign missing")
}
}
func TestVerifyArchiveMinisignFails(t *testing.T) {
defer resetMocks()
p := &CustomPackage{Name: "x", SHA256URLTemplate: "http://example.com/{version}.sig", Version: "1", MinisignKey: "key"}
download = func(_, _ string) bool { return true }
hasCmd = func(_ string) bool { return true }
runCmd = func(_ []string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 1} }
if verifyArchive("/tmp/foo", p) {
t.Error("expected verifyArchive false when minisign verification fails")
}
}
func TestVerifyArchiveMinisignOK(t *testing.T) {
defer resetMocks()
p := &CustomPackage{Name: "x", SHA256URLTemplate: "http://example.com/{version}.sig", Version: "1"}
download = func(_, _ string) bool { return true }
hasCmd = func(_ string) bool { return true }
runCmd = func(_ []string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 0} }
if !verifyArchive("/tmp/foo", p) {
t.Error("expected verifyArchive true when minisign succeeds")
}
}
func TestUrlArchOKEmptyTemplate(t *testing.T) {
defer resetMocks()
if !urlArchOK(&CustomPackage{Name: "x"}) {
t.Error("expected urlArchOK true for empty URL")
}
}
func TestUrlArchOKNoArchToken(t *testing.T) {
defer resetMocks()
archName = "x86_64"
// URL doesn't contain an arch token at all — treated as OK.
p := &CustomPackage{Name: "x", URLTemplate: "http://example.com/generic.tar.gz"}
if !urlArchOK(p) {
t.Error("expected urlArchOK true for arch-agnostic URL")
}
}
func TestInstallGoWithExistingDir(t *testing.T) {
defer resetMocks()
osStat = func(name string) (os.FileInfo, error) {
if name == "/usr/local/go" {
return nil, nil
}
return nil, os.ErrNotExist
}
var cmds [][]string
runCmd = func(argv []string, _ CmdOpts) CmdResult {
cmds = append(cmds, append([]string(nil), argv...))
return CmdResult{ExitCode: 0}
}
installGo("/tmp/go.tgz")
// First call should be "rm -rf /usr/local/go".
if len(cmds) < 1 || cmds[0][0] != "rm" {
t.Errorf("expected rm -rf as first call, got: %v", cmds)
}
}
func TestInstallFirecrackerTarFail(t *testing.T) {
defer resetMocks()
runCmd = func(_ []string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 1} }
installFirecracker("/tmp/foo.tgz", "/tmp")
if !hasErrors() {
t.Error("expected error logged when tar fails")
}
}
func TestInstallFirecrackerNoBinaryFound(t *testing.T) {
defer resetMocks()
tmp := t.TempDir()
runCmd = func(_ []string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 0} }
installFirecracker(filepath.Join(tmp, "x.tgz"), tmp)
if !hasErrors() {
t.Error("expected error logged when no firecracker binary in archive")
}
}
func TestInstallZigWithExistingDir(t *testing.T) {
defer resetMocks()
osName = "linux"
archName = "x86_64"
osStat = func(name string) (os.FileInfo, error) {
if strings.Contains(name, "zig-1.2.3") {
return nil, nil
}
return nil, os.ErrNotExist
}
var cmds [][]string
runCmd = func(argv []string, _ CmdOpts) CmdResult {
cmds = append(cmds, append([]string(nil), argv...))
return CmdResult{ExitCode: 0}
}
pkg := &CustomPackage{Name: "zig", Version: "1.2.3"}
installZig(pkg, "/tmp/zig.tar.xz")
if len(cmds) < 1 || cmds[0][0] != "rm" {
t.Errorf("expected rm -rf as first call, got %v", cmds)
}
}
func TestInstallNeovimAssetMissing(t *testing.T) {
defer resetMocks()
tmp := t.TempDir()
osName = "linux"
archName = "x86_64"
fetchJSON = func(_ string, v any) bool {
rel := v.(*ghRelease)
rel.Assets = []ghAsset{{Name: "wrong-name.tar.gz"}}
return true
}
installNeovim(nil, tmp)
if !hasErrors() {
t.Error("expected error when asset name not found")
}
}
func TestResolveLatestGoNoMatchingFile(t *testing.T) {
defer resetMocks()
osName = "linux"
archName = "x86_64"
fetchJSON = func(_ string, v any) bool {
// Provide a release but no archive file with the expected name.
data := `[{"version":"go1.99.0","files":[]}]`
return json.Unmarshal([]byte(data), v) == nil
}
_, _, ok := resolveLatestGo(nil)
if ok {
t.Error("expected resolveLatestGo to fail when no matching archive in release")
}
}
func TestResolveLatestGoFetchFails(t *testing.T) {
defer resetMocks()
fetchJSON = func(_ string, _ any) bool { return false }
if _, _, ok := resolveLatestGo(nil); ok {
t.Error("expected resolveLatestGo to fail on HTTP error")
}
}
func TestResolveLatestGoEmptyArray(t *testing.T) {
defer resetMocks()
fetchJSON = func(_ string, v any) bool {
return json.Unmarshal([]byte("[]"), v) == nil
}
if _, _, ok := resolveLatestGo(nil); ok {
t.Error("expected resolveLatestGo to fail on empty array")
}
}
func TestResolveLatestGoSingleObject(t *testing.T) {
defer resetMocks()
osName = "linux"
archName = "x86_64"
fetchJSON = func(_ string, v any) bool {
// Server returns a single object (not array) — fallback path.
data := `{"version":"go1.50.0","files":[{"filename":"go1.50.0.linux-amd64.tar.gz","kind":"archive","sha256":"abc"}]}`
return json.Unmarshal([]byte(data), v) == nil
}
v, sha, ok := resolveLatestGo(nil)
if !ok || v != "1.50.0" || sha != "abc" {
t.Errorf("expected fallback parse to yield 1.50.0/abc, got %q/%q/%v", v, sha, ok)
}
}
func TestResolveLatestFirecrackerMacOS(t *testing.T) {
defer resetMocks()
isMacOS = true
if _, _, ok := resolveLatestFirecracker(nil); ok {
t.Error("expected resolveLatestFirecracker false on macOS")
}
}
func TestResolveLatestFirecrackerNoTag(t *testing.T) {
defer resetMocks()
isMacOS = false
fetchJSON = func(_ string, v any) bool {
rel := v.(*ghRelease)
rel.TagName = ""
return true
}
if _, _, ok := resolveLatestFirecracker(nil); ok {
t.Error("expected false when tag missing")
}
}
func TestResolveLatestFirecrackerNoMatchingAsset(t *testing.T) {
defer resetMocks()
isMacOS = false
archName = "x86_64"
fetchJSON = func(_ string, v any) bool {
rel := v.(*ghRelease)
rel.TagName = "v1.0.0"
rel.Assets = []ghAsset{{Name: "wrong"}}
return true
}
if _, _, ok := resolveLatestFirecracker(nil); ok {
t.Error("expected false when no matching .sha256.txt asset")
}
}
func TestResolveLatestFirecrackerEmptySHA(t *testing.T) {
defer resetMocks()
isMacOS = false
archName = "x86_64"
fetchJSON = func(_ string, v any) bool {
rel := v.(*ghRelease)
rel.TagName = "v1.0.0"
rel.Assets = []ghAsset{{Name: "firecracker-v1.0.0-x86_64.tgz.sha256.txt", BrowserDownloadURL: "http://x"}}
return true
}
fetchText = func(_ string) string { return "" }
if _, _, ok := resolveLatestFirecracker(nil); ok {
t.Error("expected false when SHA body is empty")
}
}
func TestResolveLatestZigEmpty(t *testing.T) {
defer resetMocks()
fetchJSON = func(_ string, v any) bool {
return json.Unmarshal([]byte(`{"master":{}}`), v) == nil
}
if _, _, ok := resolveLatestZig(nil); ok {
t.Error("expected false when only master version present")
}
}
func TestResolveLatestZigMissingPlatformKey(t *testing.T) {
defer resetMocks()
osName = "linux"
archName = "x86_64"
fetchJSON = func(_ string, v any) bool {
// Has a stable version but missing the current platform key.
return json.Unmarshal([]byte(`{"0.11.0":{"aarch64-linux":{"shasum":"abc"}}}`), v) == nil
}
if _, _, ok := resolveLatestZig(nil); ok {
t.Error("expected false when platform key missing")
}
}
func TestResolveLatestZigEmptySHA(t *testing.T) {
defer resetMocks()
osName = "linux"
archName = "x86_64"
fetchJSON = func(_ string, v any) bool {
return json.Unmarshal([]byte(`{"0.11.0":{"x86_64-linux":{"shasum":""}}}`), v) == nil
}
if _, _, ok := resolveLatestZig(nil); ok {
t.Error("expected false when shasum empty")
}
}
func TestResolveLatestFetchJSONFail(t *testing.T) {
defer resetMocks()
fetchJSON = func(_ string, _ any) bool { return false }
if _, _, ok := resolveLatestZig(nil); ok {
t.Error("expected false on fetch failure")
}
}
func TestResolveLatestUnknownHint(t *testing.T) {
defer resetMocks()
resolveLatest(&CustomPackage{Name: "x"}) // no FetchLatest → no-op
resolveLatest(&CustomPackage{Name: "x", FetchLatest: "nonexistent"}) // unknown → no-op
}
func TestResolveLatestUpgrades(t *testing.T) {
defer resetMocks()
latestResolvers["upgrade-fixture"] = func(_ *CustomPackage) (string, string, bool) {
return "2.0.0", "FACE", true
}
defer delete(latestResolvers, "upgrade-fixture")
p := &CustomPackage{Name: "x", Version: "1.0.0", FetchLatest: "upgrade-fixture", SHA256URLTemplate: "sig"}
resolveLatest(p)
if p.Version != "2.0.0" || p.SHA256 != "face" || p.SHA256URLTemplate != "" {
t.Errorf("expected upgrade applied with lowercase SHA and cleared template, got %+v", p)
}
}
// runOneCustomInstall coverage: hit a few branches.
func TestRunOneCustomInstallFirecrackerOnMacOS(t *testing.T) {
defer resetMocks()
isMacOS = true
runOneCustomInstall(&CustomPackage{Name: "firecracker"})
// Should warn-and-skip without error.
issuesMu.Lock()
hasWarn := false
for _, msg := range issues {
if strings.Contains(msg, "Linux-only") {
hasWarn = true
}
}
issuesMu.Unlock()
if !hasWarn {
t.Error("expected Linux-only warning")
}
}
func TestRunOneCustomInstallNoURLNoHandler(t *testing.T) {
defer resetMocks()
osStat = func(_ string) (os.FileInfo, error) { return nil, os.ErrNotExist }
hasCmd = func(_ string) bool { return false }
runOneCustomInstall(&CustomPackage{Name: "unknownpkg"})
// Should warn about no URL / no handler.
if !hasIssueContaining("No URL or install handler") {
t.Errorf("expected 'no URL' warning, issues: %v", issuesSnapshot())
}
}
func TestRunOneCustomInstallDownloadFail(t *testing.T) {
defer resetMocks()
archName = "x86_64"
osStat = func(_ string) (os.FileInfo, error) { return nil, os.ErrNotExist }
hasCmd = func(_ string) bool { return false }
download = func(_, _ string) bool { return false }
pkg := &CustomPackage{
Name: "go",
Version: "1.0.0",
URLTemplate: "http://example.com/go-{arch}.tar.gz",
SHA256: "abc",
}
runOneCustomInstall(pkg)
}
func TestRunOneCustomInstallArchMismatch(t *testing.T) {
defer resetMocks()
archName = "x86_64"
osStat = func(_ string) (os.FileInfo, error) { return nil, os.ErrNotExist }
hasCmd = func(_ string) bool { return false }
pkg := &CustomPackage{
Name: "weird",
URLTemplate: "http://example.com/weird-aarch64.tar.gz",
}
runOneCustomInstall(pkg)
}
func TestRunOneCustomInstallVerifyFail(t *testing.T) {
defer resetMocks()
archName = "x86_64"
osStat = func(_ string) (os.FileInfo, error) { return nil, os.ErrNotExist }
hasCmd = func(_ string) bool { return false }
download = func(_, dest string) bool {
// Write empty file so sha256Of works but the digest mismatches.
return os.WriteFile(dest, []byte("x"), 0o644) == nil
}
pkg := &CustomPackage{
Name: "go",
Version: "1.0.0",
URLTemplate: "http://example.com/go-{arch}.tar.gz",
SHA256: "deadbeef",
}
runOneCustomInstall(pkg)
}
func TestInstallNpmToolsBatchNoNVM(t *testing.T) {
defer resetMocks()
osStat = func(_ string) (os.FileInfo, error) { return nil, os.ErrNotExist }
installNpmToolsBatch([]*CustomPackage{{Name: "claude"}})
if !hasIssueContaining("NVM is not installed") {
t.Error("expected error about missing NVM")
}
}
func TestInstallNpmToolsBatchEmpty(t *testing.T) {
defer resetMocks()
installNpmToolsBatch(nil)
}
func TestInstallNpmToolsBatchNonNpmFiltered(t *testing.T) {
defer resetMocks()
osStat = func(name string) (os.FileInfo, error) {
if strings.HasSuffix(name, ".nvm") {
return nil, nil
}
return nil, os.ErrNotExist
}
called := false
runShell = func(_ string, _ CmdOpts) CmdResult {
called = true
return CmdResult{ExitCode: 0}
}
// Only an unknown name — should filter to nothing and short-circuit.
installNpmToolsBatch([]*CustomPackage{{Name: "not-an-npm-tool"}})
// ensureNodeLTS still runs, so shell calls *are* expected from that.
_ = called
}
func TestInstallNpmToolsBatchPlaywrightBrowsers(t *testing.T) {
defer resetMocks()
pkgMgr = "apt-get"
osStat = func(name string) (os.FileInfo, error) {
if strings.HasSuffix(name, ".nvm") {
return nil, nil
}
return nil, os.ErrNotExist
}
var cmds []string
runShell = func(cmd string, _ CmdOpts) CmdResult {
cmds = append(cmds, cmd)
return CmdResult{ExitCode: 0}
}
installNpmToolsBatch([]*CustomPackage{{Name: "playwright"}})
hasBrowserInstall := false
for _, c := range cmds {
if strings.Contains(c, "pnpx playwright install --with-deps") {
hasBrowserInstall = true
}
}
if !hasBrowserInstall {
t.Errorf("expected pnpx playwright install --with-deps call, got: %v", cmds)
}
}
func TestInstallCustomPackagesEmpty(t *testing.T) {
defer resetMocks()
captureStdout(t, func() {
installCustomPackages(nil)
})
}
// ── post.go ─────────────────────────────────────────────────────────────
func TestInstallPyenvFailure(t *testing.T) {
defer resetMocks()
runShell = func(_ string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 1} }
installPyenv()
if !hasErrors() {
t.Error("expected error on pyenv install failure")
}
}
func TestInstallNVMFetchFail(t *testing.T) {
defer resetMocks()
fetchJSON = func(_ string, _ any) bool { return false }
installNVM()
}
func TestInstallNVMNoTag(t *testing.T) {
defer resetMocks()
fetchJSON = func(_ string, v any) bool {
v.(*ghRelease).TagName = ""
return true
}
installNVM()
if !hasIssueContaining("NVM tag_name missing") {
t.Error("expected NVM tag missing error")
}
}
func TestInstallNVMShellFail(t *testing.T) {
defer resetMocks()
fetchJSON = func(_ string, v any) bool {
v.(*ghRelease).TagName = "v0.39.0"
return true
}
runShell = func(_ string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 1} }
installNVM()
if !hasIssueContaining("NVM installation failed") {
t.Error("expected NVM install failed error")
}
}
func TestInstallAgyFail(t *testing.T) {
defer resetMocks()
runShell = func(_ string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 1} }
installAgy()
if !hasErrors() {
t.Error("expected error from installAgy failure")
}
}
func TestInstallNpmPackageNoNvm(t *testing.T) {
defer resetMocks()
osStat = func(_ string) (os.FileInfo, error) { return nil, os.ErrNotExist }
installNpmPackage("@scope/pkg")
if !hasIssueContaining("NVM is not installed") {
t.Error("expected NVM-missing error")
}
}
func TestInstallNpmPackageShellFail(t *testing.T) {
defer resetMocks()
osStat = func(_ string) (os.FileInfo, error) { return nil, nil }
runShell = func(_ string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 1} }
installNpmPackage("@scope/pkg")
if !hasIssueContaining("installation failed") {
t.Error("expected install failure error")
}
}
func TestInstallPlaywrightBrowsersNonApt(t *testing.T) {
defer resetMocks()
pkgMgr = "dnf"
called := false
runShell = func(cmd string, _ CmdOpts) CmdResult {
called = strings.Contains(cmd, "pnpx playwright install")
if strings.Contains(cmd, "--with-deps") {
t.Errorf("did not expect --with-deps on non-apt, got: %q", cmd)
}
return CmdResult{ExitCode: 0}
}
installPlaywrightBrowsers()
if !called {
t.Error("expected pnpx playwright install call")
}
}
func TestInstallPlaywrightBrowsersFail(t *testing.T) {
defer resetMocks()
pkgMgr = "dnf"
runShell = func(_ string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 1} }
installPlaywrightBrowsers()
if !hasErrors() {
t.Error("expected error on browser install failure")
}
}
func TestInstallPlaywrightNoNvm(t *testing.T) {
defer resetMocks()
osStat = func(_ string) (os.FileInfo, error) { return nil, os.ErrNotExist }
installPlaywright()
if !hasIssueContaining("NVM is not installed") {
t.Error("expected NVM error")
}
}
func TestInstallPlaywrightAddFails(t *testing.T) {
defer resetMocks()
osStat = func(_ string) (os.FileInfo, error) { return nil, nil }
calls := 0
runShell = func(_ string, _ CmdOpts) CmdResult {
calls++
// ensureNodeLTS issues a series of shell calls; fail the pnpm add step.
// Easiest: just fail everything that contains "pnpm add -g playwright".
return CmdResult{ExitCode: 0}
}
runShell = func(cmd string, _ CmdOpts) CmdResult {
if strings.Contains(cmd, "pnpm add -g playwright") {
return CmdResult{ExitCode: 1}
}
return CmdResult{ExitCode: 0}
}
installPlaywright()
if !hasIssueContaining("playwright installation failed") {
t.Errorf("expected playwright install failure, issues: %v", issuesSnapshot())
}
}
func TestInstallPipPython3Missing(t *testing.T) {
defer resetMocks()
hasCmd = func(_ string) bool { return false }
installPip()
if !hasIssueContaining("python3 is not installed") {
t.Error("expected python3-missing error")
}
}
func TestInstallPipDecimalFixFails(t *testing.T) {
defer resetMocks()
pkgMgr = "apt-get"
hasCmd = func(_ string) bool { return true }
// Decimal probe fails both before and after attempted fix.
probe = func(_ []string, _ time.Duration) (CmdResult, bool) {
return CmdResult{ExitCode: 1}, true
}
runCmd = func(_ []string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 0} }
installPip()
if !hasIssueContaining("_decimal C extension could not be fixed") {
t.Error("expected decimal-fix error")
}
}
func TestInstallPipEnsurepipFailApt(t *testing.T) {
defer resetMocks()
pkgMgr = "apt-get"
hasCmd = func(_ string) bool { return true }
probe = func(_ []string, _ time.Duration) (CmdResult, bool) {
return CmdResult{ExitCode: 0}, true
}
calls := 0
runCmd = func(argv []string, _ CmdOpts) CmdResult {
calls++
// ensurepip is the first runCmd call → fail it.
if calls == 1 {
return CmdResult{ExitCode: 1}
}
return CmdResult{ExitCode: 0}
}
installPip()
// Should attempt fallback `apt-get install python3-pip`.
}
func TestInstallPipEnsurepipFailUnknownMgr(t *testing.T) {
defer resetMocks()
pkgMgr = "brew"
hasCmd = func(_ string) bool { return true }
probe = func(_ []string, _ time.Duration) (CmdResult, bool) {
return CmdResult{ExitCode: 0}, true
}
runCmd = func(_ []string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 1} }
installPip()
if !hasIssueContaining("ensurepip failed") {
t.Error("expected ensurepip-failure error on unknown pkgmgr")
}
}
func TestEnsureZshDefaultNoZsh(t *testing.T) {
defer resetMocks()
hasCmd = func(_ string) bool { return false }
ensureZshDefault()
if !hasIssueContaining("zsh not installed") {
t.Error("expected zsh-missing warning")
}
}
func TestEnsureZshDefaultRHEL(t *testing.T) {
defer resetMocks()
hasCmd = func(_ string) bool { return true }
probe = func(_ []string, _ time.Duration) (CmdResult, bool) {
return CmdResult{ExitCode: 0, Stdout: []byte("/bin/zsh\n")}, true
}
isRHELFamily = true
tmpDir := t.TempDir()
passwdPath = filepath.Join(tmpDir, "passwd")
t.Setenv("SUDO_USER", "testuser")
// Real getpwnam will fail for "testuser" — that's fine, we just want
// to exercise the RHEL branch up to the user lookup.
ensureZshDefault()
}
func TestEnsureZshDefaultAlreadyZsh(t *testing.T) {
defer resetMocks()
hasCmd = func(_ string) bool { return true }
probe = func(_ []string, _ time.Duration) (CmdResult, bool) {
return CmdResult{ExitCode: 0, Stdout: []byte("/bin/zsh\n")}, true
}
t.Setenv("SUDO_USER", os.Getenv("USER"))
if u := os.Getenv("USER"); u == "" {
t.Skip("USER env not set; cannot test")
}
tmp := t.TempDir()
passwdPath = filepath.Join(tmp, "passwd")
// Write a passwd entry that says the user's shell is already zsh.
uid := fmt.Sprintf("%d", os.Getuid())
entry := fmt.Sprintf("%s:x:%s:0::/home/%s:/bin/zsh\n", os.Getenv("USER"), uid, os.Getenv("USER"))
os.WriteFile(passwdPath, []byte(entry), 0o644)
ensureZshDefault()
}
func TestEnsureZshDefaultChshFails(t *testing.T) {
defer resetMocks()
hasCmd = func(_ string) bool { return true }
probe = func(_ []string, _ time.Duration) (CmdResult, bool) {
return CmdResult{ExitCode: 0, Stdout: []byte("/bin/zsh\n")}, true
}
t.Setenv("SUDO_USER", os.Getenv("USER"))
if os.Getenv("USER") == "" {
t.Skip("USER env not set")
}
tmp := t.TempDir()
passwdPath = filepath.Join(tmp, "passwd")
uid := fmt.Sprintf("%d", os.Getuid())
entry := fmt.Sprintf("%s:x:%s:0::/home/%s:/bin/bash\n", os.Getenv("USER"), uid, os.Getenv("USER"))
os.WriteFile(passwdPath, []byte(entry), 0o644)
runCmd = func(_ []string, _ CmdOpts) CmdResult { return CmdResult{ExitCode: 1} }
ensureZshDefault()
if !hasIssueContaining("Failed to set default shell") {
t.Error("expected chsh-failure error")
}
}
func TestInvokingUserNoSudo(t *testing.T) {
defer resetMocks()
t.Setenv("SUDO_USER", "")
u := invokingUser()
if u == "" {
t.Error("expected invokingUser to fall back to user.Current()")
}
}
func TestEnsureNodeLTSAlreadyInstalled(t *testing.T) {
defer resetMocks()
osStat = func(_ string) (os.FileInfo, error) { return nil, nil }
runShell = func(cmd string, _ CmdOpts) CmdResult {
if strings.Contains(cmd, "nvm version lts") {
return CmdResult{ExitCode: 0, Stdout: []byte("v20.10.0\n")}
}
return CmdResult{ExitCode: 0}
}
ensureNodeLTS()
}
func TestEnsureNodeLTSInstallFail(t *testing.T) {
defer resetMocks()
osStat = func(_ string) (os.FileInfo, error) { return nil, nil }
runShell = func(cmd string, _ CmdOpts) CmdResult {
if strings.Contains(cmd, "nvm install --lts") {
return CmdResult{ExitCode: 1}