-
Notifications
You must be signed in to change notification settings - Fork 13
/
testutil.go
103 lines (85 loc) · 2.21 KB
/
testutil.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
package testutil
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"github.com/deis/controller-sdk-go"
"github.com/deis/workflow-cli/settings"
)
// TestServer represents a test HTTP server along with a path to a config file
type TestServer struct {
Server *httptest.Server
Mux *http.ServeMux
}
// NewTestServer sets up a test HTTP Server without a configuration file.
func NewTestServer() *TestServer {
// test server
mux := http.NewServeMux()
server := httptest.NewServer(mux)
return &TestServer{
Server: server,
Mux: mux,
}
}
// Close closes the test HTTP server.
func (t *TestServer) Close() {
t.Server.Close()
}
// NewTestServerAndClient sets up a test HTTP Server along with a configuration file to talk to it
func NewTestServerAndClient() (string, *TestServer, error) {
server := NewTestServer()
name, err := ioutil.TempDir("", "client")
if err != nil {
server.Close()
return "", nil, err
}
filename := filepath.Join(name, "test.json")
client, err := deis.New(false, server.Server.URL, "")
if err != nil {
server.Close()
return "", nil, err
}
config := settings.Settings{
Username: "test",
Client: client,
}
filename, err = config.Save(filename)
if err != nil {
server.Close()
return "", nil, err
}
return filename, server, nil
}
// AssertBody asserts the value of the body of a request.
func AssertBody(t *testing.T, expected interface{}, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
t.Fatal(err)
}
value, err := json.Marshal(expected)
if err != nil {
t.Fatal(err)
}
if string(body) != string(value) {
t.Errorf("Expected body '%s' actually got '%s'\n", value, body)
}
}
// StripProgress strips the output from the progress method
func StripProgress(input string) string {
first := strings.Index(input, "\b")
// If \b charecter not part of string
if first == -1 {
return input
}
last := strings.LastIndex(input, "\b")
// return string without \b or the characters it deletes.
return input[:first-(last-first+1)] + input[last+1:]
}
// SetHeaders sets standard headers for requests
func SetHeaders(w http.ResponseWriter) {
w.Header().Add("DEIS_API_VERSION", deis.APIVersion)
}