]> Sergey Matveev's repositories - btrtrc.git/blob - torrent_test.go
Merge commit 'c8dffdb'
[btrtrc.git] / torrent_test.go
1 package torrent
2
3 import (
4         "os"
5         "path/filepath"
6         "testing"
7
8         "github.com/anacrolix/missinggo"
9         "github.com/bradfitz/iter"
10         "github.com/stretchr/testify/assert"
11         "github.com/stretchr/testify/require"
12
13         "github.com/anacrolix/torrent/bencode"
14         "github.com/anacrolix/torrent/internal/testutil"
15         "github.com/anacrolix/torrent/metainfo"
16         "github.com/anacrolix/torrent/peer_protocol"
17         "github.com/anacrolix/torrent/storage"
18 )
19
20 func r(i, b, l peer_protocol.Integer) request {
21         return request{i, chunkSpec{b, l}}
22 }
23
24 // Check the given Request is correct for various torrent offsets.
25 func TestTorrentRequest(t *testing.T) {
26         const s = 472183431 // Length of torrent.
27         for _, _case := range []struct {
28                 off int64   // An offset into the torrent.
29                 req request // The expected Request. The zero value means !ok.
30         }{
31                 // Invalid offset.
32                 {-1, request{}},
33                 {0, r(0, 0, 16384)},
34                 // One before the end of a piece.
35                 {1<<18 - 1, r(0, 1<<18-16384, 16384)},
36                 // Offset beyond torrent length.
37                 {472 * 1 << 20, request{}},
38                 // One before the end of the torrent. Complicates the chunk length.
39                 {s - 1, r((s-1)/(1<<18), (s-1)%(1<<18)/(16384)*(16384), 12935)},
40                 {1, r(0, 0, 16384)},
41                 // One before end of chunk.
42                 {16383, r(0, 0, 16384)},
43                 // Second chunk.
44                 {16384, r(0, 16384, 16384)},
45         } {
46                 req, ok := torrentOffsetRequest(472183431, 1<<18, 16384, _case.off)
47                 if (_case.req == request{}) == ok {
48                         t.Fatalf("expected %v, got %v", _case.req, req)
49                 }
50                 if req != _case.req {
51                         t.Fatalf("expected %v, got %v", _case.req, req)
52                 }
53         }
54 }
55
56 func TestAppendToCopySlice(t *testing.T) {
57         orig := []int{1, 2, 3}
58         dupe := append([]int{}, orig...)
59         dupe[0] = 4
60         if orig[0] != 1 {
61                 t.FailNow()
62         }
63 }
64
65 func TestTorrentString(t *testing.T) {
66         tor := &Torrent{}
67         s := tor.InfoHash().HexString()
68         if s != "0000000000000000000000000000000000000000" {
69                 t.FailNow()
70         }
71 }
72
73 // This benchmark is from the observation that a lot of overlapping Readers on
74 // a large torrent with small pieces had a lot of overhead in recalculating
75 // piece priorities everytime a reader (possibly in another Torrent) changed.
76 func BenchmarkUpdatePiecePriorities(b *testing.B) {
77         cl := &Client{}
78         t := cl.newTorrent(metainfo.Hash{})
79         t.info = &metainfo.Info{
80                 Pieces:      make([]byte, 20*13410),
81                 PieceLength: 256 << 10,
82         }
83         t.makePieces()
84         assert.EqualValues(b, 13410, t.numPieces())
85         for range iter.N(7) {
86                 r := t.NewReader()
87                 r.SetReadahead(32 << 20)
88                 r.Seek(3500000, 0)
89         }
90         assert.Len(b, t.readers, 7)
91         t.pendPieceRange(0, t.numPieces())
92         for i := 0; i < t.numPieces(); i += 3 {
93                 t.completedPieces.Set(i, true)
94         }
95         for range iter.N(b.N) {
96                 t.updateAllPiecePriorities()
97         }
98 }
99
100 // Check that a torrent containing zero-length file(s) will start, and that
101 // they're created in the filesystem. The client storage is assumed to be
102 // file-based on the native filesystem based.
103 func testEmptyFilesAndZeroPieceLength(t *testing.T, cs storage.ClientImpl) {
104         cfg := TestingConfig
105         cfg.DefaultStorage = cs
106         cl, err := NewClient(&TestingConfig)
107         require.NoError(t, err)
108         defer cl.Close()
109         ib, err := bencode.Marshal(metainfo.Info{
110                 Name:        "empty",
111                 Length:      0,
112                 PieceLength: 0,
113         })
114         require.NoError(t, err)
115         fp := filepath.Join(TestingConfig.DataDir, "empty")
116         os.Remove(fp)
117         assert.False(t, missinggo.FilePathExists(fp))
118         tt, err := cl.AddTorrent(&metainfo.MetaInfo{
119                 InfoBytes: ib,
120         })
121         require.NoError(t, err)
122         defer tt.Drop()
123         tt.DownloadAll()
124         require.True(t, cl.WaitAll())
125         assert.True(t, missinggo.FilePathExists(fp))
126 }
127
128 func TestEmptyFilesAndZeroPieceLengthWithFileStorage(t *testing.T) {
129         testEmptyFilesAndZeroPieceLength(t, storage.NewFile(TestingConfig.DataDir))
130 }
131
132 func TestEmptyFilesAndZeroPieceLengthWithMMapStorage(t *testing.T) {
133         testEmptyFilesAndZeroPieceLength(t, storage.NewMMap(TestingConfig.DataDir))
134 }
135
136 func TestPieceHashFailed(t *testing.T) {
137         mi := testutil.GreetingMetaInfo()
138         tt := Torrent{
139                 cl:            new(Client),
140                 infoHash:      mi.HashInfoBytes(),
141                 storageOpener: storage.NewClient(badStorage{}),
142                 chunkSize:     2,
143         }
144         require.NoError(t, tt.setInfoBytes(mi.InfoBytes))
145         tt.pieces[1].DirtyChunks.AddRange(0, 3)
146         require.True(t, tt.pieceAllDirty(1))
147         tt.pieceHashed(1, false)
148         // Dirty chunks should be cleared so we can try again.
149         require.False(t, tt.pieceAllDirty(1))
150 }