github.com/webdestroya/awsmocker@v0.2.6/response_test.go (about)

     1  package awsmocker_test
     2  
     3  import (
     4  	"crypto/tls"
     5  	"io"
     6  	"net/http"
     7  	"net/url"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/require"
    11  	"github.com/webdestroya/awsmocker"
    12  )
    13  
    14  func TestResponseDebugLogging(t *testing.T) {
    15  	info := awsmocker.Start(t, &awsmocker.MockerOptions{
    16  		SkipDefaultMocks: true,
    17  		ReturnAwsConfig:  true,
    18  		Mocks: []*awsmocker.MockedEndpoint{
    19  			{
    20  				Request: &awsmocker.MockedRequest{
    21  					Hostname: "httptest.com",
    22  				},
    23  				Response: awsmocker.MockResponse_Error(400, "SomeCode_HTTP", "SomeMessage"),
    24  			},
    25  			{
    26  				Request: &awsmocker.MockedRequest{
    27  					Hostname: "httpstest.com",
    28  				},
    29  				Response: awsmocker.MockResponse_Error(401, "SomeCode_HTTPS", "SomeMessage"),
    30  			},
    31  		},
    32  	})
    33  
    34  	client := &http.Client{
    35  		Transport: &http.Transport{
    36  			Proxy: func(r *http.Request) (*url.URL, error) {
    37  				return url.Parse(info.ProxyURL)
    38  			},
    39  			TLSClientConfig: &tls.Config{
    40  				InsecureSkipVerify: true,
    41  			},
    42  		},
    43  	}
    44  
    45  	tables := []struct {
    46  		method       string
    47  		url          string
    48  		statusCode   int
    49  		expErrorCode string
    50  	}{
    51  
    52  		{http.MethodGet, "http://httptest.com/err400", 400, "SomeCode_HTTP"},
    53  		{http.MethodGet, "https://httpstest.com/err401", 401, "SomeCode_HTTPS"},
    54  	}
    55  
    56  	for _, table := range tables {
    57  		req, err := http.NewRequest(table.method, table.url, nil)
    58  		require.NoError(t, err)
    59  
    60  		resp, err := client.Do(req)
    61  		require.NoError(t, err)
    62  		defer resp.Body.Close()
    63  
    64  		// dump, err := httputil.DumpResponse(resp, true)
    65  		// if err != nil {
    66  		// 	t.Error(err)
    67  		// }
    68  		// fmt.Printf("RECEIVED:\n%s\n", dump)
    69  
    70  		require.Equal(t, table.statusCode, resp.StatusCode)
    71  
    72  		respBodyRaw, err := io.ReadAll(resp.Body)
    73  		require.NoError(t, err)
    74  
    75  		respBody := string(respBodyRaw)
    76  		if table.expErrorCode != "" {
    77  			require.Contains(t, respBody, table.expErrorCode)
    78  		}
    79  
    80  	}
    81  
    82  }