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