github.com/jd-ly/tools@v0.5.7/internal/imports/mod_cache_test.go (about) 1 package imports 2 3 import ( 4 "fmt" 5 "reflect" 6 "sort" 7 "testing" 8 ) 9 10 func TestDirectoryPackageInfoReachedStatus(t *testing.T) { 11 tests := []struct { 12 info directoryPackageInfo 13 target directoryPackageStatus 14 wantStatus bool 15 wantError bool 16 }{ 17 { 18 info: directoryPackageInfo{ 19 status: directoryScanned, 20 err: nil, 21 }, 22 target: directoryScanned, 23 wantStatus: true, 24 }, 25 { 26 info: directoryPackageInfo{ 27 status: directoryScanned, 28 err: fmt.Errorf("error getting to directory scanned"), 29 }, 30 target: directoryScanned, 31 wantStatus: true, 32 wantError: true, 33 }, 34 { 35 info: directoryPackageInfo{}, 36 target: directoryScanned, 37 wantStatus: false, 38 }, 39 } 40 41 for _, tt := range tests { 42 gotStatus, gotErr := tt.info.reachedStatus(tt.target) 43 if gotErr != nil { 44 if !tt.wantError { 45 t.Errorf("unexpected error: %s", gotErr) 46 } 47 continue 48 } 49 50 if tt.wantStatus != gotStatus { 51 t.Errorf("reached status expected: %v, got: %v", tt.wantStatus, gotStatus) 52 } 53 } 54 } 55 56 func TestModCacheInfo(t *testing.T) { 57 m := &dirInfoCache{ 58 dirs: make(map[string]*directoryPackageInfo), 59 } 60 61 dirInfo := []struct { 62 dir string 63 info directoryPackageInfo 64 }{ 65 { 66 dir: "mypackage", 67 info: directoryPackageInfo{ 68 status: directoryScanned, 69 dir: "mypackage", 70 nonCanonicalImportPath: "example.com/mypackage", 71 }, 72 }, 73 { 74 dir: "bad package", 75 info: directoryPackageInfo{ 76 status: directoryScanned, 77 err: fmt.Errorf("bad package"), 78 }, 79 }, 80 { 81 dir: "mypackage/other", 82 info: directoryPackageInfo{ 83 dir: "mypackage/other", 84 nonCanonicalImportPath: "example.com/mypackage/other", 85 }, 86 }, 87 } 88 89 for _, d := range dirInfo { 90 m.Store(d.dir, d.info) 91 } 92 93 for _, d := range dirInfo { 94 val, ok := m.Load(d.dir) 95 if !ok { 96 t.Errorf("directory not loaded: %s", d.dir) 97 } 98 99 if !reflect.DeepEqual(d.info, val) { 100 t.Errorf("expected: %v, got: %v", d.info, val) 101 } 102 } 103 104 var wantKeys []string 105 for _, d := range dirInfo { 106 wantKeys = append(wantKeys, d.dir) 107 } 108 sort.Strings(wantKeys) 109 110 gotKeys := m.Keys() 111 sort.Strings(gotKeys) 112 113 if len(gotKeys) != len(wantKeys) { 114 t.Errorf("different length of keys. expected: %d, got: %d", len(wantKeys), len(gotKeys)) 115 } 116 117 for i, want := range wantKeys { 118 if want != gotKeys[i] { 119 t.Errorf("%d: expected %s, got %s", i, want, gotKeys[i]) 120 } 121 } 122 }