Skip to content

Instantly share code, notes, and snippets.

@doublerebel
Forked from epelc/your_test.go
Last active March 11, 2024 11:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doublerebel/8b95c5c118e958e495d2 to your computer and use it in GitHub Desktop.
Save doublerebel/8b95c5c118e958e495d2 to your computer and use it in GitHub Desktop.
Use pflags and regular `go test` flags in your tests
package yourpackage
import (
goflag "flag"
"fmt"
"os"
"strings"
"testing"
flag "github.com/spf13/pflag"
)
func filterGoFlags(args []string, prefixes map[string]bool) ([]string, []string) {
var goFlags []string
for i := 0; 0 < len(args) && i < len(args); i++ {
for prefix, hasValue := range prefixes {
if strings.HasPrefix(args[i], "-"+prefix) {
// Add the flag to our goflags slice so we can parse it seperatly
goFlags = append(goFlags, args[i])
skip := 1
// If the flag has a corresponding value, add that too
if hasValue && i+1 < len(args) {
goFlags = append(goFlags, args[i+1])
skip = 2
}
// Remove the go flags from our pflags slice
if i+skip <= len(args) {
args = append(args[:i], args[i+skip:]...)
}
// go back one as we just deleted an element
i--
break
}
}
}
return args, goFlags
}
func TestMain(m *testing.M) {
// We need to split up the test flags and the regular app pflags.
// Then hand them off the the std flags and pflags parsers respectively.
args, testFlags := filterGoFlags(os.Args, map[string]bool{"test.": true})
os.Args = args
// Parse the testing flags
if err := goflag.CommandLine.Parse(testFlags); err != nil {
fmt.Println("Error parsing regular test flags:",err)
}
// Parse our pflags
flag.Parse()
os.Exit(m.Run())
}
// your tests ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment