-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtest_setup_test.go
105 lines (88 loc) · 2.34 KB
/
test_setup_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
package httpbackoff
import (
"fmt"
"io"
"net"
"net/http"
"os"
"testing"
"time"
"github.com/cenkalti/backoff/v3"
)
var (
err error
handler *MyHandler
listener net.Listener
server *http.Server
testClient *Client
)
// Handler for stubbing http requests from auth API endpoint
type MyHandler struct {
QueuedResponses []HTTPResponse
}
type HTTPResponse struct {
body string
statusCode int
}
// Fake auth endpoint
func (handler *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
response := handler.QueuedResponses[0]
handler.QueuedResponses = handler.QueuedResponses[1:]
w.WriteHeader(response.statusCode)
_, _ = io.WriteString(w, response.body)
}
func (handler *MyHandler) QueueResponse(statusCode int) {
body := fmt.Sprintf("This is a *fake* HTTP %d response body for testing purposes", statusCode)
handler.QueuedResponses = append(handler.QueuedResponses, HTTPResponse{body: body, statusCode: statusCode})
}
func (handler *MyHandler) ClearResponseQueue() {
handler.QueuedResponses = make([]HTTPResponse, 0)
}
func NewMyHandler() *MyHandler {
return &MyHandler{QueuedResponses: make([]HTTPResponse, 0)}
}
// Custom setup and tear down
func TestMain(m *testing.M) {
// Set up appropriate backoff settings to tests run quickly...
testClient = &Client{
BackOffSettings: &backoff.ExponentialBackOff{
InitialInterval: 1 * time.Millisecond,
RandomizationFactor: 0.2,
Multiplier: 1.2,
MaxInterval: 5 * time.Millisecond,
MaxElapsedTime: 20 * time.Millisecond,
Clock: backoff.SystemClock,
},
}
err = startServingHTTP()
if err != nil {
fmt.Println("ERROR: unable to serve HTTP for stub auth service!")
fmt.Printf("%v\n", err)
os.Exit(1)
}
// Start the listener...
go func() {
_ = server.Serve(listener)
}()
// Run all the tests...
returnCode := m.Run()
// Tear down
err = stopServingHTTP()
if err != nil {
fmt.Println("ERROR: Failed to shut down http server")
fmt.Printf("%v\n", err)
}
os.Exit(returnCode)
}
// start up http service
func startServingHTTP() error {
handler = NewMyHandler()
server = &http.Server{Addr: "localhost:50849", Handler: handler}
listener, err = net.Listen("tcp", "localhost:50849")
return err
}
// bring down http service
func stopServingHTTP() error {
server.SetKeepAlivesEnabled(false)
return listener.Close()
}