-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
123 lines (101 loc) · 2.13 KB
/
main_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
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"bytes"
"fmt"
"net/http"
"sync"
"testing"
"time"
)
const (
naiveURL = "http://localhost:9999/naive"
mutexURL = "http://localhost:9999/mutex"
channelURL = "http://localhost:9999/channel"
)
// Run server
func init() {
go main()
postJSON(naiveURL)
postJSON(mutexURL)
postJSON(channelURL)
}
func postJSON(url string) {
var jsonStr = []byte(`{"url":"http://localhost:9999/Gophers.jpg","width":80}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("[POST] error:", err)
return
}
defer resp.Body.Close()
}
func getResult(url string) {
resp, err := http.Get(url)
if err != nil {
fmt.Println("[GET] error:", err)
return
}
defer resp.Body.Close()
}
func runSeriesAsRoutine(f func(), count int, wait time.Duration, group *sync.WaitGroup) {
group.Add(1)
go func() {
defer group.Done()
for i := 0; i < count; i++ {
f()
time.Sleep(wait)
}
}()
}
func testDataraceURL(url string) {
var group sync.WaitGroup
for i := 0; i < 2; i++ {
runSeriesAsRoutine(func() { postJSON(url) }, 10, 20*time.Millisecond, &group)
time.Sleep(time.Second)
}
for i := 0; i < 2; i++ {
runSeriesAsRoutine(func() { getResult(url) }, 10, 20*time.Millisecond, &group)
}
group.Wait()
}
func TestDataraceNaive(t *testing.T) {
testDataraceURL(naiveURL)
}
func TestDataraceMutex(t *testing.T) {
testDataraceURL(mutexURL)
}
func TestDataraceChannel(t *testing.T) {
testDataraceURL(channelURL)
}
func BenchmarkGetNaive(b *testing.B) {
for n := 0; n < b.N; n++ {
getResult(naiveURL)
}
}
func BenchmarkGetMutex(b *testing.B) {
for n := 0; n < b.N; n++ {
getResult(mutexURL)
}
}
func BenchmarkGetChannel(b *testing.B) {
for n := 0; n < b.N; n++ {
getResult(channelURL)
}
}
func BenchmarkPostNaive(b *testing.B) {
for n := 0; n < b.N; n++ {
postJSON(naiveURL)
}
}
func BenchmarkPostMutex(b *testing.B) {
for n := 0; n < b.N; n++ {
postJSON(mutexURL)
}
}
func BenchmarkPostChannel(b *testing.B) {
for n := 0; n < b.N; n++ {
postJSON(channelURL)
}
}