-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathetag_test.go
More file actions
114 lines (80 loc) · 2.32 KB
/
etag_test.go
File metadata and controls
114 lines (80 loc) · 2.32 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package etag
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"crypto/sha1"
"encoding/hex"
"github.com/go-http-utils/headers"
"github.com/stretchr/testify/suite"
)
var testStrBytes = []byte("Hello World")
var testStrEtag = "11-0a4d55a8d778e5022fab701977c5d840bbc486d0"
type EmptyEtagSuite struct {
suite.Suite
server *httptest.Server
}
func (s *EmptyEtagSuite) SetupTest() {
mux := http.NewServeMux()
mux.Handle("/", Handler(http.HandlerFunc(emptyHandlerFunc), false))
s.server = httptest.NewServer(mux)
}
func (s *EmptyEtagSuite) TestNoEtag() {
res, err := http.Get(s.server.URL + "/")
s.Nil(err)
s.Equal(http.StatusNoContent, res.StatusCode)
s.Empty(res.Header.Get(headers.ETag))
}
func TestEmptyEtag(t *testing.T) {
suite.Run(t, new(EmptyEtagSuite))
}
type EtagSuite struct {
suite.Suite
server *httptest.Server
weakServer *httptest.Server
}
func (s *EtagSuite) SetupTest() {
mux := http.NewServeMux()
mux.Handle("/", Handler(http.HandlerFunc(handlerFunc), false))
s.server = httptest.NewServer(mux)
wmux := http.NewServeMux()
wmux.Handle("/", Handler(http.HandlerFunc(handlerFunc), true))
s.weakServer = httptest.NewServer(wmux)
}
func (s EtagSuite) TestEtagExists() {
res, err := http.Get(s.server.URL + "/")
s.Nil(err)
s.Equal(http.StatusOK, res.StatusCode)
h := sha1.New()
h.Write(testStrBytes)
s.Equal(fmt.Sprintf("%v-%v", len(testStrBytes), hex.EncodeToString(h.Sum(nil))), res.Header.Get(headers.ETag))
}
func (s EtagSuite) TestWeakEtagExists() {
res, err := http.Get(s.weakServer.URL + "/")
s.Nil(err)
s.Equal(http.StatusOK, res.StatusCode)
h := sha1.New()
h.Write(testStrBytes)
s.Equal(fmt.Sprintf("W/%v-%v", len(testStrBytes), hex.EncodeToString(h.Sum(nil))), res.Header.Get(headers.ETag))
}
func (s EtagSuite) TestMatch() {
req, err := http.NewRequest(http.MethodGet, s.server.URL+"/", nil)
s.Nil(err)
req.Header.Set(headers.IfNoneMatch, testStrEtag)
cli := &http.Client{}
res, err := cli.Do(req)
s.Nil(err)
s.Equal(http.StatusNotModified, res.StatusCode)
}
func TestEtag(t *testing.T) {
suite.Run(t, new(EtagSuite))
}
func emptyHandlerFunc(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusNoContent)
res.Write(nil)
}
func handlerFunc(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
res.Write(testStrBytes)
}