Skip to content

Commit

Permalink
js/k6/http: Fix linter errors
Browse files Browse the repository at this point in the history
  • Loading branch information
codebien authored and mstoykov committed Jan 29, 2024
1 parent 69ce06a commit 2d8104a
Show file tree
Hide file tree
Showing 7 changed files with 30 additions and 23 deletions.
2 changes: 1 addition & 1 deletion js/modules/k6/http/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type FileData struct {
ContentType string
}

var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"") //nolint:gochecknoglobals

func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
Expand Down
4 changes: 2 additions & 2 deletions js/modules/k6/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ func (mi *ModuleInstance) defineConstants() {
mustAddProp("OCSP_REASON_AA_COMPROMISE", netext.OCSP_REASON_AA_COMPROMISE)
}

func (mi *ModuleInstance) newCookieJar(call goja.ConstructorCall) *goja.Object {
func (mi *ModuleInstance) newCookieJar(_ goja.ConstructorCall) *goja.Object {
rt := mi.vu.Runtime()
jar, err := cookiejar.New(nil)
if err != nil {
Expand All @@ -151,7 +151,7 @@ func (mi *ModuleInstance) newCookieJar(call goja.ConstructorCall) *goja.Object {
}

// getVUCookieJar returns the active cookie jar for the current VU.
func (mi *ModuleInstance) getVUCookieJar(call goja.FunctionCall) goja.Value {
func (mi *ModuleInstance) getVUCookieJar(_ goja.FunctionCall) goja.Value {
rt := mi.vu.Runtime()
if state := mi.vu.State(); state != nil {
return rt.ToValue(&CookieJar{mi, state.CookieJar})
Expand Down
19 changes: 12 additions & 7 deletions js/modules/k6/http/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ import (
)

// ErrHTTPForbiddenInInitContext is used when a http requests was made in the init context
var ErrHTTPForbiddenInInitContext = common.NewInitContextError("Making http requests in the init context is not supported")
var ErrHTTPForbiddenInInitContext = common.NewInitContextError(
"Making http requests in the init context is not supported")

// ErrBatchForbiddenInInitContext is used when batch was made in the init context
var ErrBatchForbiddenInInitContext = common.NewInitContextError("Using batch in the init context is not supported")
var ErrBatchForbiddenInInitContext = common.NewInitContextError(
"Using batch in the init context is not supported")

func (c *Client) getMethodClosure(method string) func(url goja.Value, args ...goja.Value) (*Response, error) {
return func(url goja.Value, args ...goja.Value) (*Response, error) {
Expand Down Expand Up @@ -125,7 +127,11 @@ func (c *Client) asyncRequest(method string, url goja.Value, args ...goja.Value)
// a reverse dependency on js/common or goja.
func (c *Client) processResponse(resp *httpext.Response, respType httpext.ResponseType) {
if respType == httpext.ResponseTypeBinary && resp.Body != nil {
resp.Body = c.moduleInstance.vu.Runtime().NewArrayBuffer(resp.Body.([]byte))
b, ok := resp.Body.([]byte)
if !ok {
panic("got an unexpected type for the response body, only []byte is accepted")
}
resp.Body = c.moduleInstance.vu.Runtime().NewArrayBuffer(b)
}
}

Expand Down Expand Up @@ -278,6 +284,7 @@ func (c *Client) parseRequest(
}

// TODO: ditch goja.Value, reflections and Object and use a simple go map and type assertions?
//nolint: nestif
if params != nil && !goja.IsUndefined(params) && !goja.IsNull(params) {
params := params.ToObject(rt)
for _, k := range params.Keys() {
Expand Down Expand Up @@ -333,8 +340,7 @@ func (c *Client) parseRequest(
if goja.IsUndefined(jarV) || goja.IsNull(jarV) {
continue
}
switch v := jarV.Export().(type) {
case *CookieJar:
if v, ok := jarV.Export().(*CookieJar); ok {
result.ActiveJar = v.Jar
}
case "compression":
Expand Down Expand Up @@ -569,8 +575,7 @@ func (c *Client) parseBatchRequest(key interface{}, val interface{}) (*httpext.P

func requestContainsFile(data map[string]interface{}) bool {
for _, v := range data {
switch v.(type) {
case FileData:
if _, ok := v.(FileData); ok {
return true
}
}
Expand Down
8 changes: 3 additions & 5 deletions js/modules/k6/http/request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,7 @@ func TestRequest(t *testing.T) {
logEntry := ts.hook.LastEntry()
require.NotNil(t, logEntry)
assert.Equal(t, logrus.WarnLevel, logEntry.Level)
assert.Contains(t, logEntry.Data["error"].(error).Error(), expErr)
assert.ErrorContains(t, logEntry.Data["error"].(error), expErr) //nolint:forcetypeassert
assert.Equal(t, "Request Failed", logEntry.Message)
})

Expand All @@ -599,7 +599,7 @@ func TestRequest(t *testing.T) {
logEntry := ts.hook.LastEntry()
require.NotNil(t, logEntry)
assert.Equal(t, logrus.WarnLevel, logEntry.Level)
assert.Contains(t, logEntry.Data["error"].(error).Error(), expErr)
assert.ErrorContains(t, logEntry.Data["error"].(error), expErr) //nolint:forcetypeassert
assert.Equal(t, "Request Failed", logEntry.Message)
})
})
Expand Down Expand Up @@ -908,7 +908,6 @@ func TestRequest(t *testing.T) {
assertRequestMetricsEmitted(t, metrics.GetBufferedSamples(samples), "GET", sr("HTTPBIN_URL/cookies"), 200, "")
})

//nolint:paralleltest
t.Run("clear", func(t *testing.T) {
cookieJar, err := cookiejar.New(nil)
assert.NoError(t, err)
Expand All @@ -926,7 +925,6 @@ func TestRequest(t *testing.T) {
assertRequestMetricsEmitted(t, metrics.GetBufferedSamples(samples), "GET", sr("HTTPBIN_URL/cookies"), 200, "")
})

//nolint:paralleltest
t.Run("delete", func(t *testing.T) {
cookieJar, err := cookiejar.New(nil)
assert.NoError(t, err)
Expand Down Expand Up @@ -2010,7 +2008,7 @@ func BenchmarkHandlingOfResponseBodies(b *testing.B) {
`)

testResponseType := func(responseType string) func(b *testing.B) {
testCode := strings.Replace(testCodeTemplate, "TEST_RESPONSE_TYPE", responseType, -1)
testCode := strings.ReplaceAll(testCodeTemplate, "TEST_RESPONSE_TYPE", responseType)
return func(b *testing.B) {
for i := 0; i < b.N; i++ {
_, err := rt.RunString(testCode)
Expand Down
5 changes: 4 additions & 1 deletion js/modules/k6/http/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ func checkErrorInJSON(input []byte, offset int, err error) error {

// SubmitForm parses the body as an html looking for a from and then submitting it
// TODO: document the actual arguments that can be provided
//
//nolint:funlen
func (res *Response) SubmitForm(args ...goja.Value) (*Response, error) {
rt := res.client.moduleInstance.vu.Runtime()

Expand Down Expand Up @@ -251,7 +253,8 @@ func (res *Response) ClickLink(args ...goja.Value) (*Response, error) {
}
hrefAttr := link.Attr("href")
if hrefAttr == goja.Undefined() {
common.Throw(rt, fmt.Errorf("no valid href attribute value found on element '%s' in response '%s'", selector, res.URL))
errmsg := fmt.Errorf("no valid href attribute value found on element '%s' in response '%s'", selector, res.URL)
common.Throw(rt, errmsg)
}
hrefURL, err := url.Parse(hrefAttr.String())
if err != nil {
Expand Down
10 changes: 6 additions & 4 deletions js/modules/k6/http/response_callback_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package http

import (
"errors"
"fmt"
"sort"
"strings"
Expand Down Expand Up @@ -70,8 +71,9 @@ func TestExpectedStatuses(t *testing.T) {
}

require.Error(t, err)
exc := err.(*goja.Exception)
require.Contains(t, exc.Error(), testCase.err)
var exc *goja.Exception
errors.As(err, &exc)
require.ErrorContains(t, exc, testCase.err)
})
}
}
Expand Down Expand Up @@ -100,7 +102,7 @@ func TestResponseCallbackInAction(t *testing.T) {
metrics.HTTPReqTLSHandshakingName,
}

allHTTPMetrics := append(HTTPMetricsWithoutFailed, metrics.HTTPReqFailedName)
allHTTPMetrics := append(HTTPMetricsWithoutFailed, metrics.HTTPReqFailedName) //nolint: gocritic

testCases := map[string]struct {
code string
Expand Down Expand Up @@ -310,7 +312,7 @@ func TestResponseCallbackBatch(t *testing.T) {
metrics.HTTPReqTLSHandshakingName,
}

allHTTPMetrics := append(HTTPMetricsWithoutFailed, metrics.HTTPReqFailedName)
allHTTPMetrics := append(HTTPMetricsWithoutFailed, metrics.HTTPReqFailedName) //nolint:gocritic
// IMPORTANT: the tests here depend on the fact that the url they hit can be ordered in the same
// order as the expectedSamples even if they are made concurrently
testCases := map[string]struct {
Expand Down
5 changes: 2 additions & 3 deletions js/modules/k6/http/response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,23 +87,22 @@ func myFormHandler(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(body)
}

func jsonHandler(w http.ResponseWriter, r *http.Request) {
func jsonHandler(w http.ResponseWriter, _ *http.Request) {
body := []byte(jsonData)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body)))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(body)
}

func invalidJSONHandler(w http.ResponseWriter, r *http.Request) {
func invalidJSONHandler(w http.ResponseWriter, _ *http.Request) {
body := []byte(invalidJSONData)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body)))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(body)
}

//nolint:paralleltest
func TestResponse(t *testing.T) {
ts := newTestCase(t)
tb := ts.tb
Expand Down

0 comments on commit 2d8104a

Please sign in to comment.