github.com/akamai/AkamaiOPEN-edgegrid-golang/v2@v2.17.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  	json.Unmarshal([]byte(respData), &result)
    22  
    23  	tests := map[string]struct {
    24  		params           GetSiemDefinitionsRequest
    25  		responseStatus   int
    26  		responseBody     string
    27  		expectedPath     string
    28  		expectedResponse *GetSiemDefinitionsResponse
    29  		withError        error
    30  	}{
    31  		"200 OK": {
    32  			params:           GetSiemDefinitionsRequest{},
    33  			responseStatus:   http.StatusOK,
    34  			responseBody:     respData,
    35  			expectedPath:     "/appsec/v1/siem-definitions",
    36  			expectedResponse: &result,
    37  		},
    38  		"500 internal server error": {
    39  			params:         GetSiemDefinitionsRequest{},
    40  			responseStatus: http.StatusInternalServerError,
    41  			responseBody: (`
    42  {
    43      "type": "internal_error",
    44      "title": "Internal Server Error",
    45      "detail": "Error fetching SiemDefinitions"
    46  }`),
    47  			expectedPath: "/appsec/v1/siem-definitions",
    48  			withError: &Error{
    49  				Type:       "internal_error",
    50  				Title:      "Internal Server Error",
    51  				Detail:     "Error fetching SiemDefinitions",
    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.GetSiemDefinitions(context.Background(), test.params)
    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  }