]> Sergey Matveev's repositories - btrtrc.git/blob - connection_test.go
77dbb53b50551b43b7e0dcb175cfa72763ca7e86
[btrtrc.git] / connection_test.go
1 package torrent
2
3 import (
4         "testing"
5         "time"
6
7         "github.com/stretchr/testify/assert"
8
9         "github.com/anacrolix/torrent/internal/pieceordering"
10         "github.com/anacrolix/torrent/peer_protocol"
11 )
12
13 func TestCancelRequestOptimized(t *testing.T) {
14         c := &connection{
15                 PeerMaxRequests: 1,
16                 PeerPieces:      []bool{false, true},
17                 post:            make(chan peer_protocol.Message),
18                 writeCh:         make(chan []byte),
19         }
20         if len(c.Requests) != 0 {
21                 t.FailNow()
22         }
23         // Keepalive timeout of 0 works because I'm just that good.
24         go c.writeOptimizer(0 * time.Millisecond)
25         c.Request(newRequest(1, 2, 3))
26         if len(c.Requests) != 1 {
27                 t.Fatal("request was not posted")
28         }
29         // Posting this message should removing the pending Request.
30         if !c.Cancel(newRequest(1, 2, 3)) {
31                 t.Fatal("request was not found")
32         }
33         // Check that the write optimization has filtered out the Request message.
34         for _, b := range []string{
35                 // The initial request triggers an Interested message.
36                 "\x00\x00\x00\x01\x02",
37                 // Let a keep-alive through to verify there were no pending messages.
38                 "\x00\x00\x00\x00",
39         } {
40                 bb := string(<-c.writeCh)
41                 if b != bb {
42                         t.Fatalf("received message %q is not expected: %q", bb, b)
43                 }
44         }
45         close(c.post)
46         // Drain the write channel until it closes.
47         for b := range c.writeCh {
48                 bs := string(b)
49                 if bs != "\x00\x00\x00\x00" {
50                         t.Fatal("got unexpected non-keepalive")
51                 }
52         }
53 }
54
55 func pieceOrderingAsSlice(po *pieceordering.Instance) (ret []int) {
56         for e := po.First(); e != nil; e = e.Next() {
57                 ret = append(ret, e.Piece())
58         }
59         return
60 }
61
62 func testRequestOrder(expected []int, ro *pieceordering.Instance, t *testing.T) {
63         assert.EqualValues(t, pieceOrderingAsSlice(ro), expected)
64 }