github.com/akamai/AkamaiOPEN-edgegrid-golang/v2@v2.17.0/pkg/datastream/errors_test.go (about)

     1  package datastream
     2  
     3  import (
     4  	"context"
     5  	"io/ioutil"
     6  	"net/http"
     7  	"strings"
     8  	"testing"
     9  
    10  	"github.com/akamai/AkamaiOPEN-edgegrid-golang/v2/pkg/session"
    11  	"github.com/stretchr/testify/assert"
    12  	"github.com/stretchr/testify/require"
    13  )
    14  
    15  func TestNewError(t *testing.T) {
    16  	sess, err := session.New()
    17  	require.NoError(t, err)
    18  
    19  	req, err := http.NewRequestWithContext(
    20  		context.TODO(),
    21  		http.MethodHead,
    22  		"/",
    23  		nil)
    24  	require.NoError(t, err)
    25  
    26  	tests := map[string]struct {
    27  		response *http.Response
    28  		expected *Error
    29  	}{
    30  		"valid response, status code 500": {
    31  			response: &http.Response{
    32  				Status:     "Internal Server Error",
    33  				StatusCode: http.StatusInternalServerError,
    34  				Body: ioutil.NopCloser(strings.NewReader(
    35  					`{"type":"a","title":"b","detail":"c"}`),
    36  				),
    37  				Request: req,
    38  			},
    39  			expected: &Error{
    40  				Type:       "a",
    41  				Title:      "b",
    42  				Detail:     "c",
    43  				StatusCode: http.StatusInternalServerError,
    44  			},
    45  		},
    46  		"invalid response body, assign status code": {
    47  			response: &http.Response{
    48  				Status:     "Internal Server Error",
    49  				StatusCode: http.StatusInternalServerError,
    50  				Body: ioutil.NopCloser(strings.NewReader(
    51  					`test`),
    52  				),
    53  				Request: req,
    54  			},
    55  			expected: &Error{
    56  				Title:      "Failed to unmarshal error body",
    57  				Detail:     "invalid character 'e' in literal true (expecting 'r')",
    58  				StatusCode: http.StatusInternalServerError,
    59  			},
    60  		},
    61  	}
    62  	for name, test := range tests {
    63  		t.Run(name, func(t *testing.T) {
    64  			res := Client(sess).(*ds).Error(test.response)
    65  			assert.Equal(t, test.expected, res)
    66  		})
    67  	}
    68  }