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