Skip to content

Commit

Permalink
[TT-9829] Fix checking json.Marshal errors in tests (#5426)
Browse files Browse the repository at this point in the history
- Added `test.MarshalJSON` utility for encoding json in tests and
asserting the error return is nil,
- Updated usage in tests

This is required to resolve some sonarcloud errors in existing tests
code.

https://tyktech.atlassian.net/browse/TT-9829

---------

Co-authored-by: Tit Petric <tit@tyk.io>
(cherry picked from commit c985ee4)
  • Loading branch information
titpetric committed Nov 7, 2023
1 parent f83b98f commit 4c172c4
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 27 deletions.
43 changes: 24 additions & 19 deletions gateway/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,14 @@ func TestKeyHandler(t *testing.T) {

// Access right not specified
masterKey := CreateStandardSession()
masterKeyJSON, _ := json.Marshal(masterKey)
masterKeyJSON := test.MarshalJSON(t)(masterKey)
//TestTykMakeHTTPRequest
// with access
withAccess := CreateStandardSession()
withAccess.AccessRights = map[string]user.AccessDefinition{"test": {
APIID: "test", Versions: []string{"v1"},
}}
withAccessJSON, _ := json.Marshal(withAccess)
withAccessJSON := test.MarshalJSON(t)(withAccess)

// with policy
ts.Gw.policiesMu.Lock()
Expand All @@ -170,12 +170,12 @@ func TestKeyHandler(t *testing.T) {
}
ts.Gw.policiesMu.Unlock()
withPolicy := CreateStandardSession()
withoutPolicyJSON, _ := json.Marshal(withPolicy)
withoutPolicyJSON := test.MarshalJSON(t)(withPolicy)

withPolicy.ApplyPolicies = []string{
"abc_policy",
}
withPolicyJSON, _ := json.Marshal(withPolicy)
withPolicyJSON := test.MarshalJSON(t)(withPolicy)

// with invalid policy
withBadPolicy := CreateStandardSession()
Expand All @@ -185,7 +185,7 @@ func TestKeyHandler(t *testing.T) {
withBadPolicy.ApplyPolicies = []string{
"xyz_policy",
}
withBadPolicyJSON, _ := json.Marshal(withBadPolicy)
withBadPolicyJSON := test.MarshalJSON(t)(withBadPolicy)

t.Run("Create key", func(t *testing.T) {
ts.Run(t, []test.TestCase{
Expand Down Expand Up @@ -379,7 +379,7 @@ func TestKeyHandler_UpdateKey(t *testing.T) {

t.Run("Add policy not enforcing acl", func(t *testing.T) {
session.ApplyPolicies = append(session.ApplyPolicies, pID2)
sessionData, _ := json.Marshal(session)
sessionData := test.MarshalJSON(t)(session)
path := fmt.Sprintf("/tyk/keys/%s", key)

_, _ = ts.Run(t, []test.TestCase{
Expand All @@ -394,7 +394,7 @@ func TestKeyHandler_UpdateKey(t *testing.T) {

t.Run("Remove policy not enforcing acl", func(t *testing.T) {
session.ApplyPolicies = []string{}
sessionData, _ := json.Marshal(session)
sessionData := test.MarshalJSON(t)(session)
path := fmt.Sprintf("/tyk/keys/%s", key)

_, _ = ts.Run(t, []test.TestCase{
Expand All @@ -409,7 +409,7 @@ func TestKeyHandler_UpdateKey(t *testing.T) {

t.Run("Tags on key level", func(t *testing.T) {
assertTags := func(session *user.SessionState, expected []string) {
sessionData, _ := json.Marshal(session)
sessionData := test.MarshalJSON(t)(session)
path := fmt.Sprintf("/tyk/keys/%s", key)

_, _ = ts.Run(t, []test.TestCase{
Expand Down Expand Up @@ -450,7 +450,7 @@ func TestKeyHandler_UpdateKey(t *testing.T) {

t.Run("MetaData on key level", func(t *testing.T) {
assertMetaData := func(session *user.SessionState, expected map[string]interface{}) {
sessionData, _ := json.Marshal(session)
sessionData := test.MarshalJSON(t)(session)
path := fmt.Sprintf("/tyk/keys/%s", key)

_, _ = ts.Run(t, []test.TestCase{
Expand Down Expand Up @@ -630,7 +630,7 @@ func TestUpdateKeyWithCert(t *testing.T) {
})

session.Certificate = newCertID
sessionData, _ := json.Marshal(session)
sessionData := test.MarshalJSON(t)(session)

path := fmt.Sprintf("/tyk/keys/%s", key)
_, _ = ts.Run(t, []test.TestCase{
Expand All @@ -653,7 +653,7 @@ func TestUpdateKeyWithCert(t *testing.T) {

// attempt to set an empty cert
session.Certificate = ""
sessionData, _ := json.Marshal(session)
sessionData := test.MarshalJSON(t)(session)

path := fmt.Sprintf("/tyk/keys/%s", key)
_, _ = ts.Run(t, []test.TestCase{
Expand All @@ -675,7 +675,7 @@ func TestUpdateKeyWithCert(t *testing.T) {
})

session.Certificate = "invalid-cert-id"
sessionData, _ := json.Marshal(session)
sessionData := test.MarshalJSON(t)(session)

path := fmt.Sprintf("/tyk/keys/%s", key)
_, _ = ts.Run(t, []test.TestCase{
Expand Down Expand Up @@ -752,7 +752,7 @@ func TestKeyHandler_CheckKeysNotDuplicateOnUpdate(t *testing.T) {
t.Error("Failed to create key, ensure security settings are correct:" + err.Error())
}

requestByte, _ := json.Marshal(session)
requestByte := test.MarshalJSON(t)(session)
r := httptest.NewRequest(http.MethodPut, "/tyk/keys/"+keyName, bytes.NewReader(requestByte))
ts.Gw.handleAddOrUpdate(keyName, r, tc.HashKeys)

Expand Down Expand Up @@ -861,7 +861,7 @@ func (ts *Test) testHashKeyHandlerHelper(t *testing.T, expectedHashSize int) {
withAccess.AccessRights = map[string]user.AccessDefinition{"test": {
APIID: "test", Versions: []string{"v1"},
}}
withAccessJSON, _ := json.Marshal(withAccess)
withAccessJSON := test.MarshalJSON(t)(withAccess)

myKey := "my_key_id"
myKeyHash := storage.HashKey(ts.Gw.generateToken("default", myKey), ts.Gw.GetConfig().HashKeys)
Expand Down Expand Up @@ -1029,7 +1029,7 @@ func TestHashKeyListingDisabled(t *testing.T) {
withAccess.AccessRights = map[string]user.AccessDefinition{"test": {
APIID: "test", Versions: []string{"v1"},
}}
withAccessJSON, _ := json.Marshal(withAccess)
withAccessJSON := test.MarshalJSON(t)(withAccess)

myKey := "my_key_id"
myKeyHash := storage.HashKey(ts.Gw.generateToken("default", myKey), ts.Gw.GetConfig().HashKeys)
Expand Down Expand Up @@ -1145,7 +1145,7 @@ func TestKeyHandler_HashingDisabled(t *testing.T) {
withAccess.AccessRights = map[string]user.AccessDefinition{"test": {
APIID: "test", Versions: []string{"v1"},
}}
withAccessJSON, _ := json.Marshal(withAccess)
withAccessJSON := test.MarshalJSON(t)(withAccess)

myKeyID := "my_key_id"
token := ts.Gw.generateToken("default", myKeyID)
Expand Down Expand Up @@ -1238,7 +1238,7 @@ func TestGetOAuthClients(t *testing.T) {
APIID: "test",
ClientSecret: "secret",
}
validOauthRequest, _ := json.Marshal(oauthRequest)
validOauthRequest := test.MarshalJSON(t)(oauthRequest)

ts.Run(t, []test.TestCase{
{Path: "/tyk/oauth/clients/unknown", AdminAuth: true, Code: 404},
Expand Down Expand Up @@ -1343,8 +1343,13 @@ func TestCreateOAuthClient(t *testing.T) {

for testName, testData := range tests {
t.Run(testName, func(t *testing.T) {
<<<<<<< HEAD
requestData, _ := json.Marshal(testData.req)
ts.Run(
=======
requestData := test.MarshalJSON(t)(testData.req)
_, _ = ts.Run(
>>>>>>> c985ee42... [TT-9829] Fix checking json.Marshal errors in tests (#5426)
t,
test.TestCase{
Method: http.MethodPost,
Expand Down Expand Up @@ -1468,7 +1473,7 @@ func TestUpdateOauthClientHandler(t *testing.T) {

for testName, testData := range tests {
t.Run(testName, func(t *testing.T) {
requestData, _ := json.Marshal(testData.req)
requestData := test.MarshalJSON(t)(testData.req)
testCase := test.TestCase{
Method: http.MethodPut,
Path: "/tyk/oauth/clients/test/12345",
Expand Down Expand Up @@ -1813,7 +1818,7 @@ func TestRotateClientSecretHandler(t *testing.T) {

for testName, testData := range tests {
t.Run(testName, func(t *testing.T) {
requestData, _ := json.Marshal(testData.req)
requestData := test.MarshalJSON(t)(testData.req)
testCase := test.TestCase{
Method: http.MethodPut,
Path: "/tyk/oauth/clients/test/12345/rotate",
Expand Down
2 changes: 1 addition & 1 deletion gateway/gateway_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -999,7 +999,7 @@ func TestManagementNodeRedisEvents(t *testing.T) {
}
n.Sign()
msg := redis.Message{}
payload, _ := json.Marshal(n)
payload := test.MarshalJSON(t)(n)
msg.Payload = string(payload)

callbackRun := false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ package gateway

import (
"context"
"encoding/json"
"io"
"math/rand"
"sync"
Expand All @@ -33,6 +32,8 @@ import (

"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/route_guide/routeguide"

"github.com/TykTechnologies/tyk/test"
)

// printFeature gets the feature for the given point.
Expand Down Expand Up @@ -71,7 +72,7 @@ func printFeatures(t *testing.T, client pb.RouteGuideClient, rect *pb.Rectangle)
for {
feature, err := stream.Recv()
if err == io.EOF {
b, _ := json.Marshal(features)
b := test.MarshalJSON(t)(features)
got := string(b)
if got != expectedFeatures {
t.Error("Failed to get features")
Expand Down
2 changes: 1 addition & 1 deletion gateway/oauth_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1237,7 +1237,7 @@ func TestJSONToFormValues(t *testing.T) {
"client_secret": "test-client-secret",
"grant_type": "password",
}
b, _ := json.Marshal(o)
b := test.MarshalJSON(t)(o)
r, err := http.NewRequest(http.MethodPost, "/token", bytes.NewReader(b))
if err != nil {
t.Fatal(err)
Expand Down
5 changes: 1 addition & 4 deletions gateway/testutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -886,10 +886,7 @@ func TestReqBody(t testing.TB, body interface{}) io.Reader {
case nil:
return nil
default: // JSON objects (structs)
bs, err := json.Marshal(x)
if err != nil {
t.Fatal(err)
}
bs := test.MarshalJSON(t)(x)
return bytes.NewReader(bs)
}
}
Expand Down
20 changes: 20 additions & 0 deletions test/json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package test

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/require"
)

// MarshalJSON returns a closure returning the marshalled json
// while asserting no error occurred during marshalling.
func MarshalJSON(tb testing.TB) func(interface{}) []byte {
tb.Helper()

return func(in interface{}) []byte {
b, err := json.Marshal(in)
require.NoError(tb, err)
return b
}
}
14 changes: 14 additions & 0 deletions test/json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package test

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestMarshalJSON(t *testing.T) {
value := "foo"
marshal := MarshalJSON(t)
out := marshal(value)
assert.Equal(t, []byte(`"foo"`), out)
}

0 comments on commit 4c172c4

Please sign in to comment.