diff --git a/gateway/api_test.go b/gateway/api_test.go index cffb5f0db6c..23a06c77fab 100644 --- a/gateway/api_test.go +++ b/gateway/api_test.go @@ -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() @@ -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() @@ -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{ @@ -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{ @@ -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{ @@ -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{ @@ -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{ @@ -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{ @@ -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{ @@ -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{ @@ -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) @@ -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) @@ -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) @@ -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) @@ -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}, @@ -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{ @@ -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", @@ -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", diff --git a/gateway/gateway_test.go b/gateway/gateway_test.go index d864a78d178..fd53d2b75fc 100644 --- a/gateway/gateway_test.go +++ b/gateway/gateway_test.go @@ -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 diff --git a/gateway/grpc_streamin_client_test.go b/gateway/grpc_streaming_client_test.go similarity index 99% rename from gateway/grpc_streamin_client_test.go rename to gateway/grpc_streaming_client_test.go index 3cd2c7d98bf..2ded216b093 100644 --- a/gateway/grpc_streamin_client_test.go +++ b/gateway/grpc_streaming_client_test.go @@ -24,7 +24,6 @@ package gateway import ( "context" - "encoding/json" "io" "math/rand" "sync" @@ -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. @@ -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") diff --git a/gateway/oauth_manager_test.go b/gateway/oauth_manager_test.go index 3a7ca0760bb..db17c2d7c0c 100644 --- a/gateway/oauth_manager_test.go +++ b/gateway/oauth_manager_test.go @@ -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) diff --git a/gateway/testutil.go b/gateway/testutil.go index e973cc20518..d1396e3d8bb 100644 --- a/gateway/testutil.go +++ b/gateway/testutil.go @@ -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) } } diff --git a/test/json.go b/test/json.go new file mode 100644 index 00000000000..1a6faa56780 --- /dev/null +++ b/test/json.go @@ -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 + } +} diff --git a/test/json_test.go b/test/json_test.go new file mode 100644 index 00000000000..fbb12f2ae9c --- /dev/null +++ b/test/json_test.go @@ -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) +}