aboutsummaryrefslogtreecommitdiffstats
path: root/plumbing/memory_test.go
blob: 2a141f4917c9bbc6f18842fccb4237196a7d94b5 (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
package plumbing

import (
	"io"
	"io/ioutil"

	. "gopkg.in/check.v1"
)

type MemoryObjectSuite struct{}

var _ = Suite(&MemoryObjectSuite{})

func (s *MemoryObjectSuite) TestHash(c *C) {
	o := &MemoryObject{}
	o.SetType(BlobObject)
	o.SetSize(14)

	_, err := o.Write([]byte("Hello, World!\n"))
	c.Assert(err, IsNil)

	c.Assert(o.Hash().String(), Equals, "8ab686eafeb1f44702738c8b0f24f2567c36da6d")

	o.SetType(CommitObject)
	c.Assert(o.Hash().String(), Equals, "8ab686eafeb1f44702738c8b0f24f2567c36da6d")
}

func (s *MemoryObjectSuite) TestHashNotFilled(c *C) {
	o := &MemoryObject{}
	o.SetType(BlobObject)
	o.SetSize(14)

	c.Assert(o.Hash(), Equals, ZeroHash)
}

func (s *MemoryObjectSuite) TestType(c *C) {
	o := &MemoryObject{}
	o.SetType(BlobObject)
	c.Assert(o.Type(), Equals, BlobObject)
}

func (s *MemoryObjectSuite) TestSize(c *C) {
	o := &MemoryObject{}
	o.SetSize(42)
	c.Assert(o.Size(), Equals, int64(42))
}

func (s *MemoryObjectSuite) TestReader(c *C) {
	o := &MemoryObject{cont: []byte("foo")}

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

	b, err := ioutil.ReadAll(reader)
	c.Assert(err, IsNil)
	c.Assert(b, DeepEquals, []byte("foo"))
}

func (s *MemoryObjectSuite) TestSeekableReader(c *C) {
	const pageSize = 4096
	const payload = "foo"
	content := make([]byte, pageSize+len(payload))
	copy(content[pageSize:], []byte(payload))

	o := &MemoryObject{cont: content}

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

	rs, ok := reader.(io.ReadSeeker)
	c.Assert(ok, Equals, true)

	_, err = rs.Seek(pageSize, io.SeekStart)
	c.Assert(err, IsNil)

	b, err := ioutil.ReadAll(rs)
	c.Assert(err, IsNil)
	c.Assert(b, DeepEquals, []byte(payload))

	// Check that our Reader isn't also accidentally writable
	_, ok = reader.(io.WriteSeeker)
	c.Assert(ok, Equals, false)
}

func (s *MemoryObjectSuite) TestWriter(c *C) {
	o := &MemoryObject{}

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

	n, err := writer.Write([]byte("foo"))
	c.Assert(err, IsNil)
	c.Assert(n, Equals, 3)

	c.Assert(o.cont, DeepEquals, []byte("foo"))
}