mux/middleware/helmet_test.go

53 lines
1.1 KiB
Go

package middleware
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"gitserver.in/patialtech/mux"
)
func TestHelmet(t *testing.T) {
r := mux.NewRouter()
r.Use(Helmet(HelmetOption{}))
r.Get("/hello", func(writer http.ResponseWriter, request *http.Request) {
_, _ = writer.Write([]byte("hello there"))
})
srv := httptest.NewServer(r)
defer srv.Close()
w, _ := testRequest(t, srv, "GET", "/hello", nil)
csp := w.Header.Get("Content-Security-Policy")
// must not have a csp header, technically no header related to helmet but lets test with one.
if csp == "" {
t.Error("csp header is expected")
}
}
func testRequest(t *testing.T, ts *httptest.Server, method, path string, body io.Reader) (*http.Response, string) {
req, err := http.NewRequest(method, ts.URL+path, body)
if err != nil {
t.Fatal(err)
return nil, ""
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
return nil, ""
}
respBody, err := io.ReadAll(io.Reader(resp.Body))
if err != nil {
t.Fatal(err)
return nil, ""
}
defer resp.Body.Close()
return resp, string(respBody)
}