go test
refuses to build when a call to a function in the library to be tested by design contains a formatting directive. Is this intentional or is this a bug? Either way, is there a workaround?
Please note, unlike Call has possible formatting directive, this is not a call to a built-in function that doesn't accept formatting directives. It is a call to a function that I wrote and which is specifically designed to accept formatting directives.
Here is a contrived but complete reproduction. Note makeError
is designed to handle a format string. go build
works fine, but go test
produces the following error and does not run any tests:
.\example.go:16:13: makeError call has possible formatting directive %v
FAIL sandbox/example [build failed]
go version: go version go1.12.7 windows/amd64
example.go
:
package example
import "fmt"
type ErrExample struct {
data interface{}
msg string
}
func (e *ErrExample) Error() string {
return e.msg
}
func Divide(f1 float64, f2 float64) (float64, error) {
if f2 == 0.0 {
return 0, makeError(nil, "Cannot divide %v by 0", f1)
}
return f1 / f2, nil
}
func makeError(data interface{}, msgAndArgs ...interface{}) error {
msg := ""
switch len(msgAndArgs) {
case 0:
// Ignore
case 1:
msg = fmt.Sprint(msgAndArgs[0])
default:
if str, ok := msgAndArgs[0].(string); ok {
msg = fmt.Sprintf(str, msgAndArgs[1:]...)
}
msg = fmt.Sprint(msgAndArgs...)
}
return &ErrExample{data: data, msg: msg}
}
example_test.go
:
package example
import (
"testing"
)
func TestDivide(t *testing.T) {
_, err := Divide(1230, 0)
if err == nil {
t.Errorf("Expected error when dividing by 0")
}
}