git.iko.soy/typeable/oauth2-proxy
on v6.0.0 help sign in
typeable/oauth2-proxy/http_test.go
90 lines 2.3 kB history raw
1package main
3import (
4 "net/http"
5 "net/http/httptest"
6 "sync"
7 "testing"
8 "time"
10 "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/options"
11 "github.com/stretchr/testify/assert"
14func TestRedirectToHTTPSTrue(t *testing.T) {
15 opts := options.NewOptions()
16 opts.ForceHTTPS = true
17 handler := func(w http.ResponseWriter, req *http.Request) {
18 w.Write([]byte("test"))
19 }
21 h := redirectToHTTPS(opts, http.HandlerFunc(handler))
22 rw := httptest.NewRecorder()
23 r, _ := http.NewRequest("GET", "/", nil)
24 h.ServeHTTP(rw, r)
26 assert.Equal(t, http.StatusPermanentRedirect, rw.Code, "status code should be %d, got: %d", http.StatusPermanentRedirect, rw.Code)
29func TestRedirectToHTTPSFalse(t *testing.T) {
30 opts := options.NewOptions()
31 handler := func(w http.ResponseWriter, req *http.Request) {
32 w.Write([]byte("test"))
33 }
35 h := redirectToHTTPS(opts, http.HandlerFunc(handler))
36 rw := httptest.NewRecorder()
37 r, _ := http.NewRequest("GET", "/", nil)
38 h.ServeHTTP(rw, r)
40 assert.Equal(t, http.StatusOK, rw.Code, "status code should be %d, got: %d", http.StatusOK, rw.Code)
43func TestRedirectNotWhenHTTPS(t *testing.T) {
44 opts := options.NewOptions()
45 opts.ForceHTTPS = true
46 handler := func(w http.ResponseWriter, req *http.Request) {
47 w.Write([]byte("test"))
48 }
50 h := redirectToHTTPS(opts, http.HandlerFunc(handler))
51 s := httptest.NewTLSServer(h)
52 defer s.Close()
54 opts.HTTPSAddress = s.URL
55 client := s.Client()
56 res, err := client.Get(s.URL)
57 if err != nil {
58 t.Fatalf("request to test server failed with error: %v", err)
59 }
61 assert.Equal(t, http.StatusOK, res.StatusCode, "status code should be %d, got: %d", http.StatusOK, res.StatusCode)
64func TestGracefulShutdown(t *testing.T) {
65 opts := options.NewOptions()
66 stop := make(chan struct{}, 1)
67 srv := Server{Handler: http.DefaultServeMux, Opts: opts, stop: stop}
68 var wg sync.WaitGroup
69 wg.Add(1)
70 go func() {
71 defer wg.Done()
72 srv.ServeHTTP()
73 }()
75 stop <- struct{}{} // emulate catching signals
77 // An idiomatic for sync.WaitGroup with timeout
78 c := make(chan struct{})
79 go func() {
80 defer close(c)
81 wg.Wait()
82 }()
83 select {
84 case <-c:
85 case <-time.After(1 * time.Second):
86 t.Fatal("Server should return gracefully but timeout has occurred")
87 }
89 assert.Len(t, stop, 0) // check if stop chan is empty