-
Notifications
You must be signed in to change notification settings - Fork 1
/
user_agent_decorator_test.go
91 lines (78 loc) · 2.01 KB
/
user_agent_decorator_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
package uadeco
import (
"fmt"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestCommitHash(t *testing.T) {
InitServiceName(`uadeco`)
if !strings.Contains(userAgent, `go1.19`) &&
!strings.Contains(userAgent, `go1.20`) {
t.Errorf(`Test run using outdated go version %v`, userAgent)
}
fmt.Println(userAgent)
}
type FakeClient struct {
RoundTripFunc func(r *http.Request) (*http.Response, error)
}
func (s *FakeClient) RoundTrip(r *http.Request) (*http.Response, error) {
return s.RoundTripFunc(r)
}
func TestUADeco(t *testing.T) {
var rt http.RoundTripper = &FakeClient{
RoundTripFunc: func(r *http.Request) (*http.Response, error) {
assert.Equal(t, userAgent, r.Header.Get("User-Agent"))
return &http.Response{}, nil
},
}
req, err := NewHttpRequest("GET", "/", nil)
assert.Nil(t, err)
client := http.Client{
Transport: rt,
}
_, _ = client.Do(req)
}
func TestDecoratedClientTransport(t *testing.T) {
const testHost = `localhost:65533`
go func() {
http.HandleFunc(`/`, func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprint(w, r.Header.Get(`user-agent`))
})
_ = http.ListenAndServe(testHost, nil)
}()
compareUA := func(t *testing.T, resp *http.Response, err error) {
if assert.Nil(t, err) {
ua, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
assert.Equal(t, userAgent, string(ua))
}
}
t.Run(`HttpGet`, func(t *testing.T) {
for z := 0; z < 10; z++ {
resp, err := HttpGet(`http://` + testHost)
if err != nil {
time.Sleep(time.Millisecond * 100)
continue
}
compareUA(t, resp, err)
}
})
t.Run(`decorated-client`, func(t *testing.T) {
client := DecoratedClient
resp, err := client.Get(`http://` + testHost)
compareUA(t, resp, err)
})
t.Run(`default-client`, func(t *testing.T) {
resp, err := http.Get(`http://` + testHost)
compareUA(t, resp, err)
})
t.Run(`custom-client`, func(t *testing.T) {
client := &http.Client{}
resp, err := client.Get(`http://` + testHost)
compareUA(t, resp, err)
})
}