github.com/akamai/AkamaiOPEN-edgegrid-golang/v8@v8.1.0/pkg/papi/contract_test.go (about) 1 package papi 2 3 import ( 4 "context" 5 "errors" 6 "net/http" 7 "net/http/httptest" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 "github.com/stretchr/testify/require" 12 ) 13 14 func TestPapi_GetContracts(t *testing.T) { 15 tests := map[string]struct { 16 responseStatus int 17 responseBody string 18 expectedPath string 19 expectedResponse *GetContractsResponse 20 withError error 21 }{ 22 "200 OK": { 23 responseStatus: http.StatusOK, 24 responseBody: ` 25 { 26 "accountId": "act_1-1TJZFB", 27 "contracts": { 28 "items": [ 29 { 30 "contractId": "ctr_1-1TJZH5", 31 "contractTypeName": "DIRECT_CUSTOMER" 32 } 33 ] 34 } 35 }`, 36 expectedPath: "/papi/v1/contracts", 37 expectedResponse: &GetContractsResponse{ 38 AccountID: "act_1-1TJZFB", 39 40 Contracts: ContractsItems{Items: []*Contract{ 41 { 42 ContractID: "ctr_1-1TJZH5", 43 ContractTypeName: "DIRECT_CUSTOMER", 44 }, 45 }}, 46 }, 47 }, 48 "500 internal server error": { 49 responseStatus: http.StatusInternalServerError, 50 responseBody: ` 51 { 52 "type": "internal_error", 53 "title": "Internal Server Error", 54 "detail": "Error fetching contracts", 55 "status": 500 56 }`, 57 expectedPath: "/papi/v1/contracts", 58 withError: &Error{ 59 Type: "internal_error", 60 Title: "Internal Server Error", 61 Detail: "Error fetching contracts", 62 StatusCode: http.StatusInternalServerError, 63 }, 64 }, 65 } 66 67 for name, test := range tests { 68 t.Run(name, func(t *testing.T) { 69 mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 70 assert.Equal(t, test.expectedPath, r.URL.String()) 71 assert.Equal(t, http.MethodGet, r.Method) 72 w.WriteHeader(test.responseStatus) 73 _, err := w.Write([]byte(test.responseBody)) 74 assert.NoError(t, err) 75 })) 76 client := mockAPIClient(t, mockServer) 77 result, err := client.GetContracts(context.Background()) 78 if test.withError != nil { 79 assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) 80 return 81 } 82 require.NoError(t, err) 83 assert.Equal(t, test.expectedResponse, result) 84 }) 85 } 86 }