blob: ef7f19a5d8d18b995d90e573c810d8b1c15654b3 [file] [log] [blame]
Samuel A. Falvo II2e2b8772013-07-04 15:40:15 -07001package gophercloud
2
3import (
4 "encoding/json"
Samuel A. Falvo II20f1aa42013-07-31 14:32:03 -07005 "fmt"
Samuel A. Falvo II2e2b8772013-07-04 15:40:15 -07006 "io/ioutil"
7 "net/http"
8 "strings"
Samuel A. Falvo II2d0f6da2013-07-15 16:41:52 -07009 "testing"
Samuel A. Falvo II2e2b8772013-07-04 15:40:15 -070010)
11
12type transport struct {
13 called int
14 response string
15 expectTenantId bool
16 tenantIdFound bool
Samuel A. Falvo II20f1aa42013-07-31 14:32:03 -070017 status int
Samuel A. Falvo II2e2b8772013-07-04 15:40:15 -070018}
19
20func (t *transport) RoundTrip(req *http.Request) (rsp *http.Response, err error) {
21 var authContainer *AuthContainer
22
23 t.called++
24
25 headers := make(http.Header)
26 headers.Add("Content-Type", "application/xml; charset=UTF-8")
27
28 body := ioutil.NopCloser(strings.NewReader(t.response))
29
Samuel A. Falvo II2d0f6da2013-07-15 16:41:52 -070030 if t.status == 0 {
31 t.status = 200
32 }
33 statusMsg := "OK"
34 if (t.status < 200) || (299 < t.status) {
35 statusMsg = "Error"
36 }
37
Samuel A. Falvo II2e2b8772013-07-04 15:40:15 -070038 rsp = &http.Response{
Samuel A. Falvo II2d0f6da2013-07-15 16:41:52 -070039 Status: fmt.Sprintf("%d %s", t.status, statusMsg),
40 StatusCode: t.status,
Samuel A. Falvo II2e2b8772013-07-04 15:40:15 -070041 Proto: "HTTP/1.1",
42 ProtoMajor: 1,
43 ProtoMinor: 1,
44 Header: headers,
45 Body: body,
46 ContentLength: -1,
47 TransferEncoding: nil,
48 Close: true,
49 Trailer: nil,
50 Request: req,
51 }
52
53 bytes, err := ioutil.ReadAll(req.Body)
54 if err != nil {
55 return nil, err
56 }
57 err = json.Unmarshal(bytes, &authContainer)
58 if err != nil {
59 return nil, err
60 }
61 t.tenantIdFound = (authContainer.Auth.TenantId != "")
62
63 if t.tenantIdFound != t.expectTenantId {
64 rsp.Status = "500 Internal Server Error"
65 rsp.StatusCode = 500
66 }
67 return
68}
69
70func newTransport() *transport {
71 return &transport{}
72}
73
74func (t *transport) IgnoreTenantId() *transport {
75 t.expectTenantId = false
76 return t
77}
78
79func (t *transport) ExpectTenantId() *transport {
80 t.expectTenantId = true
81 return t
82}
83
84func (t *transport) WithResponse(r string) *transport {
85 t.response = r
Samuel A. Falvo II2d0f6da2013-07-15 16:41:52 -070086 t.status = 200
Samuel A. Falvo II2e2b8772013-07-04 15:40:15 -070087 return t
88}
Samuel A. Falvo II2d0f6da2013-07-15 16:41:52 -070089
90func (t *transport) WithError(code int) *transport {
91 t.response = fmt.Sprintf("Error %d", code)
92 t.status = code
93 return t
94}
95
96func (t *transport) VerifyCalls(test *testing.T, n int) error {
97 if t.called != n {
98 err := fmt.Errorf("Expected Transport to be called %d times; found %d instead", n, t.called)
99 test.Error(err)
100 return err
101 }
102 return nil
Samuel A. Falvo II20f1aa42013-07-31 14:32:03 -0700103}