From 46942c5042876c63f7632e7967a97a40d8565a4f Mon Sep 17 00:00:00 2001 From: Kartikay Date: Thu, 6 Feb 2025 00:35:09 +0530 Subject: [PATCH] different profiles for tests Signed-off-by: Kartikay --- magefiles/test.go | 4 ++-- magefiles/util.go | 48 +++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/magefiles/test.go b/magefiles/test.go index 231fbca463..330b726753 100644 --- a/magefiles/test.go +++ b/magefiles/test.go @@ -22,7 +22,7 @@ func (t Test) All() error { mg.Deps(t.Unit, t.Integration, t.Steelthread, t.Image, t.Analyzers, ds.Crdb, ds.Postgres, ds.Spanner, ds.Mysql, c.Crdb, c.Spanner, c.Postgres, c.Mysql) - return nil + return combineCoverage() } // UnitCover Runs the unit tests and generates a coverage report @@ -31,7 +31,7 @@ func (t Test) UnitCover() error { return err } fmt.Println("Running coverage...") - return sh.RunV("go", "tool", "cover", "-html=coverage.txt") + return sh.RunV("go", "tool", "cover", "-html=coverage-unit.txt") } // Unit Runs the unit tests diff --git a/magefiles/util.go b/magefiles/util.go index 6c46d0af0b..7a5e58fc5a 100644 --- a/magefiles/util.go +++ b/magefiles/util.go @@ -8,6 +8,7 @@ import ( "log" "os" "os/exec" + "path/filepath" "strings" "github.com/magefile/mage/mg" @@ -24,7 +25,7 @@ func goDirTest(dir string, path string, args ...string) error { testArgs := append([]string{ "test", "-covermode=atomic", - "-coverprofile=coverage.txt", + fmt.Sprintf("-coverprofile=coverage-%s.txt", sanitizePath(path)), "-failfast", "-count=1", }, args...) @@ -35,7 +36,7 @@ func goDirTestWithEnv(dir string, path string, env map[string]string, args ...st testArgs := append([]string{ "test", "-covermode=atomic", - "-coverprofile=coverage.txt", + fmt.Sprintf("-coverprofile=coverage-%s.txt", sanitizePath(path)), "-failfast", "-count=1", }, args...) @@ -222,3 +223,46 @@ func run(dir string, env map[string]string, stdout, stderr io.Writer, cmd string err = c.Run() return sh.CmdRan(err), sh.ExitStatus(err), err } + +func sanitizePath(path string) string { + // Get last meaningful directory from path + parts := strings.Split(strings.TrimPrefix(path, "./"), "/") + for i := len(parts) - 1; i >= 0; i-- { + if parts[i] != "..." && parts[i] != "" { + return strings.ReplaceAll(parts[i], "/", "-") + } + } + return "all" +} + +func combineCoverage() error { + files, err := filepath.Glob("coverage-*.txt") + if err != nil { + return err + } + if len(files) == 0 { + return fmt.Errorf("no coverage files found") + } + + f, err := os.Create("coverage.txt") + if err != nil { + return err + } + defer f.Close() + + args := []string{"run", "github.com/wadey/gocovmerge@latest"} + args = append(args, files...) + + err = RunSh(goCmdForTests(), WithV(), WithStdout(f))(args...) + if err != nil { + return err + } + + for _, file := range files { + if err := os.Remove(file); err != nil { + return err + } + } + + return nil +}