-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_test.go
77 lines (61 loc) · 2.48 KB
/
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
package requests
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/test-go/testify/assert"
)
// createTestServerForProxy creates a simple HTTP server for testing purposes.
func createTestServerForProxy() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
}
// TestSetProxyValidProxy tests setting a valid proxy and making a request through it.
func TestSetProxyValidProxy(t *testing.T) {
server := createTestServerForProxy()
defer server.Close()
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Indicate the request passed through the proxy
w.Header().Set("X-Test-Proxy", "true")
w.WriteHeader(http.StatusOK)
}))
defer proxyServer.Close()
client := URL(server.URL)
err := client.SetProxy(proxyServer.URL)
assert.Nil(t, err, "Setting a valid proxy should not result in an error.")
resp, err := client.Get("/").Send(context.Background())
assert.Nil(t, err, "Request through a valid proxy should succeed.")
assert.NotNil(t, resp, "Response should not be nil.")
assert.Equal(t, "true", resp.Header().Get("X-Test-Proxy"), "Request should have passed through the proxy.")
}
// TestSetProxyInvalidProxy tests handling of invalid proxy URLs.
func TestSetProxyInvalidProxy(t *testing.T) {
server := createTestServerForProxy()
defer server.Close()
client := URL(server.URL)
invalidProxyURL := "://invalid_url"
err := client.SetProxy(invalidProxyURL)
assert.NotNil(t, err, "Setting an invalid proxy URL should result in an error.")
}
// TestSetProxyRemoveProxy tests removing proxy settings.
func TestSetProxyRemoveProxy(t *testing.T) {
server := createTestServerForProxy()
defer server.Close()
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Proxy server response
w.WriteHeader(http.StatusOK)
}))
defer proxyServer.Close()
client := URL(server.URL)
// Set then remove the proxy
err := client.SetProxy(proxyServer.URL)
assert.Nil(t, err, "Setting a proxy should not result in an error.")
client.RemoveProxy()
// Make a request and check it doesn't go through the proxy
resp, err := client.Get("/").Send(context.Background())
assert.Nil(t, err, "Request after removing proxy should succeed.")
assert.NotNil(t, resp, "Response should not be nil.")
assert.NotEqual(t, "true", resp.Header().Get("X-Test-Proxy"), "Request should not have passed through the proxy.")
}