Check for `t.Error(fmt.Sprintf(...))` where t is a *testing.T.
Suggest replacing it with `t.Errorf(...)`.
Fixes #115.
Signed-off-by: David Symonds <dsymonds@golang.org>
diff --git a/lint.go b/lint.go
index 66fc69f..5749484 100644
--- a/lint.go
+++ b/lint.go
@@ -1038,14 +1038,17 @@
})
}
-// lintErrorf examines errors.New calls. It complains if its only argument is an fmt.Sprintf invocation.
+// lintErrorf examines errors.New and testing.Error calls. It complains if its only argument is an fmt.Sprintf invocation.
func (f *file) lintErrorf() {
f.walk(func(node ast.Node) bool {
ce, ok := node.(*ast.CallExpr)
- if !ok {
+ if !ok || len(ce.Args) != 1 {
return true
}
- if !isPkgDot(ce.Fun, "errors", "New") || len(ce.Args) != 1 {
+ isErrorsNew := isPkgDot(ce.Fun, "errors", "New")
+ se, ok := ce.Fun.(*ast.SelectorExpr)
+ isTestingError := ok && se.Sel.Name == "Error" && f.pkg.typeOf(se.X).String() == "*testing.T"
+ if !isErrorsNew && !isTestingError {
return true
}
arg := ce.Args[0]
@@ -1053,7 +1056,11 @@
if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") {
return true
}
- f.errorf(node, 1, category("errors"), "should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...)")
+ errorfPrefix := "fmt"
+ if isTestingError {
+ errorfPrefix = f.render(se.X)
+ }
+ f.errorf(node, 1, category("errors"), "should replace %s(fmt.Sprintf(...)) with %s.Errorf(...)", f.render(se), errorfPrefix)
return true
})
}
diff --git a/testdata/errorf.go b/testdata/errorf.go
index 2d26721..5a7efeb 100644
--- a/testdata/errorf.go
+++ b/testdata/errorf.go
@@ -1,4 +1,4 @@
-// Test for not using fmt.Errorf.
+// Test for not using fmt.Errorf or testing.Errorf.
// Package foo ...
package foo
@@ -6,6 +6,7 @@
import (
"errors"
"fmt"
+ "testing"
)
func f(x int) error {
@@ -21,4 +22,19 @@
return nil
}
+// TestF is a dummy test
+func TestF(t *testing.T) error {
+ x := 1
+ if x > 10 {
+ return t.Error(fmt.Sprintf("something %d", x)) // MATCH /should replace.*t\.Error\(fmt\.Sprintf\(\.\.\.\)\).*t\.Errorf\(\.\.\.\)/
+ }
+ if x > 5 {
+ return t.Error(g("blah")) // ok
+ }
+ if x > 4 {
+ return t.Error("something else") // ok
+ }
+ return nil
+}
+
func g(s string) string { return "prefix: " + s }