]> Sergey Matveev's repositories - btrtrc.git/blob - torrent_test.go
Fix BenchmarkUpdatePiecePriorities
[btrtrc.git] / torrent_test.go
1 package torrent
2
3 import (
4         "fmt"
5         "io"
6         "net"
7         "os"
8         "path/filepath"
9         "testing"
10
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"
15
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"
21 )
22
23 func r(i, b, l pp.Integer) Request {
24         return Request{i, ChunkSpec{b, l}}
25 }
26
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.
33         }{
34                 // Invalid offset.
35                 {-1, Request{}},
36                 {0, r(0, 0, 16384)},
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)},
43                 {1, r(0, 0, 16384)},
44                 // One before end of chunk.
45                 {16383, r(0, 0, 16384)},
46                 // Second chunk.
47                 {16384, r(0, 16384, 16384)},
48         } {
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)
52                 }
53                 if req != _case.req {
54                         t.Fatalf("expected %v, got %v", _case.req, req)
55                 }
56         }
57 }
58
59 func TestAppendToCopySlice(t *testing.T) {
60         orig := []int{1, 2, 3}
61         dupe := append([]int{}, orig...)
62         dupe[0] = 4
63         if orig[0] != 1 {
64                 t.FailNow()
65         }
66 }
67
68 func TestTorrentString(t *testing.T) {
69         tor := &Torrent{}
70         s := tor.InfoHash().HexString()
71         if s != "0000000000000000000000000000000000000000" {
72                 t.FailNow()
73         }
74 }
75
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) {
80         const (
81                 numPieces   = 13410
82                 pieceLength = 256 << 10
83         )
84         cl := &Client{config: TestingConfig(b)}
85         cl.initLogger()
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,
91         }))
92         t.onSetInfo()
93         assert.EqualValues(b, 13410, t.numPieces())
94         for i := 0; i < 7; i += 1 {
95                 r := t.NewReader()
96                 r.SetReadahead(32 << 20)
97                 r.Seek(3500000, io.SeekStart)
98         }
99         assert.Len(b, t.readers, 7)
100         for i := 0; i < t.numPieces(); i += 3 {
101                 t._completedPieces.Add(bitmap.BitIndex(i))
102         }
103         t.DownloadPieces(0, t.numPieces())
104         for i := 0; i < b.N; i += 1 {
105                 t.updateAllPiecePriorities("")
106         }
107 }
108
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)
115         defer cl.Close()
116         ib, err := bencode.Marshal(metainfo.Info{
117                 Name:        "empty",
118                 Length:      0,
119                 PieceLength: 0,
120         })
121         require.NoError(t, err)
122         fp := filepath.Join(cfg.DataDir, "empty")
123         os.Remove(fp)
124         assert.False(t, missinggo.FilePathExists(fp))
125         tt, err := cl.AddTorrent(&metainfo.MetaInfo{
126                 InfoBytes: ib,
127         })
128         require.NoError(t, err)
129         defer tt.Drop()
130         tt.DownloadAll()
131         require.True(t, cl.WaitAll())
132         assert.True(t, tt.Complete.Bool())
133         assert.True(t, missinggo.FilePathExists(fp))
134 }
135
136 func TestEmptyFilesAndZeroPieceLengthWithFileStorage(t *testing.T) {
137         cfg := TestingConfig(t)
138         ci := storage.NewFile(cfg.DataDir)
139         defer ci.Close()
140         cfg.DefaultStorage = ci
141         testEmptyFilesAndZeroPieceLength(t, cfg)
142 }
143
144 func TestPieceHashFailed(t *testing.T) {
145         mi := testutil.GreetingMetaInfo()
146         cl := new(Client)
147         cl.config = TestingConfig(t)
148         cl.initLogger()
149         tt := cl.newTorrent(mi.HashInfoBytes(), badStorage{})
150         tt.setChunkSize(2)
151         require.NoError(t, tt.setInfoBytesLocked(mi.InfoBytes))
152         tt.cl.lock()
153         tt.dirtyChunks.AddRange(
154                 uint64(tt.pieceRequestIndexOffset(1)),
155                 uint64(tt.pieceRequestIndexOffset(1)+3))
156         require.True(t, tt.pieceAllDirty(1))
157         tt.pieceHashed(1, false, nil)
158         // Dirty chunks should be cleared so we can try again.
159         require.False(t, tt.pieceAllDirty(1))
160         tt.cl.unlock()
161 }
162
163 // Check the behaviour of Torrent.Metainfo when metadata is not completed.
164 func TestTorrentMetainfoIncompleteMetadata(t *testing.T) {
165         cfg := TestingConfig(t)
166         cfg.Debug = true
167         // Disable this just because we manually initiate a connection without it.
168         cfg.MinPeerExtensions.SetBit(pp.ExtensionBitFast, false)
169         cl, err := NewClient(cfg)
170         require.NoError(t, err)
171         defer cl.Close()
172
173         mi := testutil.GreetingMetaInfo()
174         ih := mi.HashInfoBytes()
175
176         tt, _ := cl.AddTorrentInfoHash(ih)
177         assert.Nil(t, tt.Metainfo().InfoBytes)
178         assert.False(t, tt.haveAllMetadataPieces())
179
180         nc, err := net.Dial("tcp", fmt.Sprintf(":%d", cl.LocalPort()))
181         require.NoError(t, err)
182         defer nc.Close()
183
184         var pex PeerExtensionBits
185         pex.SetBit(pp.ExtensionBitExtended, true)
186         hr, err := pp.Handshake(nc, &ih, [20]byte{}, pex)
187         require.NoError(t, err)
188         assert.True(t, hr.PeerExtensionBits.GetBit(pp.ExtensionBitExtended))
189         assert.EqualValues(t, cl.PeerID(), hr.PeerID)
190         assert.EqualValues(t, ih, hr.Hash)
191
192         assert.EqualValues(t, 0, tt.metadataSize())
193
194         func() {
195                 cl.lock()
196                 defer cl.unlock()
197                 go func() {
198                         _, err = nc.Write(pp.Message{
199                                 Type:       pp.Extended,
200                                 ExtendedID: pp.HandshakeExtendedID,
201                                 ExtendedPayload: func() []byte {
202                                         d := map[string]interface{}{
203                                                 "metadata_size": len(mi.InfoBytes),
204                                         }
205                                         b, err := bencode.Marshal(d)
206                                         if err != nil {
207                                                 panic(err)
208                                         }
209                                         return b
210                                 }(),
211                         }.MustMarshalBinary())
212                         require.NoError(t, err)
213                 }()
214                 tt.metadataChanged.Wait()
215         }()
216         assert.Equal(t, make([]byte, len(mi.InfoBytes)), tt.metadataBytes)
217         assert.False(t, tt.haveAllMetadataPieces())
218         assert.Nil(t, tt.Metainfo().InfoBytes)
219 }