Skip to content

Commit

Permalink
feat(gotools): ✨ gotestsum command now works and allows passing path
Browse files Browse the repository at this point in the history
- This tool is great for CI as it captures the output to artifacts for coverage and junit format.
- Resolved the issues with it running by removing the quotes for the packages path, as this is a shell need not required in Go.
  • Loading branch information
sheldonhull committed Mar 25, 2022
1 parent 55eac5a commit 1cebe84
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 76 deletions.
1 change: 1 addition & 0 deletions .tool-versions
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mage 1.13.0
1 change: 1 addition & 0 deletions .tools/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ import (
_ "github.com/sheldonhull/magetools/gotools" // Gotools contains tasks for setting up tooling with standard gofumpt, testing output, and setup of standard gopls tooling.
_ "github.com/sheldonhull/magetools/licensing" // Licensing is a tool for generating license audit capture.
_ "github.com/sheldonhull/magetools/tooling" // Tooling has helpers to do low noise updates on actions like go install, go mod tidy, using pterm spinners.
_ "golang.org/x/sync/errgroup" // errgroup is a Go library for managing multiple tasks and wait for them to complete. Used by gotestsum right now.
)
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# magetools

![Coverage](https://img.shields.io/badge/Coverage-53.9%25-yellow)
![Coverage](https://img.shields.io/badge/Coverage-50.9%25-yellow)

General tooling helpers for simplifying cross repository automation using Mage.

Expand Down
87 changes: 70 additions & 17 deletions gotools/gotools.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"os"
"path/filepath"
"runtime"
"strings"

"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
Expand Down Expand Up @@ -53,7 +54,7 @@ const (
var toolList = []string{ //nolint:gochecknoglobals // ok to be global for tooling setup

// build tools
"github.com/goreleaser/[email protected]",
"github.com/goreleaser/[email protected]", // NOTE: 2022-03-25: latest results in error with undefined: strings.Cut note: module requires Go 1.18 WHEN BUILDING FROM SOURCE
"github.com/dustinkirkland/golang-petname/cmd/petname@latest",
"github.com/AlexBeauchemin/gobadge@latest", // create a badge for your markdown from the coverage files.
// linting tools
Expand Down Expand Up @@ -147,9 +148,19 @@ func (Go) Test() error {
return nil
}

// 🧪 Run gotestsum.
func (Go) TestSum() error {
// 🧪 Run gotestsum (Params: Path just like you pass to go test, ie ./..., pkg/, etc ).
// If gotestsum is not installed, it will install it.
//
// - Test outputs junit, json, and coverfiles.
//
// - Test shuffles and adds race flag.
//
// - Test running manually like this from current repo: GOTEST_DISABLE_RACE=1 mage -d magefiles -w . -v go:testsum ./pkg/...
//
//nolint:funlen,cyclop // Not refactoring this right now, it works and that's what matters ;-)
func (Go) TestSum(path string) error {
magetoolsutils.CheckPtermDebug()
pterm.DefaultHeader.Println("GOTESTSUM")
appgotestsum := "gotestsum"
gotestsum, err := req.ResolveBinaryByInstall(appgotestsum, "gotest.tools/gotestsum@latest")
if err != nil {
Expand All @@ -165,37 +176,79 @@ func (Go) TestSum() error {
if testFlags != "" {
pterm.Info.Printf("GOTEST_FLAGS provided: %q\n", testFlags)
}
raceflag := "-race"
if os.Getenv("GOTEST_DISABLE_RACE") == "1" {
pterm.Debug.Println("Not running with race conditions per GOTEST_DISABLE_RACE provided")
raceflag = ""
}
// The artifact directory will atttempt to be set to the environment variable: BUILD_ARTIFACTSTAGINGDIRECTORY, but if it isn't set then it will default to .artifacts, which should be excluded in gitignore.
var artifactDir string
var ok bool
artifactDir, ok = os.LookupEnv("BUILD_ARTIFACTSTAGINGDIRECTORY")
if !ok {
artifactDir = ".artifacts"
}
pterm.Info.Printfln("test artifacts will be dropped in: %s", artifactDir)
junitFile := filepath.Join(artifactDir, "junit.xml")
jsonFile := filepath.Join(artifactDir, "gotest.json")
coverfile := filepath.Join(artifactDir, "cover.out")
if err := os.MkdirAll(artifactDir, os.FileMode(0o755)); err != nil { //nolint: gomnd // gomnd, acceptable per permissions
return err
}
additionalGoArgs := []string{}
additionalGoArgs = append(additionalGoArgs, "--format")
additionalGoArgs = append(additionalGoArgs, "pkgname")
additionalGoArgs = append(additionalGoArgs, "--junitfile "+junitFile)
additionalGoArgs = append(additionalGoArgs, "--jsonfile "+jsonFile)
additionalGoArgs = append(additionalGoArgs, fmt.Sprintf("--packages=%s", path))

additionalGoArgs = append(additionalGoArgs, "--")
additionalGoArgs = append(additionalGoArgs, "-coverpkg=./...")
// additionalGoArgs = append(additionalGoArgs, "-covermode atomic")
additionalGoArgs = append(additionalGoArgs, "-coverprofile="+coverfile)
additionalGoArgs = append(additionalGoArgs, "-shuffle=on")
additionalGoArgs = append(additionalGoArgs, raceflag)
additionalGoArgs = append(additionalGoArgs, vflag)
additionalGoArgs = append(additionalGoArgs, testFlags)

// Trim out any empty args
cleanedGoArgs := make([]string, 0)
for i := range additionalGoArgs {
pterm.Debug.Printfln("additionalGoArgs[%d]: %q", i, additionalGoArgs[i])
trimmedString := strings.TrimSpace(additionalGoArgs[i])
if trimmedString == "" {
pterm.Debug.Printfln("[SKIP] empty string[%d]: %q", i, trimmedString)
continue
}
cleanedGoArgs = append(cleanedGoArgs, trimmedString)
pterm.Debug.Printfln("cleanedGoArgs[%d]: %q", i, trimmedString)
}
pterm.Debug.Printfln("final arguments for gotestsum: %+v", cleanedGoArgs)
pterm.Info.Println("Running go test")
if err := sh.RunV("gotestsum",
"--format", "pkgname",
"--junitfile", junitFile,
"--jsonfile", jsonFile,
"--",

"-coverpkg=./...",
fmt.Sprintf("-coverprofile=%s", coverfile),
"-covermode", "atomic",
"-shuffle=on",
"-race",
vflag,
testFlags,
"./...",

// cmd := exec.Command("gotestsum", cleanedGoArgs...)
// cmd.Env = append([]string{}, os.Environ()...)
// cmd.Env = append(cmd.Env, "NODE_ENV=acceptance")
if err := sh.RunV(
gotestsum,
cleanedGoArgs...,
); err != nil {
if strings.Contains(err.Error(), "race") {
pterm.Warning.Println(
"If your package doesn't support race conditions, then add:\n\nGOTEST_DISABLE_RACE=1 mage go:testsum\n\nThis will remove the -race flag.",
)
}

return err
}
// // strings.Join(cleanedGoArgs, " "),
// ); err != nil {
// return err
// }
// if err := cmd.Run(); err != nil {
// return err
// }

pterm.Success.Println("✅ gotestsum")
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion gotools/gotools_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func ExampleGo_TestSum() {
// t.Skip("GOTESTS should include 'slow' to run this test")
}
// Running as mage task
if err := (gotools.Go{}.TestSum()); err != nil {
if err := (gotools.Go{}.TestSum("pkg")); err != nil {
pterm.Error.Printf("ExampleGo_TestSum: %v\n", err)
}

Expand Down
14 changes: 0 additions & 14 deletions mage.go

This file was deleted.

36 changes: 0 additions & 36 deletions magefile.go

This file was deleted.

17 changes: 10 additions & 7 deletions .tasks/tasks.go → magefiles/mage.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//go:build mage

// ⚡ Core Mage Tasks
package tasks
package main

import (
"os"
Expand All @@ -11,12 +13,17 @@ import (

// mage:import
"github.com/sheldonhull/magetools/gotools"

// mage:import
_ "github.com/sheldonhull/magetools/gittools" // gotools provides Git tooling to install git town and bit.

// mage:import
_ "github.com/sheldonhull/magetools/licensing" // licensing provides a license checker and vendor tooling for the project
)

// Default target to run when none is specified
// If not set, running mage will list available targets
// var Default = Build.
const ptermMargin = 10

// artifactDirectory is a directory containing artifacts for the project and shouldn't be committed to source.
const artifactDirectory = ".artifacts"
Expand Down Expand Up @@ -50,7 +57,7 @@ func createDirectories() error {
}

// Init runs multiple tasks to initialize all the requirements for running a project for a new contributor.
func Init() error {
func Init() { //nolint:deadcode // This is not dead code, and I find this insulting golangci-lint.
fancy.IntroScreen(ci.IsCI())
pterm.Success.Println("running Init()...")

Expand All @@ -60,10 +67,6 @@ func Init() error {
gotools.Go{}.Init,
// tooling.SilentInstallTools(toolList),
)
// if err := (gotools.Go{}.Init()); err != nil {
// return err
// }
return nil
}

// Clean up after yourself.
Expand Down

0 comments on commit 1cebe84

Please sign in to comment.