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

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