1// Copyright (c) 2015 Serge Gebhardt. All rights reserved. 2// 3// Use of this source code is governed by the ISC 4// license that can be found in the LICENSE file. 5 6package acd 7 8import ( 9 "bytes" 10 "io/ioutil" 11 "net/http" 12) 13 14// MockResponse is a static HTTP response. 15type MockResponse struct { 16 Code int 17 Body []byte 18} 19 20// NewMockResponseOkString creates a new MockResponse with Code 200 (OK) 21// and Body built from string argument 22func NewMockResponseOkString(response string) *MockResponse { 23 return &MockResponse{ 24 Code: 200, 25 Body: []byte(response), 26 } 27} 28 29// mockTransport is a mocked Transport that always returns the same MockResponse. 30type mockTransport struct { 31 resp MockResponse 32} 33 34// Satisfies the RoundTripper interface. 35func (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) { 36 r := http.Response{ 37 StatusCode: t.resp.Code, 38 Proto: "HTTP/1.0", 39 ProtoMajor: 1, 40 ProtoMinor: 0, 41 } 42 43 if len(t.resp.Body) > 0 { 44 buf := bytes.NewBuffer(t.resp.Body) 45 r.Body = ioutil.NopCloser(buf) 46 } 47 48 return &r, nil 49} 50 51// MockClient is a mocked Client that is used for tests. 52func NewMockClient(response MockResponse) *Client { 53 t := &mockTransport{resp: response} 54 c := &http.Client{Transport: t} 55 return NewClient(c) 56} 57