Debian Codegraph @

blob_test.go

raw
1 package gitobj
2
3 import (
4 "bytes"
5 "crypto/sha1"
6 "errors"
7 "io/ioutil"
8 "strings"
9 "sync/atomic"
10 "testing"
11
12 "github.com/stretchr/testify/assert"
13 )
14
15 func TestBlobReturnsCorrectObjectType(t *testing.T) {
16 assert.Equal(t, BlobObjectType, new(Blob).Type())
17 }
18
19 func TestBlobFromString(t *testing.T) {
20 given := []byte("example")
21 glen := len(given)
22
23 b := NewBlobFromBytes(given)
24
25 assert.EqualValues(t, glen, b.Size)
26
27 contents, err := ioutil.ReadAll(b.Contents)
28 assert.NoError(t, err)
29 assert.Equal(t, given, contents)
30 }
31
32 func TestBlobEncoding(t *testing.T) {
33 const contents = "Hello, world!\n"
34
35 b := &Blob{
36 Size: int64(len(contents)),
37 Contents: strings.NewReader(contents),
38 }
39
40 var buf bytes.Buffer
41 if _, err := b.Encode(&buf); err != nil {
42 t.Fatal(err.Error())
43 }
44 assert.Equal(t, contents, (&buf).String())
45 }
46
47 func TestBlobDecoding(t *testing.T) {
48 const contents = "Hello, world!\n"
49 from := strings.NewReader(contents)
50
51 b := new(Blob)
52 n, err := b.Decode(sha1.New(), from, int64(len(contents)))
53
54 assert.Equal(t, 0, n)
55 assert.Nil(t, err)
56
57 assert.EqualValues(t, len(contents), b.Size)
58
59 got, err := ioutil.ReadAll(b.Contents)
60 assert.Nil(t, err)
61 assert.Equal(t, []byte(contents), got)
62 }
63
64 func TestBlobCallCloseFn(t *testing.T) {
65 var calls uint32
66
67 expected := errors.New("some close error")
68
69 b := &Blob{
70 closeFn: func() error {
71 atomic.AddUint32(&calls, 1)
72 return expected
73 },
74 }
75
76 got := b.Close()
77
78 assert.Equal(t, expected, got)
79 assert.EqualValues(t, 1, calls)
80 }
81
82 func TestBlobCanCloseWithoutCloseFn(t *testing.T) {
83 b := &Blob{
84 closeFn: nil,
85 }
86
87 assert.Nil(t, b.Close())
88 }
89
90 func TestBlobEqualReturnsTrueWithUnchangedContents(t *testing.T) {
91 c := strings.NewReader("Hello, world!")
92
93 b1 := &Blob{Size: int64(c.Len()), Contents: c}
94 b2 := &Blob{Size: int64(c.Len()), Contents: c}
95
96 assert.True(t, b1.Equal(b2))
97 }
98
99 func TestBlobEqualReturnsFalseWithChangedContents(t *testing.T) {
100 c1 := strings.NewReader("Hello, world!")
101 c2 := strings.NewReader("Goodbye, world!")
102
103 b1 := &Blob{Size: int64(c1.Len()), Contents: c1}
104 b2 := &Blob{Size: int64(c2.Len()), Contents: c2}
105
106 assert.False(t, b1.Equal(b2))
107 }
108
109 func TestBlobEqualReturnsTrueWhenOneBlobIsNil(t *testing.T) {
110 b1 := &Blob{Size: 1, Contents: bytes.NewReader([]byte{0xa})}
111 b2 := (*Blob)(nil)
112
113 assert.False(t, b1.Equal(b2))
114 assert.False(t, b2.Equal(b1))
115 }
116
117 func TestBlobEqualReturnsTrueWhenBothBlobsAreNil(t *testing.T) {
118 b1 := (*Blob)(nil)
119 b2 := (*Blob)(nil)
120
121 assert.True(t, b1.Equal(b2))
122 }