File: client_mock_test.go

package info (click to toggle)
golang-github-ncw-go-acd 0.0~git20161119.0.7954f1f-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 104 kB
  • ctags: 94
  • sloc: makefile: 40
file content (56 lines) | stat: -rw-r--r-- 1,247 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright (c) 2015 Serge Gebhardt. All rights reserved.
//
// Use of this source code is governed by the ISC
// license that can be found in the LICENSE file.

package acd

import (
	"bytes"
	"io/ioutil"
	"net/http"
)

// MockResponse is a static HTTP response.
type MockResponse struct {
	Code int
	Body []byte
}

// NewMockResponseOkString creates a new MockResponse with Code 200 (OK)
// and Body built from string argument
func NewMockResponseOkString(response string) *MockResponse {
	return &MockResponse{
		Code: 200,
		Body: []byte(response),
	}
}

// mockTransport is a mocked Transport that always returns the same MockResponse.
type mockTransport struct {
	resp MockResponse
}

// Satisfies the RoundTripper interface.
func (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	r := http.Response{
		StatusCode: t.resp.Code,
		Proto:      "HTTP/1.0",
		ProtoMajor: 1,
		ProtoMinor: 0,
	}

	if len(t.resp.Body) > 0 {
		buf := bytes.NewBuffer(t.resp.Body)
		r.Body = ioutil.NopCloser(buf)
	}

	return &r, nil
}

// MockClient is a mocked Client that is used for tests.
func NewMockClient(response MockResponse) *Client {
	t := &mockTransport{resp: response}
	c := &http.Client{Transport: t}
	return NewClient(c)
}