-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseragent_test.go
More file actions
96 lines (79 loc) · 2.41 KB
/
useragent_test.go
File metadata and controls
96 lines (79 loc) · 2.41 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
package webtools
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/mileusna/useragent"
"github.com/shoenig/test/must"
)
func TestOrigin_From(t *testing.T) {
t.Parallel()
t.Run("forward set", func(t *testing.T) {
o := &Origin{
Host: "10.0.0.1",
Forward: "example.com",
}
s := o.From()
must.Eq(t, "example.com", s)
})
t.Run("not set", func(t *testing.T) {
o := &Origin{
Host: "10.0.0.1",
}
s := o.From()
must.Eq(t, "10.0.0.1", s)
})
}
func TestOrigin_Anchor(t *testing.T) {
t.Parallel()
cases := []struct {
name string
reference string
exp string
}{
{"Empty reference", "", "-"},
{"Standard URL", "https://example.com/path/to/page", "example.com/path/to/page"},
{"URL with query", "http://google.com/search?q=golang", "google.com/search"},
{"URL with fragment", "https://github.com/mileusna/useragent#readme", "github.com/mileusna/useragent"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
o := &Origin{Reference: tc.reference}
must.Eq(t, tc.exp, o.Anchor())
})
}
}
func TestOrigin_String(t *testing.T) {
t.Parallel()
cases := []struct {
name string
userAgent useragent.UserAgent
want string
}{
{"Bot", useragent.UserAgent{Name: "Googlebot", Bot: true}, "Googlebot/bot"},
{"Mobile", useragent.UserAgent{Name: "Safari", Mobile: true}, "Safari/phone"},
{"Tablet", useragent.UserAgent{Name: "Chrome", Tablet: true}, "Chrome/tablet"},
{"Desktop", useragent.UserAgent{Name: "Firefox", Desktop: true}, "Firefox/desktop"},
{"Unknown", useragent.UserAgent{Name: "MyBrowser"}, "MyBrowser/unknown"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
o := &Origin{UserAgent: tc.userAgent}
must.Eq(t, tc.want, o.String())
})
}
}
func TestOrigins(t *testing.T) {
t.Parallel()
agent := "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
r := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "https://example.org/v1/data", nil)
r.Header.Set("X-Forwarded-For", "10.1.1.1")
r.Header.Set("Referer", "https://dashboard.example.org/home")
r.Header.Set("User-Agent", agent)
origin := Origins(r)
must.Eq(t, "POST", origin.Method)
must.Eq(t, "example.org", origin.Host)
must.Eq(t, "10.1.1.1", origin.Forward)
must.Eq(t, "https://dashboard.example.org/home", origin.Reference)
must.Eq(t, "Chrome", origin.UserAgent.Name)
}