File: netctl_test.go

package info (click to toggle)
golang-github-henrybear327-go-proton-api 1.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,088 kB
  • sloc: sh: 55; makefile: 26
file content (79 lines) | stat: -rw-r--r-- 2,028 bytes parent folder | download
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
package proton_test

import (
	"bytes"
	"crypto/tls"
	"io"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/henrybear327/go-proton-api"
)

func TestNetCtl_ReadLimit(t *testing.T) {
	// Create a test http server that writes 100 bytes.
	// Including the header, this is 217 bytes (100 bytes + 117 bytes).
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		if _, err := w.Write(make([]byte, 100)); err != nil {
			t.Fatal(err)
		}
	}))
	defer ts.Close()

	// Create a new net controller.
	ctl := proton.NewNetCtl()

	// Set the read limit to 300 bytes -- the first request should succeed, the second should fail.
	ctl.SetReadLimit(300)

	// Create a new http client with the dialer.
	client := &http.Client{
		Transport: ctl.NewRoundTripper(&tls.Config{InsecureSkipVerify: true}),
	}

	// This should succeed.
	if resp, err := client.Get(ts.URL); err != nil {
		t.Fatal(err)
	} else {
		resp.Body.Close()
	}

	// This should fail.
	if _, err := client.Get(ts.URL); err == nil {
		t.Fatal("expected error")
	}
}

func TestNetCtl_WriteLimit(t *testing.T) {
	// Create a test http server that reads the given body.
	ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
		if _, err := io.ReadAll(r.Body); err != nil {
			t.Fatal(err)
		}
	}))
	defer ts.Close()

	// Create a new net controller.
	ctl := proton.NewNetCtl()

	// Set the read limit to 300 bytes -- the first request should succeed, the second should fail.
	ctl.SetWriteLimit(300)

	// Create a new http client with the dialer.
	client := &http.Client{
		Transport: ctl.NewRoundTripper(&tls.Config{InsecureSkipVerify: true}),
	}

	// This should succeed.
	if resp, err := client.Post(ts.URL, "application/octet-stream", bytes.NewReader(make([]byte, 100))); err != nil {
		t.Fatal(err)
	} else {
		resp.Body.Close()
	}

	// This should fail.
	if _, err := client.Post(ts.URL, "application/octet-stream", bytes.NewReader(make([]byte, 100))); err == nil {
		t.Fatal("expected error")
	}
}