github.com/anacrolix/torrent@v1.61.0/internal/testutil/spec.go (about) 1 package testutil 2 3 import ( 4 "io" 5 "strings" 6 7 "github.com/anacrolix/missinggo/expect" 8 9 "github.com/anacrolix/torrent/bencode" 10 "github.com/anacrolix/torrent/metainfo" 11 ) 12 13 type File struct { 14 Name string 15 Data string 16 } 17 18 // High-level description of a torrent for testing purposes. 19 type Torrent struct { 20 Files []File 21 Name string 22 } 23 24 func (t *Torrent) IsDir() bool { 25 return len(t.Files) == 1 && t.Files[0].Name == "" 26 } 27 28 func (t *Torrent) GetFile(name string) *File { 29 if t.IsDir() && t.Name == name { 30 return &t.Files[0] 31 } 32 for _, f := range t.Files { 33 if f.Name == name { 34 return &f 35 } 36 } 37 return nil 38 } 39 40 func (t *Torrent) Info(pieceLength int64) metainfo.Info { 41 info := metainfo.Info{ 42 Name: t.Name, 43 PieceLength: pieceLength, 44 } 45 if t.IsDir() { 46 info.Length = int64(len(t.Files[0].Data)) 47 } else { 48 for _, f := range t.Files { 49 info.Files = append(info.Files, metainfo.FileInfo{ 50 Path: []string{f.Name}, 51 Length: int64(len(f.Data)), 52 }) 53 } 54 } 55 err := info.GeneratePieces(func(fi metainfo.FileInfo) (io.ReadCloser, error) { 56 return io.NopCloser(strings.NewReader(t.GetFile(strings.Join(fi.BestPath(), "/")).Data)), nil 57 }) 58 expect.Nil(err) 59 return info 60 } 61 62 // Create an info and metainfo with bytes set for the torrent with the provided piece length. 63 func (t *Torrent) Generate(pieceLength int64) (mi metainfo.MetaInfo, info metainfo.Info) { 64 var err error 65 info = t.Info(pieceLength) 66 mi.InfoBytes, err = bencode.Marshal(info) 67 expect.Nil(err) 68 return 69 }