]> Sergey Matveev's repositories - btrtrc.git/blob - internal/testutil/spec.go
Begin restructuring testutil to support testing torrents with various properties
[btrtrc.git] / internal / testutil / spec.go
1 package testutil
2
3 import (
4         "io"
5         "io/ioutil"
6         "strings"
7
8         "github.com/anacrolix/missinggo/assert"
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 type Torrent struct {
19         Files []File
20         Name  string
21 }
22
23 func (t *Torrent) IsDir() bool {
24         return len(t.Files) == 1 && t.Files[0].Name == ""
25 }
26
27 func (t *Torrent) GetFile(name string) *File {
28         if t.IsDir() && t.Name == name {
29                 return &t.Files[0]
30         }
31         for _, f := range t.Files {
32                 if f.Name == name {
33                         return &f
34                 }
35         }
36         return nil
37 }
38
39 func (t *Torrent) Info(pieceLength int64) metainfo.Info {
40         info := metainfo.Info{
41                 Name:        t.Name,
42                 PieceLength: pieceLength,
43         }
44         if t.IsDir() {
45                 info.Length = int64(len(t.Files[0].Data))
46         }
47         err := info.GeneratePieces(func(fi metainfo.FileInfo) (io.ReadCloser, error) {
48                 return ioutil.NopCloser(strings.NewReader(t.GetFile(strings.Join(fi.Path, "/")).Data)), nil
49         })
50         assert.Nil(err)
51         return info
52 }
53
54 func (t *Torrent) Metainfo(pieceLength int64) *metainfo.MetaInfo {
55         mi := metainfo.MetaInfo{}
56         var err error
57         mi.InfoBytes, err = bencode.Marshal(t.Info(pieceLength))
58         assert.Nil(err)
59         return &mi
60 }