github.com/anacrolix/torrent@v1.61.0/bencode/encode_test.go (about) 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}, "4:\x01\x02\x03\x04"}, 54 {nil, ""}, 55 {[]byte{}, "0:"}, 56 {[]byte(nil), "0:"}, 57 {"", "0:"}, 58 {[]int{}, "le"}, 59 {map[string]int{}, "de"}, 60 {&dummy{1, 2, 3}, "i2ei3ei4e"}, 61 {struct { 62 A *string 63 }{nil}, "d1:A0:e"}, 64 {struct { 65 A *string 66 }{new(string)}, "d1:A0:e"}, 67 {struct { 68 A *string `bencode:",omitempty"` 69 }{nil}, "de"}, 70 {struct { 71 A *string `bencode:",omitempty"` 72 }{new(string)}, "d1:A0:e"}, 73 {bigIntFromString("62208002200000000000"), "i62208002200000000000e"}, 74 {*bigIntFromString("62208002200000000000"), "i62208002200000000000e"}, 75 } 76 77 func bigIntFromString(s string) *big.Int { 78 bi, ok := new(big.Int).SetString(s, 10) 79 if !ok { 80 panic(s) 81 } 82 return bi 83 } 84 85 func TestRandomEncode(t *testing.T) { 86 for _, test := range random_encode_tests { 87 data, err := Marshal(test.value) 88 assert.NoError(t, err, "%s", test) 89 assert.EqualValues(t, test.expected, string(data)) 90 } 91 }