Created
February 10, 2016 03:56
-
-
Save epelc/02011f31bd7e227de1c8 to your computer and use it in GitHub Desktop.
Use pflags and regular `go test` flags in your tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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