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