11 "github.com/anacrolix/missinggo"
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
15 "github.com/anacrolix/torrent/bencode"
18 func testFile(t *testing.T, filename string) {
19 mi, err := LoadFromFile(filename)
20 require.NoError(t, err)
22 info := mi.UnmarshalInfo()
23 if len(info.Files) == 1 {
24 t.Logf("Single file: %s (length: %d)\n", info.Name, info.Files[0].Length)
26 t.Logf("Multiple files: %s\n", info.Name)
27 for _, f := range info.Files {
28 t.Logf(" - %s (length: %d)\n", path.Join(f.Path...), f.Length)
32 for _, group := range mi.AnnounceList {
33 for _, tracker := range group {
34 t.Logf("Tracker: %s\n", tracker)
38 b, err := bencode.Marshal(&info)
39 require.NoError(t, err)
40 assert.EqualValues(t, string(b), string(mi.InfoBytes))
43 func TestFile(t *testing.T) {
44 testFile(t, "testdata/archlinux-2011.08.19-netinstall-i686.iso.torrent")
45 testFile(t, "testdata/continuum.torrent")
46 testFile(t, "testdata/23516C72685E8DB0C8F15553382A927F185C4F01.torrent")
47 testFile(t, "testdata/trackerless.torrent")
50 // Ensure that the correct number of pieces are generated when hashing files.
51 func TestNumPieces(t *testing.T) {
52 for _, _case := range []struct {
57 {256 * 1024, []FileInfo{{Length: 1024*1024 + -1}}, 4},
58 {256 * 1024, []FileInfo{{Length: 1024 * 1024}}, 4},
59 {256 * 1024, []FileInfo{{Length: 1024*1024 + 1}}, 5},
60 {5, []FileInfo{{Length: 1}, {Length: 12}}, 3},
61 {5, []FileInfo{{Length: 4}, {Length: 12}}, 4},
65 PieceLength: _case.PieceLength,
67 err := info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) {
68 return ioutil.NopCloser(missinggo.ZeroReader), nil
70 assert.NoError(t, err)
71 assert.EqualValues(t, _case.NumPieces, info.NumPieces())
75 func touchFile(path string) (err error) {
76 f, err := os.Create(path)
84 func TestBuildFromFilePathOrder(t *testing.T) {
85 td, err := ioutil.TempDir("", "anacrolix")
86 require.NoError(t, err)
87 defer os.RemoveAll(td)
88 require.NoError(t, touchFile(filepath.Join(td, "b")))
89 require.NoError(t, touchFile(filepath.Join(td, "a")))
93 require.NoError(t, info.BuildFromFilePath(td))
94 assert.EqualValues(t, []FileInfo{{
101 func testUnmarshal(t *testing.T, input string, expected *MetaInfo) {
103 err := bencode.Unmarshal([]byte(input), &actual)
108 assert.NoError(t, err)
109 assert.EqualValues(t, *expected, actual)
112 func TestUnmarshal(t *testing.T) {
113 testUnmarshal(t, `de`, &MetaInfo{})
114 testUnmarshal(t, `d4:infoe`, &MetaInfo{})
115 testUnmarshal(t, `d4:infoabce`, nil)
116 testUnmarshal(t, `d4:infodee`, &MetaInfo{InfoBytes: []byte("de")})