Skip to content

Commit

Permalink
Fix checking json.Marshal errors in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Tit Petric committed Aug 16, 2023
1 parent a36deba commit 6fa659c
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 28 deletions.
40 changes: 20 additions & 20 deletions gateway/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,14 +230,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 @@ -252,12 +252,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 @@ -267,7 +267,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 @@ -461,7 +461,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 @@ -477,7 +477,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 @@ -492,7 +492,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 @@ -533,7 +533,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 @@ -712,7 +712,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 @@ -735,7 +735,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 @@ -757,7 +757,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 @@ -834,7 +834,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 @@ -1020,7 +1020,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 @@ -1194,7 +1194,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 @@ -1312,7 +1312,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 @@ -1453,7 +1453,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 @@ -1558,7 +1558,7 @@ func TestCreateOAuthClient(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)
_, _ = ts.Run(
t,
test.TestCase{
Expand Down Expand Up @@ -1683,7 +1683,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 @@ -2029,7 +2029,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 @@ -593,7 +593,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,13 +24,13 @@ package gateway

import (
"context"
"encoding/json"
"io"
"math/rand"
"sync"
"testing"
"time"

"github.com/TykTechnologies/tyk/test"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/route_guide/routeguide"
)
Expand Down Expand Up @@ -71,7 +71,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 @@ -1239,7 +1239,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 @@ -914,10 +914,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
18 changes: 18 additions & 0 deletions test/json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package test

import (
"encoding/json"
"testing"

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

// MarshalJSON returns a closure returning the marshalled json
// while asserting no error occured during marshalling.
func MarshalJSON(t testing.TB) func(interface{}) []byte {
return func(in interface{}) []byte {
b, err := json.Marshal(in)
require.NoError(t, 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 6fa659c

Please sign in to comment.