-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache_test.go
75 lines (69 loc) · 1.32 KB
/
cache_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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"sync"
"testing"
"time"
)
var urls = []string{
"https://golang.org",
"https://godoc.org",
"https://play.golang.org",
"http://gopl.io",
"https://golang.org",
"https://godoc.org",
"https://play.golang.org",
"http://gopl.io",
}
func httpGetBody(url string) func() ([]byte, error) {
return func() ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
}
func incomingURLs() <-chan string {
ch := make(chan string)
go func() {
for _, url := range urls {
ch <- url
}
close(ch)
}()
return ch
}
func TestSequential(t *testing.T) {
cache := NewCache()
for url := range incomingURLs() {
func(url string) {
start := time.Now()
value, err := cache.Get(url, httpGetBody(url))
if err != nil {
t.Error(err)
}
fmt.Printf("%s, %s, %d bytes\n", url, time.Since(start), len(value))
}(url)
}
}
func TestConcurrent(t *testing.T) {
cache := NewCache()
var n sync.WaitGroup
for url := range incomingURLs() {
n.Add(1)
go func(url string) {
start := time.Now()
value, err := cache.Get(url, httpGetBody(url))
if err != nil {
t.Error(err)
}
fmt.Printf("%s, %s, %d bytes\n", url, time.Since(start), len(value))
n.Done()
}(url)
}
n.Wait()
}