github.com/Songmu/gocredits@v0.3.1-0.20231111084238-af961788d757/gocredits_test.go (about) 1 package gocredits 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "os/exec" 8 "path/filepath" 9 "reflect" 10 "testing" 11 ) 12 13 func TestLicenseDirs_set(t *testing.T) { 14 ld := &licenseDirs{} 15 ld.set(&licenseDir{ 16 name: "test", 17 version: "v0.1.2", 18 }) 19 ld.set(&licenseDir{ 20 name: "test", 21 version: "v0.1.3", 22 }) 23 24 if len(ld.names) != 1 { 25 t.Errorf("len(ld.names) should be 1 but: %d", len(ld.names)) 26 } 27 28 if len(ld.dirs["test"]) != 2 { 29 t.Errorf("len(ld.dirs[test]) should be 2 but: %d", len(ld.dirs["test"])) 30 } 31 } 32 33 func TestTakeCredits(t *testing.T) { 34 tmpd, err := ioutil.TempDir("", "gocredits-") 35 if err != nil { 36 t.Fatal(err) 37 } 38 origCache := os.Getenv("GOCACHE") 39 os.Setenv("GOCACHE", tmpd) 40 defer os.Setenv("GOCACHE", origCache) 41 42 wd, err := os.Getwd() 43 if err != nil { 44 t.Fatal(err) 45 } 46 47 if err := os.Chdir(tmpd); err != nil { 48 t.Fatal(err) 49 } 50 cmd := exec.Command("go", "install", "github.com/Songmu/gocredits/cmd/gocredits@v0.1.0") 51 if err := cmd.Run(); err != nil { 52 t.Fatal(err) 53 } 54 55 if err := os.Chdir(wd); err != nil { 56 t.Fatal(err) 57 } 58 59 tests := []struct { 60 name string 61 dir string 62 skipMissing bool 63 wantErr error 64 }{ 65 {"go.sum only", "gosum_only", false, nil}, 66 {"go.mod only", "gomod_only", false, nil}, 67 {"there is neither go.mod nor go.sum", "no_gomod_no_gosum", false, fmt.Errorf("use go modules")}, 68 {"gocredits can't fild the license", "no_license", false, fmt.Errorf("could not find the license for \"github.com/Songmu/no_license_pkg\"")}, 69 {"gocredits can't fild the license. but skip", "no_license", true, nil}, 70 } 71 for _, tt := range tests { 72 dir := filepath.Join(testdataDir(t), tt.dir) 73 _, gotErr := takeCredits(dir, tt.skipMissing) 74 if !reflect.DeepEqual(gotErr, tt.wantErr) { 75 t.Errorf("%s:\ngot %v\nwant %v", tt.name, gotErr, tt.wantErr) 76 } 77 } 78 } 79 80 func testdataDir(t *testing.T) string { 81 t.Helper() 82 wd, err := os.Getwd() 83 if err != nil { 84 t.Fatal(err) 85 } 86 dir, err := filepath.Abs(filepath.Join(wd, "testdata")) 87 if err != nil { 88 t.Fatal(err) 89 } 90 return dir 91 }