forked from gin-contrib/size
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsize_test.go
98 lines (86 loc) · 1.84 KB
/
size_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
package limits
import (
"bytes"
"fmt"
"net/http"
"os"
"os/exec"
"testing"
"text/template"
"time"
)
var (
params = struct {
Size int
Port int
}{10, 9388}
codeFile = "/tmp/ratelimit_test_server.go"
serverURL string
)
func init() {
tmpl := template.Must(template.ParseFiles("test_server.tmpl"))
fp, err := os.Create(codeFile)
if err != nil {
panic(fmt.Errorf("can't open %s - %s", codeFile, err))
}
err = tmpl.Execute(fp, params)
if err != nil {
panic(fmt.Errorf("can't create %s - %s", codeFile, err))
}
serverURL = fmt.Sprintf("http://localhost:%d", params.Port)
}
func waitForServer() error {
timeout := 30 * time.Second
ch := make(chan bool)
go func() {
for {
_, err := http.Post(serverURL, "text/plain", nil)
if err == nil {
ch <- true
}
time.Sleep(10 * time.Millisecond)
}
}()
select {
case <-ch:
return nil
case <-time.After(timeout):
return fmt.Errorf("server did not reply after %v", timeout)
}
}
func runServer() (*exec.Cmd, error) {
cmd := exec.Command("go", "run", codeFile)
cmd.Start()
if err := waitForServer(); err != nil {
return nil, err
}
return cmd, nil
}
func doPost(val string) (*http.Response, error) {
cmd, err := runServer()
if err != nil {
return nil, err
}
defer cmd.Process.Kill()
var buf bytes.Buffer
fmt.Fprintf(&buf, "big=%s", val)
return http.Post(serverURL, "application/x-www-form-urlencoded", &buf)
}
func TestRateLimiterOK(t *testing.T) {
resp, err := doPost("abc")
if err != nil {
t.Fatalf("error posting - %s", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("bad status - %d", resp.StatusCode)
}
}
func TestRateLimiterOver(t *testing.T) {
resp, err := doPost("abcdefghijklmnop")
if err != nil {
t.Fatalf("error posting - %s", err)
}
if resp.StatusCode != http.StatusRequestEntityTooLarge {
t.Fatalf("bad status - %d", resp.StatusCode)
}
}