-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
82 lines (66 loc) · 2.15 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
package main
import (
"net/http"
"net/http/httptest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
)
var _ = Describe("Building the HTTP server", func() {
var (
port int
username string
password string
server *http.Server
promHandler *ghttp.Server
)
BeforeEach(func() {
port = 8080
username, password = "", ""
promHandler = ghttp.NewUnstartedServer()
promHandler.AllowUnhandledRequests = true
promHandler.UnhandledRequestStatusCode = http.StatusOK
})
JustBeforeEach(func() {
server = buildHTTPServer(port, promHandler, username, password)
})
It("constructs the server to listen on the given port", func() {
Expect(server.Addr).To(Equal(":8080"))
})
It("passes /metrics requests to the given handler", func() {
req := httptest.NewRequest("GET", "http://www.example.com/metrics", nil)
resp := httptest.NewRecorder()
server.Handler.ServeHTTP(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK))
Expect(promHandler.ReceivedRequests()).To(HaveLen(1))
})
It("returns a 404 for other paths", func() {
req := httptest.NewRequest("GET", "http://www.example.com/", nil)
resp := httptest.NewRecorder()
server.Handler.ServeHTTP(resp, req)
Expect(resp.Code).To(Equal(http.StatusNotFound))
Expect(promHandler.ReceivedRequests()).To(HaveLen(0))
})
Context("with basic auth", func() {
BeforeEach(func() {
username = "user"
password = "secret"
})
It("rejects requests without basic auth", func() {
req := httptest.NewRequest("GET", "http://www.example.com/metrics", nil)
req.SetBasicAuth(username, "not-the-password")
resp := httptest.NewRecorder()
server.Handler.ServeHTTP(resp, req)
Expect(resp.Code).To(Equal(http.StatusUnauthorized))
Expect(promHandler.ReceivedRequests()).To(HaveLen(0))
})
It("allows valid requests through", func() {
req := httptest.NewRequest("GET", "http://www.example.com/metrics", nil)
req.SetBasicAuth(username, password)
resp := httptest.NewRecorder()
server.Handler.ServeHTTP(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK))
Expect(promHandler.ReceivedRequests()).To(HaveLen(1))
})
})
})