]> Sergey Matveev's repositories - btrtrc.git/blob - bencode/decode_test.go
Fix bugs, implement missing bits. Made a mess, can't describe properly.
[btrtrc.git] / bencode / decode_test.go
1 package bencode
2
3 import "testing"
4 import "reflect"
5
6 type random_decode_test struct {
7         data     string
8         expected interface{}
9 }
10
11 var random_decode_tests = []random_decode_test{
12         {"i57e", int64(57)},
13         {"i-9223372036854775808e", int64(-9223372036854775808)},
14         {"5:hello", "hello"},
15         {"29:unicode test проверка", "unicode test проверка"},
16         {"d1:ai5e1:b5:helloe", map[string]interface{}{"a": int64(5), "b": "hello"}},
17         {"li5ei10ei15ei20e7:bencodee",
18                 []interface{}{int64(5), int64(10), int64(15), int64(20), "bencode"}},
19         {"ldedee", []interface{}{map[string]interface{}{}, map[string]interface{}{}}},
20         {"le", []interface{}{}},
21 }
22
23 func TestRandomDecode(t *testing.T) {
24         for _, test := range random_decode_tests {
25                 var value interface{}
26                 err := Unmarshal([]byte(test.data), &value)
27                 if err != nil {
28                         t.Error(err)
29                         continue
30                 }
31                 if !reflect.DeepEqual(test.expected, value) {
32                         t.Errorf("got: %v (%T), expected: %v (%T)\n",
33                                 value, value, test.expected, test.expected)
34                 }
35         }
36 }
37
38 func check_error(t *testing.T, err error) {
39         if err != nil {
40                 t.Error(err)
41         }
42 }
43
44 func assert_equal(t *testing.T, x, y interface{}) {
45         if !reflect.DeepEqual(x, y) {
46                 t.Errorf("got: %v (%T), expected: %v (%T)\n", x, x, y, y)
47         }
48 }
49
50 type unmarshaler_int struct {
51         x int
52 }
53
54 func (this *unmarshaler_int) UnmarshalBencode(data []byte) error {
55         return Unmarshal(data, &this.x)
56 }
57
58 type unmarshaler_string struct {
59         x string
60 }
61
62 func (this *unmarshaler_string) UnmarshalBencode(data []byte) error {
63         this.x = string(data)
64         return nil
65 }
66
67 func TestUnmarshalerBencode(t *testing.T) {
68         var i unmarshaler_int
69         var ss []unmarshaler_string
70         check_error(t, Unmarshal([]byte("i71e"), &i))
71         assert_equal(t, i.x, 71)
72         check_error(t, Unmarshal([]byte("l5:hello5:fruit3:waye"), &ss))
73         assert_equal(t, ss[0].x, "5:hello")
74         assert_equal(t, ss[1].x, "5:fruit")
75         assert_equal(t, ss[2].x, "3:way")
76
77 }