]> Sergey Matveev's repositories - btrtrc.git/blob - bencode/encode_test.go
bencode: Avoid an extra getTags call
[btrtrc.git] / bencode / encode_test.go
1 package bencode
2
3 import (
4         "bytes"
5         "fmt"
6         "math/big"
7         "testing"
8
9         "github.com/stretchr/testify/assert"
10 )
11
12 type random_encode_test struct {
13         value    interface{}
14         expected string
15 }
16
17 type random_struct struct {
18         ABC         int    `bencode:"abc"`
19         SkipThisOne string `bencode:"-"`
20         CDE         string
21 }
22
23 type dummy struct {
24         a, b, c int
25 }
26
27 func (d *dummy) MarshalBencode() ([]byte, error) {
28         var b bytes.Buffer
29         _, err := fmt.Fprintf(&b, "i%dei%dei%de", d.a+1, d.b+1, d.c+1)
30         if err != nil {
31                 return nil, err
32         }
33         return b.Bytes(), nil
34 }
35
36 var random_encode_tests = []random_encode_test{
37         {int(10), "i10e"},
38         {uint(10), "i10e"},
39         {"hello, world", "12:hello, world"},
40         {true, "i1e"},
41         {false, "i0e"},
42         {int8(-8), "i-8e"},
43         {int16(-16), "i-16e"},
44         {int32(32), "i32e"},
45         {int64(-64), "i-64e"},
46         {uint8(8), "i8e"},
47         {uint16(16), "i16e"},
48         {uint32(32), "i32e"},
49         {uint64(64), "i64e"},
50         {random_struct{123, "nono", "hello"}, "d3:CDE5:hello3:abci123ee"},
51         {map[string]string{"a": "b", "c": "d"}, "d1:a1:b1:c1:de"},
52         {[]byte{1, 2, 3, 4}, "4:\x01\x02\x03\x04"},
53         {[4]byte{1, 2, 3, 4}, "li1ei2ei3ei4ee"},
54         {nil, ""},
55         {[]byte{}, "0:"},
56         {"", "0:"},
57         {[]int{}, "le"},
58         {map[string]int{}, "de"},
59         {&dummy{1, 2, 3}, "i2ei3ei4e"},
60         {struct {
61                 A *string
62         }{nil}, "d1:A0:e"},
63         {struct {
64                 A *string
65         }{new(string)}, "d1:A0:e"},
66         {struct {
67                 A *string `bencode:",omitempty"`
68         }{nil}, "de"},
69         {struct {
70                 A *string `bencode:",omitempty"`
71         }{new(string)}, "d1:A0:e"},
72         {bigIntFromString("62208002200000000000"), "i62208002200000000000e"},
73         {*bigIntFromString("62208002200000000000"), "i62208002200000000000e"},
74 }
75
76 func bigIntFromString(s string) *big.Int {
77         bi, ok := new(big.Int).SetString(s, 10)
78         if !ok {
79                 panic(s)
80         }
81         return bi
82 }
83
84 func TestRandomEncode(t *testing.T) {
85         for _, test := range random_encode_tests {
86                 data, err := Marshal(test.value)
87                 assert.NoError(t, err, "%s", test)
88                 assert.EqualValues(t, test.expected, string(data))
89         }
90 }