7 "github.com/bradfitz/iter"
10 "github.com/anacrolix/torrent/internal/pieceordering"
11 "github.com/anacrolix/torrent/peer_protocol"
14 func TestCancelRequestOptimized(t *testing.T) {
17 PeerPieces: []bool{false, true},
18 post: make(chan peer_protocol.Message),
19 writeCh: make(chan []byte),
21 if len(c.Requests) != 0 {
24 // Keepalive timeout of 0 works because I'm just that good.
25 go c.writeOptimizer(0 * time.Millisecond)
26 c.Request(newRequest(1, 2, 3))
27 if len(c.Requests) != 1 {
28 t.Fatal("request was not posted")
30 // Posting this message should removing the pending Request.
31 if !c.Cancel(newRequest(1, 2, 3)) {
32 t.Fatal("request was not found")
34 // Check that the write optimization has filtered out the Request message.
35 for _, b := range []string{
36 // The initial request triggers an Interested message.
37 "\x00\x00\x00\x01\x02",
38 // Let a keep-alive through to verify there were no pending messages.
41 bb := string(<-c.writeCh)
43 t.Fatalf("received message %q is not expected: %q", bb, b)
47 // Drain the write channel until it closes.
48 for b := range c.writeCh {
50 if bs != "\x00\x00\x00\x00" {
51 t.Fatal("got unexpected non-keepalive")
56 func pieceOrderingAsSlice(po *pieceordering.Instance) (ret []int) {
57 for e := po.First(); e != nil; e = e.Next() {
58 ret = append(ret, e.Piece())
63 func testRequestOrder(expected []int, ro *pieceordering.Instance, t *C) {
64 t.Assert(pieceOrderingAsSlice(ro), DeepEquals, expected)
69 var _ = Suite(suite{})
71 func Test(t *testing.T) { TestingT(t) }
73 // Tests the request ordering based on a connections priorities.
74 func (suite) TestPieceRequestOrder(t *C) {
76 pieceRequestOrder: pieceordering.New(),
77 piecePriorities: []int{1, 4, 0, 3, 2},
79 testRequestOrder(nil, c.pieceRequestOrder, t)
80 c.pendPiece(2, PiecePriorityNone)
81 testRequestOrder(nil, c.pieceRequestOrder, t)
82 c.pendPiece(1, PiecePriorityNormal)
83 c.pendPiece(2, PiecePriorityNormal)
84 testRequestOrder([]int{2, 1}, c.pieceRequestOrder, t)
85 c.pendPiece(0, PiecePriorityNormal)
86 testRequestOrder([]int{2, 0, 1}, c.pieceRequestOrder, t)
87 c.pendPiece(1, PiecePriorityReadahead)
88 testRequestOrder([]int{1, 2, 0}, c.pieceRequestOrder, t)
89 c.pendPiece(4, PiecePriorityNow)
90 // now(4), r(1), normal(0, 2)
91 testRequestOrder([]int{4, 1, 2, 0}, c.pieceRequestOrder, t)
92 c.pendPiece(2, PiecePriorityReadahead)
93 // N(4), R(1, 2), N(0)
94 testRequestOrder([]int{4, 2, 1, 0}, c.pieceRequestOrder, t)
95 c.pendPiece(1, PiecePriorityNow)
96 // now(4, 1), readahead(2), normal(0)
97 // in the same order, the keys will be: -15+6, -15+12, -5, 1
98 // so we test that a very low priority (for this connection), "now"
99 // piece has been placed after a readahead piece.
100 testRequestOrder([]int{4, 2, 1, 0}, c.pieceRequestOrder, t)
101 // Note this intentially sets to None a piece that's not in the order.
102 for i := range iter.N(5) {
103 c.pendPiece(i, PiecePriorityNone)
105 testRequestOrder(nil, c.pieceRequestOrder, t)