github.com/akamai/AkamaiOPEN-edgegrid-golang/v8@v8.1.0/pkg/appsec/siem_definitions_test.go (about)

     1  package appsec
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"errors"
     7  	"net/http"
     8  	"net/http/httptest"
     9  	"testing"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  	"github.com/stretchr/testify/require"
    13  )
    14  
    15  // Test SiemDefinitions
    16  func TestAppSec_GetSiemDefinitions(t *testing.T) {
    17  
    18  	result := GetSiemDefinitionsResponse{}
    19  
    20  	respData := compactJSON(loadFixtureBytes("testdata/TestSiemDefinitions/SiemDefinitions.json"))
    21  	err := json.Unmarshal([]byte(respData), &result)
    22  	require.NoError(t, err)
    23  
    24  	tests := map[string]struct {
    25  		params           GetSiemDefinitionsRequest
    26  		responseStatus   int
    27  		responseBody     string
    28  		expectedPath     string
    29  		expectedResponse *GetSiemDefinitionsResponse
    30  		withError        error
    31  	}{
    32  		"200 OK": {
    33  			params:           GetSiemDefinitionsRequest{},
    34  			responseStatus:   http.StatusOK,
    35  			responseBody:     respData,
    36  			expectedPath:     "/appsec/v1/siem-definitions",
    37  			expectedResponse: &result,
    38  		},
    39  		"500 internal server error": {
    40  			params:         GetSiemDefinitionsRequest{},
    41  			responseStatus: http.StatusInternalServerError,
    42  			responseBody: (`
    43  {
    44      "type": "internal_error",
    45      "title": "Internal Server Error",
    46      "detail": "Error fetching SiemDefinitions"
    47  }`),
    48  			expectedPath: "/appsec/v1/siem-definitions",
    49  			withError: &Error{
    50  				Type:       "internal_error",
    51  				Title:      "Internal Server Error",
    52  				Detail:     "Error fetching SiemDefinitions",
    53  				StatusCode: http.StatusInternalServerError,
    54  			},
    55  		},
    56  	}
    57  
    58  	for name, test := range tests {
    59  		t.Run(name, func(t *testing.T) {
    60  			mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    61  				assert.Equal(t, test.expectedPath, r.URL.String())
    62  				assert.Equal(t, http.MethodGet, r.Method)
    63  				w.WriteHeader(test.responseStatus)
    64  				_, err := w.Write([]byte(test.responseBody))
    65  				assert.NoError(t, err)
    66  			}))
    67  			client := mockAPIClient(t, mockServer)
    68  			result, err := client.GetSiemDefinitions(context.Background(), test.params)
    69  			if test.withError != nil {
    70  				assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err)
    71  				return
    72  			}
    73  			require.NoError(t, err)
    74  			assert.Equal(t, test.expectedResponse, result)
    75  		})
    76  	}
    77  }