9 "github.com/anacrolix/missinggo/pubsub"
10 "github.com/bradfitz/iter"
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
14 "github.com/anacrolix/torrent/metainfo"
15 pp "github.com/anacrolix/torrent/peer_protocol"
16 "github.com/anacrolix/torrent/storage"
19 // Ensure that no race exists between sending a bitfield, and a subsequent
20 // Have that would potentially alter it.
21 func TestSendBitfieldThenHave(t *testing.T) {
25 c := cl.newConnection(nil)
26 c.setTorrent(cl.newTorrent(metainfo.Hash{}, nil))
27 c.t.setInfo(&metainfo.Info{
28 Pieces: make([]byte, metainfo.HashSize*3),
32 go c.writer(time.Minute)
34 c.t.completedPieces.Add(1)
35 c.PostBitfield( /*[]bool{false, true, false}*/ )
41 n, err := io.ReadFull(r, b)
43 // This will cause connection.writer to terminate.
46 require.NoError(t, err)
47 require.EqualValues(t, 15, n)
48 // Here we see that the bitfield doesn't have piece 2 set, as that should
49 // arrive in the following Have message.
50 require.EqualValues(t, "\x00\x00\x00\x02\x05@\x00\x00\x00\x05\x04\x00\x00\x00\x02", string(b))
53 type torrentStorage struct {
57 func (me *torrentStorage) Close() error { return nil }
59 func (me *torrentStorage) Piece(mp metainfo.Piece) storage.PieceImpl {
63 func (me *torrentStorage) Completion() storage.Completion {
64 return storage.Completion{}
67 func (me *torrentStorage) MarkComplete() error {
71 func (me *torrentStorage) MarkNotComplete() error {
75 func (me *torrentStorage) ReadAt([]byte, int64) (int, error) {
76 panic("shouldn't be called")
79 func (me *torrentStorage) WriteAt(b []byte, _ int64) (int, error) {
80 if len(b) != defaultChunkSize {
87 func BenchmarkConnectionMainReadLoop(b *testing.B) {
89 ts := &torrentStorage{}
92 storage: &storage.Torrent{ts},
93 pieceStateChanges: pubsub.NewPubSub(),
95 require.NoError(b, t.setInfo(&metainfo.Info{
96 Pieces: make([]byte, 20),
100 t.setChunkSize(defaultChunkSize)
101 t.pendingPieces.Set(0, PiecePriorityNormal.BitmapPriority())
107 mrlErr := make(chan error)
110 err := cn.mainReadLoop()
118 Piece: make([]byte, defaultChunkSize),
120 wb, err := msg.MarshalBinary()
121 require.NoError(b, err)
122 b.SetBytes(int64(len(msg.Piece)))
124 for range iter.N(b.N) {
126 t.pieces[0].dirtyChunks.Clear()
128 n, err := w.Write(wb)
129 require.NoError(b, err)
130 require.EqualValues(b, len(wb), n)
134 require.NoError(b, <-mrlErr)
135 require.EqualValues(b, b.N, cn.stats.ChunksReadUseful)
138 func TestConnectionReceiveBadChunkIndex(t *testing.T) {
142 require.False(t, cn.t.haveInfo())
143 assert.NotPanics(t, func() { cn.receiveChunk(&pp.Message{Type: pp.Piece}) })
144 cn.t.info = &metainfo.Info{}
145 require.True(t, cn.t.haveInfo())
146 assert.NotPanics(t, func() { cn.receiveChunk(&pp.Message{Type: pp.Piece}) })