]> Sergey Matveev's repositories - btrtrc.git/blob - internal/testutil/testutil.go
b43ddffa64f6064b385bff03ba06b5260d41dcb0
[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         "fmt"
11         "io"
12         "io/ioutil"
13         "net/http"
14         "os"
15         "path/filepath"
16
17         "github.com/anacrolix/missinggo"
18
19         "github.com/anacrolix/torrent/metainfo"
20 )
21
22 const GreetingFileContents = "hello, world\n"
23
24 func CreateDummyTorrentData(dirName string) string {
25         f, _ := os.Create(filepath.Join(dirName, "greeting"))
26         defer f.Close()
27         f.WriteString(GreetingFileContents)
28         return f.Name()
29 }
30
31 // Writes to w, a metainfo containing the file at name.
32 func CreateMetaInfo(name string, w io.Writer) {
33         var mi metainfo.MetaInfo
34         mi.Info.Name = filepath.Base(name)
35         fi, _ := os.Stat(name)
36         mi.Info.Length = fi.Size()
37         mi.Announce = "lol://cheezburger"
38         mi.Info.PieceLength = 5
39         err := mi.Info.GeneratePieces(func(metainfo.FileInfo) (io.ReadCloser, error) {
40                 return os.Open(name)
41         })
42         if err != nil {
43                 panic(err)
44         }
45         err = mi.Write(w)
46         if err != nil {
47                 panic(err)
48         }
49 }
50
51 // Gives a temporary directory containing the completed "greeting" torrent,
52 // and a corresponding metainfo describing it. The temporary directory can be
53 // cleaned away with os.RemoveAll.
54 func GreetingTestTorrent() (tempDir string, metaInfo *metainfo.MetaInfo) {
55         tempDir, err := ioutil.TempDir(os.TempDir(), "")
56         if err != nil {
57                 panic(err)
58         }
59         name := CreateDummyTorrentData(tempDir)
60         w := &bytes.Buffer{}
61         CreateMetaInfo(name, w)
62         metaInfo, _ = metainfo.Load(w)
63         return
64 }
65
66 type StatusWriter interface {
67         WriteStatus(io.Writer)
68 }
69
70 func ExportStatusWriter(sw StatusWriter, path string) {
71         http.HandleFunc(
72                 fmt.Sprintf("/%s/%s", missinggo.GetTestName(), path),
73                 func(w http.ResponseWriter, r *http.Request) {
74                         sw.WriteStatus(w)
75                 },
76         )
77 }