aboutsummaryrefslogtreecommitdiffstats
path: root/plumbing/object/blob_test.go
blob: 9481dbe44ae7856bd5bf5f7833d38a734cc5a151 (plain) (blame)
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
107
108
109
110
111
112
113
114
package object

import (
	"bytes"
	"io"

	"github.com/go-git/go-git/v5/plumbing"

	. "gopkg.in/check.v1"
)

type BlobsSuite struct {
	BaseObjectsSuite
}

var _ = Suite(&BlobsSuite{})

func (s *BlobsSuite) TestBlobHash(c *C) {
	o := &plumbing.MemoryObject{}
	o.SetType(plumbing.BlobObject)
	o.SetSize(3)

	writer, err := o.Writer()
	c.Assert(err, IsNil)
	defer func() { c.Assert(writer.Close(), IsNil) }()

	writer.Write([]byte{'F', 'O', 'O'})

	blob := &Blob{}
	c.Assert(blob.Decode(o), IsNil)

	c.Assert(blob.Size, Equals, int64(3))
	c.Assert(blob.Hash.String(), Equals, "d96c7efbfec2814ae0301ad054dc8d9fc416c9b5")

	reader, err := blob.Reader()
	c.Assert(err, IsNil)
	defer func() { c.Assert(reader.Close(), IsNil) }()

	data, err := io.ReadAll(reader)
	c.Assert(err, IsNil)
	c.Assert(string(data), Equals, "FOO")
}

func (s *BlobsSuite) TestBlobDecodeEncodeIdempotent(c *C) {
	var objects []*plumbing.MemoryObject
	for _, str := range []string{"foo", "foo\n"} {
		obj := &plumbing.MemoryObject{}
		obj.Write([]byte(str))
		obj.SetType(plumbing.BlobObject)
		obj.Hash()
		objects = append(objects, obj)
	}
	for _, object := range objects {
		blob := &Blob{}
		err := blob.Decode(object)
		c.Assert(err, IsNil)
		newObject := &plumbing.MemoryObject{}
		err = blob.Encode(newObject)
		c.Assert(err, IsNil)
		newObject.Hash() // Ensure Hash is pre-computed before deep comparison
		c.Assert(newObject, DeepEquals, object)
	}
}

func (s *BlobsSuite) TestBlobIter(c *C) {
	encIter, err := s.Storer.IterEncodedObjects(plumbing.BlobObject)
	c.Assert(err, IsNil)
	iter := NewBlobIter(s.Storer, encIter)

	blobs := []*Blob{}
	iter.ForEach(func(b *Blob) error {
		blobs = append(blobs, b)
		return nil
	})

	c.Assert(len(blobs) > 0, Equals, true)
	iter.Close()

	encIter, err = s.Storer.IterEncodedObjects(plumbing.BlobObject)
	c.Assert(err, IsNil)
	iter = NewBlobIter(s.Storer, encIter)

	i := 0
	for {
		b, err := iter.Next()
		if err == io.EOF {
			break
		}

		c.Assert(err, IsNil)
		c.Assert(b.ID(), Equals, blobs[i].ID())
		c.Assert(b.Size, Equals, blobs[i].Size)
		c.Assert(b.Type(), Equals, blobs[i].Type())

		r1, err := b.Reader()
		c.Assert(err, IsNil)

		b1, err := io.ReadAll(r1)
		c.Assert(err, IsNil)
		c.Assert(r1.Close(), IsNil)

		r2, err := blobs[i].Reader()
		c.Assert(err, IsNil)

		b2, err := io.ReadAll(r2)
		c.Assert(err, IsNil)
		c.Assert(r2.Close(), IsNil)

		c.Assert(bytes.Compare(b1, b2), Equals, 0)
		i++
	}

	iter.Close()
}