7 "github.com/stretchr/testify/assert"
9 "github.com/anacrolix/torrent/internal/pieceordering"
10 "github.com/anacrolix/torrent/peer_protocol"
13 func TestCancelRequestOptimized(t *testing.T) {
16 PeerPieces: []bool{false, true},
17 post: make(chan peer_protocol.Message),
18 writeCh: make(chan []byte),
20 if len(c.Requests) != 0 {
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")
29 // Posting this message should removing the pending Request.
30 if !c.Cancel(newRequest(1, 2, 3)) {
31 t.Fatal("request was not found")
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.
40 bb := string(<-c.writeCh)
42 t.Fatalf("received message %q is not expected: %q", bb, b)
46 // Drain the write channel until it closes.
47 for b := range c.writeCh {
49 if bs != "\x00\x00\x00\x00" {
50 t.Fatal("got unexpected non-keepalive")
55 func pieceOrderingAsSlice(po *pieceordering.Instance) (ret []int) {
56 for e := po.First(); e != nil; e = e.Next() {
57 ret = append(ret, e.Piece())
62 func testRequestOrder(expected []int, ro *pieceordering.Instance, t *testing.T) {
63 assert.EqualValues(t, pieceOrderingAsSlice(ro), expected)