From 09870c18716d94dd75898157e2fd77078b2a7f6b Mon Sep 17 00:00:00 2001 From: Anton Telyshev Date: Mon, 27 May 2024 20:50:44 +0300 Subject: [PATCH] helpers: isError: strict type comparison instead of implementing check (#97) --- analyzer/analyzer_test.go | 4 +++ .../mixed_struct_type_test.go | 33 +++++++++++++++++++ internal/checkers/helpers_error.go | 2 +- 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 analyzer/testdata/src/error-nil-issue95/mixed_struct_type_test.go diff --git a/analyzer/analyzer_test.go b/analyzer/analyzer_test.go index 6aadf6bc..aaf0996c 100644 --- a/analyzer/analyzer_test.go +++ b/analyzer/analyzer_test.go @@ -41,6 +41,10 @@ func TestTestifyLint(t *testing.T) { dir: "error-as-target", flags: map[string]string{"disable-all": "true", "enable": checkers.NewErrorIsAs().Name()}, }, + { + dir: "error-nil-issue95", + flags: map[string]string{"disable-all": "true", "enable": checkers.NewErrorNil().Name()}, + }, { dir: "expected-var-custom-pattern", flags: map[string]string{ diff --git a/analyzer/testdata/src/error-nil-issue95/mixed_struct_type_test.go b/analyzer/testdata/src/error-nil-issue95/mixed_struct_type_test.go new file mode 100644 index 00000000..15f23004 --- /dev/null +++ b/analyzer/testdata/src/error-nil-issue95/mixed_struct_type_test.go @@ -0,0 +1,33 @@ +package errornilissue95 + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// APIResponse can be an error or not. +type APIResponse struct { + Status int + Data string + ErrorMsg string +} + +func (a APIResponse) Error() string { + return a.ErrorMsg +} + +func Update(a string) (*APIResponse, error) { + if a == "a" { + return &APIResponse{Status: 200, Data: "fake"}, nil + } + + return nil, &APIResponse{Status: 500, ErrorMsg: "Oops"} +} + +func TestName(t *testing.T) { + resp, err := Update("b") + require.Error(t, err, new(*APIResponse)) + assert.Nil(t, resp) +} diff --git a/internal/checkers/helpers_error.go b/internal/checkers/helpers_error.go index ce5e918b..55cd5fd0 100644 --- a/internal/checkers/helpers_error.go +++ b/internal/checkers/helpers_error.go @@ -16,7 +16,7 @@ var ( ) func isError(pass *analysis.Pass, expr ast.Expr) bool { - return implements(pass, expr, errorObj) + return pass.TypesInfo.TypeOf(expr) == errorType } func isErrorsIsCall(pass *analysis.Pass, ce *ast.CallExpr) bool {