-
Notifications
You must be signed in to change notification settings - Fork 17.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: testing: add Setargs to set os.Args #63607
Comments
Normally we just make a helper function and then test that, like so: func ParseArgs() {
parseArgs(os.Args)
}
func parseArgs(args []string) {
...
} func TestParseArgs(t *testing.T) {
parseArgs([]string{ ... })
} |
That works when the function uses |
I see https://pkg.go.dev/testing#T.Setenv and #62516 at a different level as this proposal, because rewriting one's code to avoid relying on the global state is non-trivial. For example, there's no easy type to replace environment variables with; there's
|
Also logging packages can use, to extract for example command line used. |
In general you can already test CLI parsing in a couple of ways:
|
The main reason to set an environment variable in a test is that either (1) some code checks the environment variable directly, or (2) some code runs a subprocess that inherits the environment (rather than creating its own custom one for the exec) and that subprocess needs the variable. Neither of these applies to os.Args. Normal functions don't read from os.Args, and os.Args is not inherited by exec. This seems like significant complexity and an implicit suggestion that code should be doing things that it really should not be doing. |
This proposal has been added to the active column of the proposals project |
I see many arguments against it. I will then retract this proposal. In my own project I ended up simply having a bash script provide sets of arguments and checking exit codes each time. While using Coverage profiling support for integration tests to obtain coverage. |
This proposal has been declined as retracted. |
os.Args
is similar toos.Getenv
that it is a global state of the process.testing
package provides a functionSetenv
onT
which tries to help tests which use environment variables:Currently, nothing similar exist for
os.Args
. But sometimes it is necessary to do so to be able to test CLI parsing (especially in tools which expect to read fromos.Args
. Current option to do the change toos.Args
yourself and then restore it has a downside that it does not check ift.Parallel
has been called.I understand that global state is tricky, but making a function which checks for parallel execution could help here.
The text was updated successfully, but these errors were encountered: