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