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

     1  package appsec
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/tls"
     6  	"crypto/x509"
     7  	"encoding/json"
     8  	"fmt"
     9  	"io/ioutil"
    10  	"net/http"
    11  	"net/http/httptest"
    12  	"net/url"
    13  	"testing"
    14  
    15  	"github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid"
    16  	"github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session"
    17  	"github.com/stretchr/testify/assert"
    18  	"github.com/stretchr/testify/require"
    19  )
    20  
    21  func mockAPIClient(t *testing.T, mockServer *httptest.Server) APPSEC {
    22  	serverURL, err := url.Parse(mockServer.URL)
    23  	require.NoError(t, err)
    24  	certPool := x509.NewCertPool()
    25  	certPool.AddCert(mockServer.Certificate())
    26  	httpClient := &http.Client{
    27  		Transport: &http.Transport{
    28  			TLSClientConfig: &tls.Config{
    29  				RootCAs: certPool,
    30  			},
    31  		},
    32  	}
    33  	s, err := session.New(session.WithClient(httpClient), session.WithSigner(&edgegrid.Config{Host: serverURL.Host}))
    34  	assert.NoError(t, err)
    35  	return Client(s)
    36  }
    37  
    38  func dummyOpt() Option {
    39  	return func(*appsec) {
    40  
    41  	}
    42  }
    43  
    44  // loadFixtureBytes returns the entire contents of the given file as a byte slice
    45  func loadFixtureBytes(path string) []byte {
    46  	contents, err := ioutil.ReadFile(path)
    47  	if err != nil {
    48  		panic(err)
    49  	}
    50  	return contents
    51  }
    52  
    53  // compactJSON converts a JSON-encoded byte slice to a compact form (so our JSON fixtures can be readable)
    54  func compactJSON(encoded []byte) string {
    55  	buf := bytes.Buffer{}
    56  	if err := json.Compact(&buf, encoded); err != nil {
    57  		panic(fmt.Sprintf("%s: %s", err, string(encoded)))
    58  	}
    59  
    60  	return buf.String()
    61  }
    62  
    63  func TestClient(t *testing.T) {
    64  	sess, err := session.New()
    65  	require.NoError(t, err)
    66  	tests := map[string]struct {
    67  		options  []Option
    68  		expected *appsec
    69  	}{
    70  		"no options provided, return default": {
    71  			options: nil,
    72  			expected: &appsec{
    73  				Session: sess,
    74  			},
    75  		},
    76  		"dummy option": {
    77  			options: []Option{dummyOpt()},
    78  			expected: &appsec{
    79  				Session: sess,
    80  			},
    81  		},
    82  	}
    83  	for name, test := range tests {
    84  		t.Run(name, func(t *testing.T) {
    85  			res := Client(sess, test.options...)
    86  			assert.Equal(t, res, test.expected)
    87  		})
    88  	}
    89  }