]> Sergey Matveev's repositories - btrtrc.git/blob - internal/testutil/testutil.go
Rename TorrentData->Data
[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/libtorgo/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         builder := metainfo.Builder{}
30         builder.AddFile(name)
31         builder.AddAnnounceGroup([]string{"lol://cheezburger"})
32         builder.SetPieceLength(5)
33         batch, err := builder.Submit()
34         if err != nil {
35                 panic(err)
36         }
37         errs, _ := batch.Start(w, 1)
38         <-errs
39 }
40
41 // Gives a temporary directory containing the completed "greeting" torrent,
42 // and a corresponding metainfo describing it. The temporary directory can be
43 // cleaned away with os.RemoveAll.
44 func GreetingTestTorrent() (tempDir string, metaInfo *metainfo.MetaInfo) {
45         tempDir, err := ioutil.TempDir(os.TempDir(), "")
46         if err != nil {
47                 panic(err)
48         }
49         name := CreateDummyTorrentData(tempDir)
50         w := &bytes.Buffer{}
51         CreateMetaInfo(name, w)
52         metaInfo, _ = metainfo.Load(w)
53         return
54 }