-
Notifications
You must be signed in to change notification settings - Fork 13
/
http_proxy_test.go
111 lines (94 loc) · 2.33 KB
/
http_proxy_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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Copyright 2022-2024 Sauce Labs Inc., all rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package forwarder
import (
"context"
"errors"
"net"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/saucelabs/forwarder/log/stdlog"
"golang.org/x/net/http2"
)
func TestAbortIf(t *testing.T) {
// Create proxy with basic auth.
cfg := DefaultHTTPProxyConfig()
cfg.BasicAuth = url.UserPassword("user", "pass")
p, err := NewHTTPProxy(cfg, nil, nil, nil, stdlog.Default())
if err != nil {
t.Fatal(err)
}
defer p.Close()
check := func(t *testing.T, rt http.RoundTripper) {
t.Helper()
req, err := http.NewRequest(http.MethodGet, "http://foobar", http.NoBody)
if err != nil {
t.Fatal(err)
}
resp, err := rt.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusProxyAuthRequired {
t.Fatalf("expected %d, got %d", http.StatusProxyAuthRequired, resp.StatusCode)
}
}
t.Run("http", func(t *testing.T) {
s := httptest.NewServer(p.handler())
defer s.Close()
tr := &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
return net.Dial(network, s.Listener.Addr().String())
},
}
check(t, tr)
})
t.Run("http2", func(t *testing.T) {
c0, c1 := net.Pipe()
defer c0.Close()
defer c1.Close()
var s http2.Server
go s.ServeConn(c1, &http2.ServeConnOpts{
Handler: p.handler(),
})
var tr http2.Transport
tr.AllowHTTP = true
cc, err := tr.NewClientConn(c0)
if err != nil {
t.Fatal(err)
}
defer cc.Close()
check(t, cc)
})
}
func TestNopDialer(t *testing.T) {
nopDialerErr := errors.New("nop dialer")
tr := &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return nil, nopDialerErr
},
}
p, err := NewHTTPProxy(DefaultHTTPProxyConfig(), nil, nil, tr, stdlog.Default())
if err != nil {
t.Fatal(err)
}
defer p.Close()
req := &http.Request{
Method: http.MethodGet,
Header: map[string][]string{},
URL: &url.URL{
Scheme: "http",
Host: "foobar",
},
Host: "foobar",
}
_, err = p.proxy.RoundTripper.RoundTrip(req)
if !errors.Is(err, nopDialerErr) {
t.Fatalf("expected %v, got %v", nopDialerErr, err)
}
}