Skip to content

Instantly share code, notes, and snippets.

@epelc
Created February 10, 2016 03:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save epelc/02011f31bd7e227de1c8 to your computer and use it in GitHub Desktop.
Save epelc/02011f31bd7e227de1c8 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 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.
var testFlags []string
for i := 0; i < len(os.Args); i++ {
if strings.HasPrefix(os.Args[i], "-test.") {
// Add the test flag to our testing flags slice so we can parse it seperatly
testFlags = append(testFlags, os.Args[i])
// Remove the test flag from our pflags slice
os.Args = append(os.Args[:i], os.Args[i+1:]...)
// go back one as we just deleted an element
i--
}
}
// 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