-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathprotocol_test.go
More file actions
96 lines (84 loc) · 1.77 KB
/
protocol_test.go
File metadata and controls
96 lines (84 loc) · 1.77 KB
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
package desync
import (
"bytes"
"context"
"errors"
"io"
"testing"
"golang.org/x/sync/errgroup"
)
func TestProtocol(t *testing.T) {
r1, w1 := io.Pipe()
r2, w2 := io.Pipe()
server := NewProtocol(r1, w2)
client := NewProtocol(r2, w1)
// Test data
uncompressed := []byte{0, 0, 1, 1, 2, 2}
inChunk := NewChunk(uncompressed)
compressed, _ := Compressor{}.toStorage(uncompressed)
cID := inChunk.ID()
ctx, cancel := context.WithCancel(t.Context())
g, gCtx := errgroup.WithContext(ctx)
defer cancel()
// Server
g.Go(func() error {
flags, err := client.Initialize(CaProtocolReadableStore)
if err != nil {
return err
}
if flags&CaProtocolPullChunks == 0 {
return errors.New("client not asking for chunks")
}
for {
m, err := client.ReadMessage()
if err != nil {
if errors.Is(ctx.Err(), context.Canceled) {
return nil
}
return err
}
switch m.Type {
case CaProtocolRequest:
id, err := ChunkIDFromSlice(m.Body[8:40])
if err != nil {
return err
}
if err := client.SendProtocolChunk(id, 0, compressed); err != nil {
return err
}
default:
return errors.New("unexpected message")
}
}
})
// Client
g.Go(func() error {
defer cancel()
flags, err := server.Initialize(CaProtocolPullChunks)
if err != nil {
return err
}
if flags&CaProtocolReadableStore == 0 {
return errors.New("server not offering chunks")
}
chunk, err := server.RequestChunk(cID)
if err != nil {
return err
}
b, _ := chunk.Data()
if !bytes.Equal(b, uncompressed) {
return errors.New("chunk data doesn't match expected")
}
return nil
})
<-gCtx.Done()
// unblock client/server in case of an error
r1.Close()
r2.Close()
w1.Close()
w2.Close()
err := g.Wait()
if err != nil {
t.Fatal(err)
}
}