forked from flexera-public/rsc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
95 lines (81 loc) · 2.36 KB
/
main_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
package main
import (
"bytes"
"io/ioutil"
"net/http"
"github.com/rightscale/rsc/cmd"
"gopkg.in/alecthomas/kingpin.v2"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
type timeoutError struct{ error }
func (e *timeoutError) Error() string { return "i/o timeout" }
func (e *timeoutError) Timeout() bool { return true }
func (e *timeoutError) Temporary() bool { return true }
var _ = Describe("Main", func() {
Context("Creating response from JSON input", func() {
var (
resp *http.Response
json = []byte(`{"foo":"bar","baz":42,"m":[{"a":1},{"a":2}]}`)
bom = []byte{0xef, 0xbb, 0xbf}
respBody []byte
err error
)
JustBeforeEach(func() {
resp = CreateJSONResponse(json)
respBody, err = ioutil.ReadAll(resp.Body)
})
Context("Creates valid response from JSON without BOM", func() {
It("creates valid response", func() {
Ω(err).ShouldNot(HaveOccurred())
Ω(bytes.HasPrefix(respBody, bom)).Should(BeFalse())
Ω(respBody).Should(Equal(json))
})
})
Context("Creates valid response from JSON with BOM", func() {
BeforeEach(func() {
json = append(bom, json...)
})
It("creates valid response", func() {
Ω(err).ShouldNot(HaveOccurred())
Ω(bytes.HasPrefix(respBody, bom)).Should(BeFalse())
Ω(respBody).Should(Equal(bytes.TrimPrefix(json, bom)))
})
})
})
Context("retry option", func() {
var app = kingpin.New("rsc", "rsc - tests")
var retries = 6
var cmdLine = cmd.CommandLine{Retry: retries}
var origDoAPIRequest func(string, *cmd.CommandLine) (*http.Response, error)
BeforeEach(func() {
origDoAPIRequest = doAPIRequest
})
AfterEach(func() {
doAPIRequest = origDoAPIRequest
})
It("retries if error on API call occurs", func() {
counter := 0
doAPIRequest = func(string, *cmd.CommandLine) (*http.Response, error) {
counter += 1
return nil, &timeoutError{}
}
ExecuteCommand(app, &cmdLine)
Ω(counter).Should(Equal(1 + retries))
})
It("doesn't retry more than necessary", func() {
counter := 0
doAPIRequest = func(string, *cmd.CommandLine) (*http.Response, error) {
counter += 1
if counter < 3 {
return &http.Response{StatusCode: 503}, nil
} else {
return nil, nil
}
}
_, err := ExecuteCommand(app, &cmdLine)
Ω(err).ShouldNot(HaveOccurred())
Ω(counter).Should(BeNumerically("<", 1+retries))
})
})
})