]> Sergey Matveev's repositories - btrtrc.git/blob - internal/testutil/testutil.go
metainfo: Add alternative "builder" API
[btrtrc.git] / internal / testutil / testutil.go
1 // Package testutil contains stuff for testing torrent-related behaviour.
2 //
3 // "greeting" is a single-file torrent of a file called "greeting" that
4 // "contains "hello, world\n".
5
6 package testutil
7
8 import (
9         "bytes"
10         "io"
11         "io/ioutil"
12         "os"
13         "path/filepath"
14
15         "github.com/anacrolix/torrent/metainfo"
16 )
17
18 const GreetingFileContents = "hello, world\n"
19
20 func CreateDummyTorrentData(dirName string) string {
21         f, _ := os.Create(filepath.Join(dirName, "greeting"))
22         defer f.Close()
23         f.WriteString(GreetingFileContents)
24         return f.Name()
25 }
26
27 // Writes to w, a metainfo containing the file at name.
28 func CreateMetaInfo(name string, w io.Writer) {
29         var mi metainfo.MetaInfo
30         mi.Info.Name = filepath.Base(name)
31         fi, _ := os.Stat(name)
32         mi.Info.Length = fi.Size()
33         mi.Announce = "lol://cheezburger"
34         mi.Info.PieceLength = 5
35         err := mi.Info.GeneratePieces(func(metainfo.FileInfo) (io.ReadCloser, error) {
36                 return os.Open(name)
37         })
38         if err != nil {
39                 panic(err)
40         }
41         err = mi.Write(w)
42         if err != nil {
43                 panic(err)
44         }
45 }
46
47 // Gives a temporary directory containing the completed "greeting" torrent,
48 // and a corresponding metainfo describing it. The temporary directory can be
49 // cleaned away with os.RemoveAll.
50 func GreetingTestTorrent() (tempDir string, metaInfo *metainfo.MetaInfo) {
51         tempDir, err := ioutil.TempDir(os.TempDir(), "")
52         if err != nil {
53                 panic(err)
54         }
55         name := CreateDummyTorrentData(tempDir)
56         w := &bytes.Buffer{}
57         CreateMetaInfo(name, w)
58         metaInfo, _ = metainfo.Load(w)
59         return
60 }