github.com/akamai/AkamaiOPEN-edgegrid-golang/v8@v8.1.0/pkg/papi/ruleformats_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_GetRuleFormats(t *testing.T) {
    15  	tests := map[string]struct {
    16  		responseStatus   int
    17  		responseBody     string
    18  		expectedPath     string
    19  		expectedResponse *GetRuleFormatsResponse
    20  		withError        error
    21  	}{
    22  		"200 OK": {
    23  			responseStatus: http.StatusOK,
    24  			responseBody: `
    25  {
    26      "ruleFormats": {
    27          "items": [
    28              "latest",
    29              "v2015-08-08"
    30          ]
    31      }
    32  }`,
    33  			expectedPath: "/papi/v1/rule-formats",
    34  			expectedResponse: &GetRuleFormatsResponse{RuleFormatItems{
    35  				Items: []string{"latest", "v2015-08-08"},
    36  			}},
    37  		},
    38  		"500 internal server error": {
    39  			responseStatus: http.StatusInternalServerError,
    40  			responseBody: `
    41  {
    42  	"type": "internal_error",
    43      "title": "Internal Server Error",
    44      "detail": "Error fetching rule formats",
    45      "status": 500
    46  }`,
    47  			expectedPath: "/papi/v1/rule-formats",
    48  			withError: &Error{
    49  				Type:       "internal_error",
    50  				Title:      "Internal Server Error",
    51  				Detail:     "Error fetching rule formats",
    52  				StatusCode: http.StatusInternalServerError,
    53  			},
    54  		},
    55  	}
    56  
    57  	for name, test := range tests {
    58  		t.Run(name, func(t *testing.T) {
    59  			mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    60  				assert.Equal(t, test.expectedPath, r.URL.String())
    61  				assert.Equal(t, http.MethodGet, r.Method)
    62  				w.WriteHeader(test.responseStatus)
    63  				_, err := w.Write([]byte(test.responseBody))
    64  				assert.NoError(t, err)
    65  			}))
    66  			client := mockAPIClient(t, mockServer)
    67  			result, err := client.GetRuleFormats(context.Background())
    68  			if test.withError != nil {
    69  				assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err)
    70  				return
    71  			}
    72  			require.NoError(t, err)
    73  			assert.Equal(t, test.expectedResponse, result)
    74  		})
    75  	}
    76  }