github.com/verrazzano/verrazzano@v1.7.0/pkg/httputil/httputil_test.go (about) 1 // Copyright (c) 2021, 2023, Oracle and/or its affiliates. 2 // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. 3 package httputil_test 4 5 import ( 6 "net/http" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 "github.com/verrazzano/verrazzano/pkg/httputil" 11 ) 12 13 func TestExtractTokenFromResponseBody(t *testing.T) { 14 asserts := assert.New(t) 15 16 // Empty response 17 var body = "" 18 token, err := httputil.ExtractFieldFromResponseBodyOrReturnError(body, "token") 19 asserts.Error(err) 20 asserts.Empty(token) 21 22 // Valid response 23 body = `{"token": "abcd"}` 24 token, err = httputil.ExtractFieldFromResponseBodyOrReturnError(body, "token") 25 asserts.NoError(err) 26 asserts.Equal("abcd", token) 27 28 // Valid non-string response 29 body = `{"token": [{"abcd": "efgh"}]}` 30 token, err = httputil.ExtractFieldFromResponseBodyOrReturnError(body, "token") 31 asserts.NoError(err) 32 asserts.Equal(`[{"abcd":"efgh"}]`, token) 33 34 // Expected error message 35 body = `{"notoken": "yes"}` 36 errMsg := "unable to find auth code" 37 token, err = httputil.ExtractFieldFromResponseBodyOrReturnError(body, "token", errMsg) 38 asserts.Error(err) 39 asserts.Empty(token) 40 asserts.Equal(err.Error(), errMsg) 41 } 42 43 func TestValidateResponseCode(t *testing.T) { 44 asserts := assert.New(t) 45 46 // Unexpected response code 47 var response = http.Response{StatusCode: http.StatusAccepted, Request: &http.Request{}} 48 err := httputil.ValidateResponseCode(&response, http.StatusCreated) 49 asserts.Error(err) 50 asserts.Contains(err.Error(), "expected response code") 51 52 // Unexpected response code with multiple accepted response codes 53 response = http.Response{StatusCode: http.StatusAccepted, Request: &http.Request{}} 54 err = httputil.ValidateResponseCode(&response, http.StatusCreated, http.StatusAlreadyReported) 55 asserts.Error(err) 56 asserts.Contains(err.Error(), "expected one of response codes") 57 58 // Valid response code 59 response = http.Response{StatusCode: http.StatusAccepted, Request: &http.Request{}} 60 err = httputil.ValidateResponseCode(&response, http.StatusAccepted) 61 asserts.NoError(err) 62 63 }