github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/internal/restclient/ffresty_test.go (about)

     1  // Copyright © 2021 Kaleido, Inc.
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  //
     5  // Licensed under the Apache License, Version 2.0 (the "License");
     6  // you may not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing, software
    12  // distributed under the License is distributed on an "AS IS" BASIS,
    13  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  // See the License for the specific language governing permissions and
    15  // limitations under the License.
    16  
    17  package restclient
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"net/http"
    23  	"strings"
    24  	"testing"
    25  
    26  	"github.com/jarcoal/httpmock"
    27  	"github.com/kaleido-io/firefly/internal/config"
    28  	"github.com/kaleido-io/firefly/internal/i18n"
    29  	"github.com/stretchr/testify/assert"
    30  )
    31  
    32  var utConfPrefix = config.NewPluginConfig("http_unit_tests")
    33  
    34  func resetConf() {
    35  	config.Reset()
    36  	InitPrefix(utConfPrefix)
    37  }
    38  
    39  func TestRequestOK(t *testing.T) {
    40  
    41  	customClient := &http.Client{}
    42  
    43  	resetConf()
    44  	utConfPrefix.Set(HTTPConfigURL, "http://localhost:12345")
    45  	utConfPrefix.Set(HTTPConfigHeaders, map[string]interface{}{
    46  		"someheader": "headervalue",
    47  	})
    48  	utConfPrefix.Set(HTTPConfigAuthUsername, "user")
    49  	utConfPrefix.Set(HTTPConfigAuthPassword, "pass")
    50  	utConfPrefix.Set(HTTPConfigRetryEnabled, true)
    51  	utConfPrefix.Set(HTTPCustomClient, customClient)
    52  
    53  	c := New(context.Background(), utConfPrefix)
    54  	httpmock.ActivateNonDefault(customClient)
    55  	defer httpmock.DeactivateAndReset()
    56  
    57  	httpmock.RegisterResponder("GET", "http://localhost:12345/test",
    58  		func(req *http.Request) (*http.Response, error) {
    59  			assert.Equal(t, "headervalue", req.Header.Get("someheader"))
    60  			assert.Equal(t, "Basic dXNlcjpwYXNz", req.Header.Get("Authorization"))
    61  			return httpmock.NewStringResponder(200, `{"some": "data"}`)(req)
    62  		})
    63  
    64  	resp, err := c.R().Get("/test")
    65  	assert.NoError(t, err)
    66  	assert.Equal(t, 200, resp.StatusCode())
    67  	assert.Equal(t, `{"some": "data"}`, resp.String())
    68  
    69  	assert.Equal(t, 1, httpmock.GetTotalCallCount())
    70  }
    71  
    72  func TestRequestRetry(t *testing.T) {
    73  
    74  	ctx := context.Background()
    75  
    76  	resetConf()
    77  	utConfPrefix.Set(HTTPConfigURL, "http://localhost:12345")
    78  	utConfPrefix.Set(HTTPConfigRetryEnabled, true)
    79  	utConfPrefix.Set(HTTPConfigRetryInitDelay, 1)
    80  
    81  	c := New(ctx, utConfPrefix)
    82  	httpmock.ActivateNonDefault(c.GetClient())
    83  	defer httpmock.DeactivateAndReset()
    84  
    85  	httpmock.RegisterResponder("GET", "http://localhost:12345/test",
    86  		httpmock.NewStringResponder(500, `{"message": "pop"}`))
    87  
    88  	resp, err := c.R().Get("/test")
    89  	assert.NoError(t, err)
    90  	assert.Equal(t, 500, resp.StatusCode())
    91  	assert.Equal(t, 6, httpmock.GetTotalCallCount())
    92  
    93  	err = WrapRestErr(ctx, resp, err, i18n.MsgEthconnectRESTErr)
    94  	assert.Error(t, err)
    95  
    96  }
    97  
    98  func TestLongResponse(t *testing.T) {
    99  
   100  	ctx := context.Background()
   101  
   102  	resetConf()
   103  	utConfPrefix.Set(HTTPConfigURL, "http://localhost:12345")
   104  	utConfPrefix.Set(HTTPConfigRetryEnabled, false)
   105  
   106  	c := New(ctx, utConfPrefix)
   107  	httpmock.ActivateNonDefault(c.GetClient())
   108  	defer httpmock.DeactivateAndReset()
   109  
   110  	resText := strings.Builder{}
   111  	for i := 0; i < 512; i++ {
   112  		resText.WriteByte(byte('a' + (i % 26)))
   113  	}
   114  	httpmock.RegisterResponder("GET", "http://localhost:12345/test",
   115  		httpmock.NewStringResponder(500, resText.String()))
   116  
   117  	resp, err := c.R().Get("/test")
   118  	err = WrapRestErr(ctx, resp, err, i18n.MsgEthconnectRESTErr)
   119  	assert.Error(t, err)
   120  }
   121  
   122  func TestErrResponse(t *testing.T) {
   123  
   124  	ctx := context.Background()
   125  
   126  	resetConf()
   127  	utConfPrefix.Set(HTTPConfigURL, "http://localhost:12345")
   128  	utConfPrefix.Set(HTTPConfigRetryEnabled, false)
   129  
   130  	c := New(ctx, utConfPrefix)
   131  	httpmock.ActivateNonDefault(c.GetClient())
   132  	defer httpmock.DeactivateAndReset()
   133  
   134  	resText := strings.Builder{}
   135  	for i := 0; i < 512; i++ {
   136  		resText.WriteByte(byte('a' + (i % 26)))
   137  	}
   138  	httpmock.RegisterResponder("GET", "http://localhost:12345/test",
   139  		httpmock.NewErrorResponder(fmt.Errorf("pop")))
   140  
   141  	resp, err := c.R().Get("/test")
   142  	err = WrapRestErr(ctx, resp, err, i18n.MsgEthconnectRESTErr)
   143  	assert.Error(t, err)
   144  }
   145  
   146  func TestOnAfterResponseNil(t *testing.T) {
   147  	OnAfterResponse(nil, nil)
   148  }