-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_test.go
108 lines (86 loc) · 1.94 KB
/
handler_test.go
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type mock struct {
t *testing.T
called bool
body string
closed bool
err error
}
func (m *mock) SendRequest(path, method string, body io.Reader) ([]byte, error) {
m.called = true
if path != "vms?clone=true" {
m.t.Fatalf("expected call with path 'vms', got %s", path)
}
if method != "POST" {
m.t.Fatalf("expected call with method POST, got %s", method)
}
b, err := ioutil.ReadAll(body)
if err != nil {
m.t.Fatal("could not read body")
}
m.body = strings.TrimSpace(string(b))
return []byte{}, m.err
}
func (m *mock) Close() {
m.closed = true
}
func TestHandlerCreatesVM(t *testing.T) {
m := runTest(t, nil, http.StatusOK)
if !m.called {
t.Fatal("no request was sent")
}
expected := expectedBody()
if m.body != expected {
t.Fatalf("got unexpected body\nexpected:\n%s\n\ngot:\n%s", expected, m.body)
}
}
func expectedBody() string {
b, err := ioutil.ReadFile("tests/body.xml")
if err != nil {
panic(err)
}
return strings.TrimSpace(string(b))
}
func TestHandlerClosesClient(t *testing.T) {
m := runTest(t, nil, http.StatusOK)
if !m.closed {
t.Fatal("handler does not close api connection")
}
}
func runTest(t *testing.T, err error, expectedStatus int) *mock {
m := &mock{t: t, err: err}
api := func() (apiClient, error) {
return m, nil
}
h := newHandler(api, loadTestTemplate)
srv := httptest.NewServer(h)
defer srv.Close()
b := loadTestRequest()
res, err := http.Post(srv.URL, "", b)
if err != nil {
t.Fatal("got error:", err)
}
if res.StatusCode != expectedStatus {
t.Fatalf("expected status %v, got %v", expectedStatus, res.Status)
}
return m
}
func loadTestRequest() io.Reader {
b, err := ioutil.ReadFile("examples/request.json")
if err != nil {
panic(err)
}
return bytes.NewReader(b)
}
func loadTestTemplate() ([]byte, error) {
return ioutil.ReadFile("examples/template.xml")
}