11 "github.com/anacrolix/missinggo/v2"
12 "github.com/anacrolix/missinggo/v2/bitmap"
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
16 "github.com/anacrolix/torrent/bencode"
17 "github.com/anacrolix/torrent/internal/testutil"
18 "github.com/anacrolix/torrent/metainfo"
19 pp "github.com/anacrolix/torrent/peer_protocol"
20 "github.com/anacrolix/torrent/storage"
23 func r(i, b, l pp.Integer) Request {
24 return Request{i, ChunkSpec{b, l}}
27 // Check the given request is correct for various torrent offsets.
28 func TestTorrentRequest(t *testing.T) {
29 const s = 472183431 // Length of torrent.
30 for _, _case := range []struct {
31 off int64 // An offset into the torrent.
32 req Request // The expected request. The zero value means !ok.
37 // One before the end of a piece.
38 {1<<18 - 1, r(0, 1<<18-16384, 16384)},
39 // Offset beyond torrent length.
40 {472 * 1 << 20, Request{}},
41 // One before the end of the torrent. Complicates the chunk length.
42 {s - 1, r((s-1)/(1<<18), (s-1)%(1<<18)/(16384)*(16384), 12935)},
44 // One before end of chunk.
45 {16383, r(0, 0, 16384)},
47 {16384, r(0, 16384, 16384)},
49 req, ok := torrentOffsetRequest(472183431, 1<<18, 16384, _case.off)
50 if (_case.req == Request{}) == ok {
51 t.Fatalf("expected %v, got %v", _case.req, req)
54 t.Fatalf("expected %v, got %v", _case.req, req)
59 func TestAppendToCopySlice(t *testing.T) {
60 orig := []int{1, 2, 3}
61 dupe := append([]int{}, orig...)
68 func TestTorrentString(t *testing.T) {
70 s := tor.InfoHash().HexString()
71 if s != "0000000000000000000000000000000000000000" {
76 // This benchmark is from the observation that a lot of overlapping Readers on
77 // a large torrent with small pieces had a lot of overhead in recalculating
78 // piece priorities everytime a reader (possibly in another Torrent) changed.
79 func BenchmarkUpdatePiecePriorities(b *testing.B) {
82 pieceLength = 256 << 10
84 cl := &Client{config: TestingConfig(b)}
86 t := cl.newTorrent(metainfo.Hash{}, nil)
87 require.NoError(b, t.setInfo(&metainfo.Info{
88 Pieces: make([]byte, metainfo.HashSize*numPieces),
89 PieceLength: pieceLength,
90 Length: pieceLength * numPieces,
93 assert.EqualValues(b, 13410, t.numPieces())
94 for i := 0; i < 7; i += 1 {
96 r.SetReadahead(32 << 20)
97 r.Seek(3500000, io.SeekStart)
99 assert.Len(b, t.readers, 7)
100 for i := 0; i < t.numPieces(); i += 3 {
101 t._completedPieces.Add(bitmap.BitIndex(i))
103 t.DownloadPieces(0, t.numPieces())
104 for i := 0; i < b.N; i += 1 {
105 t.updateAllPiecePriorities("")
109 // Check that a torrent containing zero-length file(s) will start, and that
110 // they're created in the filesystem. The client storage is assumed to be
111 // file-based on the native filesystem based.
112 func testEmptyFilesAndZeroPieceLength(t *testing.T, cfg *ClientConfig) {
113 cl, err := NewClient(cfg)
114 require.NoError(t, err)
116 ib, err := bencode.Marshal(metainfo.Info{
121 require.NoError(t, err)
122 fp := filepath.Join(cfg.DataDir, "empty")
124 assert.False(t, missinggo.FilePathExists(fp))
125 tt, err := cl.AddTorrent(&metainfo.MetaInfo{
128 require.NoError(t, err)
131 require.True(t, cl.WaitAll())
132 assert.True(t, tt.Complete.Bool())
133 assert.True(t, missinggo.FilePathExists(fp))
136 func TestEmptyFilesAndZeroPieceLengthWithFileStorage(t *testing.T) {
137 cfg := TestingConfig(t)
138 ci := storage.NewFile(cfg.DataDir)
140 cfg.DefaultStorage = ci
141 testEmptyFilesAndZeroPieceLength(t, cfg)
144 func TestPieceHashFailed(t *testing.T) {
145 mi := testutil.GreetingMetaInfo()
146 cl := newTestingClient(t)
147 tt := cl.newTorrent(mi.HashInfoBytes(), badStorage{})
149 require.NoError(t, tt.setInfoBytesLocked(mi.InfoBytes))
151 tt.dirtyChunks.AddRange(
152 uint64(tt.pieceRequestIndexOffset(1)),
153 uint64(tt.pieceRequestIndexOffset(1)+3))
154 require.True(t, tt.pieceAllDirty(1))
155 tt.pieceHashed(1, false, nil)
156 // Dirty chunks should be cleared so we can try again.
157 require.False(t, tt.pieceAllDirty(1))
161 // Check the behaviour of Torrent.Metainfo when metadata is not completed.
162 func TestTorrentMetainfoIncompleteMetadata(t *testing.T) {
163 cfg := TestingConfig(t)
165 // Disable this just because we manually initiate a connection without it.
166 cfg.MinPeerExtensions.SetBit(pp.ExtensionBitFast, false)
167 cl, err := NewClient(cfg)
168 require.NoError(t, err)
171 mi := testutil.GreetingMetaInfo()
172 ih := mi.HashInfoBytes()
174 tt, _ := cl.AddTorrentInfoHash(ih)
175 assert.Nil(t, tt.Metainfo().InfoBytes)
176 assert.False(t, tt.haveAllMetadataPieces())
178 nc, err := net.Dial("tcp", fmt.Sprintf(":%d", cl.LocalPort()))
179 require.NoError(t, err)
182 var pex PeerExtensionBits
183 pex.SetBit(pp.ExtensionBitExtended, true)
184 hr, err := pp.Handshake(nc, &ih, [20]byte{}, pex)
185 require.NoError(t, err)
186 assert.True(t, hr.PeerExtensionBits.GetBit(pp.ExtensionBitExtended))
187 assert.EqualValues(t, cl.PeerID(), hr.PeerID)
188 assert.EqualValues(t, ih, hr.Hash)
190 assert.EqualValues(t, 0, tt.metadataSize())
196 _, err = nc.Write(pp.Message{
198 ExtendedID: pp.HandshakeExtendedID,
199 ExtendedPayload: func() []byte {
200 d := map[string]interface{}{
201 "metadata_size": len(mi.InfoBytes),
203 b, err := bencode.Marshal(d)
209 }.MustMarshalBinary())
210 require.NoError(t, err)
212 tt.metadataChanged.Wait()
214 assert.Equal(t, make([]byte, len(mi.InfoBytes)), tt.metadataBytes)
215 assert.False(t, tt.haveAllMetadataPieces())
216 assert.Nil(t, tt.Metainfo().InfoBytes)