I am using a flag when testing in go:
file_test.govar ip = flag.String("ip", "noip", "test")
I am only using this in one test file. And it works fine when only testing that one test file, but when I run:go test ./... -ip 127.0.0.1
all of the other test files saying:flag provided but not defined
.
Have you seen this?
Regards
6 Answers6
flag.Parse()
is being called before your flag is defined.
You have to make sure that all flag definitions happen before callingflag.Parse()
, usually by defining all flags insideinit()
functions.
4 Comments
go test
on the./...
wildcard. That's not a single test run, it's testing every matching package in succession. Simply don't use./...
and test the packages you want to test.If you've migrated to golang 13, it changed the order of the test initializer,so it could lead to something like
flag provided but not defined: -test.timeout
as a possible workaround, you can use
var _ = func() bool { testing.Init() return true}()
that would call test initialization before the application one. More info can be found on the original thread:
https://github.com/golang/go/issues/31859#issuecomment-489889428
Comments
I'm very late to the party; but is this broken (again) on Go 1.19.5?
I hit the same errors reported on this thread and the same solution reported above (https://github.com/golang/go/issues/31859#issuecomment-489889428) fixes it.
I see a call toflags.Parse()
was added back ingo_test.go
inv1.18
I am only just learning Go so it'd be nice to have some verification from people more skilled before I report this elsewhere.
Comments
Do not callflag.Parse()
in anyinit()
method
3 Comments
init()
as well. However, using init to do things makes testing difficult, and you're better off using a helper function off of main to do this work.If you get this, when running command viadocker-compose
then you do incorrect quoting. Eg.
services: app: ... image: kumina/openvpn-exporter:latest command: [ "--openvpn.status_paths", "/etc/openvpn_exporter/openvpn-status.log", "--openvpn.status_paths /etc/openvpn_exporter/openvpn-status.log", ]
First is correct, second is wrong, because whole line counted as one parameter. You need to split them by passing two separate strings, like in first line.
Comments
You can runflag.Parse()
only one time, check if you are calling another code withflag.Parse()
Comments
Explore related questions
See similar questions with these tags.