aboutsummaryrefslogtreecommitdiff
path: root/objects/object_test.go
blob: 3808d132f47d66480018ea783c198094b481e401 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package objects

import (
	"bufio"
	"bytes"
	"testing"
)

func TestUnserializeSuccess(t *testing.T) {
	r := bufio.NewReader(bytes.NewBuffer([]byte("blob 16\n0123456789abcdef")))

	o, err := Unserialize(r)
	if err != nil {
		t.Fatalf("Unserialize failed: %s", err)
	}

	if o.Type != OTBlob {
		t.Errorf("expected type %s, got %s", OTBlob, o.Type)
	}

	if !bytes.Equal([]byte("0123456789abcdef"), o.Payload) {
		t.Errorf("Unexpected payload: (size %d) %v", len(o.Payload), o.Payload)
	}
}

func TestUnserializeSuccess0Payload(t *testing.T) {
	r := bufio.NewReader(bytes.NewBuffer([]byte("blob 0\n")))

	o, err := Unserialize(r)
	if err != nil {
		t.Fatalf("Unserialize failed: %s", err)
	}

	if o.Type != OTBlob {
		t.Errorf("expected type %s, got %s", OTBlob, o.Type)
	}

	if !bytes.Equal([]byte{}, o.Payload) {
		t.Errorf("Unexpected payload: (size %d) %v", len(o.Payload), o.Payload)
	}
}

func unserializeMustFail(b []byte, t *testing.T) {
	r := bufio.NewReader(bytes.NewBuffer(b))

	o, err := Unserialize(r)
	if err == nil {
		t.Fatalf("Expected an error, but object was successfully read: %#v", o)
	}

	_, ok := err.(UnserializeError)
	if !ok {
		t.Fatalf("Unknown error, expected an UnserializeError: %#v", err)
	}
}

func TestUnserializeInvalidEmpty(t *testing.T) {
	unserializeMustFail([]byte{}, t)
}

func TestUnserializeIncompleteHeader(t *testing.T) {
	unserializeMustFail([]byte("foo\nbar"), t)
}

func TestUnserializeInvalidNumber(t *testing.T) {
	unserializeMustFail([]byte("blob abc\nbar"), t)
}

func TestUnserializePayloadTooSmall(t *testing.T) {
	unserializeMustFail([]byte("blob 10\nbar"), t)
}

func TestSerialize(t *testing.T) {
	o := RawObject{
		Type:    OTBlob,
		Payload: []byte("foo bar\nbaz"),
	}

	buf := new(bytes.Buffer)
	if err := o.Serialize(buf); err != nil {
		t.Fatalf("Serialization failed:%s", err)
	}

	b := buf.Bytes()
	if !bytes.Equal(b, []byte("blob 11\nfoo bar\nbaz")) {
		t.Errorf("Unexpected serialization result: %v", b)
	}
}

func TestSerializeAndId(t *testing.T) {
	o := RawObject{
		Type:    OTBlob,
		Payload: []byte("foo bar\nbaz"),
	}

	buf := new(bytes.Buffer)
	id, err := o.SerializeAndId(buf, OIdAlgoDefault)

	if err != nil {
		t.Fatalf("Serialization failed:%s", err)
	}

	if !id.VerifyObject(o) {
		t.Errorf("Verification failed")
	}
}