-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Description
$ go version 1.16
Does this issue reproduce with the latest release?
sure
What operating system and processor architecture are you using (go env)?
N/A
What did you do?
if err != nil {
t.Fatalf("explanation: %v", err)
}
Hundreds of times. Maybe thousands by now.
Also, I keep finding helper functions like
func PanicOn(err error) {
if err != nil { panic(err.Error()) }
}
in various other people's code, which all seem focused on the problem of "it is inconvenient to write three lines of code and you might prefer to write one".
What did you expect to see?
I don't know about expected, but it occurs to me: In general, you can't call a function which makes the caller return early, but in the specific case of tests, we actually do have a way to express "return early from this entire test". And you are likely to want to do so fairly often. Extremely often, even.
Obviously, I can write a helper function that takes all the parameters, but this seems like a case where the reduced verbosity really helps code clarity a lot.
Approximate proposal:
func (t *testing.T) Check(err error, msg string) {
if err != nil {
t.Fatalf("%s: %v", msg, err)
}
}
It's harder to express this as a *f function, like Fatalf, because then the parameter which is The Error is less obvious if you use message-parameter ordering for formatting arguments, and which argument to bind it to is less obvious if you put the parameter first, and if you put it in both places it stutters, but it might be worth trying to get that right.
What did you see instead?
A twisty maze of little test helper functions, all very slightly different and many sort of bad.