-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestutils.go
69 lines (63 loc) · 2.45 KB
/
testutils.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
package goscm
import (
"net/http"
"net/http/httptest"
"os"
"testing"
)
// This starts a Testify server which responds with a JSON if and only if the requested URL matches the expected one.
// It is advised to end each Server instance with a server.Close() statement after finishing a unit test.
//
// If SendsMethodResponse is set to true, the server will respond with a generic template by the pattern of OK-[Method]
// if and only if both the expected URL and the method as a value match.
func setupTestServer(urlToJson map[string]string, sendsMethodResponse bool, t *testing.T) *httptest.Server {
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if sendsMethodResponse {
urlIncluded, _ := checkMethodResponse(urlToJson, request, writer)
if !urlIncluded {
t.Logf("Received url " + request.RequestURI + " with method " + request.Method + " doesn't match any predefined url and method for this server.")
writer.WriteHeader(404)
}
} else {
urlIncluded, _ := checkJsonResponse(urlToJson, request, writer)
if !urlIncluded {
t.Logf("Received url " + request.RequestURI + " doesn't match any predefined url for this server.")
writer.WriteHeader(404)
}
}
}))
return server
}
// Checks whether both URL and method are registered and sends back a signal text.
func checkMethodResponse(urlToMethod map[string]string, request *http.Request, writer http.ResponseWriter) (bool, error) {
for expectedURL, method := range urlToMethod {
if request.RequestURI == expectedURL && request.Method == method {
writer.Header().Set("Content-Type", "text/plain")
_, err := writer.Write([]byte("OK-" + method))
if err != nil {
return false, err
}
return true, nil
}
}
return false, nil
}
// Checks whether the URL is registered and sends back the predefined JSON file.
func checkJsonResponse(urlToJson map[string]string, request *http.Request, writer http.ResponseWriter) (bool, error) {
for expectedUrl, jsonFile := range urlToJson {
if request.RequestURI == expectedUrl {
writer.Header().Set("Content-Type", "application/json")
content, _ := os.ReadFile(jsonFile)
_, err := writer.Write(content)
if err != nil {
return false, err
}
return true, nil
}
}
return false, nil
}
// Cf. setupTestServer.
func setupSingleTestServer(jsonFile string, expectedUrl string, t *testing.T) *httptest.Server {
return setupTestServer(map[string]string{expectedUrl: jsonFile}, false, t)
}