Debian Codegraph @

protocol_test.go

raw
1 package desync
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "io"
8 "testing"
9
10 "github.com/stretchr/testify/require"
11 "golang.org/x/sync/errgroup"
12 )
13
14 func TestProtocol(t *testing.T) {
15 r1, w1 := io.Pipe()
16 r2, w2 := io.Pipe()
17
18 server := NewProtocol(r1, w2)
19 client := NewProtocol(r2, w1)
20
21 // Test data
22 uncompressed := []byte{0, 0, 1, 1, 2, 2}
23 inChunk := NewChunk(uncompressed)
24 compressed, _ := Compressor{}.toStorage(uncompressed)
25 cID := inChunk.ID()
26
27 ctx, cancel := context.WithCancel(t.Context())
28 g, gCtx := errgroup.WithContext(ctx)
29 defer cancel()
30
31 // Server
32 g.Go(func() error {
33 flags, err := client.Initialize(CaProtocolReadableStore)
34 if err != nil {
35 return err
36 }
37 if flags&CaProtocolPullChunks == 0 {
38 return errors.New("client not asking for chunks")
39 }
40 for {
41 m, err := client.ReadMessage()
42 if err != nil {
43 if errors.Is(ctx.Err(), context.Canceled) {
44 return nil
45 }
46 return err
47 }
48 switch m.Type {
49 case CaProtocolRequest:
50 id, err := ChunkIDFromSlice(m.Body[8:40])
51 if err != nil {
52 return err
53 }
54 if err := client.SendProtocolChunk(id, 0, compressed); err != nil {
55 return err
56 }
57 default:
58
59 return errors.New("unexpected message")
60 }
61 }
62 })
63
64 // Client
65 g.Go(func() error {
66 defer cancel()
67 flags, err := server.Initialize(CaProtocolPullChunks)
68 if err != nil {
69 return err
70 }
71 if flags&CaProtocolReadableStore == 0 {
72 return errors.New("server not offering chunks")
73 }
74
75 chunk, err := server.RequestChunk(cID)
76 if err != nil {
77 return err
78 }
79 b, _ := chunk.Data()
80 if !bytes.Equal(b, uncompressed) {
81 return errors.New("chunk data doesn't match expected")
82 }
83 return nil
84 })
85
86 <-gCtx.Done()
87 // unblock client/server in case of an error
88 r1.Close()
89 r2.Close()
90 w1.Close()
91 w2.Close()
92
93 require.NoError(t, g.Wait())
94 }