Skip to content

Commit 8526911

Browse files
committed
Add test package
1 parent 389c9e7 commit 8526911

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed

test/http.go

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package test
2+
3+
import (
4+
"net/http"
5+
)
6+
7+
func IsSuccessfulResponse(r *http.Response) bool {
8+
return (r.StatusCode >= 200 && r.StatusCode <= 299) || r.StatusCode == 304
9+
}
10+
11+
func HasExpectedHeader(r *http.Response, header http.Header) bool {
12+
for key, values := range header {
13+
actual := r.Header.Values(key)
14+
if len(actual) != len(values) {
15+
return false
16+
}
17+
18+
for i, v := range values {
19+
if v != actual[i] {
20+
return false
21+
}
22+
}
23+
}
24+
25+
return true
26+
}

test/http_test.go

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package test
2+
3+
import (
4+
"net/http"
5+
"testing"
6+
)
7+
8+
func TestIsSuccessfulResponse(t *testing.T) {
9+
res := &http.Response{}
10+
11+
expects := map[int]bool{
12+
200: true,
13+
201: true,
14+
204: true,
15+
299: true,
16+
300: false,
17+
303: false,
18+
304: true,
19+
305: false,
20+
404: false,
21+
}
22+
23+
for statusCode, ok := range expects {
24+
res.StatusCode = statusCode
25+
if IsSuccessfulResponse(res) != ok {
26+
t.Fatalf("%d: %v / %v", statusCode, IsSuccessfulResponse(res), ok)
27+
}
28+
}
29+
}
30+
31+
func TestHasExpectedHeader(t *testing.T) {
32+
res := &http.Response{
33+
Header: make(http.Header),
34+
}
35+
36+
res.Header.Set("X-Drive", "1")
37+
res.Header.Add("X-Drive", "2")
38+
39+
expected := http.Header{
40+
"X-Drive": []string{"1", "2"},
41+
}
42+
43+
if !HasExpectedHeader(res, expected) {
44+
t.Fatal("header check failed")
45+
}
46+
47+
notFound := http.Header{
48+
"X-Not-Found": []string{"value"},
49+
}
50+
if HasExpectedHeader(res, notFound) {
51+
t.Fatal("header check failed")
52+
}
53+
54+
invalidLength := http.Header{
55+
"X-Drive": []string{"1"},
56+
}
57+
if HasExpectedHeader(res, invalidLength) {
58+
t.Fatal("header check failed")
59+
}
60+
61+
invalidValue := http.Header{
62+
"X-Drive": []string{"1", "3"},
63+
}
64+
if HasExpectedHeader(res, invalidValue) {
65+
t.Fatal("header check failed")
66+
}
67+
}

0 commit comments

Comments
 (0)