File: middleware_test.go

package info (click to toggle)
golang-github-zenazn-goji 1.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 464 kB
  • sloc: makefile: 3
file content (71 lines) | stat: -rw-r--r-- 1,520 bytes parent folder | download | duplicates (3)
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
// +build !go1.3

package graceful

import (
	"net/http"
	"sync/atomic"
	"testing"
)

type fakeWriter http.Header

func (f fakeWriter) Header() http.Header {
	return http.Header(f)
}
func (f fakeWriter) Write(buf []byte) (int, error) {
	return len(buf), nil
}
func (f fakeWriter) WriteHeader(status int) {}

func testClose(t *testing.T, h http.Handler, expectClose bool) {
	m := middleware(h)
	r, _ := http.NewRequest("GET", "/", nil)
	w := make(fakeWriter)
	m.ServeHTTP(w, r)

	c, ok := w["Connection"]
	if expectClose {
		if !ok || len(c) != 1 || c[0] != "close" {
			t.Fatal("Expected 'Connection: close'")
		}
	} else {
		if ok {
			t.Fatal("Did not expect Connection header")
		}
	}
}

func TestNormal(t *testing.T) {
	atomic.StoreInt32(&closing, 0)
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte{})
	})
	testClose(t, h, false)
}

func TestClose(t *testing.T) {
	atomic.StoreInt32(&closing, 0)
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		atomic.StoreInt32(&closing, 1)
	})
	testClose(t, h, true)
}

func TestCloseWriteHeader(t *testing.T) {
	atomic.StoreInt32(&closing, 0)
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		atomic.StoreInt32(&closing, 1)
		w.WriteHeader(200)
	})
	testClose(t, h, true)
}

func TestCloseWrite(t *testing.T) {
	atomic.StoreInt32(&closing, 0)
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		atomic.StoreInt32(&closing, 1)
		w.Write([]byte{})
	})
	testClose(t, h, true)
}