In `go test`, is it possible to pass custom flags?

70 views Asked by At

As far as I tested, go test -- <custom flag(s)> works but I couldn't find any documentation for it.


I have this test code:

package main

import (
    "os"
    "testing"
)

var isVerbose = false

func init() {
    for _, flag := range os.Args {
        if flag == "-my-verbose" {
            isVerbose = true
        }
    }
}

func Test_1(t *testing.T) {
    if isVerbose {
        t.Log("hello")
    }
    t.Log("world")
}

The output is this:

$ go test . -v
=== RUN   Test_1
    main_test.go:22: world
--- PASS: Test_1 (0.00s)
PASS
ok      a   0.137s
$ go test . -v -- -my-verbose
=== RUN   Test_1
    main_test.go:20: hello
    main_test.go:22: world
--- PASS: Test_1 (0.00s)
PASS
ok      a   0.140s

Is this -- <custom flag(s)> syntax guaranteed to work always? I greped go help build, go help test and go help testflag to find the string -- to no avail.

1

There are 1 answers

0
Mac Lawson On

While it might not be documented, the -- delimiter to pass custom flags to test commands in Go is a pretty standard practice.

In your case, go test . -v -- -my-verbose works because anything after -- is treated as arguments to the test binary, rather than options to go test. So, your test binary (main_test.go in this case) can interpret -my-verbose as a custom flag.