| 1 |
package proton_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"crypto/tls" |
| 6 |
"io" |
| 7 |
"net/http" |
| 8 |
"net/http/httptest" |
| 9 |
"testing" |
| 10 |
|
| 11 |
"github.com/henrybear327/go-proton-api" |
| 12 |
) |
| 13 |
|
| 14 |
func TestNetCtl_ReadLimit(t *testing.T) { |
| 15 |
// Create a test http server that writes 100 bytes. |
| 16 |
// Including the header, this is 217 bytes (100 bytes + 117 bytes). |
| 17 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 18 |
if _, err := w.Write(make([]byte, 100)); err != nil { |
| 19 |
t.Fatal(err) |
| 20 |
} |
| 21 |
})) |
| 22 |
defer ts.Close() |
| 23 |
|
| 24 |
// Create a new net controller. |
| 25 |
ctl := proton.NewNetCtl() |
| 26 |
|
| 27 |
// Set the read limit to 300 bytes -- the first request should succeed, the second should fail. |
| 28 |
ctl.SetReadLimit(300) |
| 29 |
|
| 30 |
// Create a new http client with the dialer. |
| 31 |
client := &http.Client{ |
| 32 |
Transport: ctl.NewRoundTripper(&tls.Config{InsecureSkipVerify: true}), |
| 33 |
} |
| 34 |
|
| 35 |
// This should succeed. |
| 36 |
if resp, err := client.Get(ts.URL); err != nil { |
| 37 |
t.Fatal(err) |
| 38 |
} else { |
| 39 |
resp.Body.Close() |
| 40 |
} |
| 41 |
|
| 42 |
// This should fail. |
| 43 |
if _, err := client.Get(ts.URL); err == nil { |
| 44 |
t.Fatal("expected error") |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
func TestNetCtl_WriteLimit(t *testing.T) { |
| 49 |
// Create a test http server that reads the given body. |
| 50 |
ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { |
| 51 |
if _, err := io.ReadAll(r.Body); err != nil { |
| 52 |
t.Fatal(err) |
| 53 |
} |
| 54 |
})) |
| 55 |
defer ts.Close() |
| 56 |
|
| 57 |
// Create a new net controller. |
| 58 |
ctl := proton.NewNetCtl() |
| 59 |
|
| 60 |
// Set the read limit to 300 bytes -- the first request should succeed, the second should fail. |
| 61 |
ctl.SetWriteLimit(300) |
| 62 |
|
| 63 |
// Create a new http client with the dialer. |
| 64 |
client := &http.Client{ |
| 65 |
Transport: ctl.NewRoundTripper(&tls.Config{InsecureSkipVerify: true}), |
| 66 |
} |
| 67 |
|
| 68 |
// This should succeed. |
| 69 |
if resp, err := client.Post(ts.URL, "application/octet-stream", bytes.NewReader(make([]byte, 100))); err != nil { |
| 70 |
t.Fatal(err) |
| 71 |
} else { |
| 72 |
resp.Body.Close() |
| 73 |
} |
| 74 |
|
| 75 |
// This should fail. |
| 76 |
if _, err := client.Post(ts.URL, "application/octet-stream", bytes.NewReader(make([]byte, 100))); err == nil { |
| 77 |
t.Fatal("expected error") |
| 78 |
} |
| 79 |
} |