github.com/please-build/puku@v1.7.3-0.20240516143641-f7d7f4941f57/sync/integration/syncmod/sync_mod_test.go (about) 1 package syncmod 2 3 import ( 4 "os" 5 "path/filepath" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 "github.com/stretchr/testify/require" 10 "golang.org/x/mod/modfile" 11 12 "github.com/please-build/puku/config" 13 "github.com/please-build/puku/graph" 14 "github.com/please-build/puku/please" 15 "github.com/please-build/puku/sync" 16 ) 17 18 func TestModSync(t *testing.T) { 19 if err := os.Chdir(os.Getenv("DATA_REPO")); err != nil { 20 panic(err) 21 } 22 23 conf, err := config.ReadConfig(".") 24 require.NoError(t, err) 25 26 conf.PleasePath = filepath.Join(os.Getenv("TMP_DIR"), os.Getenv("DATA_PLZ")) 27 28 plzConf, err := please.QueryConfig(conf.GetPlzPath()) 29 require.NoError(t, err) 30 31 g := graph.New(plzConf.BuildFileNames()) 32 err = sync.SyncToStdout("text", plzConf, g) 33 require.NoError(t, err) 34 35 thirdPartyBuildFile, err := g.LoadFile(conf.GetThirdPartyDir()) 36 require.NoError(t, err) 37 38 expectedVers := readModFileVersions() 39 40 // We expect to generate the following for the replace in the go.mod: 41 // go_mod_download( 42 // name = "github.com_peterebden_buildtools_dl", 43 // module = "github.com/peterebden/buildtools", 44 // version = "v1.6.0", 45 // ) 46 // 47 // go_repo( 48 // download = ":github.com_peterebden_buildtools_dl", 49 // module = "github.com/bazelbuild/buildtools", 50 // ) 51 52 for _, repoRule := range thirdPartyBuildFile.Rules("go_repo") { 53 t.Run(repoRule.AttrString("module"), func(t *testing.T) { 54 // Check that we've replaced build tools 55 if repoRule.AttrString("version") == "" { 56 assert.Equal(t, "github.com/bazelbuild/buildtools", repoRule.AttrString("module")) 57 assert.Equal(t, ":github.com_peterebden_buildtools_dl", repoRule.AttrString("download")) 58 return 59 } 60 // All rules start off at v0.0.1 and should be updated to v1.0.0 as per the go.mod 61 assert.Equal(t, expectedVers[repoRule.AttrString("module")], repoRule.AttrString("version")) 62 }) 63 } 64 65 dlRules := thirdPartyBuildFile.Rules("go_mod_download") 66 require.Len(t, dlRules, 1) 67 68 dlRule := dlRules[0] 69 assert.Equal(t, "github.com_peterebden_buildtools_dl", dlRule.Name()) 70 assert.Equal(t, "github.com/peterebden/buildtools", dlRule.AttrString("module")) 71 assert.Equal(t, expectedVers[dlRule.AttrString("module")], dlRule.AttrString("version")) 72 } 73 74 func readModFileVersions() map[string]string { 75 f, err := os.ReadFile("go.mod") 76 if err != nil { 77 panic(err) 78 } 79 80 file, err := modfile.Parse("go.mod", f, nil) 81 if err != nil { 82 panic(err) 83 } 84 85 ret := make(map[string]string) 86 for _, req := range file.Require { 87 ret[req.Mod.Path] = req.Mod.Version 88 } 89 90 for _, replace := range file.Replace { 91 ret[replace.New.Path] = replace.New.Version 92 } 93 return ret 94 }