1package cache 2 3import ( 4 "context" 5 "encoding/json" 6 "fmt" 7 "io/ioutil" 8 "net/http" 9 "strings" 10 "time" 11 12 "github.com/hashicorp/vault/api" 13) 14 15// mockProxier is a mock implementation of the Proxier interface, used for testing purposes. 16// The mock will return the provided responses every time it reaches its Send method, up to 17// the last provided response. This lets tests control what the next/underlying Proxier layer 18// might expect to return. 19type mockProxier struct { 20 proxiedResponses []*SendResponse 21 responseIndex int 22} 23 24func newMockProxier(responses []*SendResponse) *mockProxier { 25 return &mockProxier{ 26 proxiedResponses: responses, 27 } 28} 29 30func (p *mockProxier) Send(ctx context.Context, req *SendRequest) (*SendResponse, error) { 31 if p.responseIndex >= len(p.proxiedResponses) { 32 return nil, fmt.Errorf("index out of bounds: responseIndex = %d, responses = %d", p.responseIndex, len(p.proxiedResponses)) 33 } 34 resp := p.proxiedResponses[p.responseIndex] 35 36 p.responseIndex++ 37 38 return resp, nil 39} 40 41func (p *mockProxier) ResponseIndex() int { 42 return p.responseIndex 43} 44 45func newTestSendResponse(status int, body string) *SendResponse { 46 resp := &SendResponse{ 47 Response: &api.Response{ 48 Response: &http.Response{ 49 StatusCode: status, 50 Header: http.Header{}, 51 }, 52 }, 53 } 54 resp.Response.Header.Set("Date", time.Now().Format(http.TimeFormat)) 55 56 if body != "" { 57 resp.Response.Body = ioutil.NopCloser(strings.NewReader(body)) 58 resp.ResponseBody = []byte(body) 59 } 60 61 if json.Valid([]byte(body)) { 62 resp.Response.Header.Set("content-type", "application/json") 63 } 64 65 return resp 66} 67