dongyue934001 2019-08-28 16:10
浏览 146

不能建立测试:呼叫可能包含格式指令

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")
    }
}
  • 写回答

1条回答 默认 最新

  • dtja73027 2019-08-28 16:25
    关注

    From the help text of go test:

    As part of building a test binary, go test runs go vet on the package and its test source files to identify significant problems. If go vet finds any problems, go test reports those and does not run the test binary. Only a high-confidence subset of the default go vet checks are used. That subset is: 'atomic', 'bool', 'buildtags', 'nilfunc', and 'printf'. You can see the documentation for these and other vet tests via "go doc cmd/vet". To disable the running of go vet, use the -vet=off flag."

    评论

报告相同问题?

悬赏问题

  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?