how do I use go test for code that needs a flag defined in flag package

116 views
Skip to first unread message

Robert Solomon

unread,
May 6, 2023, 9:02:35 AM5/6/23
to golang-nuts

I have a routine that I want to test, that I have to pass a flag into this test.  This is on Win10 using Go 1.20.4.  This code is here:
https://go.dev/play/p/p-YeGDk1KaM

I want to pass a flag I call dots into the test code for this function.  I tried from within the correct directory

    go test --args -dots
or
    go test . --args -dots

Or from the top of my source tree where the go.mod file is :

    go test .\detox --args -dots
    go test .\detox\... --args -dots

I get an error message saying:

flag provided but not defined: -dots.  

But that flag does show up when I run the program using the -h flag, and it works when not in go test mode.
The full pgm is in the link above.

What am I missing?

--rob solomon

PS: a stackoverflow question that's similar to this, from 2014, does not work for me.

Brian Candler

unread,
May 6, 2023, 11:24:11 AM5/6/23
to golang-nuts
Your code is incomplete (it's missing all the imports), and "go test" doesn't run your main() function anyway, so it's not going to parse the flags.

But otherwise I think it would be something like this: (single dash, -args not --args)

go test . -v -args - -dots


Robert Solomon

unread,
May 6, 2023, 3:45:10 PM5/6/23
to golang-nuts
Looks like I didn't copy everything I have to the playground.  But I do have the correct imports and the top statement, package main.

Thank you for answering, that's working.

--rob solomon

Robert Solomon

unread,
May 6, 2023, 4:03:59 PM5/6/23
to golang-nuts
A related issue:
Now that I can run go test and it's running, how do I define the flag.  Currently, I define it in main(), and also the flag.Parse() is in main().
But main() is not run in go test, so I tried putting flag.BoolVar() and flag.Parse() in an init() function, but that doesn''t work either.

How do I test the operations of the flag package when running go test?

Jason Phillips

unread,
May 6, 2023, 4:32:57 PM5/6/23
to golang-nuts
The testing package documentation mentions this case explicitly:

In short, you can define a main function (called TestMain) for your test package and call flag.Parse from there.

Robert Solomon

unread,
May 6, 2023, 4:50:16 PM5/6/23
to golang-nuts
thank you

Brian Candler

unread,
May 7, 2023, 3:38:21 AM5/7/23
to golang-nuts
Since the CLI parsing sets global variables which affect how your code operates, you can just set those variables directly in your test functions.

func TestWithDots(t *testing.T) {
    noDotsFlag = false
    ...
}

func TestWithNoDots(t *testing.T) {
    noDotsFlag = true
    ...
}

Reply all
Reply to author
Forward
0 new messages