-
Notifications
You must be signed in to change notification settings - Fork 2
/
merger_test.go
79 lines (68 loc) · 1.7 KB
/
merger_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
package par_test
import (
"bytes"
"code.google.com/p/go.net/context"
"github.com/savaki/par"
. "github.com/visionmedia/go-debug"
"io"
"net/http"
"testing"
"time"
)
var debug = Debug("par_test")
type weather struct {
city string
value string
}
func FindWeather(city string, results chan weather) par.RequestFunc {
_city := city
return func(ctx context.Context) error {
request, _ := http.NewRequest("GET", "http://api.openweathermap.org/data/2.5/weather?q="+_city, nil)
return par.Do(ctx, request, func(response *http.Response, err error) error {
if err != nil {
return err
}
defer response.Body.Close()
// extract the body of the response and toss it onto the results channel
buffer := bytes.NewBuffer([]byte{})
io.Copy(buffer, response.Body)
results <- weather{_city, buffer.String()}
return nil
})
}
}
func TestPar(t *testing.T) {
// Given a channel of requests
redundancy := 2
cities := []string{
"San Francisco",
"Oakland",
"Berkeley",
"Palo Alto",
"San Jose",
}
requests := make(chan par.RequestFunc, len(cities))
results := make(chan weather, len(cities)*redundancy) // buffer for clarity of example
for _, city := range cities {
requests <- FindWeather(city, results)
}
close(requests)
// When
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
parallel := par.
Requests(requests).
WithRedundancy(redundancy).
WithConcurrency(3)
err := parallel.DoWithContext(ctx)
// Then - I expect success
if err != nil {
t.Fail()
}
// And - I can easily extract my resulting values
close(results)
allWeathers := map[string]string{}
for result := range results {
allWeathers[result.city] = result.value
}
}