-
Notifications
You must be signed in to change notification settings - Fork 6
/
cors_test.go
71 lines (54 loc) · 1.92 KB
/
cors_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
package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type testrwcors struct{}
func (trw testrwcors) Header() http.Header { return http.Header{} }
func (trw testrwcors) Write(b []byte) (int, error) { return len(b), nil }
func (trw testrwcors) WriteHeader(int) {}
type testhandler int
func (h *testhandler) ServeHTTP(_ http.ResponseWriter, _ *http.Request) { *h++ }
func TestNewCors(t *testing.T) {
t.Run("passed handler is called", func(t *testing.T) {
var h testhandler
wrapped := newCors(&h)
req, _ := http.NewRequest("GET", "/", strings.NewReader(""))
var rw testrwcors
for range [134]struct{}{} {
wrapped.ServeHTTP(rw, req)
}
if want, have := 134, int(h); want != have {
t.Errorf("expected the handler to be called %d times, found %d", want, have)
}
})
t.Run("cors headers are injected", func(t *testing.T) {
var h testhandler
wrapped := newCors(&h)
req, _ := http.NewRequest("GET", "/", strings.NewReader(""))
rw := httptest.NewRecorder()
wrapped.ServeHTTP(rw, req)
for k, v := range map[string]string{
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, PUT, POST, DELETE, HEAD, OPTIONS",
"Access-Control-Allow-Headers": "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,X-Api-Key,If-Modified-Since,Cache-Control,Content-Type",
} {
if want, have := v, rw.HeaderMap.Get(k); want != have {
t.Errorf("expected header %q to have value %q, found %q", k, want, have)
}
}
})
t.Run("cors cache ttl is injected in OPTIONS calls", func(t *testing.T) {
var h testhandler
wrapped := newCors(&h)
req, _ := http.NewRequest("OPTIONS", "/", strings.NewReader(""))
rw := httptest.NewRecorder()
wrapped.ServeHTTP(rw, req)
key := "Access-Control-Max-Age"
if want, have := "1728000", rw.HeaderMap.Get(key); want != have {
t.Errorf("expected header %q to have value %q, found %q", key, want, have)
}
})
}