From 54a7e02d4dac7d0e85177dee0d3f9b2e806bdbf1 Mon Sep 17 00:00:00 2001 From: Anton Telyshev Date: Sun, 3 Mar 2024 09:55:04 +0300 Subject: [PATCH] go-require: more tests --- analyzer/analyzer_test.go | 4 ++ .../gorequire_requireerror_conflict_test.go | 50 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 analyzer/testdata/src/go-require-issue66/gorequire_requireerror_conflict_test.go diff --git a/analyzer/analyzer_test.go b/analyzer/analyzer_test.go index 2552e5e7..6cd2d2ce 100644 --- a/analyzer/analyzer_test.go +++ b/analyzer/analyzer_test.go @@ -38,6 +38,10 @@ func TestTestifyLint(t *testing.T) { }, }, {dir: "ginkgo"}, + { + dir: "go-require-issue66", + flags: map[string]string{"enable-all": "true"}, + }, { dir: "go-require-issue67", flags: map[string]string{"disable-all": "true", "enable": checkers.NewGoRequire().Name()}, diff --git a/analyzer/testdata/src/go-require-issue66/gorequire_requireerror_conflict_test.go b/analyzer/testdata/src/go-require-issue66/gorequire_requireerror_conflict_test.go new file mode 100644 index 00000000..03ae3036 --- /dev/null +++ b/analyzer/testdata/src/go-require-issue66/gorequire_requireerror_conflict_test.go @@ -0,0 +1,50 @@ +package gorequireissue66 + +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// NOTE(a.telyshev): Neither assert nor require is the best way to test an HTTP handler: +// it leads to redundant stack traces, as well as EOF from the HTTP client. +// Use HTTP mechanisms and place assertions in the main test function. + +var mockHTTPFromFile = func(t *testing.T) http.HandlerFunc { + t.Helper() + + return func(w http.ResponseWriter, _ *http.Request) { + file, err := os.Open("some file.json") + assert.NoError(t, err) // want "require-error: for error assertions use require" + + data, err := io.ReadAll(file) + require.NoError(t, err) + + w.Header().Set("Content-Type", "application/json") + _, err = w.Write(data) + assert.NoError(t, err) + } +} + +func TestGoRequireAndRequireErrorConflict(t *testing.T) { + ts := httptest.NewServer(mockHTTPFromFile(t)) + defer ts.Close() + + client := ts.Client() + + req, err := http.NewRequest("GET", ts.URL+"/example", nil) + assert.NoError(t, err) // want "require-error: for error assertions use require" + + resp, err := client.Do(req) + require.NoError(t, err) + defer func() { + require.NoError(t, resp.Body.Close()) + }() + + assert.Equal(t, http.StatusOK, resp.StatusCode) +}