-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware_test.go
92 lines (82 loc) · 2.25 KB
/
middleware_test.go
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
package redirecter
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
func next(w http.ResponseWriter, r *http.Request) error {
return nil
}
func TestUrlWithoutQuery(t *testing.T) {
r := httptest.NewRequest("GET", "/path?a=1&b=2", strings.NewReader(""))
r.Host = "domain.cat"
got := buildUrlWithoutQuery(r)
expected := "http://domain.cat/path"
if expected != got {
t.Errorf("Expected %s got %s", expected, got)
}
}
func TestRedirect(t *testing.T) {
tests := []struct {
caddyfile string
reqPath string
locationHeader string
}{
{`redirecter {
host "127.0.0.1"
port 5432
user "patates"
password "bullides"
db_name "vinissimus"
}`, "https://sub.domain.cat/old-page-needs-redirect", "/new-page"},
{`redirecter {
host "127.0.0.1"
port 5432
user "patates"
password "bullides"
db_name "vinissimus"
}`, "https://sub.domain.cat/working-page", ""},
}
loader = func(r *Redirecter) (map[string]string, error) {
newUrlMap := make(map[string]string)
newUrlMap["https://sub.domain.cat/old-page-needs-redirect"] = "/new-page"
return newUrlMap, nil
}
for i, test := range tests {
redirecter = nil
h := httpcaddyfile.Helper{
Dispenser: caddyfile.NewTestDispenser(test.caddyfile),
}
actual, err := parseCaddyfile(h)
if err != nil {
panic(err)
}
handler := actual.(*Middleware)
errProv := handler.Provision(caddy.Context{})
if errProv != nil {
panic(errProv)
}
r := httptest.NewRequest("GET", test.reqPath, strings.NewReader(""))
w := httptest.NewRecorder()
handler.ServeHTTP(w, r, caddyhttp.HandlerFunc(next))
headers := w.Header()
location, ok := headers["Location"]
expectHeader := len(test.locationHeader) > 0
if expectHeader {
if !ok {
t.Errorf("Text %v: Expected redirect but Location header is missing", i)
} else if test.locationHeader != location[0] {
t.Errorf("Test %v: Expected %s got %s", i, test.locationHeader, location[0])
}
} else {
if ok {
t.Errorf("Test %v: Did not expect Location header but got %s", i, location[0])
}
}
}
}